_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
|
---|---|---|---|---|---|---|---|---|
ce42a9b4e11474d4264d43ba4e2394fffb37fa476df7ad1dd212cbe054c222da | albertoruiz/easyVision | runmode2.hs | -- threaded GUI, returning result
-- (this mode drops display frames)
import Vision.GUI
import Image.Processing
main = do
r <- runT camera (observe "image" rgb >>> arr (sumPixels.grayscale))
print r
putStrLn "bye!"
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/tour/runmode2.hs | haskell | threaded GUI, returning result
(this mode drops display frames) |
import Vision.GUI
import Image.Processing
main = do
r <- runT camera (observe "image" rgb >>> arr (sumPixels.grayscale))
print r
putStrLn "bye!"
|
64a8d4693942f485b7e9dc15b2de8339645634e2b542e43794b736f8b3655ffb | gas2serra/mcclim-desktop | browser.lisp | (in-package :desktop-user)
(register-application "browser" 'standard-alias-application
:pretty-name "Browser"
:icon nil
;;:reference (find-application "closure")
:reference (find-application "system-browser")
)
| null | https://raw.githubusercontent.com/gas2serra/mcclim-desktop/f85d19c57d76322ae3c05f98ae43bfc8c0d0a554/dot-mcclim-desktop/apps/browser.lisp | lisp | :reference (find-application "closure") | (in-package :desktop-user)
(register-application "browser" 'standard-alias-application
:pretty-name "Browser"
:icon nil
:reference (find-application "system-browser")
)
|
76e3501b8cc89f10ae517c68d5e4f12f52408f7f7e5488c3eefafbec23e202ba | cark/cark.behavior-tree | base_nodes.cljc | (ns cark.behavior-tree.base-nodes
"Some utility function with usefull defaults for the broad node types"
(:require [cark.behavior-tree.type :as type]
[cark.behavior-tree.hiccup.spec :as hs]
[clojure.spec.alpha :as s]))
(defn log [value]
(tap> value)
value)
(defn params-spec
"Returns the spec for the hiccup params map of given node type"
[type]
(if-let [params-spec (type/get-params-spec type)]
params-spec
(s/? ::hs/params)))
(defn children-spec
"Returns the spec for the hiccup children of given node type"
[type]
(if-let [children-spec (type/get-children-spec type)]
children-spec
(s/* ::hs/child)))
(defn leaf
"Provides usefull spec defaults for leaf node types"
[type]
(merge {::type/node-spec (s/cat :tag ::hs/tag
:params (params-spec type))
::type/children-spec nil?}
type))
(defn decorator
"Provides usefull spec defaults for decorator node types"
[type]
(merge {::type/node-spec (s/cat :tag ::hs/tag
:params (params-spec type)
:children (children-spec
(merge {::type/children-spec (s/& (s/+ ::hs/child)
#(= (count %) 1))}
type)))}
type))
(defn branch
"Provides usefull spec defaults for branch node types"
[type]
(merge {::type/node-spec (s/cat :tag ::hs/tag
:params (params-spec type)
:children (children-spec
(merge {::type/children-spec (s/+ ::hs/child)}
type)))}
type))
| null | https://raw.githubusercontent.com/cark/cark.behavior-tree/4e229fcc2ed3af3c66e74d2c51dda6684927d254/src/main/cark/behavior_tree/base_nodes.cljc | clojure | (ns cark.behavior-tree.base-nodes
"Some utility function with usefull defaults for the broad node types"
(:require [cark.behavior-tree.type :as type]
[cark.behavior-tree.hiccup.spec :as hs]
[clojure.spec.alpha :as s]))
(defn log [value]
(tap> value)
value)
(defn params-spec
"Returns the spec for the hiccup params map of given node type"
[type]
(if-let [params-spec (type/get-params-spec type)]
params-spec
(s/? ::hs/params)))
(defn children-spec
"Returns the spec for the hiccup children of given node type"
[type]
(if-let [children-spec (type/get-children-spec type)]
children-spec
(s/* ::hs/child)))
(defn leaf
"Provides usefull spec defaults for leaf node types"
[type]
(merge {::type/node-spec (s/cat :tag ::hs/tag
:params (params-spec type))
::type/children-spec nil?}
type))
(defn decorator
"Provides usefull spec defaults for decorator node types"
[type]
(merge {::type/node-spec (s/cat :tag ::hs/tag
:params (params-spec type)
:children (children-spec
(merge {::type/children-spec (s/& (s/+ ::hs/child)
#(= (count %) 1))}
type)))}
type))
(defn branch
"Provides usefull spec defaults for branch node types"
[type]
(merge {::type/node-spec (s/cat :tag ::hs/tag
:params (params-spec type)
:children (children-spec
(merge {::type/children-spec (s/+ ::hs/child)}
type)))}
type))
|
|
bdbea64fd7f01519727fa5fc240c14e3b87359c8ef07f84b47f0d3d28443de03 | roblaing/erlang-webapp-howto | webutil.erl | -module(webutil).
-export([ create_hash/1
, logged_in/1
, delete_uid/1
, getuuid/1
]).
-spec create_hash(Input::binary()) -> Hexdigest :: string().
%% @doc Rehash the hexdigest read from browser cookie and return as a new hexdigest.
create_hash(Binary) ->
Salt = "Some very long randomly generated string",
<<I:256>> = crypto:mac(hmac, sha256, Salt, Binary),
string:lowercase(integer_to_binary(I, 16)).
-spec logged_in(Proplist :: [{Uuid::bitstring(), Name::bitstring()}]) -> Name::bitstring() | false.
%% @doc Check if uuid is false, and if not that it's a valid ID.
logged_in(Proplist) ->
Bin = proplists:get_value(<<"uuid">>, Proplist, false),
case Bin of
false -> false;
Uuid -> case ets:lookup(uuids, Uuid) of
[] -> false;
[{Uuid, Name}] -> ets:lookup(uuids, Uuid),
Name
end
end.
-spec delete_uid(Proplist::[{Uuid::bitstring(), Name::bitstring()}]) -> true.
%% @doc Call before new login or signup to avoid cluttering ETS with uuid/name pairs which have been overwitten in browsers.
delete_uid(Proplist) ->
Logged = logged_in(Proplist),
case Logged of
false -> true;
_Name -> Uuid = proplists:get_value(<<"uuid">>, Proplist),
ets:delete(uuids, Uuid)
end.
-spec getuuid(Proplist::[{Uuid::bitstring(), Name::bitstring()}]) -> Uuid::bitstring() | false.
%% @doc Return a unique hashkey if the supplied user_id is valid, else false.
getuuid(Proplist) ->
case proplists:get_value(<<"user_id">>, Proplist, false) of
false -> false;
Hash ->
#{rows := Rows} = pgo:query("SELECT name FROM users WHERE id=$1::text", [create_hash(Hash)]),
case Rows of
[] -> false;
[{Name}] -> delete_uid(Proplist),
String = io_lib:format("~p~p~p", [erlang:system_time(millisecond), make_ref(), node()]),
<<I:128>> = crypto:hash(md5, String),
Uuid = integer_to_binary(I, 16),
Unique = ets:insert_new(uuids, {Uuid, Name}),
case Unique of
true -> Uuid;
false -> getuuid(Proplist)
end,
Uuid
end
end.
| null | https://raw.githubusercontent.com/roblaing/erlang-webapp-howto/e1731dfc4e2cfdfee88e982d67155b83acd5cc04/unit6/apps/unit6/src/webutil.erl | erlang | @doc Rehash the hexdigest read from browser cookie and return as a new hexdigest.
@doc Check if uuid is false, and if not that it's a valid ID.
@doc Call before new login or signup to avoid cluttering ETS with uuid/name pairs which have been overwitten in browsers.
@doc Return a unique hashkey if the supplied user_id is valid, else false. | -module(webutil).
-export([ create_hash/1
, logged_in/1
, delete_uid/1
, getuuid/1
]).
-spec create_hash(Input::binary()) -> Hexdigest :: string().
create_hash(Binary) ->
Salt = "Some very long randomly generated string",
<<I:256>> = crypto:mac(hmac, sha256, Salt, Binary),
string:lowercase(integer_to_binary(I, 16)).
-spec logged_in(Proplist :: [{Uuid::bitstring(), Name::bitstring()}]) -> Name::bitstring() | false.
logged_in(Proplist) ->
Bin = proplists:get_value(<<"uuid">>, Proplist, false),
case Bin of
false -> false;
Uuid -> case ets:lookup(uuids, Uuid) of
[] -> false;
[{Uuid, Name}] -> ets:lookup(uuids, Uuid),
Name
end
end.
-spec delete_uid(Proplist::[{Uuid::bitstring(), Name::bitstring()}]) -> true.
delete_uid(Proplist) ->
Logged = logged_in(Proplist),
case Logged of
false -> true;
_Name -> Uuid = proplists:get_value(<<"uuid">>, Proplist),
ets:delete(uuids, Uuid)
end.
-spec getuuid(Proplist::[{Uuid::bitstring(), Name::bitstring()}]) -> Uuid::bitstring() | false.
getuuid(Proplist) ->
case proplists:get_value(<<"user_id">>, Proplist, false) of
false -> false;
Hash ->
#{rows := Rows} = pgo:query("SELECT name FROM users WHERE id=$1::text", [create_hash(Hash)]),
case Rows of
[] -> false;
[{Name}] -> delete_uid(Proplist),
String = io_lib:format("~p~p~p", [erlang:system_time(millisecond), make_ref(), node()]),
<<I:128>> = crypto:hash(md5, String),
Uuid = integer_to_binary(I, 16),
Unique = ets:insert_new(uuids, {Uuid, Name}),
case Unique of
true -> Uuid;
false -> getuuid(Proplist)
end,
Uuid
end
end.
|
63dccd8a6c31d8b7eaab5a76fd862eeebcb941fde0dbae9c27c2b0b9a437213c | jonase/eastwood | box.clj | Copyright ( c ) , Rich Hickey & contributors .
;; 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 eastwood.copieddeps.dep2.clojure.tools.analyzer.passes.jvm.box
(:require [eastwood.copieddeps.dep2.clojure.tools.analyzer.jvm.utils :as u]
[eastwood.copieddeps.dep1.clojure.tools.analyzer.utils :refer [protocol-node? arglist-for-arity]]
[eastwood.copieddeps.dep2.clojure.tools.analyzer.passes.jvm
[validate :refer [validate]]
[infer-tag :refer [infer-tag]]]))
(defmulti box
"Box the AST node tag where necessary"
{:pass-info {:walk :pre :depends #{#'infer-tag} :after #{#'validate}}}
:op)
(defmacro if-let-box [class then else]
`(let [c# ~class
~class (u/box c#)]
(if (u/primitive? c#)
~then
~else)))
(defn -box [ast]
(let [tag (:tag ast)]
(if (u/primitive? tag)
(assoc ast :tag (u/box tag))
ast)))
(defn boxed? [tag expr]
(and (or (nil? tag) (not (u/primitive? tag)))
(u/primitive? (:tag expr))))
(defmethod box :instance-call
[{:keys [args class validated? tag] :as ast}]
(let [ast (if-let-box class
(assoc (update-in ast [:instance :tag] u/box) :class class)
ast)]
(if validated?
ast
(assoc ast :args (mapv -box args)
:o-tag Object :tag (if (not (#{Void Void/TYPE} tag))
tag
Object)))))
(defmethod box :static-call
[{:keys [args validated? tag] :as ast}]
(if validated?
ast
(assoc ast :args (mapv -box args)
:o-tag Object :tag (if (not (#{Void Void/TYPE} tag))
tag
Object))))
(defmethod box :new
[{:keys [args validated?] :as ast}]
(if validated?
ast
(assoc ast :args (mapv -box args)
:o-tag Object)))
(defmethod box :instance-field
[{:keys [class] :as ast}]
(if-let-box class
(assoc (update-in ast [:instance :tag] u/box) :class class)
ast))
(defmethod box :def
[{:keys [init] :as ast}]
(if (and init (u/primitive? (:tag init)))
(update-in ast [:init] -box)
ast))
(defmethod box :vector
[ast]
(assoc ast :items (mapv -box (:items ast))))
(defmethod box :set
[ast]
(assoc ast :items (mapv -box (:items ast))))
(defmethod box :map
[ast]
(let [keys (mapv -box (:keys ast))
vals (mapv -box (:vals ast))]
(assoc ast
:keys keys
:vals vals)))
(defmethod box :do
[ast]
(if (boxed? (:tag ast) (:ret ast))
(-> ast
(update-in [:ret] -box)
(update-in [:o-tag] u/box))
ast))
(defmethod box :quote
[ast]
(if (boxed? (:tag ast) (:ret ast))
(-> ast
(update-in [:expr] -box)
(update-in [:o-tag] u/box))
ast))
(defmethod box :protocol-invoke
[ast]
(assoc ast :args (mapv -box (:args ast))))
(defmethod box :let
[{:keys [tag body] :as ast}]
(if (boxed? tag body)
(-> ast
(update-in [:body] -box)
(update-in [:o-tag] u/box))
ast))
(defmethod box :letfn
[ast]
(if (boxed? (:tag ast) (:body ast))
(-> ast
(update-in [:body] -box)
(update-in [:o-tag] u/box))
ast))
(defmethod box :loop
[ast]
(if (boxed? (:tag ast) (:body ast))
(-> ast
(update-in [:body] -box)
(update-in [:o-tag] u/box))
ast))
(defmethod box :fn-method
[{:keys [params tag] :as ast}]
(let [ast (if (u/primitive? tag)
ast
(-> ast
(update-in [:body] -box)
(update-in [:o-tag] u/box)))]
(assoc ast
:params (mapv (fn [{:keys [o-tag] :as p}]
(assoc p :o-tag (u/prim-or-obj o-tag))) params)
:tag (u/prim-or-obj tag)
:o-tag (u/prim-or-obj tag))))
(defmethod box :if
[{:keys [test then else tag o-tag] :as ast}]
(let [test-tag (:tag test)
test (if (and (u/primitive? test-tag)
(not= Boolean/TYPE test-tag))
(assoc test :tag (u/box test-tag))
test)
[then else o-tag] (if (or (boxed? tag then)
(boxed? tag else)
(not o-tag))
(conj (mapv -box [then else]) (u/box o-tag))
[then else o-tag])]
(merge ast
{:test test
:o-tag o-tag
:then then
:else else})))
(defmethod box :case
[{:keys [tag default tests thens test-type] :as ast}]
(let [ast (if (and tag (u/primitive? tag))
ast
(-> ast
(assoc-in [:thens] (mapv (fn [t] (update-in t [:then] -box)) thens))
(update-in [:default] -box)
(update-in [:o-tag] u/box)))]
(if (= :hash-equiv test-type)
(-> ast
(update-in [:test] -box)
(assoc-in [:tests] (mapv (fn [t] (update-in t [:test] -box)) tests)))
ast)))
(defmethod box :try
[{:keys [tag] :as ast}]
(let [ast (if (and tag (u/primitive? tag))
ast
(-> ast
(update-in [:catches] #(mapv -box %))
(update-in [:body] -box)
(update-in [:o-tag] u/box)))]
(-> ast
(update-in [:finally] -box))))
(defmethod box :invoke
[ast]
(assoc ast
:args (mapv -box (:args ast))
:o-tag Object))
(defmethod box :default [ast] ast)
| null | https://raw.githubusercontent.com/jonase/eastwood/c5b7d9f8ad8f8b38dc7138d853cc65f6987d6058/copied-deps/eastwood/copieddeps/dep2/clojure/tools/analyzer/passes/jvm/box.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 ) , Rich Hickey & contributors .
(ns eastwood.copieddeps.dep2.clojure.tools.analyzer.passes.jvm.box
(:require [eastwood.copieddeps.dep2.clojure.tools.analyzer.jvm.utils :as u]
[eastwood.copieddeps.dep1.clojure.tools.analyzer.utils :refer [protocol-node? arglist-for-arity]]
[eastwood.copieddeps.dep2.clojure.tools.analyzer.passes.jvm
[validate :refer [validate]]
[infer-tag :refer [infer-tag]]]))
(defmulti box
"Box the AST node tag where necessary"
{:pass-info {:walk :pre :depends #{#'infer-tag} :after #{#'validate}}}
:op)
(defmacro if-let-box [class then else]
`(let [c# ~class
~class (u/box c#)]
(if (u/primitive? c#)
~then
~else)))
(defn -box [ast]
(let [tag (:tag ast)]
(if (u/primitive? tag)
(assoc ast :tag (u/box tag))
ast)))
(defn boxed? [tag expr]
(and (or (nil? tag) (not (u/primitive? tag)))
(u/primitive? (:tag expr))))
(defmethod box :instance-call
[{:keys [args class validated? tag] :as ast}]
(let [ast (if-let-box class
(assoc (update-in ast [:instance :tag] u/box) :class class)
ast)]
(if validated?
ast
(assoc ast :args (mapv -box args)
:o-tag Object :tag (if (not (#{Void Void/TYPE} tag))
tag
Object)))))
(defmethod box :static-call
[{:keys [args validated? tag] :as ast}]
(if validated?
ast
(assoc ast :args (mapv -box args)
:o-tag Object :tag (if (not (#{Void Void/TYPE} tag))
tag
Object))))
(defmethod box :new
[{:keys [args validated?] :as ast}]
(if validated?
ast
(assoc ast :args (mapv -box args)
:o-tag Object)))
(defmethod box :instance-field
[{:keys [class] :as ast}]
(if-let-box class
(assoc (update-in ast [:instance :tag] u/box) :class class)
ast))
(defmethod box :def
[{:keys [init] :as ast}]
(if (and init (u/primitive? (:tag init)))
(update-in ast [:init] -box)
ast))
(defmethod box :vector
[ast]
(assoc ast :items (mapv -box (:items ast))))
(defmethod box :set
[ast]
(assoc ast :items (mapv -box (:items ast))))
(defmethod box :map
[ast]
(let [keys (mapv -box (:keys ast))
vals (mapv -box (:vals ast))]
(assoc ast
:keys keys
:vals vals)))
(defmethod box :do
[ast]
(if (boxed? (:tag ast) (:ret ast))
(-> ast
(update-in [:ret] -box)
(update-in [:o-tag] u/box))
ast))
(defmethod box :quote
[ast]
(if (boxed? (:tag ast) (:ret ast))
(-> ast
(update-in [:expr] -box)
(update-in [:o-tag] u/box))
ast))
(defmethod box :protocol-invoke
[ast]
(assoc ast :args (mapv -box (:args ast))))
(defmethod box :let
[{:keys [tag body] :as ast}]
(if (boxed? tag body)
(-> ast
(update-in [:body] -box)
(update-in [:o-tag] u/box))
ast))
(defmethod box :letfn
[ast]
(if (boxed? (:tag ast) (:body ast))
(-> ast
(update-in [:body] -box)
(update-in [:o-tag] u/box))
ast))
(defmethod box :loop
[ast]
(if (boxed? (:tag ast) (:body ast))
(-> ast
(update-in [:body] -box)
(update-in [:o-tag] u/box))
ast))
(defmethod box :fn-method
[{:keys [params tag] :as ast}]
(let [ast (if (u/primitive? tag)
ast
(-> ast
(update-in [:body] -box)
(update-in [:o-tag] u/box)))]
(assoc ast
:params (mapv (fn [{:keys [o-tag] :as p}]
(assoc p :o-tag (u/prim-or-obj o-tag))) params)
:tag (u/prim-or-obj tag)
:o-tag (u/prim-or-obj tag))))
(defmethod box :if
[{:keys [test then else tag o-tag] :as ast}]
(let [test-tag (:tag test)
test (if (and (u/primitive? test-tag)
(not= Boolean/TYPE test-tag))
(assoc test :tag (u/box test-tag))
test)
[then else o-tag] (if (or (boxed? tag then)
(boxed? tag else)
(not o-tag))
(conj (mapv -box [then else]) (u/box o-tag))
[then else o-tag])]
(merge ast
{:test test
:o-tag o-tag
:then then
:else else})))
(defmethod box :case
[{:keys [tag default tests thens test-type] :as ast}]
(let [ast (if (and tag (u/primitive? tag))
ast
(-> ast
(assoc-in [:thens] (mapv (fn [t] (update-in t [:then] -box)) thens))
(update-in [:default] -box)
(update-in [:o-tag] u/box)))]
(if (= :hash-equiv test-type)
(-> ast
(update-in [:test] -box)
(assoc-in [:tests] (mapv (fn [t] (update-in t [:test] -box)) tests)))
ast)))
(defmethod box :try
[{:keys [tag] :as ast}]
(let [ast (if (and tag (u/primitive? tag))
ast
(-> ast
(update-in [:catches] #(mapv -box %))
(update-in [:body] -box)
(update-in [:o-tag] u/box)))]
(-> ast
(update-in [:finally] -box))))
(defmethod box :invoke
[ast]
(assoc ast
:args (mapv -box (:args ast))
:o-tag Object))
(defmethod box :default [ast] ast)
|
7dc762c692ba3d6de5f5a10128a29e461ae000f342b99f227533b9dc2dd9ad28 | REPROSEC/dolev-yao-star | Vale_Math_Poly2_Bits_s.ml | open Prims
let (to_uint : Prims.pos -> Vale_Math_Poly2_s.poly -> unit FStar_UInt.uint_t)
=
fun n ->
fun a ->
FStar_UInt.from_vec n
(Vale_Math_Poly2_s.to_seq
(Vale_Math_Poly2_s.reverse a (n - Prims.int_one)) n)
let (of_uint : Prims.pos -> unit FStar_UInt.uint_t -> Vale_Math_Poly2_s.poly)
=
fun n ->
fun u ->
Vale_Math_Poly2_s.reverse
(Vale_Math_Poly2_s.of_seq (FStar_UInt.to_vec n u))
(n - Prims.int_one)
let (to_double32_def : Vale_Math_Poly2_s.poly -> Vale_Def_Types_s.double32) =
fun a ->
let s =
Vale_Math_Poly2_s.to_seq
(Vale_Math_Poly2_s.reverse a (Prims.of_int (63))) (Prims.of_int (64)) in
{
Vale_Def_Words_s.lo =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s (Prims.of_int (32)) (Prims.of_int (64))));
Vale_Def_Words_s.hi =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s Prims.int_zero (Prims.of_int (32))))
}
let (of_double32_def : Vale_Def_Types_s.double32 -> Vale_Math_Poly2_s.poly) =
fun d ->
let uu___ = d in
match uu___ with
| { Vale_Def_Words_s.lo = d0; Vale_Def_Words_s.hi = d1;_} ->
let s =
FStar_Seq_Base.append (FStar_UInt.to_vec (Prims.of_int (32)) d1)
(FStar_UInt.to_vec (Prims.of_int (32)) d0) in
Vale_Math_Poly2_s.reverse (Vale_Math_Poly2_s.of_seq s)
(Prims.of_int (63))
let (to_quad32_def : Vale_Math_Poly2_s.poly -> Vale_Def_Types_s.quad32) =
fun a ->
let s =
Vale_Math_Poly2_s.to_seq
(Vale_Math_Poly2_s.reverse a (Prims.of_int (127)))
(Prims.of_int (128)) in
{
Vale_Def_Words_s.lo0 =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s (Prims.of_int (96)) (Prims.of_int (128))));
Vale_Def_Words_s.lo1 =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s (Prims.of_int (64)) (Prims.of_int (96))));
Vale_Def_Words_s.hi2 =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s (Prims.of_int (32)) (Prims.of_int (64))));
Vale_Def_Words_s.hi3 =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s Prims.int_zero (Prims.of_int (32))))
}
let (of_quad32_def : Vale_Def_Types_s.quad32 -> Vale_Math_Poly2_s.poly) =
fun q ->
let uu___ = q in
match uu___ with
| { Vale_Def_Words_s.lo0 = q0; Vale_Def_Words_s.lo1 = q1;
Vale_Def_Words_s.hi2 = q2; Vale_Def_Words_s.hi3 = q3;_} ->
let s =
FStar_Seq_Base.append
(FStar_Seq_Base.append
(FStar_Seq_Base.append
(FStar_UInt.to_vec (Prims.of_int (32)) q3)
(FStar_UInt.to_vec (Prims.of_int (32)) q2))
(FStar_UInt.to_vec (Prims.of_int (32)) q1))
(FStar_UInt.to_vec (Prims.of_int (32)) q0) in
Vale_Math_Poly2_s.reverse (Vale_Math_Poly2_s.of_seq s)
(Prims.of_int (127))
let (to_double32 : Vale_Math_Poly2_s.poly -> Vale_Def_Types_s.double32) =
fun a -> to_double32_def a
let (of_double32 : Vale_Def_Types_s.double32 -> Vale_Math_Poly2_s.poly) =
fun d -> of_double32_def d
let (to_quad32 : Vale_Math_Poly2_s.poly -> Vale_Def_Types_s.quad32) =
fun a -> to_quad32_def a
let (of_quad32 : Vale_Def_Types_s.quad32 -> Vale_Math_Poly2_s.poly) =
fun q -> of_quad32_def q
| null | https://raw.githubusercontent.com/REPROSEC/dolev-yao-star/d97a8dd4d07f2322437f186e4db6a1f4d5ee9230/concrete/hacl-star-snapshot/ml/Vale_Math_Poly2_Bits_s.ml | ocaml | open Prims
let (to_uint : Prims.pos -> Vale_Math_Poly2_s.poly -> unit FStar_UInt.uint_t)
=
fun n ->
fun a ->
FStar_UInt.from_vec n
(Vale_Math_Poly2_s.to_seq
(Vale_Math_Poly2_s.reverse a (n - Prims.int_one)) n)
let (of_uint : Prims.pos -> unit FStar_UInt.uint_t -> Vale_Math_Poly2_s.poly)
=
fun n ->
fun u ->
Vale_Math_Poly2_s.reverse
(Vale_Math_Poly2_s.of_seq (FStar_UInt.to_vec n u))
(n - Prims.int_one)
let (to_double32_def : Vale_Math_Poly2_s.poly -> Vale_Def_Types_s.double32) =
fun a ->
let s =
Vale_Math_Poly2_s.to_seq
(Vale_Math_Poly2_s.reverse a (Prims.of_int (63))) (Prims.of_int (64)) in
{
Vale_Def_Words_s.lo =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s (Prims.of_int (32)) (Prims.of_int (64))));
Vale_Def_Words_s.hi =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s Prims.int_zero (Prims.of_int (32))))
}
let (of_double32_def : Vale_Def_Types_s.double32 -> Vale_Math_Poly2_s.poly) =
fun d ->
let uu___ = d in
match uu___ with
| { Vale_Def_Words_s.lo = d0; Vale_Def_Words_s.hi = d1;_} ->
let s =
FStar_Seq_Base.append (FStar_UInt.to_vec (Prims.of_int (32)) d1)
(FStar_UInt.to_vec (Prims.of_int (32)) d0) in
Vale_Math_Poly2_s.reverse (Vale_Math_Poly2_s.of_seq s)
(Prims.of_int (63))
let (to_quad32_def : Vale_Math_Poly2_s.poly -> Vale_Def_Types_s.quad32) =
fun a ->
let s =
Vale_Math_Poly2_s.to_seq
(Vale_Math_Poly2_s.reverse a (Prims.of_int (127)))
(Prims.of_int (128)) in
{
Vale_Def_Words_s.lo0 =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s (Prims.of_int (96)) (Prims.of_int (128))));
Vale_Def_Words_s.lo1 =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s (Prims.of_int (64)) (Prims.of_int (96))));
Vale_Def_Words_s.hi2 =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s (Prims.of_int (32)) (Prims.of_int (64))));
Vale_Def_Words_s.hi3 =
(FStar_UInt.from_vec (Prims.of_int (32))
(FStar_Seq_Base.slice s Prims.int_zero (Prims.of_int (32))))
}
let (of_quad32_def : Vale_Def_Types_s.quad32 -> Vale_Math_Poly2_s.poly) =
fun q ->
let uu___ = q in
match uu___ with
| { Vale_Def_Words_s.lo0 = q0; Vale_Def_Words_s.lo1 = q1;
Vale_Def_Words_s.hi2 = q2; Vale_Def_Words_s.hi3 = q3;_} ->
let s =
FStar_Seq_Base.append
(FStar_Seq_Base.append
(FStar_Seq_Base.append
(FStar_UInt.to_vec (Prims.of_int (32)) q3)
(FStar_UInt.to_vec (Prims.of_int (32)) q2))
(FStar_UInt.to_vec (Prims.of_int (32)) q1))
(FStar_UInt.to_vec (Prims.of_int (32)) q0) in
Vale_Math_Poly2_s.reverse (Vale_Math_Poly2_s.of_seq s)
(Prims.of_int (127))
let (to_double32 : Vale_Math_Poly2_s.poly -> Vale_Def_Types_s.double32) =
fun a -> to_double32_def a
let (of_double32 : Vale_Def_Types_s.double32 -> Vale_Math_Poly2_s.poly) =
fun d -> of_double32_def d
let (to_quad32 : Vale_Math_Poly2_s.poly -> Vale_Def_Types_s.quad32) =
fun a -> to_quad32_def a
let (of_quad32 : Vale_Def_Types_s.quad32 -> Vale_Math_Poly2_s.poly) =
fun q -> of_quad32_def q
|
|
39813c7d7f1127eb6398ff67f19475b4815b9c797df338ac12382ae3c2ce35be | eareese/htdp-exercises | 200-itunes-total-time.rkt | #lang htdp/bsl+
;;---------------------------------------------------------------------------------------------------
Exercise 200 . Design the function total - time , which consumes an element of LTracks and produces
;; the total amount of play time. Once the program is done, compute the total play time of your
;; iTunes collection.
(require 2htdp/itunes)
(define ITUNES-LOCATION "itunes.xml")
LTracks
( define itunes - tracks ( read - itunes - as - tracks ITUNES - LOCATION ) )
;; TEST HELPERS
(define TEST-TRACK1
(create-track "Nearly Midnight, Honolulu"
"Neko Case"
"The Worse Things Get, The Harder I Fight, The Harder I Fight, The More I Love You"
157204
6
(create-date 2016 10 8 17 59 0)
7
(create-date 2016 11 6 21 50 58)))
(define TEST-TRACK2
(create-track "Blue Kentucky Girl"
"Emmylou Harris"
"Blue Kentucky Girl"
200045
9
(create-date 2016 10 23 17 28 22)
17
(create-date 2016 12 30 15 59 41)))
(define TEST-LTRACK (list TEST-TRACK1 TEST-TRACK2))
LTracks - > Number
; consumes a List-of-tracks and produces the total amount of play time in ms
(check-expect (total-time TEST-LTRACK) (+ (track-time TEST-TRACK1) (track-time TEST-TRACK2)))
(check-expect (total-time (list TEST-TRACK2)) (track-time TEST-TRACK2))
(check-expect (total-time '()) 0)
(define (total-time tracks)
(cond
[(empty? tracks) 0]
[else (+ (track-time (first tracks)) (total-time (rest tracks)))]))
;; TOTAL
;; (total-time itunes-tracks)
399722535
That 's about 4.6 days ' worth .
| null | https://raw.githubusercontent.com/eareese/htdp-exercises/a85ff3111d459dda0e94d9b463d01a09accbf9bf/part02-arbitrarily-large-data/200-itunes-total-time.rkt | racket | ---------------------------------------------------------------------------------------------------
the total amount of play time. Once the program is done, compute the total play time of your
iTunes collection.
TEST HELPERS
consumes a List-of-tracks and produces the total amount of play time in ms
TOTAL
(total-time itunes-tracks) | #lang htdp/bsl+
Exercise 200 . Design the function total - time , which consumes an element of LTracks and produces
(require 2htdp/itunes)
(define ITUNES-LOCATION "itunes.xml")
LTracks
( define itunes - tracks ( read - itunes - as - tracks ITUNES - LOCATION ) )
(define TEST-TRACK1
(create-track "Nearly Midnight, Honolulu"
"Neko Case"
"The Worse Things Get, The Harder I Fight, The Harder I Fight, The More I Love You"
157204
6
(create-date 2016 10 8 17 59 0)
7
(create-date 2016 11 6 21 50 58)))
(define TEST-TRACK2
(create-track "Blue Kentucky Girl"
"Emmylou Harris"
"Blue Kentucky Girl"
200045
9
(create-date 2016 10 23 17 28 22)
17
(create-date 2016 12 30 15 59 41)))
(define TEST-LTRACK (list TEST-TRACK1 TEST-TRACK2))
LTracks - > Number
(check-expect (total-time TEST-LTRACK) (+ (track-time TEST-TRACK1) (track-time TEST-TRACK2)))
(check-expect (total-time (list TEST-TRACK2)) (track-time TEST-TRACK2))
(check-expect (total-time '()) 0)
(define (total-time tracks)
(cond
[(empty? tracks) 0]
[else (+ (track-time (first tracks)) (total-time (rest tracks)))]))
399722535
That 's about 4.6 days ' worth .
|
9fd8f19f5be27b12b08e7c3a7ba209d4b50ddccc3dc744f6b1c1d5473f89fb86 | devaspot/games | relay.erl | %%% -------------------------------------------------------------------
Author : < >
%%% Description : The server for retranslating events of the table.
%%%
Created : Feb 25 , 2013
%%% -------------------------------------------------------------------
%% Table -> Relay requests:
{ register_player , UserId , } - > ok
{ unregister_player , , Reason } - > ok
%% Table -> Relay messages:
%% {publish, Event}
{ to_client , , Event }
%% {to_subscriber, SubscrId, Event}
{ allow_broadcast_for_player , }
%% stop
%% Relay -> Table notifications:
{ player_disconnected , }
{ player_connected , }
{ subscriber_added , , SubscriptionId } - it 's a hack to retrive current game state
%% Subscriber -> Relay requests:
{ subscribe , Pid , UserId , RegNum } - > { ok , SubscriptionId } | { error , Reason }
%% {unsubscribe, SubscriptionId} -> ok | {error, Reason}
%% Relay -> Subscribers notifications:
, Reason }
{ relay_event , , Event }
-module(relay).
-behaviour(gen_server).
%% --------------------------------------------------------------------
%% Include files
%% --------------------------------------------------------------------
-include_lib("server/include/basic_types.hrl").
%% --------------------------------------------------------------------
%% External exports
-export([start/1, start_link/1, table_message/2, table_request/2]).
-export([subscribe/4, unsubscribe/2, publish/2]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-record(state, {subscribers,
players,
observers_allowed :: boolean(),
table :: {atom(), pid()},
table_mon_ref :: reference()
}).
-record(subscriber,
{id :: reference(),
pid :: pid(),
user_id :: binary(),
player_id :: integer(),
mon_ref :: reference(),
broadcast_allowed :: boolean()
}).
-record(player,
{id :: integer(),
user_id :: binary(),
status :: online | offline
}).
%% ====================================================================
%% External functions
%% ====================================================================
start(Params) ->
gen_server:start(?MODULE, [Params], []).
start_link(Params) ->
gen_server:start_link(?MODULE, [Params], []).
subscribe(Relay, Pid, UserId, RegNum) ->
client_request(Relay, {subscribe, Pid, UserId, RegNum}).
unsubscribe(Relay, SubscriptionId) ->
client_request(Relay, {unsubscribe, SubscriptionId}).
publish(Relay, Message) ->
client_message(Relay, {publish, Message}).
table_message(Relay, Message) ->
gen_server:cast(Relay, {table_message, Message}).
table_request(Relay, Request) ->
table_request(Relay, Request, 5000).
table_request(Relay, Request, Timeout) ->
gen_server:call(Relay, {table_request, Request}, Timeout).
client_message(Relay, Message) ->
gen_server:cast(Relay, {client_message, Message}).
client_request(Relay, Request) ->
client_request(Relay, Request, 5000).
client_request(Relay, Request, Timeout) ->
gen_server:call(Relay, {client_request, Request}, Timeout).
%% ====================================================================
%% Server functions
%% ====================================================================
%% --------------------------------------------------------------------
init([Params]) ->
PlayersInfo = proplists:get_value(players, Params),
ObserversAllowed = proplists:get_value(observers_allowed, Params),
Table = {_, TablePid} = proplists:get_value(table, Params),
Players = init_players(PlayersInfo),
MonRef = erlang:monitor(process, TablePid),
{ok, #state{subscribers = subscribers_init(),
players = Players,
observers_allowed = ObserversAllowed,
table = Table,
table_mon_ref = MonRef}}.
%% --------------------------------------------------------------------
handle_call({client_request, Request}, From, State) ->
handle_client_request(Request, From, State);
handle_call({table_request, Request}, From, State) ->
handle_table_request(Request, From, State);
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
%% --------------------------------------------------------------------
handle_cast({client_message, Msg}, State) ->
gas:info(?MODULE,"RELAY_NG Received client message: ~p", [Msg]),
handle_client_message(Msg, State);
handle_cast({table_message, Msg}, State) ->
gas:info(?MODULE,"RELAY_NG Received table message: ~p", [Msg]),
handle_table_message(Msg, State);
handle_cast(_Msg, State) ->
{noreply, State}.
%% --------------------------------------------------------------------
handle_info({'DOWN', TableMonRef, process, _Pid, _Info},
#state{subscribers = Subscribers,
table_mon_ref = TableMonRef} = State) ->
gas:info(?MODULE,"RELAY_NG All The parent table is down. "
"Disconnecting all subscribers and sutting down.", []),
[begin
erlang:demonitor(MonRef, [flush]),
Pid ! {relay_kick, SubscrId, table_down}
end || #subscriber{id = SubscrId, pid = Pid, mon_ref = MonRef}
<- subscribers_to_list(Subscribers)],
{stop, normal, State};
handle_info({'DOWN', MonRef, process, _Pid, _Info},
#state{subscribers = Subscribers, players = Players,
table = {TableMod, TablePid}} = State) ->
case find_subscribers_by_mon_ref(MonRef, Subscribers) of
[#subscriber{player_id = undefined, id = SubscrId}] ->
NewSubscribers = del_subscriber(SubscrId, Subscribers),
{noreply, State#state{subscribers = NewSubscribers}};
[#subscriber{player_id = PlayerId, user_id = UserId, id = SubscrId}] ->
NewSubscribers = del_subscriber(SubscrId, Subscribers),
case find_subscribers_by_player_id(PlayerId, NewSubscribers) of
[] ->
gas:info(?MODULE,"RELAY_NG All sessions of player <~p> (~p) are closed. "
"Sending the notification to the table.", [PlayerId, UserId]),
NewPlayers = update_player_status(PlayerId, offline, Players),
TableMod:relay_message(TablePid, {player_disconnected, PlayerId}),
{noreply, State#state{subscribers = NewSubscribers, players = NewPlayers}};
_ ->
{noreply, State#state{subscribers = NewSubscribers}}
end;
[] ->
{noreply, State}
end;
handle_info(_Info, State) ->
{noreply, State}.
%% --------------------------------------------------------------------
terminate(_Reason, _State) ->
ok.
%% --------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% --------------------------------------------------------------------
Internal functions
%% --------------------------------------------------------------------
handle_client_request({subscribe, Pid, UserId, observer}, _From,
#state{observers_allowed = ObserversAllowed,
subscribers = Subscribers} = State) ->
if ObserversAllowed ->
MonRef = erlang:monitor(process, Pid),
SubscrId = erlang:make_ref(),
NewSubscribers = store_subscriber(SubscrId, Pid, UserId, undefined, MonRef, true, Subscribers),
{reply, ok, State#state{subscribers = NewSubscribers}};
true ->
{reply, {error, observers_not_allowed}, State}
end;
handle_client_request({subscribe, Pid, UserId, PlayerId}, _From,
#state{players = Players, subscribers = Subscribers,
table = {TableMod, TablePid}} = State) ->
gas:info(?MODULE,"RELAY_NG Subscription request from user ~p, PlayerId: <~p>", [UserId, PlayerId]),
case find_player(PlayerId, Players) of
{ok, #player{user_id = UserId, status = Status} = P} -> %% The user id is matched
gas:info(?MODULE,"RELAY_NG User ~p is registered as player <~p>", [UserId, PlayerId]),
gas:info(?MODULE,"RELAY_NG User ~p player info: ~p", [UserId, P]),
MonRef = erlang:monitor(process, Pid),
SubscrId = erlang:make_ref(),
NewSubscribers = store_subscriber(SubscrId, Pid, UserId, PlayerId, MonRef,
_BroadcastAllowed = false, Subscribers),
NewPlayers = if Status == offline ->
gas:info(?MODULE,"RELAY_NG Notifying the table about user ~p (<~p>).", [PlayerId, UserId]),
TableMod:relay_message(TablePid, {player_connected, PlayerId}),
update_player_status(PlayerId, online, Players);
true ->
gas:info(?MODULE,"RELAY_NG User ~p (<~p>) is already subscribed.", [PlayerId, UserId]),
Players
end,
TableMod:relay_message(TablePid, {subscriber_added, PlayerId, SubscrId}),
{reply, {ok, SubscrId}, State#state{players = NewPlayers, subscribers = NewSubscribers}};
{ok, #player{}=P} ->
gas:info(?MODULE,"RELAY_NG Subscription for user ~p rejected. There is another owner of the "
"PlayerId <~p>: ~p", [UserId, PlayerId, P]),
{reply, {error, not_player_id_owner}, State};
error ->
{reply, {error, unknown_player_id}, State}
end;
handle_client_request({unsubscribe, SubscrId}, _From,
#state{subscribers = Subscribers, players = Players,
table = {TableMod, TablePid}} = State) ->
case get_subscriber(SubscrId, Subscribers) of
error ->
{reply, {error, not_subscribed}, State};
{ok, #subscriber{id = SubscrId, mon_ref = MonRef, player_id = undefined}} ->
erlang:demonitor(MonRef, [flush]),
NewSubscribers = del_subscriber(SubscrId, Subscribers),
{reply, ok, State#state{subscribers = NewSubscribers}};
{ok, #subscriber{id = SubscrId, mon_ref = MonRef, player_id = PlayerId}} ->
erlang:demonitor(MonRef, [flush]),
NewSubscribers = del_subscriber(SubscrId, Subscribers),
NewPlayers = case find_subscribers_by_player_id(PlayerId, Subscribers) of
[] ->
TableMod:relay_message(TablePid, {player_disconnected, PlayerId}),
update_player_status(PlayerId, offline, Players);
_ -> Players
end,
{reply, ok, State#state{subscribers = NewSubscribers,
players = NewPlayers}}
end;
handle_client_request(_Request, _From, State) ->
{reply, {error, unknown_request}, State}.
%%===================================================================
handle_table_request({register_player, UserId, PlayerId}, _From,
#state{players = Players} = State) ->
NewPlayers = store_player(PlayerId, UserId, offline, Players),
{reply, ok, State#state{players = NewPlayers}};
handle_table_request({unregister_player, PlayerId, Reason}, _From,
#state{players = Players,
subscribers = Subscribers} = State) ->
NewPlayers = del_player(PlayerId, Players),
UpdSubscribers = find_subscribers_by_player_id(PlayerId, Subscribers),
F = fun(#subscriber{id = SubscrId, pid = Pid, mon_ref = MonRef}, Acc) ->
erlang:demonitor(MonRef, [flush]),
Pid ! {relay_kick, SubscrId, Reason},
del_subscriber(SubscrId, Acc)
end,
NewSubscribers = lists:foldl(F, Subscribers, UpdSubscribers),
{reply, ok, State#state{players = NewPlayers,
subscribers = NewSubscribers}};
handle_table_request(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
%%===================================================================
XXX : Unsecure because of spoofing posibility ( a client session can send events by the
%% name of the table). Legacy.
handle_client_message({publish, Msg}, #state{subscribers = Subscribers} = State) ->
Receipients = subscribers_to_list(Subscribers),
[Pid ! {relay_event, SubscrId, Msg} ||
#subscriber{id = SubscrId, pid = Pid, broadcast_allowed = true} <- Receipients],
{noreply, State};
handle_client_message(_Msg, State) ->
{noreply, State}.
%%===================================================================
handle_table_message({publish, Msg}, #state{subscribers = Subscribers} = State) ->
gas:info(?MODULE,"RELAY_NG The table publish message: ~p", [Msg]),
Receipients = subscribers_to_list(Subscribers),
[Pid ! {relay_event, SubscrId, Msg} ||
#subscriber{id = SubscrId, pid = Pid, broadcast_allowed = true} <- Receipients],
{noreply, State};
handle_table_message({to_client, PlayerId, Msg}, #state{subscribers = Subscribers} = State) ->
Recepients = find_subscribers_by_player_id(PlayerId, Subscribers),
gas:info(?MODULE,"RELAY_NG Send table message to player's (~p) sessions: ~p. Message: ~p",
[PlayerId, Recepients, Msg]),
handle_log(PlayerId , Players , Event , State ) ,
[Pid ! {relay_event, SubscrId, Msg} || #subscriber{id = SubscrId, pid = Pid} <- Recepients],
{noreply, State};
handle_table_message({to_subscriber, SubscrId, Msg}, #state{subscribers = Subscribers} = State) ->
gas:info(?MODULE,"RELAY_NG Send table message to subscriber: ~p. Message: ~p", [SubscrId, Msg]),
case get_subscriber(SubscrId, Subscribers) of
{ok, #subscriber{pid = Pid}} -> Pid ! {relay_event, SubscrId, Msg};
_ -> do_nothing
end,
{noreply, State};
handle_table_message({allow_broadcast_for_player, PlayerId},
#state{subscribers = Subscribers} = State) ->
gas:info(?MODULE,"RELAY_NG Received directive to allow receiving published messages for player <~p>",
[PlayerId]),
PlSubscribers = find_subscribers_by_player_id(PlayerId, Subscribers),
F = fun(Subscriber, Acc) ->
store_subscriber_rec(Subscriber#subscriber{broadcast_allowed = true}, Acc)
end,
NewSubscribers = lists:foldl(F, Subscribers, PlSubscribers),
{noreply, State#state{subscribers = NewSubscribers}};
handle_table_message(stop, #state{subscribers = Subscribers} = State) ->
[begin
erlang:demonitor(MonRef, [flush]),
Pid ! {relay_kick, SubscrId, table_closed}
end || #subscriber{id = SubscrId, pid = Pid, mon_ref = MonRef}
<- subscribers_to_list(Subscribers)],
{stop, normal, State#state{subscribers = subscribers_init()}};
handle_table_message(_Msg, State) ->
{noreply, State}.
%%===================================================================
init_players(PlayersInfo) ->
init_players(PlayersInfo, players_init()).
init_players([], Players) ->
Players;
init_players([{PlayerId, UserId} | PlayersInfo], Players) ->
NewPlayers = store_player(PlayerId, UserId, offline, Players),
init_players(PlayersInfo, NewPlayers).
%%===================================================================
players_init() -> midict:new().
store_player(PlayerId, UserId, Status, Players) ->
store_player_rec(#player{id = PlayerId, user_id = UserId, status = Status}, Players).
store_player_rec(#player{id = PlayerId, user_id = _UserId, status = _Status} = Rec, Players) ->
midict:store(PlayerId, Rec, [], Players).
del_player(PlayerId, Players) ->
midict:erase(PlayerId, Players).
fetch_player(PlayerId, Players) ->
midict:fetch(PlayerId, Players).
find_player(PlayerId, Players) ->
midict:find(PlayerId, Players).
update_player_status(PlayerId, Status, Players) ->
Rec = fetch_player(PlayerId, Players),
store_player_rec(Rec#player{status = Status}, Players).
%%===================================================================
subscribers_init() -> midict:new().
store_subscriber(SubscrId, Pid, UserId, PlayerId, MonRef, BroadcastAllowed, Subscribers) ->
store_subscriber_rec(#subscriber{id = SubscrId, pid = Pid, user_id = UserId,
player_id = PlayerId, mon_ref = MonRef,
broadcast_allowed = BroadcastAllowed}, Subscribers).
store_subscriber_rec(#subscriber{id = SubscrId, pid = Pid, user_id = _UserId,
player_id = PlayerId, mon_ref = MonRef} = Rec, Subscribers) ->
midict:store(SubscrId, Rec, [{pid, Pid}, {player_id, PlayerId}, {mon_ref, MonRef}],
Subscribers).
del_subscriber(SubscrId , Subscribers ) - > NewSubscribers
del_subscriber(SubscrId, Subscribers) ->
midict:erase(SubscrId, Subscribers).
get_subscriber(Id , Subscribers ) - > { ok , # subscriber { } } | error
get_subscriber(Id, Subscribers) ->
midict:find(Id, Subscribers).
%% find_subscribers_by_player_id(PlayerId, Subscribers) -> list(#subscriber{})
find_subscribers_by_player_id(PlayerId, Subscribers) ->
midict:geti(PlayerId, player_id, Subscribers).
%% find_subscribers_by_mon_ref(MonRef, Subscribers) -> list(#subscriber{})
find_subscribers_by_mon_ref(MonRef, Subscribers) ->
midict:geti(MonRef, mon_ref, Subscribers).
%% subscribers_to_list(Subscribers) -> list(#subscriber{})
subscribers_to_list(Subscribers) ->
midict:all_values(Subscribers).
| null | https://raw.githubusercontent.com/devaspot/games/a1f7c3169c53d31e56049e90e0094a3f309603ae/apps/server/src/modules/relay.erl | erlang | -------------------------------------------------------------------
Description : The server for retranslating events of the table.
-------------------------------------------------------------------
Table -> Relay requests:
Table -> Relay messages:
{publish, Event}
{to_subscriber, SubscrId, Event}
stop
Relay -> Table notifications:
Subscriber -> Relay requests:
{unsubscribe, SubscriptionId} -> ok | {error, Reason}
Relay -> Subscribers notifications:
--------------------------------------------------------------------
Include files
--------------------------------------------------------------------
--------------------------------------------------------------------
External exports
gen_server callbacks
====================================================================
External functions
====================================================================
====================================================================
Server functions
====================================================================
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
The user id is matched
===================================================================
===================================================================
name of the table). Legacy.
===================================================================
===================================================================
===================================================================
===================================================================
find_subscribers_by_player_id(PlayerId, Subscribers) -> list(#subscriber{})
find_subscribers_by_mon_ref(MonRef, Subscribers) -> list(#subscriber{})
subscribers_to_list(Subscribers) -> list(#subscriber{}) | Author : < >
Created : Feb 25 , 2013
{ register_player , UserId , } - > ok
{ unregister_player , , Reason } - > ok
{ to_client , , Event }
{ allow_broadcast_for_player , }
{ player_disconnected , }
{ player_connected , }
{ subscriber_added , , SubscriptionId } - it 's a hack to retrive current game state
{ subscribe , Pid , UserId , RegNum } - > { ok , SubscriptionId } | { error , Reason }
, Reason }
{ relay_event , , Event }
-module(relay).
-behaviour(gen_server).
-include_lib("server/include/basic_types.hrl").
-export([start/1, start_link/1, table_message/2, table_request/2]).
-export([subscribe/4, unsubscribe/2, publish/2]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-record(state, {subscribers,
players,
observers_allowed :: boolean(),
table :: {atom(), pid()},
table_mon_ref :: reference()
}).
-record(subscriber,
{id :: reference(),
pid :: pid(),
user_id :: binary(),
player_id :: integer(),
mon_ref :: reference(),
broadcast_allowed :: boolean()
}).
-record(player,
{id :: integer(),
user_id :: binary(),
status :: online | offline
}).
start(Params) ->
gen_server:start(?MODULE, [Params], []).
start_link(Params) ->
gen_server:start_link(?MODULE, [Params], []).
subscribe(Relay, Pid, UserId, RegNum) ->
client_request(Relay, {subscribe, Pid, UserId, RegNum}).
unsubscribe(Relay, SubscriptionId) ->
client_request(Relay, {unsubscribe, SubscriptionId}).
publish(Relay, Message) ->
client_message(Relay, {publish, Message}).
table_message(Relay, Message) ->
gen_server:cast(Relay, {table_message, Message}).
table_request(Relay, Request) ->
table_request(Relay, Request, 5000).
table_request(Relay, Request, Timeout) ->
gen_server:call(Relay, {table_request, Request}, Timeout).
client_message(Relay, Message) ->
gen_server:cast(Relay, {client_message, Message}).
client_request(Relay, Request) ->
client_request(Relay, Request, 5000).
client_request(Relay, Request, Timeout) ->
gen_server:call(Relay, {client_request, Request}, Timeout).
init([Params]) ->
PlayersInfo = proplists:get_value(players, Params),
ObserversAllowed = proplists:get_value(observers_allowed, Params),
Table = {_, TablePid} = proplists:get_value(table, Params),
Players = init_players(PlayersInfo),
MonRef = erlang:monitor(process, TablePid),
{ok, #state{subscribers = subscribers_init(),
players = Players,
observers_allowed = ObserversAllowed,
table = Table,
table_mon_ref = MonRef}}.
handle_call({client_request, Request}, From, State) ->
handle_client_request(Request, From, State);
handle_call({table_request, Request}, From, State) ->
handle_table_request(Request, From, State);
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
handle_cast({client_message, Msg}, State) ->
gas:info(?MODULE,"RELAY_NG Received client message: ~p", [Msg]),
handle_client_message(Msg, State);
handle_cast({table_message, Msg}, State) ->
gas:info(?MODULE,"RELAY_NG Received table message: ~p", [Msg]),
handle_table_message(Msg, State);
handle_cast(_Msg, State) ->
{noreply, State}.
handle_info({'DOWN', TableMonRef, process, _Pid, _Info},
#state{subscribers = Subscribers,
table_mon_ref = TableMonRef} = State) ->
gas:info(?MODULE,"RELAY_NG All The parent table is down. "
"Disconnecting all subscribers and sutting down.", []),
[begin
erlang:demonitor(MonRef, [flush]),
Pid ! {relay_kick, SubscrId, table_down}
end || #subscriber{id = SubscrId, pid = Pid, mon_ref = MonRef}
<- subscribers_to_list(Subscribers)],
{stop, normal, State};
handle_info({'DOWN', MonRef, process, _Pid, _Info},
#state{subscribers = Subscribers, players = Players,
table = {TableMod, TablePid}} = State) ->
case find_subscribers_by_mon_ref(MonRef, Subscribers) of
[#subscriber{player_id = undefined, id = SubscrId}] ->
NewSubscribers = del_subscriber(SubscrId, Subscribers),
{noreply, State#state{subscribers = NewSubscribers}};
[#subscriber{player_id = PlayerId, user_id = UserId, id = SubscrId}] ->
NewSubscribers = del_subscriber(SubscrId, Subscribers),
case find_subscribers_by_player_id(PlayerId, NewSubscribers) of
[] ->
gas:info(?MODULE,"RELAY_NG All sessions of player <~p> (~p) are closed. "
"Sending the notification to the table.", [PlayerId, UserId]),
NewPlayers = update_player_status(PlayerId, offline, Players),
TableMod:relay_message(TablePid, {player_disconnected, PlayerId}),
{noreply, State#state{subscribers = NewSubscribers, players = NewPlayers}};
_ ->
{noreply, State#state{subscribers = NewSubscribers}}
end;
[] ->
{noreply, State}
end;
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
handle_client_request({subscribe, Pid, UserId, observer}, _From,
#state{observers_allowed = ObserversAllowed,
subscribers = Subscribers} = State) ->
if ObserversAllowed ->
MonRef = erlang:monitor(process, Pid),
SubscrId = erlang:make_ref(),
NewSubscribers = store_subscriber(SubscrId, Pid, UserId, undefined, MonRef, true, Subscribers),
{reply, ok, State#state{subscribers = NewSubscribers}};
true ->
{reply, {error, observers_not_allowed}, State}
end;
handle_client_request({subscribe, Pid, UserId, PlayerId}, _From,
#state{players = Players, subscribers = Subscribers,
table = {TableMod, TablePid}} = State) ->
gas:info(?MODULE,"RELAY_NG Subscription request from user ~p, PlayerId: <~p>", [UserId, PlayerId]),
case find_player(PlayerId, Players) of
gas:info(?MODULE,"RELAY_NG User ~p is registered as player <~p>", [UserId, PlayerId]),
gas:info(?MODULE,"RELAY_NG User ~p player info: ~p", [UserId, P]),
MonRef = erlang:monitor(process, Pid),
SubscrId = erlang:make_ref(),
NewSubscribers = store_subscriber(SubscrId, Pid, UserId, PlayerId, MonRef,
_BroadcastAllowed = false, Subscribers),
NewPlayers = if Status == offline ->
gas:info(?MODULE,"RELAY_NG Notifying the table about user ~p (<~p>).", [PlayerId, UserId]),
TableMod:relay_message(TablePid, {player_connected, PlayerId}),
update_player_status(PlayerId, online, Players);
true ->
gas:info(?MODULE,"RELAY_NG User ~p (<~p>) is already subscribed.", [PlayerId, UserId]),
Players
end,
TableMod:relay_message(TablePid, {subscriber_added, PlayerId, SubscrId}),
{reply, {ok, SubscrId}, State#state{players = NewPlayers, subscribers = NewSubscribers}};
{ok, #player{}=P} ->
gas:info(?MODULE,"RELAY_NG Subscription for user ~p rejected. There is another owner of the "
"PlayerId <~p>: ~p", [UserId, PlayerId, P]),
{reply, {error, not_player_id_owner}, State};
error ->
{reply, {error, unknown_player_id}, State}
end;
handle_client_request({unsubscribe, SubscrId}, _From,
#state{subscribers = Subscribers, players = Players,
table = {TableMod, TablePid}} = State) ->
case get_subscriber(SubscrId, Subscribers) of
error ->
{reply, {error, not_subscribed}, State};
{ok, #subscriber{id = SubscrId, mon_ref = MonRef, player_id = undefined}} ->
erlang:demonitor(MonRef, [flush]),
NewSubscribers = del_subscriber(SubscrId, Subscribers),
{reply, ok, State#state{subscribers = NewSubscribers}};
{ok, #subscriber{id = SubscrId, mon_ref = MonRef, player_id = PlayerId}} ->
erlang:demonitor(MonRef, [flush]),
NewSubscribers = del_subscriber(SubscrId, Subscribers),
NewPlayers = case find_subscribers_by_player_id(PlayerId, Subscribers) of
[] ->
TableMod:relay_message(TablePid, {player_disconnected, PlayerId}),
update_player_status(PlayerId, offline, Players);
_ -> Players
end,
{reply, ok, State#state{subscribers = NewSubscribers,
players = NewPlayers}}
end;
handle_client_request(_Request, _From, State) ->
{reply, {error, unknown_request}, State}.
handle_table_request({register_player, UserId, PlayerId}, _From,
#state{players = Players} = State) ->
NewPlayers = store_player(PlayerId, UserId, offline, Players),
{reply, ok, State#state{players = NewPlayers}};
handle_table_request({unregister_player, PlayerId, Reason}, _From,
#state{players = Players,
subscribers = Subscribers} = State) ->
NewPlayers = del_player(PlayerId, Players),
UpdSubscribers = find_subscribers_by_player_id(PlayerId, Subscribers),
F = fun(#subscriber{id = SubscrId, pid = Pid, mon_ref = MonRef}, Acc) ->
erlang:demonitor(MonRef, [flush]),
Pid ! {relay_kick, SubscrId, Reason},
del_subscriber(SubscrId, Acc)
end,
NewSubscribers = lists:foldl(F, Subscribers, UpdSubscribers),
{reply, ok, State#state{players = NewPlayers,
subscribers = NewSubscribers}};
handle_table_request(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
XXX : Unsecure because of spoofing posibility ( a client session can send events by the
handle_client_message({publish, Msg}, #state{subscribers = Subscribers} = State) ->
Receipients = subscribers_to_list(Subscribers),
[Pid ! {relay_event, SubscrId, Msg} ||
#subscriber{id = SubscrId, pid = Pid, broadcast_allowed = true} <- Receipients],
{noreply, State};
handle_client_message(_Msg, State) ->
{noreply, State}.
handle_table_message({publish, Msg}, #state{subscribers = Subscribers} = State) ->
gas:info(?MODULE,"RELAY_NG The table publish message: ~p", [Msg]),
Receipients = subscribers_to_list(Subscribers),
[Pid ! {relay_event, SubscrId, Msg} ||
#subscriber{id = SubscrId, pid = Pid, broadcast_allowed = true} <- Receipients],
{noreply, State};
handle_table_message({to_client, PlayerId, Msg}, #state{subscribers = Subscribers} = State) ->
Recepients = find_subscribers_by_player_id(PlayerId, Subscribers),
gas:info(?MODULE,"RELAY_NG Send table message to player's (~p) sessions: ~p. Message: ~p",
[PlayerId, Recepients, Msg]),
handle_log(PlayerId , Players , Event , State ) ,
[Pid ! {relay_event, SubscrId, Msg} || #subscriber{id = SubscrId, pid = Pid} <- Recepients],
{noreply, State};
handle_table_message({to_subscriber, SubscrId, Msg}, #state{subscribers = Subscribers} = State) ->
gas:info(?MODULE,"RELAY_NG Send table message to subscriber: ~p. Message: ~p", [SubscrId, Msg]),
case get_subscriber(SubscrId, Subscribers) of
{ok, #subscriber{pid = Pid}} -> Pid ! {relay_event, SubscrId, Msg};
_ -> do_nothing
end,
{noreply, State};
handle_table_message({allow_broadcast_for_player, PlayerId},
#state{subscribers = Subscribers} = State) ->
gas:info(?MODULE,"RELAY_NG Received directive to allow receiving published messages for player <~p>",
[PlayerId]),
PlSubscribers = find_subscribers_by_player_id(PlayerId, Subscribers),
F = fun(Subscriber, Acc) ->
store_subscriber_rec(Subscriber#subscriber{broadcast_allowed = true}, Acc)
end,
NewSubscribers = lists:foldl(F, Subscribers, PlSubscribers),
{noreply, State#state{subscribers = NewSubscribers}};
handle_table_message(stop, #state{subscribers = Subscribers} = State) ->
[begin
erlang:demonitor(MonRef, [flush]),
Pid ! {relay_kick, SubscrId, table_closed}
end || #subscriber{id = SubscrId, pid = Pid, mon_ref = MonRef}
<- subscribers_to_list(Subscribers)],
{stop, normal, State#state{subscribers = subscribers_init()}};
handle_table_message(_Msg, State) ->
{noreply, State}.
init_players(PlayersInfo) ->
init_players(PlayersInfo, players_init()).
init_players([], Players) ->
Players;
init_players([{PlayerId, UserId} | PlayersInfo], Players) ->
NewPlayers = store_player(PlayerId, UserId, offline, Players),
init_players(PlayersInfo, NewPlayers).
players_init() -> midict:new().
store_player(PlayerId, UserId, Status, Players) ->
store_player_rec(#player{id = PlayerId, user_id = UserId, status = Status}, Players).
store_player_rec(#player{id = PlayerId, user_id = _UserId, status = _Status} = Rec, Players) ->
midict:store(PlayerId, Rec, [], Players).
del_player(PlayerId, Players) ->
midict:erase(PlayerId, Players).
fetch_player(PlayerId, Players) ->
midict:fetch(PlayerId, Players).
find_player(PlayerId, Players) ->
midict:find(PlayerId, Players).
update_player_status(PlayerId, Status, Players) ->
Rec = fetch_player(PlayerId, Players),
store_player_rec(Rec#player{status = Status}, Players).
subscribers_init() -> midict:new().
store_subscriber(SubscrId, Pid, UserId, PlayerId, MonRef, BroadcastAllowed, Subscribers) ->
store_subscriber_rec(#subscriber{id = SubscrId, pid = Pid, user_id = UserId,
player_id = PlayerId, mon_ref = MonRef,
broadcast_allowed = BroadcastAllowed}, Subscribers).
store_subscriber_rec(#subscriber{id = SubscrId, pid = Pid, user_id = _UserId,
player_id = PlayerId, mon_ref = MonRef} = Rec, Subscribers) ->
midict:store(SubscrId, Rec, [{pid, Pid}, {player_id, PlayerId}, {mon_ref, MonRef}],
Subscribers).
del_subscriber(SubscrId , Subscribers ) - > NewSubscribers
del_subscriber(SubscrId, Subscribers) ->
midict:erase(SubscrId, Subscribers).
get_subscriber(Id , Subscribers ) - > { ok , # subscriber { } } | error
get_subscriber(Id, Subscribers) ->
midict:find(Id, Subscribers).
find_subscribers_by_player_id(PlayerId, Subscribers) ->
midict:geti(PlayerId, player_id, Subscribers).
find_subscribers_by_mon_ref(MonRef, Subscribers) ->
midict:geti(MonRef, mon_ref, Subscribers).
subscribers_to_list(Subscribers) ->
midict:all_values(Subscribers).
|
0cd38982738b5a35a02b2f2668e06fb1bb8c86c2050bcb233679b231a6ccb097 | RDTK/generator | recipe-repository.lisp | ;;;; recipe-repository.lisp --- A repository for directory and filename information.
;;;;
Copyright ( C ) 2019 , 2020 , 2022 Jan Moringen
;;;;
Author : < >
(cl:in-package #:build-generator.model.project)
;;; `mode'
(defclass mode (print-items:print-items-mixin)
((%name :initarg :name
:type string
:reader name)
(%parent :initarg :parent
:reader parent
:initform nil))
(:default-initargs
:name (missing-required-initarg 'mode :name))
(:documentation
"Represents a processing mode, ultimately selecting template recipes."))
(defmethod print-items:print-items append ((object mode))
`((:name "~A" ,(name object))))
(defun ensure-mode (thing)
(labels ((rec (thing)
(etypecase thing
(mode thing)
(string (make-instance 'mode :name thing))
(cons (let+ (((first &rest rest) thing))
(make-instance 'mode :name first
:parent (when rest
(rec rest))))))))
(rec thing)))
;;; `recipe-repository'
(defclass recipe-repository (print-items:print-items-mixin)
((%name :initarg :name
:reader name
:writer (setf %name))
(%root-directory :initarg :root-directory
:type (and pathname (satisfies uiop:directory-pathname-p))
:reader root-directory
:documentation
"The root directory of the repository.")
(%recipe-directories :type hash-table
:reader %recipe-directories
:initform (make-hash-table :test #'eq)
:documentation
"A map of recipe kinds to sub-directories.")
(%mode :initarg :mode
:reader mode
:documentation
"The mode this repository should use to locate
template recipes.")
(%parents :initarg :parents
:type list
:reader parents
:initform '()
:documentation
"A list of parent repositories that should be
searched for recipes not found in this one."))
(:default-initargs
:root-directory (missing-required-initarg 'recipe-repository :root-directory)
:mode (missing-required-initarg 'recipe-repository :mode))
(:documentation
"Stores a repository root and sub-directories for recipe kinds."))
(defmethod shared-initialize :after ((instance recipe-repository)
(slot-names t)
&key
(name nil name-supplied?)
(root-directory nil root-directory-supplied?))
(declare (ignore name))
(when (and (not name-supplied?) root-directory-supplied?)
(setf (%name instance) (lastcar (pathname-directory root-directory)))))
(defmethod print-items:print-items append ((object recipe-repository))
`((:name "~A" ,(name object))
((:mode (:after :name)) " ~A mode" ,(name (mode object)))
((:root-path (:after :mode)) " [~A]" ,(root-directory object))))
(defmethod describe-object ((object recipe-repository) stream)
(utilities.print-tree:print-tree
stream object
(utilities.print-tree:make-node-printer
(lambda (stream depth node)
(declare (ignore depth))
(print-items:format-print-items stream (print-items:print-items node))
nil)
nil #'parents)))
(defun make-recipe-repository (root-directory mode-or-modes
&rest args &key name parents)
(declare (ignore name parents))
(let ((root-directory (truename root-directory))
(mode (ensure-mode mode-or-modes)))
(apply #'make-instance 'recipe-repository :root-directory root-directory
:mode mode
args)))
(defun populate-recipe-repository! (repository)
(setf (recipe-directory :template repository) #P"templates/"
(recipe-directory :project repository) #P"projects/"
(recipe-directory :distribution repository) #P"distributions/"
(recipe-directory :person repository) #P"persons/")
repository)
(defun make-populated-recipe-repository (root-directory mode-or-modes
&rest args &key name parents)
(declare (ignore name parents))
(populate-recipe-repository!
(apply #'make-recipe-repository root-directory mode-or-modes args)))
(defmethod recipe-directory ((kind t) (repository recipe-repository))
(let ((relative (or (gethash kind (%recipe-directories repository))
(error "~@<~A does not have a sub-directory for ~
recipes of kind ~A.~@:>"
repository kind))))
(merge-pathnames relative (root-directory repository))))
(defmethod recipe-directory ((kind mode) (repository recipe-repository))
(merge-pathnames (make-pathname :directory `(:relative ,(name kind)))
(recipe-directory :template repository)))
(defmethod (setf recipe-directory) ((new-value pathname)
(kind t)
(repository recipe-repository))
(unless (uiop:directory-pathname-p new-value)
(error "~@<~A is not a directory pathname.~@:>" new-value))
(setf (gethash kind (%recipe-directories repository)) new-value))
;;; Name -> pathname
;;; `recipe-path'
(defmethod recipe-path ((repository recipe-repository)
(kind t)
(name string))
(let* ((components (split-sequence:split-sequence #\/ name))
(directory (list* :relative (butlast components)))
(name (lastcar components))
(pathname (make-pathname :directory directory
:name name)))
(recipe-path repository kind pathname)))
(defmethod recipe-path ((repository recipe-repository)
(kind t)
(name (eql :wild)))
(recipe-path repository kind (make-pathname :name name)))
(defmethod recipe-path ((repository recipe-repository)
(kind t)
(name (eql :wild-inferiors)))
(let ((name (make-pathname :name :wild
:directory `(:relative :wild-inferiors))))
(recipe-path repository kind name)))
(defmethod recipe-path ((repository recipe-repository)
(kind t)
(name pathname))
(let* ((directory (recipe-directory kind repository))
(type (string-downcase kind))
(defaults (make-pathname :type type :defaults directory)))
(merge-pathnames name defaults)))
(defmethod recipe-path ((repository recipe-repository)
(kind (eql :template))
(name t))
(recipe-path repository (mode repository) name))
(defmethod recipe-path ((repository recipe-repository)
(kind mode)
(name pathname))
(let* ((directory (recipe-directory kind repository))
(type (string-downcase :template))
(defaults (make-pathname :type type :defaults directory)))
(merge-pathnames name defaults)))
;;; `probe-recipe-pathname'
(defmethod probe-recipe-pathname ((repository recipe-repository)
(pathname pathname))
(log:info "~@<Looking for ~A in ~A~@:>" pathname repository)
(cond ((wild-pathname-p pathname)
(directory pathname))
((probe-file pathname)
(list pathname))
(t
nil)))
;;; `recipe-truename'
(defmethod recipe-truename :around ((repository recipe-repository)
(kind t)
(name t)
&key
(recursive? t)
(if-does-not-exist #'error))
(or (call-next-method repository kind name :if-does-not-exist nil)
(when recursive?
(some (rcurry #'recipe-truename kind name
:if-does-not-exist nil)
(parents repository)))
(error-behavior-restart-case
(if-does-not-exist (recipe-not-found-error
:kind kind
:name name
:repository repository)))))
(defmethod recipe-truename ((repository recipe-repository)
(kind t)
(name t)
&key if-does-not-exist)
(declare (ignore if-does-not-exist))
(let ((pathname (recipe-path repository kind name)))
(when (probe-recipe-pathname repository pathname)
pathname)))
(defmethod recipe-truename ((repository recipe-repository)
(kind (eql :template))
(name t)
&key if-does-not-exist)
(declare (ignore if-does-not-exist))
(recipe-truename repository (mode repository) name
:recursive? nil :if-does-not-exist nil))
(defmethod recipe-truename ((repository recipe-repository)
(kind mode)
(name t)
&key if-does-not-exist)
(declare (ignore if-does-not-exist))
(or (call-next-method repository kind name :if-does-not-exist nil)
(when-let ((parent (parent kind)))
(recipe-truename repository parent name
:recursive? nil :if-does-not-exist nil))))
;;; `recipe-truenames'
(defmethod recipe-truenames :around ((repository t) (kind t) (name t)
&key (recursive? t))
(let ((local-results (call-next-method)))
(if recursive?
(append local-results
(mappend (rcurry #'recipe-truenames kind name)
(parents repository)))
local-results)))
(defmethod recipe-truenames ((repository recipe-repository)
(kind t)
(name t)
&key)
(probe-recipe-pathname repository (recipe-path repository kind name)))
(defmethod recipe-truenames ((repository recipe-repository)
(kind (eql :template))
(name t)
&key)
(recipe-truenames repository (mode repository) name :recursive? nil))
(defmethod recipe-truenames ((repository recipe-repository)
(kind mode)
(name t)
&key)
(append (call-next-method)
(when-let ((parent (parent kind)))
(recipe-truenames repository parent name :recursive? nil))))
;;; Pathname -> name
(defmethod recipe-name :around ((repository recipe-repository)
(kind t)
(path pathname)
&key (recursive? t))
(multiple-value-bind (name container) (call-next-method)
(cond (name
(values name container))
(recursive?
(map nil (lambda (parent)
(multiple-value-bind (name container)
(recipe-name parent kind path)
(when name
(return-from recipe-name (values name container)))))
(parents repository))))))
(defmethod recipe-name ((repository recipe-repository)
(kind t)
(path pathname)
&key)
(assert (uiop:absolute-pathname-p path))
(let ((directory (recipe-directory kind repository))
(without-type (make-pathname :type nil :defaults path)))
(when (uiop:subpathp without-type directory)
(let ((namestring (uiop:native-namestring
(uiop:enough-pathname without-type directory))))
(values namestring repository)))))
(defmethod recipe-name ((repository recipe-repository)
(kind (eql :template))
(path pathname)
&key)
(recipe-name repository (mode repository) path :recursive? nil))
(defmethod recipe-name ((repository recipe-repository)
(kind mode)
(path pathname)
&key)
(multiple-value-bind (name container) (call-next-method)
(if name
(values name container)
(when-let ((parent (parent kind)))
(recipe-name repository parent path :recursive? nil)))))
;;; Parents files
(defun make-parents-filename (directory)
(make-pathname :name "parents" :defaults directory))
(defun parse-parents-file (file)
(let ((document (%load-yaml file)))
(unless (typep document 'cons)
(object-error
(list (list document "non-sequence node" :error))
"~@<parents file must contain a non-empty sequence at the ~
top-level.~@:>"))
(map 'list (lambda (element)
(unless (stringp element)
(object-error (list (list element "here" :error))
"~@<Sequence element is not a string.~@:>"))
element)
document)))
;;; Mode parent loading
(defun load-mode-parents-file (root-directory mode)
(check-type mode string "A mode string")
(let ((filename (make-parents-filename
;; This computes the templates/MODE sub-directory
;; "manually" since the repository is not yet
;; available.
(merge-pathnames
(make-pathname :directory `(:relative "templates" ,mode))
root-directory))))
(ensure-mode (list* mode (if (probe-file filename)
(parse-parents-file filename)
'("_common"))))))
;;; Repository parent loading
(defun load-repository-parents-file (root-directory)
(let ((filename (make-parents-filename root-directory)))
(when-let ((entries (when (probe-file filename)
(parse-parents-file filename))))
(map 'list (lambda (entry)
(cond ((ppcre:scan "[^:]+://" entry)
(puri:uri entry))
(t
(uiop:ensure-directory-pathname entry))))
entries))))
;;; Loading repositories
(defun load-parent-repositories (references mode &key cache-directory)
(mapcan (lambda (reference)
(with-simple-restart (continue "~@<Skip the recipe repository designated by ~A.~@:>" reference)
(list (load-repository reference mode
:cache-directory cache-directory))))
references))
(defvar *loading-repositories?* nil)
(defmethod load-repository :around ((source t) (mode t) &key name
cache-directory)
(declare (ignore name cache-directory))
(if *loading-repositories?*
(call-next-method)
(let ((*loading-repositories?* t))
(with-trivial-progress (:load-repository)
(analysis::with-git-cache ()
(let ((result (call-next-method)))
(log:info "~@<~@;Loaded repository stack~@:_~A~@:>"
(with-output-to-string (stream)
(describe result stream)))
result))))))
(defmethod load-repository ((source pathname) (mode t) &key name
cache-directory)
(progress :load-repository nil "~A" source)
(unless (uiop:directory-pathname-p source)
(error "~@<Repository pathname ~A does not designate a directory.~@:>"
source))
(let* ((source-truename (or (probe-file source)
(error "~@<Repository directory ~A ~
does not exist.~@:>"
source)))
(mode (load-mode-parents-file source mode))
(parent-references (load-repository-parents-file source-truename))
(parents (let ((*default-pathname-defaults* source-truename))
(load-parent-repositories
parent-references (name mode)
:cache-directory cache-directory))))
(apply #'make-populated-recipe-repository source-truename mode
:parents parents (when name (list :name name)))))
(defmethod load-repository ((source puri:uri) (mode t) &key name
cache-directory)
(unless cache-directory
(error "~@<Cannot load remote repository ~A without cache ~
directory.~@:>"
source))
(let* ((branch (puri:uri-fragment source))
(name (or name
(format nil "~A~@[@~A~]"
(lastcar (puri:uri-parsed-path source))
branch)))
(clone-directory (merge-pathnames
(make-pathname :directory (list :relative name))
cache-directory)))
(uiop:delete-directory-tree
clone-directory :validate t :if-does-not-exist :ignore)
(more-conditions::without-progress
(apply #'analysis::clone-git-repository/maybe-cached
source clone-directory
:cache-directory cache-directory
:history-limit 1
(when branch (list :branch branch))))
(load-repository clone-directory mode
:name name
:cache-directory cache-directory)))
| null | https://raw.githubusercontent.com/RDTK/generator/8d9e6e47776f2ccb7b5ed934337d2db50ecbe2f5/src/model/project/concrete-syntax/recipe-repository.lisp | lisp | recipe-repository.lisp --- A repository for directory and filename information.
`mode'
`recipe-repository'
Name -> pathname
`recipe-path'
`probe-recipe-pathname'
`recipe-truename'
`recipe-truenames'
Pathname -> name
Parents files
Mode parent loading
This computes the templates/MODE sub-directory
"manually" since the repository is not yet
available.
Repository parent loading
Loading repositories | Copyright ( C ) 2019 , 2020 , 2022 Jan Moringen
Author : < >
(cl:in-package #:build-generator.model.project)
(defclass mode (print-items:print-items-mixin)
((%name :initarg :name
:type string
:reader name)
(%parent :initarg :parent
:reader parent
:initform nil))
(:default-initargs
:name (missing-required-initarg 'mode :name))
(:documentation
"Represents a processing mode, ultimately selecting template recipes."))
(defmethod print-items:print-items append ((object mode))
`((:name "~A" ,(name object))))
(defun ensure-mode (thing)
(labels ((rec (thing)
(etypecase thing
(mode thing)
(string (make-instance 'mode :name thing))
(cons (let+ (((first &rest rest) thing))
(make-instance 'mode :name first
:parent (when rest
(rec rest))))))))
(rec thing)))
(defclass recipe-repository (print-items:print-items-mixin)
((%name :initarg :name
:reader name
:writer (setf %name))
(%root-directory :initarg :root-directory
:type (and pathname (satisfies uiop:directory-pathname-p))
:reader root-directory
:documentation
"The root directory of the repository.")
(%recipe-directories :type hash-table
:reader %recipe-directories
:initform (make-hash-table :test #'eq)
:documentation
"A map of recipe kinds to sub-directories.")
(%mode :initarg :mode
:reader mode
:documentation
"The mode this repository should use to locate
template recipes.")
(%parents :initarg :parents
:type list
:reader parents
:initform '()
:documentation
"A list of parent repositories that should be
searched for recipes not found in this one."))
(:default-initargs
:root-directory (missing-required-initarg 'recipe-repository :root-directory)
:mode (missing-required-initarg 'recipe-repository :mode))
(:documentation
"Stores a repository root and sub-directories for recipe kinds."))
(defmethod shared-initialize :after ((instance recipe-repository)
(slot-names t)
&key
(name nil name-supplied?)
(root-directory nil root-directory-supplied?))
(declare (ignore name))
(when (and (not name-supplied?) root-directory-supplied?)
(setf (%name instance) (lastcar (pathname-directory root-directory)))))
(defmethod print-items:print-items append ((object recipe-repository))
`((:name "~A" ,(name object))
((:mode (:after :name)) " ~A mode" ,(name (mode object)))
((:root-path (:after :mode)) " [~A]" ,(root-directory object))))
(defmethod describe-object ((object recipe-repository) stream)
(utilities.print-tree:print-tree
stream object
(utilities.print-tree:make-node-printer
(lambda (stream depth node)
(declare (ignore depth))
(print-items:format-print-items stream (print-items:print-items node))
nil)
nil #'parents)))
(defun make-recipe-repository (root-directory mode-or-modes
&rest args &key name parents)
(declare (ignore name parents))
(let ((root-directory (truename root-directory))
(mode (ensure-mode mode-or-modes)))
(apply #'make-instance 'recipe-repository :root-directory root-directory
:mode mode
args)))
(defun populate-recipe-repository! (repository)
(setf (recipe-directory :template repository) #P"templates/"
(recipe-directory :project repository) #P"projects/"
(recipe-directory :distribution repository) #P"distributions/"
(recipe-directory :person repository) #P"persons/")
repository)
(defun make-populated-recipe-repository (root-directory mode-or-modes
&rest args &key name parents)
(declare (ignore name parents))
(populate-recipe-repository!
(apply #'make-recipe-repository root-directory mode-or-modes args)))
(defmethod recipe-directory ((kind t) (repository recipe-repository))
(let ((relative (or (gethash kind (%recipe-directories repository))
(error "~@<~A does not have a sub-directory for ~
recipes of kind ~A.~@:>"
repository kind))))
(merge-pathnames relative (root-directory repository))))
(defmethod recipe-directory ((kind mode) (repository recipe-repository))
(merge-pathnames (make-pathname :directory `(:relative ,(name kind)))
(recipe-directory :template repository)))
(defmethod (setf recipe-directory) ((new-value pathname)
(kind t)
(repository recipe-repository))
(unless (uiop:directory-pathname-p new-value)
(error "~@<~A is not a directory pathname.~@:>" new-value))
(setf (gethash kind (%recipe-directories repository)) new-value))
(defmethod recipe-path ((repository recipe-repository)
(kind t)
(name string))
(let* ((components (split-sequence:split-sequence #\/ name))
(directory (list* :relative (butlast components)))
(name (lastcar components))
(pathname (make-pathname :directory directory
:name name)))
(recipe-path repository kind pathname)))
(defmethod recipe-path ((repository recipe-repository)
(kind t)
(name (eql :wild)))
(recipe-path repository kind (make-pathname :name name)))
(defmethod recipe-path ((repository recipe-repository)
(kind t)
(name (eql :wild-inferiors)))
(let ((name (make-pathname :name :wild
:directory `(:relative :wild-inferiors))))
(recipe-path repository kind name)))
(defmethod recipe-path ((repository recipe-repository)
(kind t)
(name pathname))
(let* ((directory (recipe-directory kind repository))
(type (string-downcase kind))
(defaults (make-pathname :type type :defaults directory)))
(merge-pathnames name defaults)))
(defmethod recipe-path ((repository recipe-repository)
(kind (eql :template))
(name t))
(recipe-path repository (mode repository) name))
(defmethod recipe-path ((repository recipe-repository)
(kind mode)
(name pathname))
(let* ((directory (recipe-directory kind repository))
(type (string-downcase :template))
(defaults (make-pathname :type type :defaults directory)))
(merge-pathnames name defaults)))
(defmethod probe-recipe-pathname ((repository recipe-repository)
(pathname pathname))
(log:info "~@<Looking for ~A in ~A~@:>" pathname repository)
(cond ((wild-pathname-p pathname)
(directory pathname))
((probe-file pathname)
(list pathname))
(t
nil)))
(defmethod recipe-truename :around ((repository recipe-repository)
(kind t)
(name t)
&key
(recursive? t)
(if-does-not-exist #'error))
(or (call-next-method repository kind name :if-does-not-exist nil)
(when recursive?
(some (rcurry #'recipe-truename kind name
:if-does-not-exist nil)
(parents repository)))
(error-behavior-restart-case
(if-does-not-exist (recipe-not-found-error
:kind kind
:name name
:repository repository)))))
(defmethod recipe-truename ((repository recipe-repository)
(kind t)
(name t)
&key if-does-not-exist)
(declare (ignore if-does-not-exist))
(let ((pathname (recipe-path repository kind name)))
(when (probe-recipe-pathname repository pathname)
pathname)))
(defmethod recipe-truename ((repository recipe-repository)
(kind (eql :template))
(name t)
&key if-does-not-exist)
(declare (ignore if-does-not-exist))
(recipe-truename repository (mode repository) name
:recursive? nil :if-does-not-exist nil))
(defmethod recipe-truename ((repository recipe-repository)
(kind mode)
(name t)
&key if-does-not-exist)
(declare (ignore if-does-not-exist))
(or (call-next-method repository kind name :if-does-not-exist nil)
(when-let ((parent (parent kind)))
(recipe-truename repository parent name
:recursive? nil :if-does-not-exist nil))))
(defmethod recipe-truenames :around ((repository t) (kind t) (name t)
&key (recursive? t))
(let ((local-results (call-next-method)))
(if recursive?
(append local-results
(mappend (rcurry #'recipe-truenames kind name)
(parents repository)))
local-results)))
(defmethod recipe-truenames ((repository recipe-repository)
(kind t)
(name t)
&key)
(probe-recipe-pathname repository (recipe-path repository kind name)))
(defmethod recipe-truenames ((repository recipe-repository)
(kind (eql :template))
(name t)
&key)
(recipe-truenames repository (mode repository) name :recursive? nil))
(defmethod recipe-truenames ((repository recipe-repository)
(kind mode)
(name t)
&key)
(append (call-next-method)
(when-let ((parent (parent kind)))
(recipe-truenames repository parent name :recursive? nil))))
(defmethod recipe-name :around ((repository recipe-repository)
(kind t)
(path pathname)
&key (recursive? t))
(multiple-value-bind (name container) (call-next-method)
(cond (name
(values name container))
(recursive?
(map nil (lambda (parent)
(multiple-value-bind (name container)
(recipe-name parent kind path)
(when name
(return-from recipe-name (values name container)))))
(parents repository))))))
(defmethod recipe-name ((repository recipe-repository)
(kind t)
(path pathname)
&key)
(assert (uiop:absolute-pathname-p path))
(let ((directory (recipe-directory kind repository))
(without-type (make-pathname :type nil :defaults path)))
(when (uiop:subpathp without-type directory)
(let ((namestring (uiop:native-namestring
(uiop:enough-pathname without-type directory))))
(values namestring repository)))))
(defmethod recipe-name ((repository recipe-repository)
(kind (eql :template))
(path pathname)
&key)
(recipe-name repository (mode repository) path :recursive? nil))
(defmethod recipe-name ((repository recipe-repository)
(kind mode)
(path pathname)
&key)
(multiple-value-bind (name container) (call-next-method)
(if name
(values name container)
(when-let ((parent (parent kind)))
(recipe-name repository parent path :recursive? nil)))))
(defun make-parents-filename (directory)
(make-pathname :name "parents" :defaults directory))
(defun parse-parents-file (file)
(let ((document (%load-yaml file)))
(unless (typep document 'cons)
(object-error
(list (list document "non-sequence node" :error))
"~@<parents file must contain a non-empty sequence at the ~
top-level.~@:>"))
(map 'list (lambda (element)
(unless (stringp element)
(object-error (list (list element "here" :error))
"~@<Sequence element is not a string.~@:>"))
element)
document)))
(defun load-mode-parents-file (root-directory mode)
(check-type mode string "A mode string")
(let ((filename (make-parents-filename
(merge-pathnames
(make-pathname :directory `(:relative "templates" ,mode))
root-directory))))
(ensure-mode (list* mode (if (probe-file filename)
(parse-parents-file filename)
'("_common"))))))
(defun load-repository-parents-file (root-directory)
(let ((filename (make-parents-filename root-directory)))
(when-let ((entries (when (probe-file filename)
(parse-parents-file filename))))
(map 'list (lambda (entry)
(cond ((ppcre:scan "[^:]+://" entry)
(puri:uri entry))
(t
(uiop:ensure-directory-pathname entry))))
entries))))
(defun load-parent-repositories (references mode &key cache-directory)
(mapcan (lambda (reference)
(with-simple-restart (continue "~@<Skip the recipe repository designated by ~A.~@:>" reference)
(list (load-repository reference mode
:cache-directory cache-directory))))
references))
(defvar *loading-repositories?* nil)
(defmethod load-repository :around ((source t) (mode t) &key name
cache-directory)
(declare (ignore name cache-directory))
(if *loading-repositories?*
(call-next-method)
(let ((*loading-repositories?* t))
(with-trivial-progress (:load-repository)
(analysis::with-git-cache ()
(let ((result (call-next-method)))
(log:info "~@<~@;Loaded repository stack~@:_~A~@:>"
(with-output-to-string (stream)
(describe result stream)))
result))))))
(defmethod load-repository ((source pathname) (mode t) &key name
cache-directory)
(progress :load-repository nil "~A" source)
(unless (uiop:directory-pathname-p source)
(error "~@<Repository pathname ~A does not designate a directory.~@:>"
source))
(let* ((source-truename (or (probe-file source)
(error "~@<Repository directory ~A ~
does not exist.~@:>"
source)))
(mode (load-mode-parents-file source mode))
(parent-references (load-repository-parents-file source-truename))
(parents (let ((*default-pathname-defaults* source-truename))
(load-parent-repositories
parent-references (name mode)
:cache-directory cache-directory))))
(apply #'make-populated-recipe-repository source-truename mode
:parents parents (when name (list :name name)))))
(defmethod load-repository ((source puri:uri) (mode t) &key name
cache-directory)
(unless cache-directory
(error "~@<Cannot load remote repository ~A without cache ~
directory.~@:>"
source))
(let* ((branch (puri:uri-fragment source))
(name (or name
(format nil "~A~@[@~A~]"
(lastcar (puri:uri-parsed-path source))
branch)))
(clone-directory (merge-pathnames
(make-pathname :directory (list :relative name))
cache-directory)))
(uiop:delete-directory-tree
clone-directory :validate t :if-does-not-exist :ignore)
(more-conditions::without-progress
(apply #'analysis::clone-git-repository/maybe-cached
source clone-directory
:cache-directory cache-directory
:history-limit 1
(when branch (list :branch branch))))
(load-repository clone-directory mode
:name name
:cache-directory cache-directory)))
|
6f5a4712033d38c6c8f5b43f9360083b7e2c37730252672072377ebbfc01889c | Elzair/nazghul | loc.scm | (define (mk-loc place x y) (list place x y))
(define (loc-place loc) (car loc))
(define (loc-x loc) (cadr loc))
(define (loc-y loc) (caddr loc))
(define (loc-op a b op)
(mk-loc (loc-place a)
(op (loc-x a) (loc-x b))
(op (loc-y a) (loc-y b))))
(define (loc-sum a b) (loc-op a b +))
(define (loc-distance a b)
(kern-get-distance a b))
(define (loc-diff a b)
(let ((place (loc-place a)))
(if (kern-place-is-wrapping? place)
(let ((w (kern-place-get-width place)))
(mk-loc place
(mdist (loc-x a) (loc-x b) w)
(mdist (loc-y a) (loc-y b) w)))
(mk-loc place
(- (loc-x a) (loc-x b))
(- (loc-y a) (loc-y b))))))
(define (loc-to-cardinal-dir loc)
(let ((x (loc-x loc))
(y (loc-y loc)))
(display "loc-to-cardinal-dir")
(display " x=")(display x)
(display " y=")(display y)
(newline)
(if (> x 0)
;; eastern half
(if (> y 0)
;; southeast quarter
(if (> x y)
east
south)
;; northeast quarter
(if (> x (abs y))
east
north))
western half
(if (> y 0)
;; southwest quarter
(if (> (abs x) y)
west
south)
northwest quarter
(if (> (abs x) (abs y))
west
north)))))
;; ----------------------------------------------------------------------------
loc - grid - distance -- return the distance needed to walk between two points
;;
;; REVISIT: this has a form almost identical to the loc-adjacent? proc below
;;
;; ----------------------------------------------------------------------------
(define (loc-grid-distance a b)
(let ((place (loc-place a)))
(if (kern-place-is-wrapping? place)
(let ((w (kern-place-get-width place)))
(+ (mdist (loc-x a) (loc-x b) w)
(mdist (loc-y a) (loc-y b) w)))
(+ (abs (- (loc-x a) (loc-x b)))
(abs (- (loc-y a) (loc-y b)))))))
(define (loc-closer? a b c)
(< (loc-grid-distance a c)
(loc-grid-distance b c)))
;; Convert a location vector to "normal" form
(define (loc-norm loc)
(define (norm a)
(cond ((> a 0) 1)
((< a 0) -1)
(else 0)))
(mk-loc (loc-place loc)
(norm (loc-x loc))
(norm (loc-y loc))))
;; ----------------------------------------------------------------------------
;; loc-enum-rect -- given a rectangular region of a place return a flat list of
;; all locations in that rectangle. Useful in conjunction with map.
;; ----------------------------------------------------------------------------
(define (loc-enum-rect place x y w h)
(define (enum-row x w)
(if (= 0 w)
nil
(cons (mk-loc place x y)
(enum-row (+ x 1) (- w 1)))))
(if (= 0 h)
nil
(append (enum-row x w)
(loc-enum-rect place x (+ y 1) w (- h 1)))))
;; ----------------------------------------------------------------------------
loc - adjacent ? -- check if two locations are adjacent neighbors in one of the
four cardinal directions . This assumes that the locations are in the same
;; place and that they have been wrapped if necessary.
;; ----------------------------------------------------------------------------
(define (loc-adjacent? a b)
(define (check dx dy)
(or (and (= 1 dx) (= 0 dy))
(and (= 0 dx) (= 1 dy))))
(let ((place (loc-place a)))
(if (kern-place-is-wrapping? place)
(let ((w (kern-place-get-width place)))
(check (mdist (loc-x a) (loc-x b) w)
(mdist (loc-y a) (loc-y b) w)))
(check (abs (- (loc-x a) (loc-x b)))
(abs (- (loc-y a) (loc-y b)))))))
(define (mk-lvect dx dy dz) (list dx dy dz))
(define (lvect-dx lvect) (car lvect))
(define (lvect-dy lvect) (cadr lvect))
(define (lvect-dz lvect) (caddr lvect))
;; Convert a direction code to a location vector
(define (direction-to-lvect dir)
(cond ((= dir east) (mk-lvect 1 0 0))
((= dir west) (mk-lvect -1 0 0))
((= dir north) (mk-lvect 0 -1 0))
((= dir south) (mk-lvect 0 1 0))
((= dir northwest) (mk-lvect -1 -1 0))
((= dir northeast) (mk-lvect 1 -1 0))
((= dir southwest) (mk-lvect -1 1 0))
((= dir southeast) (mk-lvect 1 -1 0))
((= dir up) (mk-lvect 0 0 1))
((= dir down) (mk-lvect 0 0 -1))
))
(define (loc-offset loc dir)
(define (get-place place dz)
(cond ((= dz 0) place)
(else (kern-place-get-neighbor place dir))))
(let* ((vec (direction-to-lvect dir))
(place (get-place (loc-place loc) (lvect-dz vec))))
(cond ((null? place) nil)
(else
(mk-loc place
(+ (loc-x loc) (lvect-dx vec))
(+ (loc-y loc) (lvect-dy vec)))))))
| null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.001/loc.scm | scheme | eastern half
southeast quarter
northeast quarter
southwest quarter
----------------------------------------------------------------------------
REVISIT: this has a form almost identical to the loc-adjacent? proc below
----------------------------------------------------------------------------
Convert a location vector to "normal" form
----------------------------------------------------------------------------
loc-enum-rect -- given a rectangular region of a place return a flat list of
all locations in that rectangle. Useful in conjunction with map.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
place and that they have been wrapped if necessary.
----------------------------------------------------------------------------
Convert a direction code to a location vector | (define (mk-loc place x y) (list place x y))
(define (loc-place loc) (car loc))
(define (loc-x loc) (cadr loc))
(define (loc-y loc) (caddr loc))
(define (loc-op a b op)
(mk-loc (loc-place a)
(op (loc-x a) (loc-x b))
(op (loc-y a) (loc-y b))))
(define (loc-sum a b) (loc-op a b +))
(define (loc-distance a b)
(kern-get-distance a b))
(define (loc-diff a b)
(let ((place (loc-place a)))
(if (kern-place-is-wrapping? place)
(let ((w (kern-place-get-width place)))
(mk-loc place
(mdist (loc-x a) (loc-x b) w)
(mdist (loc-y a) (loc-y b) w)))
(mk-loc place
(- (loc-x a) (loc-x b))
(- (loc-y a) (loc-y b))))))
(define (loc-to-cardinal-dir loc)
(let ((x (loc-x loc))
(y (loc-y loc)))
(display "loc-to-cardinal-dir")
(display " x=")(display x)
(display " y=")(display y)
(newline)
(if (> x 0)
(if (> y 0)
(if (> x y)
east
south)
(if (> x (abs y))
east
north))
western half
(if (> y 0)
(if (> (abs x) y)
west
south)
northwest quarter
(if (> (abs x) (abs y))
west
north)))))
loc - grid - distance -- return the distance needed to walk between two points
(define (loc-grid-distance a b)
(let ((place (loc-place a)))
(if (kern-place-is-wrapping? place)
(let ((w (kern-place-get-width place)))
(+ (mdist (loc-x a) (loc-x b) w)
(mdist (loc-y a) (loc-y b) w)))
(+ (abs (- (loc-x a) (loc-x b)))
(abs (- (loc-y a) (loc-y b)))))))
(define (loc-closer? a b c)
(< (loc-grid-distance a c)
(loc-grid-distance b c)))
(define (loc-norm loc)
(define (norm a)
(cond ((> a 0) 1)
((< a 0) -1)
(else 0)))
(mk-loc (loc-place loc)
(norm (loc-x loc))
(norm (loc-y loc))))
(define (loc-enum-rect place x y w h)
(define (enum-row x w)
(if (= 0 w)
nil
(cons (mk-loc place x y)
(enum-row (+ x 1) (- w 1)))))
(if (= 0 h)
nil
(append (enum-row x w)
(loc-enum-rect place x (+ y 1) w (- h 1)))))
loc - adjacent ? -- check if two locations are adjacent neighbors in one of the
four cardinal directions . This assumes that the locations are in the same
(define (loc-adjacent? a b)
(define (check dx dy)
(or (and (= 1 dx) (= 0 dy))
(and (= 0 dx) (= 1 dy))))
(let ((place (loc-place a)))
(if (kern-place-is-wrapping? place)
(let ((w (kern-place-get-width place)))
(check (mdist (loc-x a) (loc-x b) w)
(mdist (loc-y a) (loc-y b) w)))
(check (abs (- (loc-x a) (loc-x b)))
(abs (- (loc-y a) (loc-y b)))))))
(define (mk-lvect dx dy dz) (list dx dy dz))
(define (lvect-dx lvect) (car lvect))
(define (lvect-dy lvect) (cadr lvect))
(define (lvect-dz lvect) (caddr lvect))
(define (direction-to-lvect dir)
(cond ((= dir east) (mk-lvect 1 0 0))
((= dir west) (mk-lvect -1 0 0))
((= dir north) (mk-lvect 0 -1 0))
((= dir south) (mk-lvect 0 1 0))
((= dir northwest) (mk-lvect -1 -1 0))
((= dir northeast) (mk-lvect 1 -1 0))
((= dir southwest) (mk-lvect -1 1 0))
((= dir southeast) (mk-lvect 1 -1 0))
((= dir up) (mk-lvect 0 0 1))
((= dir down) (mk-lvect 0 0 -1))
))
(define (loc-offset loc dir)
(define (get-place place dz)
(cond ((= dz 0) place)
(else (kern-place-get-neighbor place dir))))
(let* ((vec (direction-to-lvect dir))
(place (get-place (loc-place loc) (lvect-dz vec))))
(cond ((null? place) nil)
(else
(mk-loc place
(+ (loc-x loc) (lvect-dx vec))
(+ (loc-y loc) (lvect-dy vec)))))))
|
368210919387d734bdedf743c728c72231efa1e8603bdce54b61c14823f4b08b | erszcz/learning | type_encoded_properties.erl | -module(type_encoded_properties).
-compile([export_all]).
-define(N_COMMON_FIELDS, 2).
-define(COMMON_FIELDS, field1=val1,
field2=val2).
-record(unauth_state, {?COMMON_FIELDS,
extra_unauth_field3=val3}).
-record(auth_state, {?COMMON_FIELDS,
extra_auth_field3=otherval3}).
-spec authenticate(UnauthState) -> AuthState when
UnauthState :: #unauth_state{},
AuthState :: #auth_state{}.
authenticate(#unauth_state{} = US) ->
%% do clever stuff and then:
#auth_state{field1 = US#unauth_state.field1,
field2 = US#unauth_state.field2}.
state_before_auth(#unauth_state{} = US) ->
%% some action, probably proceed to auth
authenticate(US).
%% `function_clause` for unauthenticated user
state_after_auth(#auth_state{} = AS) ->
%% allow requests requiring authentication
do_things(AS).
%% possibly catch other cases and log violation
%state_after_auth(S) ->
% log_violation(S).
do_things(_) -> ok.
| null | https://raw.githubusercontent.com/erszcz/learning/b21c58a09598e2aa5fa8a6909a80c81dc6be1601/erlang-type-encoded_properties/type_encoded_properties.erl | erlang | do clever stuff and then:
some action, probably proceed to auth
`function_clause` for unauthenticated user
allow requests requiring authentication
possibly catch other cases and log violation
state_after_auth(S) ->
log_violation(S). | -module(type_encoded_properties).
-compile([export_all]).
-define(N_COMMON_FIELDS, 2).
-define(COMMON_FIELDS, field1=val1,
field2=val2).
-record(unauth_state, {?COMMON_FIELDS,
extra_unauth_field3=val3}).
-record(auth_state, {?COMMON_FIELDS,
extra_auth_field3=otherval3}).
-spec authenticate(UnauthState) -> AuthState when
UnauthState :: #unauth_state{},
AuthState :: #auth_state{}.
authenticate(#unauth_state{} = US) ->
#auth_state{field1 = US#unauth_state.field1,
field2 = US#unauth_state.field2}.
state_before_auth(#unauth_state{} = US) ->
authenticate(US).
state_after_auth(#auth_state{} = AS) ->
do_things(AS).
do_things(_) -> ok.
|
10c7ad7cfdbb236807ad3d47c53954f64a6be86586912672bcd3d97a3c25cba7 | rabbitmq/rabbitmq-tracing | rabbit_tracing_wm_files.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 ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_tracing_wm_files).
-export([init/2, to_json/2, content_types_provided/2, is_authorized/2]).
-include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl").
%%--------------------------------------------------------------------
init(Req, _State) ->
{cowboy_rest, rabbit_mgmt_cors:set_headers(Req, ?MODULE), #context{}}.
content_types_provided(ReqData, Context) ->
{[{<<"application/json">>, to_json}], ReqData, Context}.
to_json(ReqData, Context) ->
List = rabbit_tracing_util:apply_on_node(ReqData, Context,
rabbit_tracing_files, list, []),
rabbit_mgmt_util:reply(List, ReqData, Context).
is_authorized(ReqData, Context) ->
rabbit_mgmt_util:is_authorized_admin(ReqData, Context).
%%--------------------------------------------------------------------
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-tracing/85af9285bef54c1689757b3161035b21389dca2d/src/rabbit_tracing_wm_files.erl | erlang |
--------------------------------------------------------------------
-------------------------------------------------------------------- | 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 ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_tracing_wm_files).
-export([init/2, to_json/2, content_types_provided/2, is_authorized/2]).
-include_lib("rabbitmq_management_agent/include/rabbit_mgmt_records.hrl").
init(Req, _State) ->
{cowboy_rest, rabbit_mgmt_cors:set_headers(Req, ?MODULE), #context{}}.
content_types_provided(ReqData, Context) ->
{[{<<"application/json">>, to_json}], ReqData, Context}.
to_json(ReqData, Context) ->
List = rabbit_tracing_util:apply_on_node(ReqData, Context,
rabbit_tracing_files, list, []),
rabbit_mgmt_util:reply(List, ReqData, Context).
is_authorized(ReqData, Context) ->
rabbit_mgmt_util:is_authorized_admin(ReqData, Context).
|
aa6847f56ab75875ef0276e56056d1e6e94fadbe8563edb5fed66110e7805bb7 | moquist/datomic-schematode | user.clj | (ns user
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.pprint :refer (pprint)]
[clojure.repl :refer :all]
[clojure.test :as test]
[clojure.tools.namespace.repl :refer (refresh refresh-all)]
[datomic.api :as d]
[datomic-schema.schema :as dsa]
[datomic-schematode :as dst]
[datomic-schematode.constraints :as ds-constraints]
[datomic-schematode.constraints.support :as dsc-support]
[datomic-schematode.core-test :as ds-test]
[datomic-schematode.examples.deli-menu :as ds-deli]))
(def db-url "datomic:mem")
(def db-conn nil)
(defn start!
"Starts the current development system."
[]
(d/create-database db-url)
(alter-var-root #'db-conn (constantly (d/connect db-url)))
(dst/init-schematode-constraints! db-conn)
(dst/load-schema! db-conn ds-test/test-schemas))
(defn stop!
"Shuts down and destroys the current development system."
[]
(d/delete-database db-url))
(defn reset []
(stop!)
(refresh :after 'user/start!))
(defn touch-that
"Execute the specified query on the current DB and return the results of touching each entity.
The first binding must be to the entity.
All other bindings are ignored."
[query]
(map #(d/touch
(d/entity
(d/db (d/connect db-url))
(first %)))
(d/q query
(d/db (d/connect db-url)))))
(defn ptouch-that
"Example: (ptouch-that '[:find ?e :where [?e :user/username]])"
[query]
(pprint (touch-that query)))
(defn tx
"Transact the given entity map using :schematode/tx"
[enforce? attrsmap]
(d/transact
(d/connect db-url)
[[:schematode/tx enforce? [(merge {:db/id (d/tempid :db.part/user)}
attrsmap)]]]))
(comment
(tx :enforce {:user/username "mim" :user/dob "2012-01-01" :user/lastname "marp"})
(ptouch-that '[:find ?e :where [?e :user/username]])
constraints should fail by duplicating dob and lastname :
(tx :enforce {:user/username "pim" :user/dob "2012-01-01" :user/lastname "marp"})
(def m (:db/fn (d/entity (d/db db-conn) :schematode/tx*)))
(m (d/db db-conn) [{:db/id (d/tempid :db.part/user)
:user/username "jim"
:user/lastname "im"
:user/dob "2001-01-01"}
{:db/id (d/tempid :db.part/user)
:user/username "jim"
:user/lastname "im"
:user/dob "2001-01-01"}])
;;;; other stuff
(def datomic-conn (d/connect db-url))
(def db (d/db datomic-conn))
(def user (d/entity (d/db datomic-conn) :add-user))
;; -are-fn.com/2013/datomic_history_of_an_entity/
(->>
;; This query finds all transactions that touched a particular entity
(d/q
'[:find ?tx
:in $ ?e
:where
[?e _ _ ?tx]]
(d/history (d/db datomic-conn))
(:db/id user))
;; The transactions are themselves represented as entities. We get the
full tx entities from the tx entity IDs we got in the query .
(map #(d/entity (d/db datomic-conn) (first %)))
;; The transaction entity has a txInstant attribute, which is a timestmap
;; as of the transaction write.
(sort-by :db/txInstant)
;; as-of yields the database as of a t. We pass in the transaction t for
;; after, and (dec transaction-t) for before. The list of t's might have
gaps , but if you specify a t that does n't exist , Datomic will round down .
(map
(fn [tx]
{:before (d/entity (d/as-of db (dec (d/tx->t (:db/id tx)))) (:db/id user))
:after (d/entity (d/as-of db (:db/id tx)) (:db/id user))})))
;;;; -are-fn.com/2013/datomic_history_of_an_entity/
part 2
(->>
This query finds all tuples of the tx and the actual attribute that
;; changed for a specific entity.
(d/q
'[:find ?tx ?a
:in $ ?e
:where
[?e ?a _ ?tx]]
(d/history db)
(:db/id user))
We group the tuples by tx - a single tx can and will contain multiple
;; attribute changes.
(group-by (fn [[tx attr]] tx))
;; We only want the actual changes
(vals)
Sort with oldest first
(sort-by (fn [[tx attr]] tx))
;; Creates a list of maps like '({:the-attribute {:old "Old value" :new "New value"}})
(map
(fn [changes]
{:changes (into
{}
(map
(fn [[tx attr]]
(let [tx-before-db (d/as-of db (dec (d/tx->t tx)))
tx-after-db (d/as-of db tx)
tx-e (d/entity tx-after-db tx)
attr-e-before (d/entity tx-before-db attr)
attr-e-after (d/entity tx-after-db attr)]
[(:db/ident attr-e-after)
{:old (get
(d/entity tx-before-db (:db/id user))
(:db/ident attr-e-before))
:new (get
(d/entity tx-after-db (:db/id user))
(:db/ident attr-e-after))}]))
changes))
:timestamp (->> (ffirst changes)
(d/entity (d/as-of db (ffirst changes)))
:db/txInstant)})))
(d/transact (d/connect db-url)
[{:db/id #db/id [:db.part/user]
:user/username "bob"}])
(d/touch (d/entity (d/db (d/connect db-url))
(ffirst (d/q '[:find ?e :where [?e :user/username "fleem2"]]
(d/db (d/connect db-url))))))
(def fsharp (d/entity (d/db datomic-conn) 17592186045433))
((:db/fn fsharp) "yeep")
)
| null | https://raw.githubusercontent.com/moquist/datomic-schematode/b73206fc86bb61bc97ddd5df55f7441bf5fc0447/dev/user.clj | clojure | other stuff
-are-fn.com/2013/datomic_history_of_an_entity/
This query finds all transactions that touched a particular entity
The transactions are themselves represented as entities. We get the
The transaction entity has a txInstant attribute, which is a timestmap
as of the transaction write.
as-of yields the database as of a t. We pass in the transaction t for
after, and (dec transaction-t) for before. The list of t's might have
-are-fn.com/2013/datomic_history_of_an_entity/
changed for a specific entity.
attribute changes.
We only want the actual changes
Creates a list of maps like '({:the-attribute {:old "Old value" :new "New value"}}) | (ns user
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.pprint :refer (pprint)]
[clojure.repl :refer :all]
[clojure.test :as test]
[clojure.tools.namespace.repl :refer (refresh refresh-all)]
[datomic.api :as d]
[datomic-schema.schema :as dsa]
[datomic-schematode :as dst]
[datomic-schematode.constraints :as ds-constraints]
[datomic-schematode.constraints.support :as dsc-support]
[datomic-schematode.core-test :as ds-test]
[datomic-schematode.examples.deli-menu :as ds-deli]))
(def db-url "datomic:mem")
(def db-conn nil)
(defn start!
"Starts the current development system."
[]
(d/create-database db-url)
(alter-var-root #'db-conn (constantly (d/connect db-url)))
(dst/init-schematode-constraints! db-conn)
(dst/load-schema! db-conn ds-test/test-schemas))
(defn stop!
"Shuts down and destroys the current development system."
[]
(d/delete-database db-url))
(defn reset []
(stop!)
(refresh :after 'user/start!))
(defn touch-that
"Execute the specified query on the current DB and return the results of touching each entity.
The first binding must be to the entity.
All other bindings are ignored."
[query]
(map #(d/touch
(d/entity
(d/db (d/connect db-url))
(first %)))
(d/q query
(d/db (d/connect db-url)))))
(defn ptouch-that
"Example: (ptouch-that '[:find ?e :where [?e :user/username]])"
[query]
(pprint (touch-that query)))
(defn tx
"Transact the given entity map using :schematode/tx"
[enforce? attrsmap]
(d/transact
(d/connect db-url)
[[:schematode/tx enforce? [(merge {:db/id (d/tempid :db.part/user)}
attrsmap)]]]))
(comment
(tx :enforce {:user/username "mim" :user/dob "2012-01-01" :user/lastname "marp"})
(ptouch-that '[:find ?e :where [?e :user/username]])
constraints should fail by duplicating dob and lastname :
(tx :enforce {:user/username "pim" :user/dob "2012-01-01" :user/lastname "marp"})
(def m (:db/fn (d/entity (d/db db-conn) :schematode/tx*)))
(m (d/db db-conn) [{:db/id (d/tempid :db.part/user)
:user/username "jim"
:user/lastname "im"
:user/dob "2001-01-01"}
{:db/id (d/tempid :db.part/user)
:user/username "jim"
:user/lastname "im"
:user/dob "2001-01-01"}])
(def datomic-conn (d/connect db-url))
(def db (d/db datomic-conn))
(def user (d/entity (d/db datomic-conn) :add-user))
(->>
(d/q
'[:find ?tx
:in $ ?e
:where
[?e _ _ ?tx]]
(d/history (d/db datomic-conn))
(:db/id user))
full tx entities from the tx entity IDs we got in the query .
(map #(d/entity (d/db datomic-conn) (first %)))
(sort-by :db/txInstant)
gaps , but if you specify a t that does n't exist , Datomic will round down .
(map
(fn [tx]
{:before (d/entity (d/as-of db (dec (d/tx->t (:db/id tx)))) (:db/id user))
:after (d/entity (d/as-of db (:db/id tx)) (:db/id user))})))
part 2
(->>
This query finds all tuples of the tx and the actual attribute that
(d/q
'[:find ?tx ?a
:in $ ?e
:where
[?e ?a _ ?tx]]
(d/history db)
(:db/id user))
We group the tuples by tx - a single tx can and will contain multiple
(group-by (fn [[tx attr]] tx))
(vals)
Sort with oldest first
(sort-by (fn [[tx attr]] tx))
(map
(fn [changes]
{:changes (into
{}
(map
(fn [[tx attr]]
(let [tx-before-db (d/as-of db (dec (d/tx->t tx)))
tx-after-db (d/as-of db tx)
tx-e (d/entity tx-after-db tx)
attr-e-before (d/entity tx-before-db attr)
attr-e-after (d/entity tx-after-db attr)]
[(:db/ident attr-e-after)
{:old (get
(d/entity tx-before-db (:db/id user))
(:db/ident attr-e-before))
:new (get
(d/entity tx-after-db (:db/id user))
(:db/ident attr-e-after))}]))
changes))
:timestamp (->> (ffirst changes)
(d/entity (d/as-of db (ffirst changes)))
:db/txInstant)})))
(d/transact (d/connect db-url)
[{:db/id #db/id [:db.part/user]
:user/username "bob"}])
(d/touch (d/entity (d/db (d/connect db-url))
(ffirst (d/q '[:find ?e :where [?e :user/username "fleem2"]]
(d/db (d/connect db-url))))))
(def fsharp (d/entity (d/db datomic-conn) 17592186045433))
((:db/fn fsharp) "yeep")
)
|
9fde85f3ec5d2cf3e2d39164db21676a4ddc926257aaa2476b52a431ca03ff9e | inhabitedtype/ocaml-aws | addTags.mli | open Types
type input = AddTagsInput.t
type output = unit
type error = Errors_internal.t
include
Aws.Call with type input := input and type output := output and type error := error
| null | https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/elasticloadbalancing/lib/addTags.mli | ocaml | open Types
type input = AddTagsInput.t
type output = unit
type error = Errors_internal.t
include
Aws.Call with type input := input and type output := output and type error := error
|
|
bec1f32017d9725f231ee931d3626f3e7341d77476aed630a404487da502c847 | qmuli/qmuli | Gen.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
# LANGUAGE OverloadedLists #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
module Qi.Program.SQS.Ipret.Gen where
import Control.Lens (Getting, (.~), (?~), (^.))
import Control.Monad.Freer
import Data.Aeson (decode, encode)
import Network.AWS.SQS
import Protolude hiding (handle, (<&>))
import Qi.AWS.SQS
import Qi.Config.AWS
import Qi.Config.Identifier (LambdaId)
import Qi.Program.Gen.Lang
import Qi.Program.SQS.Lang
run
:: forall effs a
. (Member GenEff effs)
=> Config
-> (Eff (SqsEff ': effs) a -> Eff effs a)
run config = interpret (\case
SendSqsMessage id msg ->
void . amazonka sqs . sendMessage (unPhysicalName queueUrl) . toS $ encode msg
where
queueUrl = getPhysicalName config $ getById config id
ReceiveSqsMessage id -> do
r <- amazonka sqs $ receiveMessage (unPhysicalName queueUrl)
pure . catMaybes $ (\m -> do
msg <- decode . toS =<< m ^. mBody
rh <- m ^. mReceiptHandle
pure (msg, ReceiptHandle rh)
) <$> (r ^. rmrsMessages)
where
queueUrl = getPhysicalName config $ getById config id
DeleteSqsMessage id handle -> panic "deleteSqsMessage unimplemented"
)
| null | https://raw.githubusercontent.com/qmuli/qmuli/6ca147f94642b81ab3978d502397efb60a50215b/library/Qi/Program/SQS/Ipret/Gen.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# LANGUAGE TypeOperators # | # LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
# LANGUAGE OverloadedLists #
module Qi.Program.SQS.Ipret.Gen where
import Control.Lens (Getting, (.~), (?~), (^.))
import Control.Monad.Freer
import Data.Aeson (decode, encode)
import Network.AWS.SQS
import Protolude hiding (handle, (<&>))
import Qi.AWS.SQS
import Qi.Config.AWS
import Qi.Config.Identifier (LambdaId)
import Qi.Program.Gen.Lang
import Qi.Program.SQS.Lang
run
:: forall effs a
. (Member GenEff effs)
=> Config
-> (Eff (SqsEff ': effs) a -> Eff effs a)
run config = interpret (\case
SendSqsMessage id msg ->
void . amazonka sqs . sendMessage (unPhysicalName queueUrl) . toS $ encode msg
where
queueUrl = getPhysicalName config $ getById config id
ReceiveSqsMessage id -> do
r <- amazonka sqs $ receiveMessage (unPhysicalName queueUrl)
pure . catMaybes $ (\m -> do
msg <- decode . toS =<< m ^. mBody
rh <- m ^. mReceiptHandle
pure (msg, ReceiptHandle rh)
) <$> (r ^. rmrsMessages)
where
queueUrl = getPhysicalName config $ getById config id
DeleteSqsMessage id handle -> panic "deleteSqsMessage unimplemented"
)
|
07d50ba2eef25ea2d107fcfb05e30219df9b054b9299285cdd15ebc4543179a4 | TypedLambda/eresye | journal.erl | -module (journal).
-include ("journal.hrl").
-export ([is_class/1, is_a/2, 'journal'/1,'international-journal'/1,'national-journal'/1, childof/1]).
is_class ('journal') -> true;
is_class ('international-journal') -> true;
is_class ('national-journal') -> true;
is_class ('IEEE-journal') -> true;
is_class ('ACM-journal') -> true;
is_class ('italian-journal') -> true;
is_class (_) -> false.
is_a ('international-journal','journal') -> true;
is_a ('national-journal','journal') -> true;
is_a ('IEEE-journal','international-journal') -> true;
is_a ('IEEE-journal','journal') -> true;
is_a ('ACM-journal','international-journal') -> true;
is_a ('ACM-journal','journal') -> true;
is_a ('italian-journal','national-journal') -> true;
is_a ('italian-journal','journal') -> true;
is_a (_,_) -> false.
childof ('journal') -> ['international-journal',
'national-journal',
'IEEE-journal',
'ACM-journal',
'italian-journal'];
childof ('international-journal') -> ['IEEE-journal','ACM-journal'];
childof ('national-journal') -> ['italian-journal'];
childof ('IEEE-journal') -> [];
childof ('ACM-journal') -> [];
childof ('italian-journal') -> [];
childof (_) -> exit (undef_class).
'journal' (X = #'international-journal'{}) ->
#'journal'{
'title' = X#'international-journal'.'title',
'main_topic' = X#'international-journal'.'main_topic',
'publisher' = X#'international-journal'.'publisher',
'type' = X#'international-journal'.'type',
'impact_factor' = X#'international-journal'.'impact_factor'};
'journal' (X = #'national-journal'{}) ->
#'journal'{
'title' = X#'national-journal'.'title',
'main_topic' = X#'national-journal'.'main_topic',
'publisher' = X#'national-journal'.'publisher',
'type' = X#'national-journal'.'type',
'impact_factor' = X#'national-journal'.'impact_factor'};
'journal' (X = #'IEEE-journal'{}) ->
#'journal'{
'title' = X#'IEEE-journal'.'title',
'main_topic' = X#'IEEE-journal'.'main_topic',
'publisher' = X#'IEEE-journal'.'publisher',
'type' = X#'IEEE-journal'.'type',
'impact_factor' = X#'IEEE-journal'.'impact_factor'};
'journal' (X = #'ACM-journal'{}) ->
#'journal'{
'title' = X#'ACM-journal'.'title',
'main_topic' = X#'ACM-journal'.'main_topic',
'publisher' = X#'ACM-journal'.'publisher',
'type' = X#'ACM-journal'.'type',
'impact_factor' = X#'ACM-journal'.'impact_factor'};
'journal' (X = #'italian-journal'{}) ->
#'journal'{
'title' = X#'italian-journal'.'title',
'main_topic' = X#'italian-journal'.'main_topic',
'publisher' = X#'italian-journal'.'publisher',
'type' = X#'italian-journal'.'type',
'impact_factor' = X#'italian-journal'.'impact_factor'}.
'international-journal' (X = #'IEEE-journal'{}) ->
#'international-journal'{
'title' = X#'IEEE-journal'.'title',
'main_topic' = X#'IEEE-journal'.'main_topic',
'publisher' = X#'IEEE-journal'.'publisher',
'type' = X#'IEEE-journal'.'type',
'impact_factor' = X#'IEEE-journal'.'impact_factor'};
'international-journal' (X = #'ACM-journal'{}) ->
#'international-journal'{
'title' = X#'ACM-journal'.'title',
'main_topic' = X#'ACM-journal'.'main_topic',
'publisher' = X#'ACM-journal'.'publisher',
'type' = X#'ACM-journal'.'type',
'impact_factor' = X#'ACM-journal'.'impact_factor'}.
'national-journal' (X = #'italian-journal'{}) ->
#'national-journal'{
'title' = X#'italian-journal'.'title',
'main_topic' = X#'italian-journal'.'main_topic',
'publisher' = X#'italian-journal'.'publisher',
'type' = X#'italian-journal'.'type',
'impact_factor' = X#'italian-journal'.'impact_factor'}.
| null | https://raw.githubusercontent.com/TypedLambda/eresye/58c159e7fbe8ebaed52018b1a7761d534b4d6119/examples/journal.erl | erlang | -module (journal).
-include ("journal.hrl").
-export ([is_class/1, is_a/2, 'journal'/1,'international-journal'/1,'national-journal'/1, childof/1]).
is_class ('journal') -> true;
is_class ('international-journal') -> true;
is_class ('national-journal') -> true;
is_class ('IEEE-journal') -> true;
is_class ('ACM-journal') -> true;
is_class ('italian-journal') -> true;
is_class (_) -> false.
is_a ('international-journal','journal') -> true;
is_a ('national-journal','journal') -> true;
is_a ('IEEE-journal','international-journal') -> true;
is_a ('IEEE-journal','journal') -> true;
is_a ('ACM-journal','international-journal') -> true;
is_a ('ACM-journal','journal') -> true;
is_a ('italian-journal','national-journal') -> true;
is_a ('italian-journal','journal') -> true;
is_a (_,_) -> false.
childof ('journal') -> ['international-journal',
'national-journal',
'IEEE-journal',
'ACM-journal',
'italian-journal'];
childof ('international-journal') -> ['IEEE-journal','ACM-journal'];
childof ('national-journal') -> ['italian-journal'];
childof ('IEEE-journal') -> [];
childof ('ACM-journal') -> [];
childof ('italian-journal') -> [];
childof (_) -> exit (undef_class).
'journal' (X = #'international-journal'{}) ->
#'journal'{
'title' = X#'international-journal'.'title',
'main_topic' = X#'international-journal'.'main_topic',
'publisher' = X#'international-journal'.'publisher',
'type' = X#'international-journal'.'type',
'impact_factor' = X#'international-journal'.'impact_factor'};
'journal' (X = #'national-journal'{}) ->
#'journal'{
'title' = X#'national-journal'.'title',
'main_topic' = X#'national-journal'.'main_topic',
'publisher' = X#'national-journal'.'publisher',
'type' = X#'national-journal'.'type',
'impact_factor' = X#'national-journal'.'impact_factor'};
'journal' (X = #'IEEE-journal'{}) ->
#'journal'{
'title' = X#'IEEE-journal'.'title',
'main_topic' = X#'IEEE-journal'.'main_topic',
'publisher' = X#'IEEE-journal'.'publisher',
'type' = X#'IEEE-journal'.'type',
'impact_factor' = X#'IEEE-journal'.'impact_factor'};
'journal' (X = #'ACM-journal'{}) ->
#'journal'{
'title' = X#'ACM-journal'.'title',
'main_topic' = X#'ACM-journal'.'main_topic',
'publisher' = X#'ACM-journal'.'publisher',
'type' = X#'ACM-journal'.'type',
'impact_factor' = X#'ACM-journal'.'impact_factor'};
'journal' (X = #'italian-journal'{}) ->
#'journal'{
'title' = X#'italian-journal'.'title',
'main_topic' = X#'italian-journal'.'main_topic',
'publisher' = X#'italian-journal'.'publisher',
'type' = X#'italian-journal'.'type',
'impact_factor' = X#'italian-journal'.'impact_factor'}.
'international-journal' (X = #'IEEE-journal'{}) ->
#'international-journal'{
'title' = X#'IEEE-journal'.'title',
'main_topic' = X#'IEEE-journal'.'main_topic',
'publisher' = X#'IEEE-journal'.'publisher',
'type' = X#'IEEE-journal'.'type',
'impact_factor' = X#'IEEE-journal'.'impact_factor'};
'international-journal' (X = #'ACM-journal'{}) ->
#'international-journal'{
'title' = X#'ACM-journal'.'title',
'main_topic' = X#'ACM-journal'.'main_topic',
'publisher' = X#'ACM-journal'.'publisher',
'type' = X#'ACM-journal'.'type',
'impact_factor' = X#'ACM-journal'.'impact_factor'}.
'national-journal' (X = #'italian-journal'{}) ->
#'national-journal'{
'title' = X#'italian-journal'.'title',
'main_topic' = X#'italian-journal'.'main_topic',
'publisher' = X#'italian-journal'.'publisher',
'type' = X#'italian-journal'.'type',
'impact_factor' = X#'italian-journal'.'impact_factor'}.
|
|
11cabcf45fb134ffb64ea08019a78c977c89ca756288a52e7e973a2c661b44b6 | bracevac/corrl | Range.hs | -----------------------------------------------------------------------------
Copyright 2012 Microsoft Corporation .
--
-- This is free software; you can redistribute it and/or modify it under the
terms of the Apache License , Version 2.0 . A copy of the License can be
found in the file " license.txt " at the root of this distribution .
-----------------------------------------------------------------------------
{-
Source ranges and positions.
-}
-----------------------------------------------------------------------------
{-# OPTIONS_GHC -funbox-strict-fields #-}
module Common.Range
( Pos, makePos, minPos, maxPos, posColumn, posLine
, posMove8, posMoves8, posNull
, Range, showFullRange
, makeRange, rangeNull, combineRange, rangeEnd, rangeStart
, Ranged( getRange ), combineRanged
, combineRangeds, combineRanges
, Source(Source,sourceName, sourceBString), sourceText, sourceFromRange
, posSource
, rangeSource
, sourceNull
, bigLine
, after
, showRange
, BString, bstringToString, bstringToText, stringToBString
, bstringEmpty
, readInput
, extractLiterate
) where
import Lib . Trace
import Common.Failure( assertion )
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.Text as T (Text, pack, unpack)
import qualified Data.Text.Encoding as T (decodeUtf8) -- ,decodeUtf8With)
import qualified Data . Text . Encoding . Error as E(lenientDecode )
import Common . )
-------------------------------------------------------------------------
BStrings
-------------------------------------------------------------------------
BStrings
--------------------------------------------------------------------------}
type BString = B.ByteString
bstringEmpty = B.empty
utfDecode bstr -- T.decodeUtf8With
bstringToString bstr = T.unpack (T.decodeUtf8 bstr) -- (bstringToText bstr)
stringToBString str = BC.pack str
readInput :: FilePath -> IO BString
readInput fname
= do input <- B.readFile fname
trace ( " input bytes : " + + show ( map ( - > showHex ( fromEnum c ) " " ) ( take 400 ( BC.unpack input ) ) ) ) $
case BC.unpack $ B.take 3 input of
"\xEF\xBB\xBF" -> return (B.drop 3 input) -- remove BOM
_ -> return input
utfDecode :: B.ByteString -> T.Text
utfDecode bs
= decode "" (BC.unpack bs)
where
decode acc s
= case s of
[] -> T.pack (reverse acc)
(c:cs) | (c <= '\x7F') -> decode (c:acc) cs
(c1:c2:cs) | (c1 >= '\xC2' && c1 <= '\xDF' && isCont c2) -> decode (decode2 c1 c2:acc) cs
(c1:c2:c3:cs) | (c1 >= '\xE0' && c1 <= '\xEF' && isCont c2 && isCont c3) -> decode (decode3 c1 c2 c3:acc) cs
(c1:c2:c3:c4:cs) | (c1 >= '\xF0' && c1 <= '\xF4' && isCont c2 && isCont c3 && isCont c4) -> decode (decode4 c1 c2 c3 c4:acc) cs
modified encoding of 0
(c1:c2:cs) | (c1 == '\xC0' && c2 == '\x80') -> decode ('\x00':acc) cs
invalid sequence of 4 : use replacement
(c1:c2:c3:c4:cs) | (c1 >= '\xF5' && c1 <= '\xF7' && isCont c2 && isCont c3 && isCont c4) -> decode (replacement:acc) cs
invalid sequence of 5 : use replacement
(c1:c2:c3:c4:c5:cs) | (c1 >= '\xF8' && c1 <= '\xFB' && isCont c2 && isCont c3 && isCont c4 && isCont c5) -> decode (replacement:acc) cs
invalid sequence of 6 : use replacement
(c1:c2:c3:c4:c5:c6:cs) | (c1 >= '\xFC' && c1 <= '\xFD' && isCont c2 && isCont c3 && isCont c4 && isCont c5 && isCont c6) -> decode (replacement:acc) cs
-- continuation bytes: skip
(c:cs) | isCont c -> decode acc cs
( c1 : c2 : cs ) | ( c1 > = ' \x80 ' & & c1 < = ' \xBF ' & & isCont c2 ) - > decode ( decode2 c1 c2 ) cs
-- otherwise: use replacement character
(c:cs) -> decode (replacement:acc) cs
where
replacement = '\xFFFD'
isCont c = (c >= '\x80' && c <= '\xBF')
decode2 :: Char -> Char -> Char
decode2 c1 c2 = toEnum $ ((fromEnum c1 - 0xC0) * 0x40) + (fromEnum c2 - 0x80)
decode3 :: Char -> Char -> Char -> Char
decode3 c1 c2 c3 = toEnum $ ((fromEnum c1 - 0xE0) * 0x40 * 0x40) + ((fromEnum c2 - 0x80) * 0x40) + (fromEnum c3 - 0x80)
decode4 :: Char -> Char -> Char -> Char -> Char
decode4 c1 c2 c3 c4 = toEnum $ ((fromEnum c1 - 0xF0) * 0x40 * 0x40 * 0x40) + ((fromEnum c2 - 0x80) * 0x40 * 0x40) + ((fromEnum c3 - 0x80) * 0x40) + (fromEnum c4 - 0x80)
-- process literate file
extractLiterate :: BString -> BString
extractLiterate input
= let res = B.concat (scan False input)
in res
where
scan skipping input
= if (B.null input) then [] else
let (line,rest) = BC.span (/='\n') input
(qs,cs) = BC.span(=='`') $ BC.dropWhile (==' ') line
isQ3 = B.length qs == 3
in if isQ3 && not skipping && (BC.all isWhite cs || startsWith cs "koka")
then BC.pack "\n" : scanCode [] (safeTail rest)
else BC.pack "//" : line : BC.pack "\n" :
scan (if (isQ3) then not skipping else skipping) (safeTail rest)
scanCode acc input
= if (B.null input) then [] else
let (line,rest) = BC.span (/='\n') input
wline = BC.dropWhile (==' ') line
(qs,cs) = BC.span(=='`') wline
in if (B.length qs == 3 && BC.all isWhite cs)
then map (\ln -> BC.snoc ln '\n') (reverse (BC.empty : acc)) ++ scan False (safeTail rest)
else if startsWith cs "////"
then scanCode (BC.empty : map (const BC.empty) acc) (safeTail rest)
if ( B.length qs = = 1 & & BC.all isWhite cs )
-- then BC.pack "\n" : scan (safeTail rest)
-- else
else scanCode (line : acc) (safeTail rest)
safeTail bstr
= if (B.null bstr) then B.empty else B.tail bstr
isWhite c
= c `elem` " \r\v\f\n"
startsWith :: BC.ByteString -> String -> Bool
startsWith bs s
= BC.unpack (BC.take (length s) bs) == s
{--------------------------------------------------------------------------
Source
--------------------------------------------------------------------------}
data Source = Source{ sourceName :: !FilePath, sourceBString :: !BString }
instance Eq Source where
(Source fname1 _) == (Source fname2 _)
= (fname1 == fname2)
sourceNull = Source "" B.empty
sourceText src = bstringToString (sourceBString src)
{--------------------------------------------------------------------------
Positions
--------------------------------------------------------------------------}
-- | Source positions
data Pos = Pos{ posSource :: !Source
, posOfs :: !Int
, posLine :: !Int
, posColumn :: !Int
}
posNull = Pos sourceNull (-1) 0 0
instance Eq Pos where
(Pos _ o1 l1 c1) == (Pos _ o2 l2 c2)
= (l1==l2) && (c1==c2)
instance Ord Pos where
compare (Pos _ o1 l1 c1) (Pos _ o2 l2 c2)
= case compare l1 l2 of
LT -> LT
GT -> GT
EQ -> compare c1 c2
instance Show Pos where
show p = "(" ++ showPos 2 p ++ ")"
showPos alignWidth (Pos src ofs line col)
= showLine line ++ "," ++ align alignWidth (show col)
showFullPos alignWidth p
= "[" ++ show (posOfs p) ++ "] " ++ showPos alignWidth p
-- Special showing for lines > 'bigLine'. This is used for the interpreter.
showLine line
= if (line >= bigLine)
then "(" ++ show (line - bigLine) ++ ")"
else if (line <= 0)
then "1" -- to avoid bugs in rise4fun on 0 line numbers
else show line
bigLine :: Int
bigLine
about 67 million lines
align n s
= replicate (n - length s) ' ' ++ s
| Create a position from a line\/column number ( 1 - based )
makePos :: Source -> Int -> Int -> Int -> Pos
makePos = Pos
posMoves8 :: Pos -> BString -> Pos
posMoves8 pos bstr
= BC.foldl posMove8 pos bstr
posMove8 :: Pos -> Char -> Pos
posMove8 (Pos s o l c) ch
= let o1 = if o < 0 then o else o+1 in
case ch of
'\t' -> Pos s o1 l (((c+7) `div` 8)*8+1)
'\n' -> Pos s o1 (l+1) 1
_ -> Pos s o1 l (c+1)
{--------------------------------------------------------------------------
Ranges
--------------------------------------------------------------------------}
-- | Source range
data Range = Range !Pos !Pos
deriving Eq
instance Show Range where
show (Range p1 p2) = show p1
instance Ord Range where
compare (Range p1 p2) (Range q1 q2)
= case compare p1 q1 of
EQ -> compare p2 q2
ltgt -> ltgt
showRange endToo (Range p1 p2)
= (if (posLine p1 >= bigLine) then "" else sourceName (posSource p1)) ++
if (endToo)
then ("(" ++ showPos 0 p1 ++ "-" ++ showPos 0 p2 ++ ")")
else (show p1)
-- | Does r2 start after range r1?
after :: Range -> Range -> Bool
after r1 r2
= rangeEnd r1 <= rangeStart r2
rangeNull :: Range
rangeNull
= makeRange posNull posNull
showFullRange :: Range -> String
showFullRange range
= showRange True range
-- | Make a range
makeRange :: Pos -> Pos -> Range
makeRange p1 p2
= assertion "Range.makeRange: positions from different sources" (posSource p1 == posSource p2) $
Range (minPos p1 p2) (maxPos p1 p2)
-- | Return the start position of a range
rangeStart :: Range -> Pos
rangeStart (Range p1 p2) = p1
-- | Return the end position of a range
rangeEnd :: Range -> Pos
rangeEnd (Range p1 p2) = p2
-- | Return the source of a range
rangeSource :: Range -> Source
rangeSource = posSource . rangeStart
-- | Combine to ranges into a range to encompasses both.
combineRange :: Range -> Range -> Range
combineRange (Range start1 end1) (Range start2 end2)
= Range (minPos start1 start2) (maxPos end1 end2)
combineRanges :: [Range] -> Range
combineRanges rs
= foldr combineRange rangeNull rs
-- | Return the minimal position
minPos :: Pos -> Pos -> Pos
for combining nullRanges sensably
minPos p (Pos _ _ l _) | l <= 0 = p
minPos p1 p2 = if (p1 <= p2) then p1 else p2
-- | Return the furthest position
maxPos :: Pos -> Pos -> Pos
maxPos p1 p2 = if (p1 <= p2) then p2 else p1
{--------------------------------------------------------------------------
Ranged class
--------------------------------------------------------------------------}
combineRangeds :: Ranged a => [a] -> Range
combineRangeds xs
= combineRanges (map getRange xs)
combineRanged :: (Ranged a, Ranged b) => a -> b -> Range
combineRanged x y
= combineRange (getRange x) (getRange y)
class Ranged a where
getRange :: a -> Range
instance Ranged Range where
getRange r
= r
instance Ranged r => Ranged (Maybe r) where
getRange Nothing = rangeNull
getRange (Just r) = getRange r
{--------------------------------------------------------------------------
--------------------------------------------------------------------------}
sourceFromRange :: Range -> String
sourceFromRange (Range start end) | posOfs start >= 0
= let text = bstringToString $
B.take (posOfs end - posOfs start) $ B.drop (posOfs start) $
sourceBString (posSource start)
in (replicate (posColumn start - 1) ' ' ++ text)
sourceFromRange (Range start end)
= case take (l2-l1+1) $ drop (l1-1) $ lines $ sourceText $ posSource start of
(l:ls) -> case reverse ((spaces (c1-1) ++ (drop (c1-1) l)) : ls) of
(l:ls) -> unlines (reverse (take (c2) l : ls))
[] -> ""
[] -> ""
where
spaces n = take n (repeat ' ')
c1 = posColumn start
c2 = posColumn end
l1 = if posLine start >= bigLine then 1 else posLine start
l2 = if posLine end >= bigLine then (if posLine start >= bigLine then posLine end - posLine start +1 else 1) else posLine end
| null | https://raw.githubusercontent.com/bracevac/corrl/416cd107087ac070a6bcabf8e7937211b6f415bb/koka/src/Common/Range.hs | haskell | ---------------------------------------------------------------------------
This is free software; you can redistribute it and/or modify it under the
---------------------------------------------------------------------------
Source ranges and positions.
---------------------------------------------------------------------------
# OPTIONS_GHC -funbox-strict-fields #
,decodeUtf8With)
-----------------------------------------------------------------------
-----------------------------------------------------------------------
------------------------------------------------------------------------}
T.decodeUtf8With
(bstringToText bstr)
remove BOM
continuation bytes: skip
otherwise: use replacement character
process literate file
then BC.pack "\n" : scan (safeTail rest)
else
-------------------------------------------------------------------------
Source
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Positions
-------------------------------------------------------------------------
| Source positions
Special showing for lines > 'bigLine'. This is used for the interpreter.
to avoid bugs in rise4fun on 0 line numbers
-------------------------------------------------------------------------
Ranges
-------------------------------------------------------------------------
| Source range
| Does r2 start after range r1?
| Make a range
| Return the start position of a range
| Return the end position of a range
| Return the source of a range
| Combine to ranges into a range to encompasses both.
| Return the minimal position
| Return the furthest position
-------------------------------------------------------------------------
Ranged class
-------------------------------------------------------------------------
-------------------------------------------------------------------------
------------------------------------------------------------------------- | Copyright 2012 Microsoft Corporation .
terms of the Apache License , Version 2.0 . A copy of the License can be
found in the file " license.txt " at the root of this distribution .
module Common.Range
( Pos, makePos, minPos, maxPos, posColumn, posLine
, posMove8, posMoves8, posNull
, Range, showFullRange
, makeRange, rangeNull, combineRange, rangeEnd, rangeStart
, Ranged( getRange ), combineRanged
, combineRangeds, combineRanges
, Source(Source,sourceName, sourceBString), sourceText, sourceFromRange
, posSource
, rangeSource
, sourceNull
, bigLine
, after
, showRange
, BString, bstringToString, bstringToText, stringToBString
, bstringEmpty
, readInput
, extractLiterate
) where
import Lib . Trace
import Common.Failure( assertion )
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.Text as T (Text, pack, unpack)
import qualified Data . Text . Encoding . Error as E(lenientDecode )
import Common . )
BStrings
BStrings
type BString = B.ByteString
bstringEmpty = B.empty
stringToBString str = BC.pack str
readInput :: FilePath -> IO BString
readInput fname
= do input <- B.readFile fname
trace ( " input bytes : " + + show ( map ( - > showHex ( fromEnum c ) " " ) ( take 400 ( BC.unpack input ) ) ) ) $
case BC.unpack $ B.take 3 input of
_ -> return input
utfDecode :: B.ByteString -> T.Text
utfDecode bs
= decode "" (BC.unpack bs)
where
decode acc s
= case s of
[] -> T.pack (reverse acc)
(c:cs) | (c <= '\x7F') -> decode (c:acc) cs
(c1:c2:cs) | (c1 >= '\xC2' && c1 <= '\xDF' && isCont c2) -> decode (decode2 c1 c2:acc) cs
(c1:c2:c3:cs) | (c1 >= '\xE0' && c1 <= '\xEF' && isCont c2 && isCont c3) -> decode (decode3 c1 c2 c3:acc) cs
(c1:c2:c3:c4:cs) | (c1 >= '\xF0' && c1 <= '\xF4' && isCont c2 && isCont c3 && isCont c4) -> decode (decode4 c1 c2 c3 c4:acc) cs
modified encoding of 0
(c1:c2:cs) | (c1 == '\xC0' && c2 == '\x80') -> decode ('\x00':acc) cs
invalid sequence of 4 : use replacement
(c1:c2:c3:c4:cs) | (c1 >= '\xF5' && c1 <= '\xF7' && isCont c2 && isCont c3 && isCont c4) -> decode (replacement:acc) cs
invalid sequence of 5 : use replacement
(c1:c2:c3:c4:c5:cs) | (c1 >= '\xF8' && c1 <= '\xFB' && isCont c2 && isCont c3 && isCont c4 && isCont c5) -> decode (replacement:acc) cs
invalid sequence of 6 : use replacement
(c1:c2:c3:c4:c5:c6:cs) | (c1 >= '\xFC' && c1 <= '\xFD' && isCont c2 && isCont c3 && isCont c4 && isCont c5 && isCont c6) -> decode (replacement:acc) cs
(c:cs) | isCont c -> decode acc cs
( c1 : c2 : cs ) | ( c1 > = ' \x80 ' & & c1 < = ' \xBF ' & & isCont c2 ) - > decode ( decode2 c1 c2 ) cs
(c:cs) -> decode (replacement:acc) cs
where
replacement = '\xFFFD'
isCont c = (c >= '\x80' && c <= '\xBF')
decode2 :: Char -> Char -> Char
decode2 c1 c2 = toEnum $ ((fromEnum c1 - 0xC0) * 0x40) + (fromEnum c2 - 0x80)
decode3 :: Char -> Char -> Char -> Char
decode3 c1 c2 c3 = toEnum $ ((fromEnum c1 - 0xE0) * 0x40 * 0x40) + ((fromEnum c2 - 0x80) * 0x40) + (fromEnum c3 - 0x80)
decode4 :: Char -> Char -> Char -> Char -> Char
decode4 c1 c2 c3 c4 = toEnum $ ((fromEnum c1 - 0xF0) * 0x40 * 0x40 * 0x40) + ((fromEnum c2 - 0x80) * 0x40 * 0x40) + ((fromEnum c3 - 0x80) * 0x40) + (fromEnum c4 - 0x80)
extractLiterate :: BString -> BString
extractLiterate input
= let res = B.concat (scan False input)
in res
where
scan skipping input
= if (B.null input) then [] else
let (line,rest) = BC.span (/='\n') input
(qs,cs) = BC.span(=='`') $ BC.dropWhile (==' ') line
isQ3 = B.length qs == 3
in if isQ3 && not skipping && (BC.all isWhite cs || startsWith cs "koka")
then BC.pack "\n" : scanCode [] (safeTail rest)
else BC.pack "//" : line : BC.pack "\n" :
scan (if (isQ3) then not skipping else skipping) (safeTail rest)
scanCode acc input
= if (B.null input) then [] else
let (line,rest) = BC.span (/='\n') input
wline = BC.dropWhile (==' ') line
(qs,cs) = BC.span(=='`') wline
in if (B.length qs == 3 && BC.all isWhite cs)
then map (\ln -> BC.snoc ln '\n') (reverse (BC.empty : acc)) ++ scan False (safeTail rest)
else if startsWith cs "////"
then scanCode (BC.empty : map (const BC.empty) acc) (safeTail rest)
if ( B.length qs = = 1 & & BC.all isWhite cs )
else scanCode (line : acc) (safeTail rest)
safeTail bstr
= if (B.null bstr) then B.empty else B.tail bstr
isWhite c
= c `elem` " \r\v\f\n"
startsWith :: BC.ByteString -> String -> Bool
startsWith bs s
= BC.unpack (BC.take (length s) bs) == s
data Source = Source{ sourceName :: !FilePath, sourceBString :: !BString }
instance Eq Source where
(Source fname1 _) == (Source fname2 _)
= (fname1 == fname2)
sourceNull = Source "" B.empty
sourceText src = bstringToString (sourceBString src)
data Pos = Pos{ posSource :: !Source
, posOfs :: !Int
, posLine :: !Int
, posColumn :: !Int
}
posNull = Pos sourceNull (-1) 0 0
instance Eq Pos where
(Pos _ o1 l1 c1) == (Pos _ o2 l2 c2)
= (l1==l2) && (c1==c2)
instance Ord Pos where
compare (Pos _ o1 l1 c1) (Pos _ o2 l2 c2)
= case compare l1 l2 of
LT -> LT
GT -> GT
EQ -> compare c1 c2
instance Show Pos where
show p = "(" ++ showPos 2 p ++ ")"
showPos alignWidth (Pos src ofs line col)
= showLine line ++ "," ++ align alignWidth (show col)
showFullPos alignWidth p
= "[" ++ show (posOfs p) ++ "] " ++ showPos alignWidth p
showLine line
= if (line >= bigLine)
then "(" ++ show (line - bigLine) ++ ")"
else if (line <= 0)
else show line
bigLine :: Int
bigLine
about 67 million lines
align n s
= replicate (n - length s) ' ' ++ s
| Create a position from a line\/column number ( 1 - based )
makePos :: Source -> Int -> Int -> Int -> Pos
makePos = Pos
posMoves8 :: Pos -> BString -> Pos
posMoves8 pos bstr
= BC.foldl posMove8 pos bstr
posMove8 :: Pos -> Char -> Pos
posMove8 (Pos s o l c) ch
= let o1 = if o < 0 then o else o+1 in
case ch of
'\t' -> Pos s o1 l (((c+7) `div` 8)*8+1)
'\n' -> Pos s o1 (l+1) 1
_ -> Pos s o1 l (c+1)
data Range = Range !Pos !Pos
deriving Eq
instance Show Range where
show (Range p1 p2) = show p1
instance Ord Range where
compare (Range p1 p2) (Range q1 q2)
= case compare p1 q1 of
EQ -> compare p2 q2
ltgt -> ltgt
showRange endToo (Range p1 p2)
= (if (posLine p1 >= bigLine) then "" else sourceName (posSource p1)) ++
if (endToo)
then ("(" ++ showPos 0 p1 ++ "-" ++ showPos 0 p2 ++ ")")
else (show p1)
after :: Range -> Range -> Bool
after r1 r2
= rangeEnd r1 <= rangeStart r2
rangeNull :: Range
rangeNull
= makeRange posNull posNull
showFullRange :: Range -> String
showFullRange range
= showRange True range
makeRange :: Pos -> Pos -> Range
makeRange p1 p2
= assertion "Range.makeRange: positions from different sources" (posSource p1 == posSource p2) $
Range (minPos p1 p2) (maxPos p1 p2)
rangeStart :: Range -> Pos
rangeStart (Range p1 p2) = p1
rangeEnd :: Range -> Pos
rangeEnd (Range p1 p2) = p2
rangeSource :: Range -> Source
rangeSource = posSource . rangeStart
combineRange :: Range -> Range -> Range
combineRange (Range start1 end1) (Range start2 end2)
= Range (minPos start1 start2) (maxPos end1 end2)
combineRanges :: [Range] -> Range
combineRanges rs
= foldr combineRange rangeNull rs
minPos :: Pos -> Pos -> Pos
for combining nullRanges sensably
minPos p (Pos _ _ l _) | l <= 0 = p
minPos p1 p2 = if (p1 <= p2) then p1 else p2
maxPos :: Pos -> Pos -> Pos
maxPos p1 p2 = if (p1 <= p2) then p2 else p1
combineRangeds :: Ranged a => [a] -> Range
combineRangeds xs
= combineRanges (map getRange xs)
combineRanged :: (Ranged a, Ranged b) => a -> b -> Range
combineRanged x y
= combineRange (getRange x) (getRange y)
class Ranged a where
getRange :: a -> Range
instance Ranged Range where
getRange r
= r
instance Ranged r => Ranged (Maybe r) where
getRange Nothing = rangeNull
getRange (Just r) = getRange r
sourceFromRange :: Range -> String
sourceFromRange (Range start end) | posOfs start >= 0
= let text = bstringToString $
B.take (posOfs end - posOfs start) $ B.drop (posOfs start) $
sourceBString (posSource start)
in (replicate (posColumn start - 1) ' ' ++ text)
sourceFromRange (Range start end)
= case take (l2-l1+1) $ drop (l1-1) $ lines $ sourceText $ posSource start of
(l:ls) -> case reverse ((spaces (c1-1) ++ (drop (c1-1) l)) : ls) of
(l:ls) -> unlines (reverse (take (c2) l : ls))
[] -> ""
[] -> ""
where
spaces n = take n (repeat ' ')
c1 = posColumn start
c2 = posColumn end
l1 = if posLine start >= bigLine then 1 else posLine start
l2 = if posLine end >= bigLine then (if posLine start >= bigLine then posLine end - posLine start +1 else 1) else posLine end
|
b1eab9a0f2634dc6ca4099f988961ff2742bb4eb6ec35e9abc17771daf6a02da | morloc-project/morloc | AST.hs | |
Module : Morloc . Frontend . AST
Description : Functions for parsing the abstract syntax trees
Copyright : ( c ) , 2021
License : GPL-3
Maintainer :
Stability : experimental
Module : Morloc.Frontend.AST
Description : Functions for parsing the Expr abstract syntax trees
Copyright : (c) Zebulun Arendsee, 2021
License : GPL-3
Maintainer :
Stability : experimental
-}
module Morloc.Frontend.AST
( findEdges
, findExports
, findExportSet
, findSignatures
, findTypedefs
, findSignatureTypeTerms
, checkExprI
, findSources
, maxIndex
, getIndices
) where
import Morloc.Frontend.Namespace
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Morloc.Data.Text as MT
| In the DAG , the two MVar are the two keys , Import is the edge data , is the node data
findEdges :: ExprI -> (MVar, [(MVar, Import)], ExprI)
findEdges e@(ExprI _ (ModE n es)) = (n, [(importModuleName i, i) | (ExprI _ (ImpE i)) <- es], e)
findEdges _ = error "Expected a module"
findExportSet :: ExprI -> Set.Set Symbol
findExportSet = Set.fromList . map snd . findExports
findExports :: ExprI -> [(Int, Symbol)]
findExports (ExprI i (ExpE v)) = [(i, v)]
findExports (ExprI _ (ModE _ es)) = concatMap findExports es
findExports _ = []
findSources :: ExprI -> [Source]
findSources (ExprI _ (SrcE ss)) = [ss]
findSources (ExprI _ (ModE _ es)) = concatMap findSources es
findSources _ = []
findTypedefs :: ExprI -> Map.Map TVar ([TVar], TypeU)
findTypedefs (ExprI _ (TypE v vs t)) = Map.singleton v (vs, t)
findTypedefs (ExprI _ (ModE _ es)) = Map.unions (map findTypedefs es)
findTypedefs _ = Map.empty
findSignatureTypeTerms :: ExprI -> [TVar]
findSignatureTypeTerms = unique . f where
f :: ExprI -> [TVar]
f (ExprI _ (ModE _ es)) = concatMap f es
f (ExprI _ (SigE _ _ (EType t _ _))) = findTypeTerms t
f (ExprI _ (AssE _ _ es)) = concatMap f es
f _ = []
-- | find all the non-generic terms in an unresolved type
findTypeTerms :: TypeU -> [TVar]
findTypeTerms (VarU v)
| isGeneric v = [ ]
| otherwise = [v]
findTypeTerms (ExistU _ es1 es2) = concatMap findTypeTerms (es1 ++ es2)
findTypeTerms (ForallU _ e) = findTypeTerms e
findTypeTerms (FunU ts t) = concatMap findTypeTerms ts <> findTypeTerms t
findTypeTerms (AppU t ts) = findTypeTerms t <> concatMap findTypeTerms ts
findTypeTerms (NamU _ _ ps rs) = concatMap findTypeTerms (map snd rs <> ps)
-- | Find type signatures that are in the scope of the input expression. Do not
-- descend recursively into declaration where statements except if the input
-- expression is a declaration.
findSignatures :: ExprI -> [(EVar, Maybe MT.Text, EType)]
-- v is the name of the type
-- l is the optional label for the signature
-- t is the type
findSignatures (ExprI _ (ModE _ es)) = [(v, l, t) | (ExprI _ (SigE v l t)) <- es]
findSignatures (ExprI _ (AssE _ _ es)) = [(v, l, t) | (ExprI _ (SigE v l t)) <- es]
findSignatures (ExprI _ (SigE v l t)) = [(v, l, t)]
findSignatures _ = []
checkExprI :: Monad m => (ExprI -> m ()) -> ExprI -> m ()
checkExprI f e@(ExprI _ (ModE _ es)) = f e >> mapM_ (checkExprI f) es
checkExprI f e@(ExprI _ (AccE e' _)) = f e >> checkExprI f e'
checkExprI f e@(ExprI _ (AnnE e' _)) = f e >> checkExprI f e'
checkExprI f e@(ExprI _ (AssE _ e' es')) = f e >> checkExprI f e' >> mapM_ f es'
checkExprI f e@(ExprI _ (LamE _ e')) = f e >> checkExprI f e'
checkExprI f e@(ExprI _ (AppE e' es)) = f e >> checkExprI f e' >> mapM_ (checkExprI f) es
checkExprI f e@(ExprI _ (LstE es)) = f e >> mapM_ (checkExprI f) es
checkExprI f e@(ExprI _ (TupE es)) = f e >> mapM_ (checkExprI f) es
checkExprI f e@(ExprI _ (NamE rs)) = f e >> mapM_ (checkExprI f . snd) rs
checkExprI f e = f e
maxIndex :: ExprI -> Int
maxIndex (ExprI i (ModE _ es)) = maximum (i : map maxIndex es)
maxIndex (ExprI i (AccE e _)) = max i (maxIndex e)
maxIndex (ExprI i (AnnE e _)) = max i (maxIndex e)
maxIndex (ExprI i (AssE _ e es)) = maximum (i : map maxIndex (e:es))
maxIndex (ExprI i (LamE _ e)) = max i (maxIndex e)
maxIndex (ExprI i (AppE e es)) = maximum (i : map maxIndex (e:es))
maxIndex (ExprI i (LstE es)) = maximum (i : map maxIndex es)
maxIndex (ExprI i (TupE es)) = maximum (i : map maxIndex es)
maxIndex (ExprI i (NamE rs)) = maximum (i : map (maxIndex . snd) rs)
maxIndex (ExprI i _) = i
getIndices :: ExprI -> [Int]
getIndices (ExprI i (ModE _ es)) = i : concatMap getIndices es
getIndices (ExprI i (AccE e _)) = i : getIndices e
getIndices (ExprI i (AnnE e _)) = i : getIndices e
getIndices (ExprI i (AssE _ e es)) = i : concatMap getIndices (e:es)
getIndices (ExprI i (LamE _ e)) = i : getIndices e
getIndices (ExprI i (AppE e es)) = i : concatMap getIndices (e:es)
getIndices (ExprI i (LstE es)) = i : concatMap getIndices es
getIndices (ExprI i (TupE es)) = i : concatMap getIndices es
getIndices (ExprI i (NamE rs)) = i : concatMap (getIndices . snd) rs
getIndices (ExprI i _) = [i]
| null | https://raw.githubusercontent.com/morloc-project/morloc/e877221e1123b920f52b18ea7d1a319aacd0b927/library/Morloc/Frontend/AST.hs | haskell | | find all the non-generic terms in an unresolved type
| Find type signatures that are in the scope of the input expression. Do not
descend recursively into declaration where statements except if the input
expression is a declaration.
v is the name of the type
l is the optional label for the signature
t is the type | |
Module : Morloc . Frontend . AST
Description : Functions for parsing the abstract syntax trees
Copyright : ( c ) , 2021
License : GPL-3
Maintainer :
Stability : experimental
Module : Morloc.Frontend.AST
Description : Functions for parsing the Expr abstract syntax trees
Copyright : (c) Zebulun Arendsee, 2021
License : GPL-3
Maintainer :
Stability : experimental
-}
module Morloc.Frontend.AST
( findEdges
, findExports
, findExportSet
, findSignatures
, findTypedefs
, findSignatureTypeTerms
, checkExprI
, findSources
, maxIndex
, getIndices
) where
import Morloc.Frontend.Namespace
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Morloc.Data.Text as MT
| In the DAG , the two MVar are the two keys , Import is the edge data , is the node data
findEdges :: ExprI -> (MVar, [(MVar, Import)], ExprI)
findEdges e@(ExprI _ (ModE n es)) = (n, [(importModuleName i, i) | (ExprI _ (ImpE i)) <- es], e)
findEdges _ = error "Expected a module"
findExportSet :: ExprI -> Set.Set Symbol
findExportSet = Set.fromList . map snd . findExports
findExports :: ExprI -> [(Int, Symbol)]
findExports (ExprI i (ExpE v)) = [(i, v)]
findExports (ExprI _ (ModE _ es)) = concatMap findExports es
findExports _ = []
findSources :: ExprI -> [Source]
findSources (ExprI _ (SrcE ss)) = [ss]
findSources (ExprI _ (ModE _ es)) = concatMap findSources es
findSources _ = []
findTypedefs :: ExprI -> Map.Map TVar ([TVar], TypeU)
findTypedefs (ExprI _ (TypE v vs t)) = Map.singleton v (vs, t)
findTypedefs (ExprI _ (ModE _ es)) = Map.unions (map findTypedefs es)
findTypedefs _ = Map.empty
findSignatureTypeTerms :: ExprI -> [TVar]
findSignatureTypeTerms = unique . f where
f :: ExprI -> [TVar]
f (ExprI _ (ModE _ es)) = concatMap f es
f (ExprI _ (SigE _ _ (EType t _ _))) = findTypeTerms t
f (ExprI _ (AssE _ _ es)) = concatMap f es
f _ = []
findTypeTerms :: TypeU -> [TVar]
findTypeTerms (VarU v)
| isGeneric v = [ ]
| otherwise = [v]
findTypeTerms (ExistU _ es1 es2) = concatMap findTypeTerms (es1 ++ es2)
findTypeTerms (ForallU _ e) = findTypeTerms e
findTypeTerms (FunU ts t) = concatMap findTypeTerms ts <> findTypeTerms t
findTypeTerms (AppU t ts) = findTypeTerms t <> concatMap findTypeTerms ts
findTypeTerms (NamU _ _ ps rs) = concatMap findTypeTerms (map snd rs <> ps)
findSignatures :: ExprI -> [(EVar, Maybe MT.Text, EType)]
findSignatures (ExprI _ (ModE _ es)) = [(v, l, t) | (ExprI _ (SigE v l t)) <- es]
findSignatures (ExprI _ (AssE _ _ es)) = [(v, l, t) | (ExprI _ (SigE v l t)) <- es]
findSignatures (ExprI _ (SigE v l t)) = [(v, l, t)]
findSignatures _ = []
checkExprI :: Monad m => (ExprI -> m ()) -> ExprI -> m ()
checkExprI f e@(ExprI _ (ModE _ es)) = f e >> mapM_ (checkExprI f) es
checkExprI f e@(ExprI _ (AccE e' _)) = f e >> checkExprI f e'
checkExprI f e@(ExprI _ (AnnE e' _)) = f e >> checkExprI f e'
checkExprI f e@(ExprI _ (AssE _ e' es')) = f e >> checkExprI f e' >> mapM_ f es'
checkExprI f e@(ExprI _ (LamE _ e')) = f e >> checkExprI f e'
checkExprI f e@(ExprI _ (AppE e' es)) = f e >> checkExprI f e' >> mapM_ (checkExprI f) es
checkExprI f e@(ExprI _ (LstE es)) = f e >> mapM_ (checkExprI f) es
checkExprI f e@(ExprI _ (TupE es)) = f e >> mapM_ (checkExprI f) es
checkExprI f e@(ExprI _ (NamE rs)) = f e >> mapM_ (checkExprI f . snd) rs
checkExprI f e = f e
maxIndex :: ExprI -> Int
maxIndex (ExprI i (ModE _ es)) = maximum (i : map maxIndex es)
maxIndex (ExprI i (AccE e _)) = max i (maxIndex e)
maxIndex (ExprI i (AnnE e _)) = max i (maxIndex e)
maxIndex (ExprI i (AssE _ e es)) = maximum (i : map maxIndex (e:es))
maxIndex (ExprI i (LamE _ e)) = max i (maxIndex e)
maxIndex (ExprI i (AppE e es)) = maximum (i : map maxIndex (e:es))
maxIndex (ExprI i (LstE es)) = maximum (i : map maxIndex es)
maxIndex (ExprI i (TupE es)) = maximum (i : map maxIndex es)
maxIndex (ExprI i (NamE rs)) = maximum (i : map (maxIndex . snd) rs)
maxIndex (ExprI i _) = i
getIndices :: ExprI -> [Int]
getIndices (ExprI i (ModE _ es)) = i : concatMap getIndices es
getIndices (ExprI i (AccE e _)) = i : getIndices e
getIndices (ExprI i (AnnE e _)) = i : getIndices e
getIndices (ExprI i (AssE _ e es)) = i : concatMap getIndices (e:es)
getIndices (ExprI i (LamE _ e)) = i : getIndices e
getIndices (ExprI i (AppE e es)) = i : concatMap getIndices (e:es)
getIndices (ExprI i (LstE es)) = i : concatMap getIndices es
getIndices (ExprI i (TupE es)) = i : concatMap getIndices es
getIndices (ExprI i (NamE rs)) = i : concatMap (getIndices . snd) rs
getIndices (ExprI i _) = [i]
|
51a60e6cec782d6007941ce5b3f87bffcd424b8832bdf87e65553d45cf2bde0e | janestreet/core | sexpable.ml | open! Import
include Base.Sexpable
module Stable = struct
module Of_sexpable = struct
module V1
(Sexpable : S) (M : sig
type t
val to_sexpable : t -> Sexpable.t
val of_sexpable : Sexpable.t -> t
end) : S with type t := M.t = struct
let t_of_sexp sexp =
let s = Sexpable.t_of_sexp sexp in
try M.of_sexpable s with
| exn -> of_sexp_error_exn exn sexp
;;
let sexp_of_t t = Sexpable.sexp_of_t (M.to_sexpable t)
end
end
module Of_sexpable1 = struct
module V1
(Sexpable : S1) (M : sig
type 'a t
val to_sexpable : 'a t -> 'a Sexpable.t
val of_sexpable : 'a Sexpable.t -> 'a t
end) : S1 with type 'a t := 'a M.t = struct
let t_of_sexp a_of_sexp sexp =
let s = Sexpable.t_of_sexp a_of_sexp sexp in
try M.of_sexpable s with
| exn -> of_sexp_error_exn exn sexp
;;
let sexp_of_t sexp_of_a t = Sexpable.sexp_of_t sexp_of_a (M.to_sexpable t)
end
end
module Of_sexpable2 = struct
module V1
(Sexpable : S2) (M : sig
type ('a, 'b) t
val to_sexpable : ('a, 'b) t -> ('a, 'b) Sexpable.t
val of_sexpable : ('a, 'b) Sexpable.t -> ('a, 'b) t
end) : S2 with type ('a, 'b) t := ('a, 'b) M.t = struct
let t_of_sexp a_of_sexp b_of_sexp sexp =
let s = Sexpable.t_of_sexp a_of_sexp b_of_sexp sexp in
try M.of_sexpable s with
| exn -> of_sexp_error_exn exn sexp
;;
let sexp_of_t sexp_of_a sexp_of_b t =
Sexpable.sexp_of_t sexp_of_a sexp_of_b (M.to_sexpable t)
;;
end
end
module Of_sexpable3 = struct
module V1
(Sexpable : S3) (M : sig
type ('a, 'b, 'c) t
val to_sexpable : ('a, 'b, 'c) t -> ('a, 'b, 'c) Sexpable.t
val of_sexpable : ('a, 'b, 'c) Sexpable.t -> ('a, 'b, 'c) t
end) : S3 with type ('a, 'b, 'c) t := ('a, 'b, 'c) M.t = struct
let t_of_sexp a_of_sexp b_of_sexp c_of_sexp sexp =
let s = Sexpable.t_of_sexp a_of_sexp b_of_sexp c_of_sexp sexp in
try M.of_sexpable s with
| exn -> of_sexp_error_exn exn sexp
;;
let sexp_of_t sexp_of_a sexp_of_b sexp_of_c t =
Sexpable.sexp_of_t sexp_of_a sexp_of_b sexp_of_c (M.to_sexpable t)
;;
end
end
module Of_stringable = struct
module V1 (M : Stringable.S) : sig
type t [@@deriving sexp_grammar]
include S with type t := t
end
with type t := M.t = struct
let t_of_sexp sexp =
match sexp with
| Sexplib.Sexp.Atom s ->
(try M.of_string s with
| exn -> of_sexp_error_exn exn sexp)
| Sexplib.Sexp.List _ ->
of_sexp_error
"Sexpable.Of_stringable.t_of_sexp expected an atom, but got a list"
sexp
;;
let sexp_of_t t = Sexplib.Sexp.Atom (M.to_string t)
let t_sexp_grammar : M.t Sexplib.Sexp_grammar.t =
Sexplib.Sexp_grammar.coerce string_sexp_grammar
;;
end
end
module To_stringable = struct
module V1 (M : S) : Stringable.S with type t := M.t = struct
let of_string x = Sexplib.Conv.of_string__of__of_sexp M.t_of_sexp x
let to_string x = Sexplib.Conv.string_of__of__sexp_of M.sexp_of_t x
end
end
end
module To_stringable = Stable.To_stringable.V1
| null | https://raw.githubusercontent.com/janestreet/core/d0d1b3915c9350d8e9f2b395a817659e539e6155/core/src/sexpable.ml | ocaml | open! Import
include Base.Sexpable
module Stable = struct
module Of_sexpable = struct
module V1
(Sexpable : S) (M : sig
type t
val to_sexpable : t -> Sexpable.t
val of_sexpable : Sexpable.t -> t
end) : S with type t := M.t = struct
let t_of_sexp sexp =
let s = Sexpable.t_of_sexp sexp in
try M.of_sexpable s with
| exn -> of_sexp_error_exn exn sexp
;;
let sexp_of_t t = Sexpable.sexp_of_t (M.to_sexpable t)
end
end
module Of_sexpable1 = struct
module V1
(Sexpable : S1) (M : sig
type 'a t
val to_sexpable : 'a t -> 'a Sexpable.t
val of_sexpable : 'a Sexpable.t -> 'a t
end) : S1 with type 'a t := 'a M.t = struct
let t_of_sexp a_of_sexp sexp =
let s = Sexpable.t_of_sexp a_of_sexp sexp in
try M.of_sexpable s with
| exn -> of_sexp_error_exn exn sexp
;;
let sexp_of_t sexp_of_a t = Sexpable.sexp_of_t sexp_of_a (M.to_sexpable t)
end
end
module Of_sexpable2 = struct
module V1
(Sexpable : S2) (M : sig
type ('a, 'b) t
val to_sexpable : ('a, 'b) t -> ('a, 'b) Sexpable.t
val of_sexpable : ('a, 'b) Sexpable.t -> ('a, 'b) t
end) : S2 with type ('a, 'b) t := ('a, 'b) M.t = struct
let t_of_sexp a_of_sexp b_of_sexp sexp =
let s = Sexpable.t_of_sexp a_of_sexp b_of_sexp sexp in
try M.of_sexpable s with
| exn -> of_sexp_error_exn exn sexp
;;
let sexp_of_t sexp_of_a sexp_of_b t =
Sexpable.sexp_of_t sexp_of_a sexp_of_b (M.to_sexpable t)
;;
end
end
module Of_sexpable3 = struct
module V1
(Sexpable : S3) (M : sig
type ('a, 'b, 'c) t
val to_sexpable : ('a, 'b, 'c) t -> ('a, 'b, 'c) Sexpable.t
val of_sexpable : ('a, 'b, 'c) Sexpable.t -> ('a, 'b, 'c) t
end) : S3 with type ('a, 'b, 'c) t := ('a, 'b, 'c) M.t = struct
let t_of_sexp a_of_sexp b_of_sexp c_of_sexp sexp =
let s = Sexpable.t_of_sexp a_of_sexp b_of_sexp c_of_sexp sexp in
try M.of_sexpable s with
| exn -> of_sexp_error_exn exn sexp
;;
let sexp_of_t sexp_of_a sexp_of_b sexp_of_c t =
Sexpable.sexp_of_t sexp_of_a sexp_of_b sexp_of_c (M.to_sexpable t)
;;
end
end
module Of_stringable = struct
module V1 (M : Stringable.S) : sig
type t [@@deriving sexp_grammar]
include S with type t := t
end
with type t := M.t = struct
let t_of_sexp sexp =
match sexp with
| Sexplib.Sexp.Atom s ->
(try M.of_string s with
| exn -> of_sexp_error_exn exn sexp)
| Sexplib.Sexp.List _ ->
of_sexp_error
"Sexpable.Of_stringable.t_of_sexp expected an atom, but got a list"
sexp
;;
let sexp_of_t t = Sexplib.Sexp.Atom (M.to_string t)
let t_sexp_grammar : M.t Sexplib.Sexp_grammar.t =
Sexplib.Sexp_grammar.coerce string_sexp_grammar
;;
end
end
module To_stringable = struct
module V1 (M : S) : Stringable.S with type t := M.t = struct
let of_string x = Sexplib.Conv.of_string__of__of_sexp M.t_of_sexp x
let to_string x = Sexplib.Conv.string_of__of__sexp_of M.sexp_of_t x
end
end
end
module To_stringable = Stable.To_stringable.V1
|
|
3591c5a3ba12a7b2a4343503d52c0adf8639d00411b26c4a35656c5ae9100dc0 | liquidz/antq | boot.clj | (ns antq.dep.boot
(:require
[antq.constant :as const]
[antq.record :as r]
[antq.util.dep :as u.dep]
[clojure.java.io :as io]
[clojure.walk :as walk]))
(def ^:private project-file "build.boot")
(defn- exclude?
[v]
(-> (meta v)
(contains? const/deps-exclude-key)))
(defn extract-deps
{:malli/schema [:=>
[:cat 'string? 'string?]
[:sequential r/?dependency]]}
[file-path build-boot-content-str]
(let [dep-form? (atom false)
repos-form? (atom false)
deps (atom [])
repos (atom [])]
(walk/prewalk (fn [form]
(cond
(keyword? form)
(do (reset! dep-form? (= :dependencies form))
(reset! repos-form? (= :repositories form)))
(and @dep-form?
(vector? form)
(vector? (first form)))
(->> form
(seq)
(remove exclude?)
(swap! deps concat))
(and @repos-form?
(vector? form)
(string? (first form)))
(swap! repos concat form))
form)
(read-string (str "(list " build-boot-content-str " )")))
(let [repositories (apply hash-map @repos)]
(for [[dep-name version] @deps
:when (and (string? version) (seq version))]
(r/map->Dependency {:project :boot
:type :java
:file file-path
:name (if (qualified-symbol? dep-name)
(str dep-name)
(str dep-name "/" dep-name))
:version version
:repositories repositories})))))
(defn load-deps
{:malli/schema [:function
[:=> :cat [:maybe [:sequential r/?dependency]]]
[:=> [:cat 'string?] [:maybe [:sequential r/?dependency]]]]}
([] (load-deps "."))
([dir]
(let [file (io/file dir project-file)]
(when (.exists file)
(extract-deps (u.dep/relative-path file)
(slurp file))))))
| null | https://raw.githubusercontent.com/liquidz/antq/51b257d94761a4642c6d35e65774a060248624b7/src/antq/dep/boot.clj | clojure | (ns antq.dep.boot
(:require
[antq.constant :as const]
[antq.record :as r]
[antq.util.dep :as u.dep]
[clojure.java.io :as io]
[clojure.walk :as walk]))
(def ^:private project-file "build.boot")
(defn- exclude?
[v]
(-> (meta v)
(contains? const/deps-exclude-key)))
(defn extract-deps
{:malli/schema [:=>
[:cat 'string? 'string?]
[:sequential r/?dependency]]}
[file-path build-boot-content-str]
(let [dep-form? (atom false)
repos-form? (atom false)
deps (atom [])
repos (atom [])]
(walk/prewalk (fn [form]
(cond
(keyword? form)
(do (reset! dep-form? (= :dependencies form))
(reset! repos-form? (= :repositories form)))
(and @dep-form?
(vector? form)
(vector? (first form)))
(->> form
(seq)
(remove exclude?)
(swap! deps concat))
(and @repos-form?
(vector? form)
(string? (first form)))
(swap! repos concat form))
form)
(read-string (str "(list " build-boot-content-str " )")))
(let [repositories (apply hash-map @repos)]
(for [[dep-name version] @deps
:when (and (string? version) (seq version))]
(r/map->Dependency {:project :boot
:type :java
:file file-path
:name (if (qualified-symbol? dep-name)
(str dep-name)
(str dep-name "/" dep-name))
:version version
:repositories repositories})))))
(defn load-deps
{:malli/schema [:function
[:=> :cat [:maybe [:sequential r/?dependency]]]
[:=> [:cat 'string?] [:maybe [:sequential r/?dependency]]]]}
([] (load-deps "."))
([dir]
(let [file (io/file dir project-file)]
(when (.exists file)
(extract-deps (u.dep/relative-path file)
(slurp file))))))
|
|
d7a11f6c11589cf1b3455776de490919e60ae12f53476103fefb04c3e3973b04 | dergraf/epmdpxy | epmdpxy_session.erl | -module(epmdpxy_session).
-behaviour(gen_server).
%% API
-export([start_link/2,
accept/1,
cut_cable/1,
fix_cable/1,
status/1]).
%% gen_server callbacks
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-record(state, {status=not_ready,
downstream_name,
upstream_name,
upstream_port,
listen_socket,
downstream_socket,
upstream_socket,
tref}).
-define(CLOSE_AFTER, 120000). %% should be larger than netsplit time
%%%===================================================================
%%% API
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Starts the server
%%
( ) - > { ok , Pid } | ignore | { error , Error }
%% @end
%%--------------------------------------------------------------------
start_link(Name, Port) ->
gen_server:start_link(?MODULE, [Name, Port], []).
accept(Pid) ->
gen_server:call(Pid, accept).
cut_cable(Pid) ->
gen_server:call(Pid, cut_cable).
fix_cable(Pid) ->
gen_server:call(Pid, fix_cable).
status(Pid) ->
gen_server:call(Pid, status).
%%%===================================================================
%%% gen_server callbacks
%%%===================================================================
%%--------------------------------------------------------------------
@private
%% @doc
%% Initializes the server
%%
) - > { ok , State } |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%% @end
%%--------------------------------------------------------------------
init([Name, Port]) ->
{ok, ListenSocket} = gen_tcp:listen(0, [binary]),
{ok, #state{
upstream_name=Name,
upstream_port=Port,
listen_socket=ListenSocket}}.
%%--------------------------------------------------------------------
@private
%% @doc
%% Handling call messages
%%
, From , State ) - >
%% {reply, Reply, State} |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} |
%% {stop, Reason, State}
%% @end
%%--------------------------------------------------------------------
handle_call(accept, From, #state{listen_socket=ListenSocket} = State) ->
{ok, ListenPort} = inet:port(ListenSocket),
gen_server:reply(From, ListenPort),
{ok, Socket} = gen_tcp:accept(ListenSocket),
{noreply, State#state{downstream_socket=Socket}};
handle_call(cut_cable, _From, #state{downstream_socket=S,
upstream_socket=UpS} = State) ->
inet:setopts(S, [{active, false}]),
inet:setopts(UpS, [{active, false}]),
{reply, ok, State#state{status=cut}};
handle_call(fix_cable, _From, #state{downstream_socket=S,
upstream_socket=UpS} = State) ->
inet:setopts(S, [{active, true}]),
inet:setopts(UpS, [{active, true}]),
{reply, ok, State#state{status=ready}};
handle_call(status, _From, State) ->
#state{status=Status,
downstream_name=DownName,
upstream_name=UpName} = State,
{reply, [{pid, self()},
{downstream, DownName},
{upstream, UpName},
{status, Status}], State};
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
%%--------------------------------------------------------------------
@private
%% @doc
%% Handling cast messages
%%
@spec handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% @end
%%--------------------------------------------------------------------
handle_cast(_Msg, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
@private
%% @doc
%% Handling all non call/cast messages
%%
, State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% @end
%%--------------------------------------------------------------------
handle_info({tcp, DownSocket, Data}, #state{downstream_name=undefined,
downstream_socket=DownSocket,
upstream_name=UpName} = State) ->
case parse_name(UpName, Data) of
undefined ->
{stop, invalid_data, State};
{DownstreamName, IsActive} ->
case maybe_connect(State) of
{ok, #state{upstream_socket=UpSocket} = NewState} ->
inet:setopts(DownSocket, [{active, IsActive}]),
inet:setopts(UpSocket, [{active, IsActive}]),
gen_tcp:send(UpSocket, Data),
{noreply, NewState#state{
downstream_name=DownstreamName,
status=case IsActive of true -> ready; _ -> cut end,
tref=erlang:send_after(?CLOSE_AFTER, self(), die)
}};
{error, Reason} ->
gen_tcp:close(DownSocket),
{stop, Reason, State}
end
end;
handle_info(die, State) ->
{stop, normal, State};
handle_info({tcp, DownS, Data}, #state{downstream_socket=DownS,
upstream_socket=UpS,
tref=TRef} = State) ->
erlang:cancel_timer(TRef),
gen_tcp:send(UpS, Data),
{noreply, State#state{tref=erlang:send_after(?CLOSE_AFTER, self(), die)}};
handle_info({tcp, UpS, Data}, #state{downstream_socket=DownS,
upstream_socket=UpS,
tref=TRef} = State) ->
erlang:cancel_timer(TRef),
gen_tcp:send(DownS, Data),
{noreply, State#state{tref=erlang:send_after(?CLOSE_AFTER, self(), die)}};
handle_info({tcp_closed, _}, State) ->
{stop, normal, State};
handle_info({tcp_error, _, Error}, State) ->
{stop, Error, State}.
%%--------------------------------------------------------------------
@private
%% @doc
%% This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any
%% necessary cleaning up. When it returns, the gen_server terminates
with . The return value is ignored .
%%
, State ) - > void ( )
%% @end
%%--------------------------------------------------------------------
terminate(_Reason, #state{upstream_name=UpstreamName,
downstream_name=DownstreamName}) ->
epmdpxy_session_sup:connection_deleted(self(), DownstreamName,
UpstreamName),
ok.
%%--------------------------------------------------------------------
@private
%% @doc
%% Convert process state when code is changed
%%
, State , Extra ) - > { ok , NewState }
%% @end
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%===================================================================
Internal functions
%%%===================================================================
maybe_connect(#state{upstream_port=Port, upstream_socket=undefined} = State) ->
case gen_tcp:connect({127,0,0,1}, Port, [binary, {active, true}]) of
{ok, Socket} ->
{ok, State#state{upstream_socket=Socket}};
{error, Reason} ->
{error, Reason}
end;
maybe_connect(State) ->
{ok, State}.
parse_name(UpstreamName, Data) ->
case parse_name(Data) of
undefined ->
undefined;
DownstreamName ->
process_flag(trap_exit, true),
Active = epmdpxy_session_sup:connection_created(self(), DownstreamName,
UpstreamName),
{DownstreamName, Active}
end.
parse_name(<<_Len:16, "n", _Version:16, _Flags:32, DownstreamName/binary>>) ->
DownstreamName;
parse_name(<<_Len:16, "N", _Flags:64, _Creation:32, _NLen:16, DownstreamName/binary>>) ->
DownstreamName;
parse_name(_) ->
undefined. | null | https://raw.githubusercontent.com/dergraf/epmdpxy/646506ba2117cb5ac81b9d37c2fe5cb7f042b043/src/epmdpxy_session.erl | erlang | API
gen_server callbacks
should be larger than netsplit time
===================================================================
API
===================================================================
--------------------------------------------------------------------
@doc
Starts the server
@end
--------------------------------------------------------------------
===================================================================
gen_server callbacks
===================================================================
--------------------------------------------------------------------
@doc
Initializes the server
ignore |
{stop, Reason}
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Handling call messages
{reply, Reply, State} |
{stop, Reason, Reply, State} |
{stop, Reason, State}
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Handling cast messages
{stop, Reason, State}
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Handling all non call/cast messages
{stop, Reason, State}
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
This function is called by a gen_server when it is about to
terminate. It should be the opposite of Module:init/1 and do any
necessary cleaning up. When it returns, the gen_server terminates
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Convert process state when code is changed
@end
--------------------------------------------------------------------
===================================================================
=================================================================== | -module(epmdpxy_session).
-behaviour(gen_server).
-export([start_link/2,
accept/1,
cut_cable/1,
fix_cable/1,
status/1]).
-export([init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-record(state, {status=not_ready,
downstream_name,
upstream_name,
upstream_port,
listen_socket,
downstream_socket,
upstream_socket,
tref}).
( ) - > { ok , Pid } | ignore | { error , Error }
start_link(Name, Port) ->
gen_server:start_link(?MODULE, [Name, Port], []).
accept(Pid) ->
gen_server:call(Pid, accept).
cut_cable(Pid) ->
gen_server:call(Pid, cut_cable).
fix_cable(Pid) ->
gen_server:call(Pid, fix_cable).
status(Pid) ->
gen_server:call(Pid, status).
@private
) - > { ok , State } |
{ ok , State , Timeout } |
init([Name, Port]) ->
{ok, ListenSocket} = gen_tcp:listen(0, [binary]),
{ok, #state{
upstream_name=Name,
upstream_port=Port,
listen_socket=ListenSocket}}.
@private
, From , State ) - >
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call(accept, From, #state{listen_socket=ListenSocket} = State) ->
{ok, ListenPort} = inet:port(ListenSocket),
gen_server:reply(From, ListenPort),
{ok, Socket} = gen_tcp:accept(ListenSocket),
{noreply, State#state{downstream_socket=Socket}};
handle_call(cut_cable, _From, #state{downstream_socket=S,
upstream_socket=UpS} = State) ->
inet:setopts(S, [{active, false}]),
inet:setopts(UpS, [{active, false}]),
{reply, ok, State#state{status=cut}};
handle_call(fix_cable, _From, #state{downstream_socket=S,
upstream_socket=UpS} = State) ->
inet:setopts(S, [{active, true}]),
inet:setopts(UpS, [{active, true}]),
{reply, ok, State#state{status=ready}};
handle_call(status, _From, State) ->
#state{status=Status,
downstream_name=DownName,
upstream_name=UpName} = State,
{reply, [{pid, self()},
{downstream, DownName},
{upstream, UpName},
{status, Status}], State};
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
@private
@spec handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_cast(_Msg, State) ->
{noreply, State}.
@private
, State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_info({tcp, DownSocket, Data}, #state{downstream_name=undefined,
downstream_socket=DownSocket,
upstream_name=UpName} = State) ->
case parse_name(UpName, Data) of
undefined ->
{stop, invalid_data, State};
{DownstreamName, IsActive} ->
case maybe_connect(State) of
{ok, #state{upstream_socket=UpSocket} = NewState} ->
inet:setopts(DownSocket, [{active, IsActive}]),
inet:setopts(UpSocket, [{active, IsActive}]),
gen_tcp:send(UpSocket, Data),
{noreply, NewState#state{
downstream_name=DownstreamName,
status=case IsActive of true -> ready; _ -> cut end,
tref=erlang:send_after(?CLOSE_AFTER, self(), die)
}};
{error, Reason} ->
gen_tcp:close(DownSocket),
{stop, Reason, State}
end
end;
handle_info(die, State) ->
{stop, normal, State};
handle_info({tcp, DownS, Data}, #state{downstream_socket=DownS,
upstream_socket=UpS,
tref=TRef} = State) ->
erlang:cancel_timer(TRef),
gen_tcp:send(UpS, Data),
{noreply, State#state{tref=erlang:send_after(?CLOSE_AFTER, self(), die)}};
handle_info({tcp, UpS, Data}, #state{downstream_socket=DownS,
upstream_socket=UpS,
tref=TRef} = State) ->
erlang:cancel_timer(TRef),
gen_tcp:send(DownS, Data),
{noreply, State#state{tref=erlang:send_after(?CLOSE_AFTER, self(), die)}};
handle_info({tcp_closed, _}, State) ->
{stop, normal, State};
handle_info({tcp_error, _, Error}, State) ->
{stop, Error, State}.
@private
with . The return value is ignored .
, State ) - > void ( )
terminate(_Reason, #state{upstream_name=UpstreamName,
downstream_name=DownstreamName}) ->
epmdpxy_session_sup:connection_deleted(self(), DownstreamName,
UpstreamName),
ok.
@private
, State , Extra ) - > { ok , NewState }
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
maybe_connect(#state{upstream_port=Port, upstream_socket=undefined} = State) ->
case gen_tcp:connect({127,0,0,1}, Port, [binary, {active, true}]) of
{ok, Socket} ->
{ok, State#state{upstream_socket=Socket}};
{error, Reason} ->
{error, Reason}
end;
maybe_connect(State) ->
{ok, State}.
parse_name(UpstreamName, Data) ->
case parse_name(Data) of
undefined ->
undefined;
DownstreamName ->
process_flag(trap_exit, true),
Active = epmdpxy_session_sup:connection_created(self(), DownstreamName,
UpstreamName),
{DownstreamName, Active}
end.
parse_name(<<_Len:16, "n", _Version:16, _Flags:32, DownstreamName/binary>>) ->
DownstreamName;
parse_name(<<_Len:16, "N", _Flags:64, _Creation:32, _NLen:16, DownstreamName/binary>>) ->
DownstreamName;
parse_name(_) ->
undefined. |
05974a6c30af10c552c38c2cc3911563c4a259917e0ab4a2182d3cc96a11b5c8 | arcfide/chez-srfi | link-dirs.chezscheme.sps | #! /usr/bin/env scheme-script
Copyright ( c ) 2012 < >
;;;
;;; Permission to use, copy, modify, and distribute this software for
;;; any purpose with or without fee is hereby granted, provided that the
;;; above copyright notice and this permission notice appear in all
;;; copies.
;;;
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL
;;; WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
;;; AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
;;; DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
;;; TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
;;; PERFORMANCE OF THIS SOFTWARE.
(import (chezscheme))
;;; Link all of the SRFIs to their normal directories like sane
people who use Chez Scheme prefer . :-)
(define (translate-name name)
(let f ([i 0] [j 0])
(if (fx= i (string-length name))
(make-string j)
(let ([c (string-ref name i)])
(cond
[(and (char=? c #\%)
(let ([next-i (fx+ i 3)])
(and (fx<= next-i (string-length name)) next-i))) =>
(lambda (next-i)
(let ([translated-name (f next-i (fx+ j 1))])
(string-set! translated-name j
(integer->char
(string->number
(substring name (fx+ i 1) next-i) 16)))
translated-name))]
[else
(let ([translated-name (f (fx+ i 1) (fx+ j 1))])
(string-set! translated-name j c)
translated-name)])))))
(define (link-files!)
(let file-loop ([ls (directory-list (current-directory))])
(unless (null? ls)
(let ([name (car ls)])
(let ([translated-name (translate-name name)])
(unless (or (string=? name translated-name)
(file-exists? translated-name))
(system (format "ln -sf '~a' '~a'" name translated-name)))
(when (file-directory? translated-name)
(parameterize ([current-directory translated-name])
(link-files!)))
(file-loop (cdr ls)))))))
(link-files!)
| null | https://raw.githubusercontent.com/arcfide/chez-srfi/96fb553b6ba0834747d5ccfc08c181aa8fd5f612/link-dirs.chezscheme.sps | scheme |
Permission to use, copy, modify, and distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all
copies.
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
Link all of the SRFIs to their normal directories like sane | #! /usr/bin/env scheme-script
Copyright ( c ) 2012 < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL
OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
(import (chezscheme))
people who use Chez Scheme prefer . :-)
(define (translate-name name)
(let f ([i 0] [j 0])
(if (fx= i (string-length name))
(make-string j)
(let ([c (string-ref name i)])
(cond
[(and (char=? c #\%)
(let ([next-i (fx+ i 3)])
(and (fx<= next-i (string-length name)) next-i))) =>
(lambda (next-i)
(let ([translated-name (f next-i (fx+ j 1))])
(string-set! translated-name j
(integer->char
(string->number
(substring name (fx+ i 1) next-i) 16)))
translated-name))]
[else
(let ([translated-name (f (fx+ i 1) (fx+ j 1))])
(string-set! translated-name j c)
translated-name)])))))
(define (link-files!)
(let file-loop ([ls (directory-list (current-directory))])
(unless (null? ls)
(let ([name (car ls)])
(let ([translated-name (translate-name name)])
(unless (or (string=? name translated-name)
(file-exists? translated-name))
(system (format "ln -sf '~a' '~a'" name translated-name)))
(when (file-directory? translated-name)
(parameterize ([current-directory translated-name])
(link-files!)))
(file-loop (cdr ls)))))))
(link-files!)
|
027a6637dbbe14605f9429a09dec253138d189843e5f223c83f25c96ab2a3741 | yurug/ocaml4.04.0-copatterns | reachable_words.ml | let native =
match Filename.basename Sys.argv.(0) with
| "program.byte" | "program.byte.exe" -> false
| "program.native" | "program.native.exe" -> true
| s -> print_endline s; assert false
let size x = Obj.reachable_words (Obj.repr x)
let expect_size s x =
let i = size x in
if i <> s then
Printf.printf "size = %i; expected = %i\n%!" i s
type t =
| A of int
| B of t * t
let f () =
let x = Random.int 10 in
expect_size 0 42;
expect_size (if native then 0 else 3) (1, 2);
expect_size 2 [| x |];
expect_size 3 [| x; 0 |];
let a = A x in
expect_size 2 a;
expect_size 5 (B (a, a)); (* sharing *)
expect_size 7 (B (a, A (x + 1)));
let rec b = B (a, b) in (* cycle *)
expect_size 5 b;
print_endline "OK"
let () =
f ()
| null | https://raw.githubusercontent.com/yurug/ocaml4.04.0-copatterns/b3ec6a3cc203bd2cde3b618546d29e10f1102323/testsuite/tests/lib-obj/reachable_words.ml | ocaml | sharing
cycle | let native =
match Filename.basename Sys.argv.(0) with
| "program.byte" | "program.byte.exe" -> false
| "program.native" | "program.native.exe" -> true
| s -> print_endline s; assert false
let size x = Obj.reachable_words (Obj.repr x)
let expect_size s x =
let i = size x in
if i <> s then
Printf.printf "size = %i; expected = %i\n%!" i s
type t =
| A of int
| B of t * t
let f () =
let x = Random.int 10 in
expect_size 0 42;
expect_size (if native then 0 else 3) (1, 2);
expect_size 2 [| x |];
expect_size 3 [| x; 0 |];
let a = A x in
expect_size 2 a;
expect_size 7 (B (a, A (x + 1)));
expect_size 5 b;
print_endline "OK"
let () =
f ()
|
8873187c534296ff0b9b527e3a695c5bb7a494194b9757a7feaf42cb5a1e13d0 | xvw/muhokama | topic_views.ml | open Lib_common
open Lib_service
module Create = struct
let category_select categories category_id =
let open Tyxml.Html in
let options =
Preface.Nonempty_list.map
(fun category ->
let open Models.Category in
let selected =
if category_id
|> Option.map (fun x -> x = category.id)
|> Option.value ~default:false
then [ a_selected () ]
else []
in
option ~a:([ a_value category.id ] @ selected) @@ txt category.name)
categories
|> Preface.Nonempty_list.to_list
in
div
~a:[ a_class [ "field" ] ]
[ label
~a:[ a_class [ "label" ]; a_label_for "create_topic_category_id" ]
[ (if Option.is_none category_id
then txt "CatΓ©gorie dans laquelle crΓ©er le fil de conversation"
else txt "CatΓ©gorie du fil de conversation")
]
; div
~a:[ a_class [ "control" ] ]
[ div
~a:[ a_class [ "select"; "is-large"; "is-fullwidth" ] ]
[ select
~a:[ a_id "create_topic_category_id"; a_name "category_id" ]
options
]
]
]
;;
let topic_title_input title =
let title_value = Option.value ~default:"" title in
let open Tyxml.Html in
div
~a:[ a_class [ "field" ] ]
[ label
~a:[ a_class [ "label" ]; a_label_for "create_topic_title" ]
[ txt "Titre du topic" ]
; div
~a:[ a_class [ "control" ] ]
[ input
~a:
[ a_input_type `Text
; a_placeholder "Un titre comprΓ©hensible"
; a_id "create_topic_title"
; a_name "topic_title"
; a_class [ "input" ]
; a_value title_value
]
()
]
; p
~a:[ a_class [ "help" ] ]
[ txt
"Essayez de trouver un titre clair qui indique rapidement la \
thΓ©matique du fil de conversation."
]
]
;;
let topic_content_input content =
let content_value = Option.value ~default:"" content in
let open Tyxml.Html in
div
~a:[ a_class [ "field" ] ]
[ label
~a:[ a_class [ "label" ]; a_label_for "create_topic_content" ]
[ txt "Contenu du message" ]
; div
~a:[ a_class [ "control" ] ]
[ textarea
~a:
[ a_placeholder "Ecrivez ici votre message (en Markdown) ..."
; a_id "create_topic_content"
; a_rows 15
; a_name "topic_content"
; a_class [ "textarea"; "is-large" ]
]
(txt content_value)
]
]
;;
let submit_buttons topic_id =
let button_msg =
if Option.is_none topic_id then "CrΓ©er le fil" else "Modifier le message"
in
let open Tyxml.Html in
div
~a:[ a_class [ "field" ] ]
[ div
~a:[ a_class [ "control" ] ]
[ input
~a:
[ a_input_type `Submit
; a_name "Preview"
; a_value "PrΓ©visualiser le message"
; a_class [ "button"; "is-link" ]
]
()
; input
~a:
[ a_input_type `Submit
; a_name "Submit"
; a_value button_msg
; a_class [ "button"; "is-link" ]
]
()
]
]
;;
let creation_form
?topic_id
?pre_category_id
?pre_title
?pre_content
csrf_token
categories
=
let params =
[ category_select categories pre_category_id
; topic_title_input pre_title
; topic_content_input pre_content
; submit_buttons topic_id
]
in
let form =
Option.fold
~none:(fun () ->
Templates.Util.form ~:Endpoints.Topic.save ~csrf_token params)
~some:(fun topic_id () ->
Templates.Util.form
~:Endpoints.Topic.save_edit
~csrf_token
params
topic_id)
topic_id
in
form ()
;;
end
module List = struct
let line topic =
let open Tyxml.Html in
let open Models.Topic.Listable in
let src = Gravatar.(url ~default:Identicon ~size:48 topic.user_email) in
let alt = "Avatar of " ^ topic.user_name in
let responses_suffix = if topic.responses > 1 then "s" else "" in
let responses = Fmt.str "%d rΓ©ponse%s" topic.responses responses_suffix in
tr
[ td
~a:[ a_class [ "is-vcentered" ] ]
[ Templates.Util.with_tooltip
(img ~a:[ a_class [ "image"; "is-48x48" ] ] ~src ~alt ())
topic.user_name
]
; td
~a:[ a_class [ "is-vcentered"; "is-fullwidth" ] ]
[ Templates.Util.a ~:Endpoints.Topic.show [ txt topic.title ] topic.id
]
; td
~a:[ a_class [ "is-vcentered" ] ]
[ span ~a:[ a_class [ "is-pulled-right" ] ] [ txt responses ] ]
; td
~a:[ a_class [ "is-vcentered" ] ]
[ Templates.Util.a
~:Endpoints.Topic.by_category
~a:[ a_class [ "button"; "is-info"; "is-pulled-right" ] ]
[ txt @@ Lib_common.Html.escape_special_chars topic.category_name
]
topic.category_name
]
]
;;
let all topics =
let open Tyxml.Html in
table
~a:
[ a_class
[ "table"; "is-fullwidth"; "is-stripped"; "content"; "is-medium" ]
]
@@ List.map line topics
;;
end
module Show = struct
let edition_link kind current_user user_id id =
let open Tyxml.Html in
if Models.User.can_edit ~owner_id:user_id current_user
Previewed messages have no edit link
then (
match kind with
| `Topic ->
Templates.Util.a
~:Endpoints.Topic.edit
~a:[ a_class [ "pl-4" ] ]
[ txt "Γditer" ]
id
| `Message t_id ->
Templates.Util.a
~:Endpoints.Topic.edit_message
~a:[ a_class [ "pl-4" ] ]
[ txt "Γditer" ]
t_id
id
| `Preview -> span [])
else span []
;;
let show_content
kind
current_user
user_id
user_name
user_email
id
creation_date
message
=
let open Tyxml.Html in
FIXME : Maybe get rid of . Html . Unsafe
let message_html = Unsafe.data message in
div
~a:[ a_class [ "media" ] ]
[ div
~a:[ a_class [ "media-left" ] ]
[ Templates.Component.avatar ~email:user_email ~username:user_name ()
]
; div
~a:[ a_class [ "media-content" ] ]
[ p ~a:[ a_class [ "title"; "is-6" ] ] [ txt @@ "@" ^ user_name ]
; p
~a:[ a_class [ "subtitle"; "is-6" ] ]
[ span
[ txt
@@ "publiΓ© le "
^ Templates.Util.format_date creation_date
]
; edition_link kind current_user user_id id
]
; div
~a:[ a_class [ "content"; "is-medium"; "media-content" ] ]
[ p [ message_html ] ]
]
]
;;
let message_content_input ?(message_content = "") () =
let open Tyxml.Html in
div
~a:[ a_class [ "field" ] ]
[ div
~a:[ a_class [ "control" ] ]
[ textarea
~a:
[ a_placeholder "Ecrivez ici votre message (en Markdown) ..."
; a_id "create_topic_content"
; a_rows 8
; a_name "message_content"
; a_class [ "textarea"; "is-large" ]
]
(txt message_content)
]
]
;;
let submit_buttons kind =
let message =
match kind with
| `Answer -> "RΓ©pondre au fil !"
| `Edit -> "Γditer le message !"
in
let open Tyxml.Html in
div
~a:[ a_class [ "field" ] ]
[ div
~a:[ a_class [ "control" ] ]
[ input
~a:
[ a_input_type `Submit
; a_name "Preview"
; a_value "PrΓ©visualiser le message !"
; a_class [ "button"; "is-link" ]
]
()
(* TODO: space between buttons? *)
; input
~a:
[ a_input_type `Submit
; a_name "Answer"
; a_value message
; a_class [ "button"; "is-link" ]
]
()
]
]
;;
let message_form ?(prefilled = "") csrf_token user topic =
let open Tyxml.Html in
let topic_id = topic.Models.Topic.Showable.id in
div
[ h2 ~a:[ a_class [ "title"; "mt-6" ] ] [ txt "Composer une rΓ©ponse" ]
; div
~a:[ a_class [ "media" ]; a_id "answer" ]
[ div
~a:[ a_class [ "media-left" ] ]
[ Templates.Component.avatar
~email:user.Models.User.email
~username:user.name
()
]
; div
~a:[ a_class [ "media-content" ] ]
[ Templates.Util.form
~anchor:"answer"
~:Endpoints.Topic.answer
~csrf_token
[ message_content_input ~message_content:prefilled ()
; submit_buttons `Answer
]
topic_id
]
]
]
;;
let archive_button user topic =
if Models.User.can_moderate user
then
let open Tyxml.Html in
[ Templates.Util.a
~:Endpoints.Topic.archive
~a:
[ a_href "#answer"; a_class [ "button"; "is-danger"; "is-medium" ] ]
[ txt "Archiver" ]
topic.Models.Topic.Showable.id
]
else []
;;
let topic_content ?(show_buttons = true) user topic =
let open Tyxml.Html in
let open Models.Topic.Showable in
let answer_button =
a
~a:[ a_href "#answer"; a_class [ "button"; "is-success"; "is-medium" ] ]
[ txt "RΓ©pondre au fil" ]
in
div
[ div
~a:[ a_class [ "columns" ] ]
[ div
~a:[ a_class [ "column" ] ]
[ h1 ~a:[ a_class [ "title" ] ] [ txt topic.title ] ]
; div
~a:[ a_class [ "column"; "is-narrow"; "is-hidden-mobile" ] ]
(if show_buttons
then answer_button :: archive_button user topic
else [])
]
; show_content
`Topic
user
topic.user_id
topic.user_name
topic.user_email
topic.id
topic.creation_date
topic.content
]
;;
let thread ?prefilled csrf_token user topic messages =
let open Tyxml.Html in
(topic_content user topic
:: Stdlib.List.map
(fun message ->
div
~a:
(a_id message.Models.Message.id
:: (if message.id = "" then [ a_class [ "preview" ] ] else []))
[ hr ~a:[ a_class [ "mt-6"; "mb-6" ] ] ()
; show_content
(`Message topic.id)
user
message.user_id
message.user_name
message.user_email
message.id
message.creation_date
message.content
])
messages)
@ [ message_form ?prefilled csrf_token user topic ]
;;
end
module Message = struct
let edit ?preview csrf_token user topic_id message =
let open Tyxml.Html in
let open Models.Message in
let avatar =
div
~a:[ a_class [ "media-left" ] ]
[ Templates.Component.avatar
~email:message.user_email
~username:message.user_name
()
]
in
let preview =
match preview with
| None -> []
| Some raw_content ->
[ div
~a:[ a_id message.Models.Message.id ]
[ hr ~a:[ a_class [ "mt-6"; "mb-6" ] ] ()
; Show.show_content
`Preview
user
message.user_id
message.user_name
message.user_email
message.id
message.creation_date
raw_content
; hr ~a:[ a_class [ "mt-6"; "mb-6" ] ] ()
]
]
in
let message_ctn =
Show.message_content_input ~message_content:message.content ()
in
[ div
((if user.Models.User.id <> message.user_id
then
[ Templates.Component.flash_info
(Some
(Models.Flash_info.Info
"Vous allez modifier un contenu dont vous n'Γͺtes pas le \
propriΓ©taire"))
]
else [])
@ preview
@ [ h2 ~a:[ a_class [ "title"; "mt-6" ] ] [ txt "Γditer le message" ]
; div
~a:[ a_class [ "media" ]; a_id "answer" ]
[ avatar
; div
~a:[ a_class [ "media-content" ] ]
[ Templates.Util.form
~:Endpoints.Topic.save_edit_message
~csrf_token
[ message_ctn; Show.submit_buttons `Edit ]
topic_id
message.id
]
]
])
]
;;
end
let topic_form
?flash_info
?preview
~csrf_token
~user
?topic_id
?pre_title
?pre_content
?pre_category_id
categories
=
let open Tyxml.Html in
let page_title =
if Option.is_none topic_id
then "CrΓ©er un nouveau topic"
else "Γditer un message"
in
let preview =
Option.fold
~some:(fun topic ->
[ div [ Show.topic_content ~show_buttons:false user topic ] ])
~none:[ div [] ]
preview
in
Templates.Layout.default
~lang:"fr"
~page_title
~user
?flash_info
(preview
@ [ div
[ Create.creation_form
?pre_category_id
?pre_title
?pre_content
?topic_id
csrf_token
categories
]
])
;;
let topic_form ?flash_info ?preview ?prefilled ~csrf_token ~user categories =
Option.fold
~none:(topic_form ?flash_info ?preview ~csrf_token ~user categories)
~some:(fun topic ->
let open Models.Topic.Showable in
topic_form
?flash_info
?preview
~csrf_token
~user
?topic_id:(if String.length topic.id > 0 then Some topic.id else None)
~pre_title:topic.title
~pre_content:topic.content
~pre_category_id:topic.category_id
categories)
prefilled
;;
let create ?flash_info ?preview ?prefilled ~csrf_token ~user categories =
topic_form ?flash_info ?preview ?prefilled ~csrf_token ~user categories
;;
let edit ?flash_info ?preview ~prefilled ~csrf_token ~user categories =
topic_form ?flash_info ?preview ~prefilled ~csrf_token ~user categories
;;
let list ?flash_info ?user topics =
Templates.Layout.default
~lang:"fr"
~page_title:"Accueil"
?flash_info
?user
Tyxml.Html.[ div [ List.all topics ] ]
;;
let show ?flash_info ?prefilled ~csrf_token ~user topic messages =
let page_title = topic.Models.Topic.Showable.title in
Templates.Layout.default
~lang:"fr"
~page_title
?flash_info
~user
(Show.thread ?prefilled csrf_token user topic messages)
;;
let edit_message ?flash_info ?preview ~csrf_token ~user topic_id message =
let page_title = "Γditer un message" in
Templates.Layout.default
~lang:"fr"
~page_title
?flash_info
~user
(Message.edit ?preview csrf_token user topic_id message)
;;
| null | https://raw.githubusercontent.com/xvw/muhokama/dcb71b5b7055249d2d03e4d609c3cdbb61a05276/app/views/topic_views.ml | ocaml | TODO: space between buttons? | open Lib_common
open Lib_service
module Create = struct
let category_select categories category_id =
let open Tyxml.Html in
let options =
Preface.Nonempty_list.map
(fun category ->
let open Models.Category in
let selected =
if category_id
|> Option.map (fun x -> x = category.id)
|> Option.value ~default:false
then [ a_selected () ]
else []
in
option ~a:([ a_value category.id ] @ selected) @@ txt category.name)
categories
|> Preface.Nonempty_list.to_list
in
div
~a:[ a_class [ "field" ] ]
[ label
~a:[ a_class [ "label" ]; a_label_for "create_topic_category_id" ]
[ (if Option.is_none category_id
then txt "CatΓ©gorie dans laquelle crΓ©er le fil de conversation"
else txt "CatΓ©gorie du fil de conversation")
]
; div
~a:[ a_class [ "control" ] ]
[ div
~a:[ a_class [ "select"; "is-large"; "is-fullwidth" ] ]
[ select
~a:[ a_id "create_topic_category_id"; a_name "category_id" ]
options
]
]
]
;;
let topic_title_input title =
let title_value = Option.value ~default:"" title in
let open Tyxml.Html in
div
~a:[ a_class [ "field" ] ]
[ label
~a:[ a_class [ "label" ]; a_label_for "create_topic_title" ]
[ txt "Titre du topic" ]
; div
~a:[ a_class [ "control" ] ]
[ input
~a:
[ a_input_type `Text
; a_placeholder "Un titre comprΓ©hensible"
; a_id "create_topic_title"
; a_name "topic_title"
; a_class [ "input" ]
; a_value title_value
]
()
]
; p
~a:[ a_class [ "help" ] ]
[ txt
"Essayez de trouver un titre clair qui indique rapidement la \
thΓ©matique du fil de conversation."
]
]
;;
let topic_content_input content =
let content_value = Option.value ~default:"" content in
let open Tyxml.Html in
div
~a:[ a_class [ "field" ] ]
[ label
~a:[ a_class [ "label" ]; a_label_for "create_topic_content" ]
[ txt "Contenu du message" ]
; div
~a:[ a_class [ "control" ] ]
[ textarea
~a:
[ a_placeholder "Ecrivez ici votre message (en Markdown) ..."
; a_id "create_topic_content"
; a_rows 15
; a_name "topic_content"
; a_class [ "textarea"; "is-large" ]
]
(txt content_value)
]
]
;;
let submit_buttons topic_id =
let button_msg =
if Option.is_none topic_id then "CrΓ©er le fil" else "Modifier le message"
in
let open Tyxml.Html in
div
~a:[ a_class [ "field" ] ]
[ div
~a:[ a_class [ "control" ] ]
[ input
~a:
[ a_input_type `Submit
; a_name "Preview"
; a_value "PrΓ©visualiser le message"
; a_class [ "button"; "is-link" ]
]
()
; input
~a:
[ a_input_type `Submit
; a_name "Submit"
; a_value button_msg
; a_class [ "button"; "is-link" ]
]
()
]
]
;;
let creation_form
?topic_id
?pre_category_id
?pre_title
?pre_content
csrf_token
categories
=
let params =
[ category_select categories pre_category_id
; topic_title_input pre_title
; topic_content_input pre_content
; submit_buttons topic_id
]
in
let form =
Option.fold
~none:(fun () ->
Templates.Util.form ~:Endpoints.Topic.save ~csrf_token params)
~some:(fun topic_id () ->
Templates.Util.form
~:Endpoints.Topic.save_edit
~csrf_token
params
topic_id)
topic_id
in
form ()
;;
end
module List = struct
let line topic =
let open Tyxml.Html in
let open Models.Topic.Listable in
let src = Gravatar.(url ~default:Identicon ~size:48 topic.user_email) in
let alt = "Avatar of " ^ topic.user_name in
let responses_suffix = if topic.responses > 1 then "s" else "" in
let responses = Fmt.str "%d rΓ©ponse%s" topic.responses responses_suffix in
tr
[ td
~a:[ a_class [ "is-vcentered" ] ]
[ Templates.Util.with_tooltip
(img ~a:[ a_class [ "image"; "is-48x48" ] ] ~src ~alt ())
topic.user_name
]
; td
~a:[ a_class [ "is-vcentered"; "is-fullwidth" ] ]
[ Templates.Util.a ~:Endpoints.Topic.show [ txt topic.title ] topic.id
]
; td
~a:[ a_class [ "is-vcentered" ] ]
[ span ~a:[ a_class [ "is-pulled-right" ] ] [ txt responses ] ]
; td
~a:[ a_class [ "is-vcentered" ] ]
[ Templates.Util.a
~:Endpoints.Topic.by_category
~a:[ a_class [ "button"; "is-info"; "is-pulled-right" ] ]
[ txt @@ Lib_common.Html.escape_special_chars topic.category_name
]
topic.category_name
]
]
;;
let all topics =
let open Tyxml.Html in
table
~a:
[ a_class
[ "table"; "is-fullwidth"; "is-stripped"; "content"; "is-medium" ]
]
@@ List.map line topics
;;
end
module Show = struct
let edition_link kind current_user user_id id =
let open Tyxml.Html in
if Models.User.can_edit ~owner_id:user_id current_user
Previewed messages have no edit link
then (
match kind with
| `Topic ->
Templates.Util.a
~:Endpoints.Topic.edit
~a:[ a_class [ "pl-4" ] ]
[ txt "Γditer" ]
id
| `Message t_id ->
Templates.Util.a
~:Endpoints.Topic.edit_message
~a:[ a_class [ "pl-4" ] ]
[ txt "Γditer" ]
t_id
id
| `Preview -> span [])
else span []
;;
let show_content
kind
current_user
user_id
user_name
user_email
id
creation_date
message
=
let open Tyxml.Html in
FIXME : Maybe get rid of . Html . Unsafe
let message_html = Unsafe.data message in
div
~a:[ a_class [ "media" ] ]
[ div
~a:[ a_class [ "media-left" ] ]
[ Templates.Component.avatar ~email:user_email ~username:user_name ()
]
; div
~a:[ a_class [ "media-content" ] ]
[ p ~a:[ a_class [ "title"; "is-6" ] ] [ txt @@ "@" ^ user_name ]
; p
~a:[ a_class [ "subtitle"; "is-6" ] ]
[ span
[ txt
@@ "publiΓ© le "
^ Templates.Util.format_date creation_date
]
; edition_link kind current_user user_id id
]
; div
~a:[ a_class [ "content"; "is-medium"; "media-content" ] ]
[ p [ message_html ] ]
]
]
;;
let message_content_input ?(message_content = "") () =
let open Tyxml.Html in
div
~a:[ a_class [ "field" ] ]
[ div
~a:[ a_class [ "control" ] ]
[ textarea
~a:
[ a_placeholder "Ecrivez ici votre message (en Markdown) ..."
; a_id "create_topic_content"
; a_rows 8
; a_name "message_content"
; a_class [ "textarea"; "is-large" ]
]
(txt message_content)
]
]
;;
let submit_buttons kind =
let message =
match kind with
| `Answer -> "RΓ©pondre au fil !"
| `Edit -> "Γditer le message !"
in
let open Tyxml.Html in
div
~a:[ a_class [ "field" ] ]
[ div
~a:[ a_class [ "control" ] ]
[ input
~a:
[ a_input_type `Submit
; a_name "Preview"
; a_value "PrΓ©visualiser le message !"
; a_class [ "button"; "is-link" ]
]
()
; input
~a:
[ a_input_type `Submit
; a_name "Answer"
; a_value message
; a_class [ "button"; "is-link" ]
]
()
]
]
;;
let message_form ?(prefilled = "") csrf_token user topic =
let open Tyxml.Html in
let topic_id = topic.Models.Topic.Showable.id in
div
[ h2 ~a:[ a_class [ "title"; "mt-6" ] ] [ txt "Composer une rΓ©ponse" ]
; div
~a:[ a_class [ "media" ]; a_id "answer" ]
[ div
~a:[ a_class [ "media-left" ] ]
[ Templates.Component.avatar
~email:user.Models.User.email
~username:user.name
()
]
; div
~a:[ a_class [ "media-content" ] ]
[ Templates.Util.form
~anchor:"answer"
~:Endpoints.Topic.answer
~csrf_token
[ message_content_input ~message_content:prefilled ()
; submit_buttons `Answer
]
topic_id
]
]
]
;;
let archive_button user topic =
if Models.User.can_moderate user
then
let open Tyxml.Html in
[ Templates.Util.a
~:Endpoints.Topic.archive
~a:
[ a_href "#answer"; a_class [ "button"; "is-danger"; "is-medium" ] ]
[ txt "Archiver" ]
topic.Models.Topic.Showable.id
]
else []
;;
let topic_content ?(show_buttons = true) user topic =
let open Tyxml.Html in
let open Models.Topic.Showable in
let answer_button =
a
~a:[ a_href "#answer"; a_class [ "button"; "is-success"; "is-medium" ] ]
[ txt "RΓ©pondre au fil" ]
in
div
[ div
~a:[ a_class [ "columns" ] ]
[ div
~a:[ a_class [ "column" ] ]
[ h1 ~a:[ a_class [ "title" ] ] [ txt topic.title ] ]
; div
~a:[ a_class [ "column"; "is-narrow"; "is-hidden-mobile" ] ]
(if show_buttons
then answer_button :: archive_button user topic
else [])
]
; show_content
`Topic
user
topic.user_id
topic.user_name
topic.user_email
topic.id
topic.creation_date
topic.content
]
;;
let thread ?prefilled csrf_token user topic messages =
let open Tyxml.Html in
(topic_content user topic
:: Stdlib.List.map
(fun message ->
div
~a:
(a_id message.Models.Message.id
:: (if message.id = "" then [ a_class [ "preview" ] ] else []))
[ hr ~a:[ a_class [ "mt-6"; "mb-6" ] ] ()
; show_content
(`Message topic.id)
user
message.user_id
message.user_name
message.user_email
message.id
message.creation_date
message.content
])
messages)
@ [ message_form ?prefilled csrf_token user topic ]
;;
end
module Message = struct
let edit ?preview csrf_token user topic_id message =
let open Tyxml.Html in
let open Models.Message in
let avatar =
div
~a:[ a_class [ "media-left" ] ]
[ Templates.Component.avatar
~email:message.user_email
~username:message.user_name
()
]
in
let preview =
match preview with
| None -> []
| Some raw_content ->
[ div
~a:[ a_id message.Models.Message.id ]
[ hr ~a:[ a_class [ "mt-6"; "mb-6" ] ] ()
; Show.show_content
`Preview
user
message.user_id
message.user_name
message.user_email
message.id
message.creation_date
raw_content
; hr ~a:[ a_class [ "mt-6"; "mb-6" ] ] ()
]
]
in
let message_ctn =
Show.message_content_input ~message_content:message.content ()
in
[ div
((if user.Models.User.id <> message.user_id
then
[ Templates.Component.flash_info
(Some
(Models.Flash_info.Info
"Vous allez modifier un contenu dont vous n'Γͺtes pas le \
propriΓ©taire"))
]
else [])
@ preview
@ [ h2 ~a:[ a_class [ "title"; "mt-6" ] ] [ txt "Γditer le message" ]
; div
~a:[ a_class [ "media" ]; a_id "answer" ]
[ avatar
; div
~a:[ a_class [ "media-content" ] ]
[ Templates.Util.form
~:Endpoints.Topic.save_edit_message
~csrf_token
[ message_ctn; Show.submit_buttons `Edit ]
topic_id
message.id
]
]
])
]
;;
end
let topic_form
?flash_info
?preview
~csrf_token
~user
?topic_id
?pre_title
?pre_content
?pre_category_id
categories
=
let open Tyxml.Html in
let page_title =
if Option.is_none topic_id
then "CrΓ©er un nouveau topic"
else "Γditer un message"
in
let preview =
Option.fold
~some:(fun topic ->
[ div [ Show.topic_content ~show_buttons:false user topic ] ])
~none:[ div [] ]
preview
in
Templates.Layout.default
~lang:"fr"
~page_title
~user
?flash_info
(preview
@ [ div
[ Create.creation_form
?pre_category_id
?pre_title
?pre_content
?topic_id
csrf_token
categories
]
])
;;
let topic_form ?flash_info ?preview ?prefilled ~csrf_token ~user categories =
Option.fold
~none:(topic_form ?flash_info ?preview ~csrf_token ~user categories)
~some:(fun topic ->
let open Models.Topic.Showable in
topic_form
?flash_info
?preview
~csrf_token
~user
?topic_id:(if String.length topic.id > 0 then Some topic.id else None)
~pre_title:topic.title
~pre_content:topic.content
~pre_category_id:topic.category_id
categories)
prefilled
;;
let create ?flash_info ?preview ?prefilled ~csrf_token ~user categories =
topic_form ?flash_info ?preview ?prefilled ~csrf_token ~user categories
;;
let edit ?flash_info ?preview ~prefilled ~csrf_token ~user categories =
topic_form ?flash_info ?preview ~prefilled ~csrf_token ~user categories
;;
let list ?flash_info ?user topics =
Templates.Layout.default
~lang:"fr"
~page_title:"Accueil"
?flash_info
?user
Tyxml.Html.[ div [ List.all topics ] ]
;;
let show ?flash_info ?prefilled ~csrf_token ~user topic messages =
let page_title = topic.Models.Topic.Showable.title in
Templates.Layout.default
~lang:"fr"
~page_title
?flash_info
~user
(Show.thread ?prefilled csrf_token user topic messages)
;;
let edit_message ?flash_info ?preview ~csrf_token ~user topic_id message =
let page_title = "Γditer un message" in
Templates.Layout.default
~lang:"fr"
~page_title
?flash_info
~user
(Message.edit ?preview csrf_token user topic_id message)
;;
|
7dd062abda8a979864511af7b84e645168cdd01d36dbbea48fe7ee987529c99c | botsunit/bucs | buccode_tests.erl | -module(buccode_tests).
-include_lib("eunit/include/eunit.hrl").
buccode_test_() ->
{setup,
fun setup/0, fun teardown/1,
[
?_test(t_priv_dir())
]}.
setup() ->
ok.
teardown(_) ->
ok.
t_priv_dir() ->
?assertMatch({match, _}, re:run(buccode:priv_dir(bucs), "bucs/priv$")).
| null | https://raw.githubusercontent.com/botsunit/bucs/792437befd259042efaf95e301dec019a5dd6ea4/test/buccode_tests.erl | erlang | -module(buccode_tests).
-include_lib("eunit/include/eunit.hrl").
buccode_test_() ->
{setup,
fun setup/0, fun teardown/1,
[
?_test(t_priv_dir())
]}.
setup() ->
ok.
teardown(_) ->
ok.
t_priv_dir() ->
?assertMatch({match, _}, re:run(buccode:priv_dir(bucs), "bucs/priv$")).
|
|
21e76ed47ad16e8f5bc752328dd0048a8a9a4c9c9aac590584b1a4a0392ea1ff | lambdamikel/DLMAPS | spatial-substrate.lisp | -*- Mode : Lisp ; Syntax : Ansi - Common - Lisp ; Package : THEMATIC - SUBSTRATE ; Base : 10 -*-
(in-package :THEMATIC-SUBSTRATE)
;;;
;;;
;;;
(defpersistentclass spatial-substrate (rolebox-substrate)
((consistency-relevant-edges :reader consistency-relevant-edges :initform nil)))
(defmethod create-substrate ((class (eql 'spatial-substrate))
&key name tbox abox rbox (real-class 'spatial-substrate))
(create-substrate 'rolebox-substrate :name name :abox abox :tbox tbox :rbox rbox :real-class 'spatial-substrate))
;;;
;;;
;;;
(defmethod simplify ((substrate spatial-substrate))
substrate)
(defmethod add-eq-loops ((substrate spatial-substrate))
(dolist (node (network-nodes substrate))
(create-edge substrate node node 'eq)))
(defmethod complete ((substrate spatial-substrate))
(add-eq-loops substrate)
;;;(add-inverse-edges substrate)
(add-missing-edges substrate))
(defmethod enumerate-atomic-configurations ((substrate spatial-substrate)
&key
how-many
(edges (consistency-relevant-edges substrate))
(sym-gen #'(lambda (edge processed-edges)
(description edge)))
(selector-fn #'(lambda (rem-edges processed-edges)
(first rem-edges)))
(manager-fn #'(lambda (sel-edge edges processed-edges)
(values (remove sel-edge
(remove (inverse-edge sel-edge)
edges))
(cons sel-edge (cons (inverse-edge sel-edge)
processed-edges)))))
(fn #'materialize)
(final-check-fn #'(lambda (x) (consistent-p x :force-p t)))
(construction-check-fn #'(lambda (x) t)))
(apply #'call-next-method
substrate
:edges edges
:how-many how-many
:sym-gen sym-gen
:selector-fn selector-fn
:manager-fn manager-fn
:fn fn
:final-check-fn final-check-fn
:construction-check-fn construction-check-fn
nil))
;;;
;;;
;;;
(defpersistentclass spatial-object (rolebox-substrate-node)
nil)
(defmethod create-node ((substrate spatial-substrate) name description &rest args &key (real-class 'spatial-object))
(apply #'call-next-method substrate name description :real-class real-class args))
(defpersistentclass spatial-relation (rolebox-substrate-edge)
((consistency-relevant-a-triangles :reader consistency-relevant-a-triangles :initform nil)))
(defmethod create-edge ((substrate spatial-substrate) from to description &rest args &key (error-p t) (real-class 'spatial-relation))
(if (get-edges-between substrate from to)
(when error-p (error "Edge (~A,~A) already exists in substrate ~A!"
from to substrate))
(apply #'call-next-method substrate from to description :real-class real-class :error-p error-p args)))
;;;
;;; Spatial-Relation-Methoden
;;;
(defmethod initialize-instance :after ((object spatial-relation) &rest initargs)
(with-slots (consistency-relevant-edges) (in-substrate object)
(when (consistency-relevant-p object)
(push object consistency-relevant-edges))))
(defmethod consistency-relevant-p ((edge spatial-relation))
(not (eq (from edge) (to edge))))
(defmethod delete-edge :after ((substrate spatial-substrate) (edge spatial-relation) &key &allow-other-keys)
(with-slots (inverse-edge) edge
(with-slots (consistency-relevant-edges) substrate
(setf consistency-relevant-edges
(delete edge consistency-relevant-edges))
(dolist (referencing-edge (referenced-by edge))
(when (typep referencing-edge 'spatial-relation)
(with-slots (consistency-relevant-a-triangles) referencing-edge
(setf consistency-relevant-a-triangles
(delete-if #'(lambda (tri) (member edge tri))
consistency-relevant-a-triangles))))))))
(defmethod get-support ((edge spatial-relation))
(with-slots (consistency-relevant-a-triangles in-substrate) edge
(with-slots (consistency-relevant-edges) in-substrate
(or consistency-relevant-a-triangles
(setf consistency-relevant-a-triangles
(remove-if-not #'(lambda (tri)
(and (consistency-relevant-p (first tri))
(consistency-relevant-p (first tri))))
(a-triangles edge)))))))
(defun compute-label-from-given-support (edge support)
(let* ((rbox (substrate-rbox (in-substrate edge)))
(role (mapcar #'(lambda (supp)
(let* ((r (current-label (first supp)))
(s (current-label (second supp)))
(res (lookup rbox r s)))
res))
(loop as tri in (consistency-relevant-a-triangles edge)
when (and (member (first tri)
support)
(member (second tri)))
collect tri))))
(if role
(reduce #'intersection role)
(full-disjunctive-role rbox))))
| null | https://raw.githubusercontent.com/lambdamikel/DLMAPS/7f8dbb9432069d41e6a7d9c13dc5b25602ad35dc/src/thematic-substrate/unfinished/spatial-substrate.lisp | lisp | Syntax : Ansi - Common - Lisp ; Package : THEMATIC - SUBSTRATE ; Base : 10 -*-
(add-inverse-edges substrate)
Spatial-Relation-Methoden
|
(in-package :THEMATIC-SUBSTRATE)
(defpersistentclass spatial-substrate (rolebox-substrate)
((consistency-relevant-edges :reader consistency-relevant-edges :initform nil)))
(defmethod create-substrate ((class (eql 'spatial-substrate))
&key name tbox abox rbox (real-class 'spatial-substrate))
(create-substrate 'rolebox-substrate :name name :abox abox :tbox tbox :rbox rbox :real-class 'spatial-substrate))
(defmethod simplify ((substrate spatial-substrate))
substrate)
(defmethod add-eq-loops ((substrate spatial-substrate))
(dolist (node (network-nodes substrate))
(create-edge substrate node node 'eq)))
(defmethod complete ((substrate spatial-substrate))
(add-eq-loops substrate)
(add-missing-edges substrate))
(defmethod enumerate-atomic-configurations ((substrate spatial-substrate)
&key
how-many
(edges (consistency-relevant-edges substrate))
(sym-gen #'(lambda (edge processed-edges)
(description edge)))
(selector-fn #'(lambda (rem-edges processed-edges)
(first rem-edges)))
(manager-fn #'(lambda (sel-edge edges processed-edges)
(values (remove sel-edge
(remove (inverse-edge sel-edge)
edges))
(cons sel-edge (cons (inverse-edge sel-edge)
processed-edges)))))
(fn #'materialize)
(final-check-fn #'(lambda (x) (consistent-p x :force-p t)))
(construction-check-fn #'(lambda (x) t)))
(apply #'call-next-method
substrate
:edges edges
:how-many how-many
:sym-gen sym-gen
:selector-fn selector-fn
:manager-fn manager-fn
:fn fn
:final-check-fn final-check-fn
:construction-check-fn construction-check-fn
nil))
(defpersistentclass spatial-object (rolebox-substrate-node)
nil)
(defmethod create-node ((substrate spatial-substrate) name description &rest args &key (real-class 'spatial-object))
(apply #'call-next-method substrate name description :real-class real-class args))
(defpersistentclass spatial-relation (rolebox-substrate-edge)
((consistency-relevant-a-triangles :reader consistency-relevant-a-triangles :initform nil)))
(defmethod create-edge ((substrate spatial-substrate) from to description &rest args &key (error-p t) (real-class 'spatial-relation))
(if (get-edges-between substrate from to)
(when error-p (error "Edge (~A,~A) already exists in substrate ~A!"
from to substrate))
(apply #'call-next-method substrate from to description :real-class real-class :error-p error-p args)))
(defmethod initialize-instance :after ((object spatial-relation) &rest initargs)
(with-slots (consistency-relevant-edges) (in-substrate object)
(when (consistency-relevant-p object)
(push object consistency-relevant-edges))))
(defmethod consistency-relevant-p ((edge spatial-relation))
(not (eq (from edge) (to edge))))
(defmethod delete-edge :after ((substrate spatial-substrate) (edge spatial-relation) &key &allow-other-keys)
(with-slots (inverse-edge) edge
(with-slots (consistency-relevant-edges) substrate
(setf consistency-relevant-edges
(delete edge consistency-relevant-edges))
(dolist (referencing-edge (referenced-by edge))
(when (typep referencing-edge 'spatial-relation)
(with-slots (consistency-relevant-a-triangles) referencing-edge
(setf consistency-relevant-a-triangles
(delete-if #'(lambda (tri) (member edge tri))
consistency-relevant-a-triangles))))))))
(defmethod get-support ((edge spatial-relation))
(with-slots (consistency-relevant-a-triangles in-substrate) edge
(with-slots (consistency-relevant-edges) in-substrate
(or consistency-relevant-a-triangles
(setf consistency-relevant-a-triangles
(remove-if-not #'(lambda (tri)
(and (consistency-relevant-p (first tri))
(consistency-relevant-p (first tri))))
(a-triangles edge)))))))
(defun compute-label-from-given-support (edge support)
(let* ((rbox (substrate-rbox (in-substrate edge)))
(role (mapcar #'(lambda (supp)
(let* ((r (current-label (first supp)))
(s (current-label (second supp)))
(res (lookup rbox r s)))
res))
(loop as tri in (consistency-relevant-a-triangles edge)
when (and (member (first tri)
support)
(member (second tri)))
collect tri))))
(if role
(reduce #'intersection role)
(full-disjunctive-role rbox))))
|
05b8b9fa007a87d25a371c56b82ef9db2fb2667509fbbb51f586651043400dff | deg/sodium | keys.clj | Author : ( )
Copyright ( c ) 2017 ,
(ns sodium.keys)
;;; [TODO] Fill in more keys
For mapping of HTML attributes to elements , see -US/docs/Web/HTML/Attributes
;;; For list of all HTML tags, see
;;; also,
;;; and
;;; See also /
(def ui-key-set-map (atom {}))
(defn key-set [key]
(key @ui-key-set-map))
(defn add-key-set [key key-set]
(swap! ui-key-set-map assoc key (set key-set)))
;;; Common parameters; elided from the other sets below
(add-key-set :basic
[:as ;; custom
:children ;; node
:class-name ;; string
* * * NOT LISTED IN DOC !
:key
:on-click
HTML(5 ) global attributes . From -US/docs/Web/HTML/Attributes
:access-key
:autocapitalize
:contenteditable
:contextmenu
:dir
:draggable
:dropzone
:hidden
:id
:itemprop
:lang
:slot
:spellcheck
:style
:tabindex
:title
:translate])
;;; From -ui.com/views/advertisement
(add-key-set :advertisement
[:centered?
:test
:unit])
From -ui.com/elements/button
(add-key-set :button
[:active? ;; bool
:animated ;; bool|enum
:attached ;; enum: [left, right, top, bottom]
:basic? ;; bool
:circular? ;; bool
:color ;; enum: [red orange yellow olive green teal blue violet purple pink brown grey black facebook google plus instagram linkedin twitter vk youtube]
:compact? ;; bool
:content ;; custom
:disabled? ;; bool
:floated ;; enum: [left right]
:fluid? ;; bool
:icon ;; custom
:inverted? ;; bool
:label ;; custom
:label-position ;; enum [right left]
:loading? ;; bool
:negative? ;; bool
:positive? ;; bool
:primary? ;; bool
:secondary? ;; bool
:size ;; enum: [mini tiny small medium large big huge massive]
:tab-index ;; number|string
:toggle? ;; bool
])
;;; From -ui.com/modules/checkbox
(add-key-set :checkbox
[:checked?
:default-checked?
:default-indeterminate?
:disabled?
:fitted?
:indeterminate?
:label
:name
:on-change
:on-mouse-down
:radio
:read-only?
:slider
:tab-index
:toggle
:type
:value])
;;; From -ui.com/elements/container
(add-key-set :container
[:fluid?
:text?
:text-align])
;;; From -ui.com/elements/divider
(add-key-set :divider
[:clearing?
:fitted?
:hidden?
:horizontal?
:inverted?
:section?
:vertical?])
;;; From -ui.com/modules/dropdown
(add-key-set :dropdown
[:addition-label
:addition-position
:allow-additions
:basic?
:button?
:close-on-blur?
:close-on-change?
:compact?
:default-open?
:default-selected-label
:default-value
:disabled?
:error?
:floating?
:fluid?
:header
:icon
:inline?
:item?
:labeled?
:loading?
:min-characters
:multiple?
:no-results-message
:on-add-item
:on-blur
:on-change
:on-close
:on-focus
:on-label-click
:on-mouse-down
:on-open
:on-search-change
:open?
:open-on-focus?
:options
:placehoder
:pointing
:render-label
:scrolling?
:search
:search-input
:select-on-blur
:selected-label
:selection
:simple?
:tab-index
:test
:trigger
:upward?
:value
])
From
(add-key-set :form
[:action
:error?
:inverted?
:loading?
:on-submit
:reply?
:size
:success?
:warning?
:widths
])
From ( tab : Form . Field )
(add-key-set :form-field
[:control ;; custom (mutually exclusive with :children)
:disabled? ;; bool
:error? ;; bool
:inline? ;; bool
node|object ( mutually exclusive with : children )
:required? ;; bool
:type ;; custom
enum : [ 1 , , , 16 , one , , , sixteen ]
])
From
(add-key-set :form-group
[:grouped
:inline
:widths])
From -ui.com/collections/grid
(add-key-set :grid
[:celled
:celled?
:centered?
:columns
:container?
:divided
:divided?
:doubling?
:inverted?
:padded
:relaxed
:reversed
:stackable?
:stretched?
:text-align
:vertical-align])
From -ui.com/collections/grid ( tab : Grid . Column )
(add-key-set :grid-column
[:color
:computer
:floated
:large-screen
:mobile
:only
:stretched?
:tablet
:text-align
:vertical-align
:wide-screen
:width])
From -ui.com/collections/grid ( tab : Grid . Row )
(add-key-set :grid-row
[:centered?
:color
:columns
:divided?
:only
:reversed
:stretched?
:text-align
:vertical-align])
;;; From -ui.com/elements/header
(add-key-set :header
[:attached
:block?
:color
:content
:dividing?
:floated
:icon
:image
:inverted?
:size
:sub?
:subheader
:text-align
])
From -ui.com/elements/icon
(add-key-set :icon
[:bordered?
:circular?
:color
:corner?
:disabled?
:fitted?
:flipped
:inverted?
:link?
:loading?
:name
:rotated
:size
])
From -ui.com/elements/icon ( tab : Icon . Group )
(add-key-set :icon-group
[:size
])
;;; From -ui.com/elements/image
(add-key-set :image
[:alt
:avatar?
:bordered?
:centered?
:dimmer
:disabled?
:floated
:Fluid
:height
:href
:inline?
:label
:shape
:size
:spadced
:src
:ui?
:vertical-align
:width
:wrapped
])
;;; From -ui.com/elements/input
(add-key-set :input
[:action
:action-position
* * * NOT LISTED IN DOC !
:error?
:fluid?
:focus?
:icon
:icon-position
:input
:inverted?
:label
:label-position
* * * NOT LISTED IN DOC !
:loading
* * * NOT LISTED IN DOC !
:on-change
* * * NOT LISTED IN DOC !
* * * NOT LISTED IN DOC !
* * * NOT LISTED IN DOC !
* * * NOT LISTED IN DOC !
:size
:tab-index
:transparent?
:type
])
;;; HTML input parameters not listed in the semantic-ui docs
(add-key-set :input-html
[:value
:step
:placeholder
])
From -ui.com/elements/label
(add-key-set :label
[:active?
:attached
:basic?
:circular?
:color
:content
:corner
:detail
:empty
:floating?
:horizontal?
:icon
:image
:on-remove
:pointing
:remove-icon
:ribbon
:size
:tag?])
;;; From -ui.com/elements/list
(add-key-set :list
[:animated?
:bulleted?
:celled?
:divided?
:floated
:horizontal?
:inverted?
:items
:link?
:on-item-click
:ordered?
:relaxed
:selection?
:size
:vertical-align])
;;; From -ui.com/elements/list (tab: List.Item)
(add-key-set :list-item
[:active?
:content
:description
:disabled?
:header
:icon
:image
:value])
;;; From -ui.com/collections/menu
(add-key-set :menu
[:active-index
:attached
:borderless?
:color
:compact?
:default-active-index
:fixed
:floated
:fluid?
:icon
:inverted?
:items
:on-item-click
:pagination?
:pointing?
:secondary?
:size
:stackable?
:tabular?
:text?
:vertical?
:widths
])
;;; From -ui.com/collections/menu (tab: Menu.Header)
(add-key-set :menu-header
[:content
])
;;; From -ui.com/collections/menu (tab: Menu.Item)
(add-key-set :menu-item
[:active?
:color
:content
:disabled?
:fitted
:header?
:icon
:index
:link?
:name
:position
])
;;; From -ui.com/collections/menu (tab: Menu.Menu)
(add-key-set :menu-menu
[:position
])
From -ui.com/modules/modal
(add-key-set :modal
[:actions
:basic?
:close-icon
:close-on-dimmer-click?
:close-on-document-click?
:content
:default-open?
:dimmer
:event-pool
:header
:mount-node
:on-action-click
:on-close
:on-mount
:on-open
:on-unmount
:open?
:size
:style
])
From -ui.com/modules/modal ( tab : Modal . Header )
(add-key-set :modal-header
[:content
])
From -ui.com/modules/modal ( tab : Modal . Content )
(add-key-set :modal-content
[:content
:image?
:scrolling?
])
From -ui.com/modules/modal ( tab : Modal . Description )
(add-key-set :modal-description
[
])
From -ui.com/modules/modal ( tab : Modal . Actions )
(add-key-set :modal-actions
[:actions
:on-action-click])
;;; From -ui.com/elements/rail
(add-key-set :rail
[:attached?
:close
:dividing?
:internal?
:position
:size])
;;; From -ui.com/modules/search
(add-key-set :search
[:aligned
:category?
:category-renderer
:default-open?
:default-value
:fluid?
:icon
:input
:loading?
:min-characters
:no-results-description
:no-results-message
:on-blur
:on-focus
:on-mouse-down
:on-results-select
:on-search-change
:on-selection-change
:open?
:result-renderer
:results
:select-first-result?
:show-no-results?
:size
:value])
;;; From -ui.com/elements/segment
(add-key-set :segment
[:attached
:basic?
:circular?
:clearing?
:color
:compact?
:disabled?
:floated
:inverted?
:loading?
:padded
:piled?
:raised?
:secondary?
:size
:stacked?
:tertiary?
:text-align
:vertical?
])
;;; From -ui.com/elements/segment (tab: Segment.Group)
(add-key-set :segment-group
[:compact?
:horizontal?
:piled?
:raised?
:size
:stacked?])
;;; From -ui.com/addons/text-area
(add-key-set :text-area
[:auto-height
:on-change
:rows
:style
:value])
| null | https://raw.githubusercontent.com/deg/sodium/1855fe870c3719af7d16d85c2558df1799a9bd32/src/sodium/keys.clj | clojure | [TODO] Fill in more keys
For list of all HTML tags, see
also,
and
See also /
Common parameters; elided from the other sets below
custom
node
string
From -ui.com/views/advertisement
bool
bool|enum
enum: [left, right, top, bottom]
bool
bool
enum: [red orange yellow olive green teal blue violet purple pink brown grey black facebook google plus instagram linkedin twitter vk youtube]
bool
custom
bool
enum: [left right]
bool
custom
bool
custom
enum [right left]
bool
bool
bool
bool
bool
enum: [mini tiny small medium large big huge massive]
number|string
bool
From -ui.com/modules/checkbox
From -ui.com/elements/container
From -ui.com/elements/divider
From -ui.com/modules/dropdown
custom (mutually exclusive with :children)
bool
bool
bool
bool
custom
From -ui.com/elements/header
From -ui.com/elements/image
From -ui.com/elements/input
HTML input parameters not listed in the semantic-ui docs
From -ui.com/elements/list
From -ui.com/elements/list (tab: List.Item)
From -ui.com/collections/menu
From -ui.com/collections/menu (tab: Menu.Header)
From -ui.com/collections/menu (tab: Menu.Item)
From -ui.com/collections/menu (tab: Menu.Menu)
From -ui.com/elements/rail
From -ui.com/modules/search
From -ui.com/elements/segment
From -ui.com/elements/segment (tab: Segment.Group)
From -ui.com/addons/text-area | Author : ( )
Copyright ( c ) 2017 ,
(ns sodium.keys)
For mapping of HTML attributes to elements , see -US/docs/Web/HTML/Attributes
(def ui-key-set-map (atom {}))
(defn key-set [key]
(key @ui-key-set-map))
(defn add-key-set [key key-set]
(swap! ui-key-set-map assoc key (set key-set)))
(add-key-set :basic
* * * NOT LISTED IN DOC !
:key
:on-click
HTML(5 ) global attributes . From -US/docs/Web/HTML/Attributes
:access-key
:autocapitalize
:contenteditable
:contextmenu
:dir
:draggable
:dropzone
:hidden
:id
:itemprop
:lang
:slot
:spellcheck
:style
:tabindex
:title
:translate])
(add-key-set :advertisement
[:centered?
:test
:unit])
From -ui.com/elements/button
(add-key-set :button
])
(add-key-set :checkbox
[:checked?
:default-checked?
:default-indeterminate?
:disabled?
:fitted?
:indeterminate?
:label
:name
:on-change
:on-mouse-down
:radio
:read-only?
:slider
:tab-index
:toggle
:type
:value])
(add-key-set :container
[:fluid?
:text?
:text-align])
(add-key-set :divider
[:clearing?
:fitted?
:hidden?
:horizontal?
:inverted?
:section?
:vertical?])
(add-key-set :dropdown
[:addition-label
:addition-position
:allow-additions
:basic?
:button?
:close-on-blur?
:close-on-change?
:compact?
:default-open?
:default-selected-label
:default-value
:disabled?
:error?
:floating?
:fluid?
:header
:icon
:inline?
:item?
:labeled?
:loading?
:min-characters
:multiple?
:no-results-message
:on-add-item
:on-blur
:on-change
:on-close
:on-focus
:on-label-click
:on-mouse-down
:on-open
:on-search-change
:open?
:open-on-focus?
:options
:placehoder
:pointing
:render-label
:scrolling?
:search
:search-input
:select-on-blur
:selected-label
:selection
:simple?
:tab-index
:test
:trigger
:upward?
:value
])
From
(add-key-set :form
[:action
:error?
:inverted?
:loading?
:on-submit
:reply?
:size
:success?
:warning?
:widths
])
From ( tab : Form . Field )
(add-key-set :form-field
node|object ( mutually exclusive with : children )
enum : [ 1 , , , 16 , one , , , sixteen ]
])
From
(add-key-set :form-group
[:grouped
:inline
:widths])
From -ui.com/collections/grid
(add-key-set :grid
[:celled
:celled?
:centered?
:columns
:container?
:divided
:divided?
:doubling?
:inverted?
:padded
:relaxed
:reversed
:stackable?
:stretched?
:text-align
:vertical-align])
From -ui.com/collections/grid ( tab : Grid . Column )
(add-key-set :grid-column
[:color
:computer
:floated
:large-screen
:mobile
:only
:stretched?
:tablet
:text-align
:vertical-align
:wide-screen
:width])
From -ui.com/collections/grid ( tab : Grid . Row )
(add-key-set :grid-row
[:centered?
:color
:columns
:divided?
:only
:reversed
:stretched?
:text-align
:vertical-align])
(add-key-set :header
[:attached
:block?
:color
:content
:dividing?
:floated
:icon
:image
:inverted?
:size
:sub?
:subheader
:text-align
])
From -ui.com/elements/icon
(add-key-set :icon
[:bordered?
:circular?
:color
:corner?
:disabled?
:fitted?
:flipped
:inverted?
:link?
:loading?
:name
:rotated
:size
])
From -ui.com/elements/icon ( tab : Icon . Group )
(add-key-set :icon-group
[:size
])
(add-key-set :image
[:alt
:avatar?
:bordered?
:centered?
:dimmer
:disabled?
:floated
:Fluid
:height
:href
:inline?
:label
:shape
:size
:spadced
:src
:ui?
:vertical-align
:width
:wrapped
])
(add-key-set :input
[:action
:action-position
* * * NOT LISTED IN DOC !
:error?
:fluid?
:focus?
:icon
:icon-position
:input
:inverted?
:label
:label-position
* * * NOT LISTED IN DOC !
:loading
* * * NOT LISTED IN DOC !
:on-change
* * * NOT LISTED IN DOC !
* * * NOT LISTED IN DOC !
* * * NOT LISTED IN DOC !
* * * NOT LISTED IN DOC !
:size
:tab-index
:transparent?
:type
])
(add-key-set :input-html
[:value
:step
:placeholder
])
From -ui.com/elements/label
(add-key-set :label
[:active?
:attached
:basic?
:circular?
:color
:content
:corner
:detail
:empty
:floating?
:horizontal?
:icon
:image
:on-remove
:pointing
:remove-icon
:ribbon
:size
:tag?])
(add-key-set :list
[:animated?
:bulleted?
:celled?
:divided?
:floated
:horizontal?
:inverted?
:items
:link?
:on-item-click
:ordered?
:relaxed
:selection?
:size
:vertical-align])
(add-key-set :list-item
[:active?
:content
:description
:disabled?
:header
:icon
:image
:value])
(add-key-set :menu
[:active-index
:attached
:borderless?
:color
:compact?
:default-active-index
:fixed
:floated
:fluid?
:icon
:inverted?
:items
:on-item-click
:pagination?
:pointing?
:secondary?
:size
:stackable?
:tabular?
:text?
:vertical?
:widths
])
(add-key-set :menu-header
[:content
])
(add-key-set :menu-item
[:active?
:color
:content
:disabled?
:fitted
:header?
:icon
:index
:link?
:name
:position
])
(add-key-set :menu-menu
[:position
])
From -ui.com/modules/modal
(add-key-set :modal
[:actions
:basic?
:close-icon
:close-on-dimmer-click?
:close-on-document-click?
:content
:default-open?
:dimmer
:event-pool
:header
:mount-node
:on-action-click
:on-close
:on-mount
:on-open
:on-unmount
:open?
:size
:style
])
From -ui.com/modules/modal ( tab : Modal . Header )
(add-key-set :modal-header
[:content
])
From -ui.com/modules/modal ( tab : Modal . Content )
(add-key-set :modal-content
[:content
:image?
:scrolling?
])
From -ui.com/modules/modal ( tab : Modal . Description )
(add-key-set :modal-description
[
])
From -ui.com/modules/modal ( tab : Modal . Actions )
(add-key-set :modal-actions
[:actions
:on-action-click])
(add-key-set :rail
[:attached?
:close
:dividing?
:internal?
:position
:size])
(add-key-set :search
[:aligned
:category?
:category-renderer
:default-open?
:default-value
:fluid?
:icon
:input
:loading?
:min-characters
:no-results-description
:no-results-message
:on-blur
:on-focus
:on-mouse-down
:on-results-select
:on-search-change
:on-selection-change
:open?
:result-renderer
:results
:select-first-result?
:show-no-results?
:size
:value])
(add-key-set :segment
[:attached
:basic?
:circular?
:clearing?
:color
:compact?
:disabled?
:floated
:inverted?
:loading?
:padded
:piled?
:raised?
:secondary?
:size
:stacked?
:tertiary?
:text-align
:vertical?
])
(add-key-set :segment-group
[:compact?
:horizontal?
:piled?
:raised?
:size
:stacked?])
(add-key-set :text-area
[:auto-height
:on-change
:rows
:style
:value])
|
9d57dcc5636a098cd98a97982610e1549f78e51c7f34d74c5326dee2b3225a25 | jperson/cl-reddit | util.lisp | Copyright ( c ) 2013 ,
;; 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.
;;
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 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.
;;
;; The views and conclusions contained in the software and documentation are those
;; of the authors and should not be interpreted as representing official policies,
either expressed or implied , of the FreeBSD Project .
(in-package #:cl-reddit)
;;;; Helper functions ;;;;
(defun make-user (&key username password)
"Make an instance of user class with username and password"
(make-instance 'user :username username :password password))
(defun format-key-args (args)
"Format a list of key arguments"
(let ((params))
(loop for arg in (cdr args) do
(push arg params)
(push (values (intern (string-upcase `,arg) "KEYWORD")) params))
params))
(defun symbol-string(s)
"Convert the input symbol to the correct string for api call."
(case s
('up "1")
('down "-1")
('unvote "0")
(otherwise (string-downcase (symbol-name s)))))
;;;; Helper macros ;;;;
(defmacro with-user ((usr) &body body)
"Does 'body' with logged-in user usr. Logins in user if not logged-in."
(let ((json (gensym)) (result (gensym)) (cks (gensym)))
`(if (null (user-modhash ,usr))
(progn
(let* ((,cks (make-instance 'drakma:cookie-jar))
(,result (drakma:http-request ""
:method :post
:parameters `(("passwd" . ,(user-password ,usr))
("user" . ,(user-username ,usr))
("api_type" . "json"))
:cookie-jar ,cks
:want-stream t)))
(setf (flexi-streams:flexi-stream-external-format ,result) :utf-8)
(let ((,json (gethash "json" (yason:parse ,result))))
(when (not (gethash "errors" ,json))
(loop for ck in (drakma:cookie-jar-cookies ,cks)
do (if (string= "reddit_session" (drakma:cookie-name ck))
(setf (drakma:cookie-path ck) "/")))
(setf (user-modhash ,usr) (gethash "modhash" (gethash "data",json)))
(setf (user-cookie ,usr) ,cks)
,@body))))
,@body)))
(defmacro if-user-with (user then)
`(if ,user
(with-user (,user)
,(if (listp (car (last then)))
`(progn ,(append (butlast then) (list (append (car (last then)) (list user)))))
`(,@then ,user)))
(,@then)))
(defmacro api-post-generic (url user &key subreddit action id thing-id text vote spam flair-enabled sr kind title)
"Defines generic post request"
(let ((params (gensym)) (result (gensym)))
`(let ((,params nil))
,(when subreddit `(push `("sr_name" . ,subreddit) ,params))
,(when sr `(push `("sr" . ,sr) ,params))
,(when kind `(push `("kind" . ,kind) ,params))
,(when title `(push `("title" . ,title) ,params))
,(when action `(push `("action" . ,(symbol-string ,action)) ,params))
,(when id `(push `("id" . ,id) ,params))
,(when thing-id `(push `("thing_id" . ,thing-id) ,params))
,(when text `(push `("text" . ,text) ,params))
,(when vote `(push `("dir" . ,(symbol-string ,vote)) ,params))
,(when spam `(push `("spam" . ,(if ,spam "1" "0")) ,params))
,(when flair-enabled `(push `("flair_enabled" . ,(if ,flair-enabled "1" "0")) ,params))
(push `("api_type" . "json") ,params)
(push `("uh" . ,(user-modhash ,user)) ,params)
(post-request ,url ,user ,params))))
(defmacro def-post-api (api &rest args)
"Defines an api call."
`(defun ,(intern (format nil "API-~S" `,api)) (user ,@args)
(api-post-generic ,(format nil "~a/api/~a.json" *reddit* (string-downcase api)) user ,@(format-key-args args))))
(defmacro param-push (&rest commands)
"Used in cl-reddit.lisp when defining get-* fns.
Example expansion:
(param-push hello a \"this'll be in place of a\")
=>
(PROGN
(WHEN A (PUSH `(\"this'll be in place of a\" ,@A) PARAMS))
(WHEN HELLO (PUSH `(\"hello\" ,@HELLO) PARAMS)))"
(flet ((process-commands (commands)
(let (stack)
(loop for c in commands do
(typecase c
(symbol (push `(,c ,(string-downcase c)) stack))
(string (setf (car stack) `(,(caar stack) ,c)))))
stack)))
`(progn
,@(loop for c in (process-commands commands)
collect
`(when ,(car c)
(push `(,',(cadr c) . ,,(car c)) params))))))
| null | https://raw.githubusercontent.com/jperson/cl-reddit/c78d2a5854cddfd9b72ffebb51c9253c242b4f5e/util.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:
list of conditions and the following disclaimer.
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
Helper functions ;;;;
Helper macros ;;;; | Copyright ( c ) 2013 ,
1 . Redistributions of source code must retain the above copyright notice , this
2 . Redistributions in binary form must reproduce the above copyright notice ,
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND
DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT OWNER OR FOR
ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
either expressed or implied , of the FreeBSD Project .
(in-package #:cl-reddit)
(defun make-user (&key username password)
"Make an instance of user class with username and password"
(make-instance 'user :username username :password password))
(defun format-key-args (args)
"Format a list of key arguments"
(let ((params))
(loop for arg in (cdr args) do
(push arg params)
(push (values (intern (string-upcase `,arg) "KEYWORD")) params))
params))
(defun symbol-string(s)
"Convert the input symbol to the correct string for api call."
(case s
('up "1")
('down "-1")
('unvote "0")
(otherwise (string-downcase (symbol-name s)))))
(defmacro with-user ((usr) &body body)
"Does 'body' with logged-in user usr. Logins in user if not logged-in."
(let ((json (gensym)) (result (gensym)) (cks (gensym)))
`(if (null (user-modhash ,usr))
(progn
(let* ((,cks (make-instance 'drakma:cookie-jar))
(,result (drakma:http-request ""
:method :post
:parameters `(("passwd" . ,(user-password ,usr))
("user" . ,(user-username ,usr))
("api_type" . "json"))
:cookie-jar ,cks
:want-stream t)))
(setf (flexi-streams:flexi-stream-external-format ,result) :utf-8)
(let ((,json (gethash "json" (yason:parse ,result))))
(when (not (gethash "errors" ,json))
(loop for ck in (drakma:cookie-jar-cookies ,cks)
do (if (string= "reddit_session" (drakma:cookie-name ck))
(setf (drakma:cookie-path ck) "/")))
(setf (user-modhash ,usr) (gethash "modhash" (gethash "data",json)))
(setf (user-cookie ,usr) ,cks)
,@body))))
,@body)))
(defmacro if-user-with (user then)
`(if ,user
(with-user (,user)
,(if (listp (car (last then)))
`(progn ,(append (butlast then) (list (append (car (last then)) (list user)))))
`(,@then ,user)))
(,@then)))
(defmacro api-post-generic (url user &key subreddit action id thing-id text vote spam flair-enabled sr kind title)
"Defines generic post request"
(let ((params (gensym)) (result (gensym)))
`(let ((,params nil))
,(when subreddit `(push `("sr_name" . ,subreddit) ,params))
,(when sr `(push `("sr" . ,sr) ,params))
,(when kind `(push `("kind" . ,kind) ,params))
,(when title `(push `("title" . ,title) ,params))
,(when action `(push `("action" . ,(symbol-string ,action)) ,params))
,(when id `(push `("id" . ,id) ,params))
,(when thing-id `(push `("thing_id" . ,thing-id) ,params))
,(when text `(push `("text" . ,text) ,params))
,(when vote `(push `("dir" . ,(symbol-string ,vote)) ,params))
,(when spam `(push `("spam" . ,(if ,spam "1" "0")) ,params))
,(when flair-enabled `(push `("flair_enabled" . ,(if ,flair-enabled "1" "0")) ,params))
(push `("api_type" . "json") ,params)
(push `("uh" . ,(user-modhash ,user)) ,params)
(post-request ,url ,user ,params))))
(defmacro def-post-api (api &rest args)
"Defines an api call."
`(defun ,(intern (format nil "API-~S" `,api)) (user ,@args)
(api-post-generic ,(format nil "~a/api/~a.json" *reddit* (string-downcase api)) user ,@(format-key-args args))))
(defmacro param-push (&rest commands)
"Used in cl-reddit.lisp when defining get-* fns.
Example expansion:
(param-push hello a \"this'll be in place of a\")
=>
(PROGN
(WHEN A (PUSH `(\"this'll be in place of a\" ,@A) PARAMS))
(WHEN HELLO (PUSH `(\"hello\" ,@HELLO) PARAMS)))"
(flet ((process-commands (commands)
(let (stack)
(loop for c in commands do
(typecase c
(symbol (push `(,c ,(string-downcase c)) stack))
(string (setf (car stack) `(,(caar stack) ,c)))))
stack)))
`(progn
,@(loop for c in (process-commands commands)
collect
`(when ,(car c)
(push `(,',(cadr c) . ,,(car c)) params))))))
|
0f2f7f1f6bb8d9a65c519e9b744fac1bd4d76044d84dda8f0425a63b72ba67c3 | dalmatinerdb/dflow | math_eqc.erl | @author < >
( C ) 2014 ,
%%% @doc
%%%
%%% @end
Created : 15 Dec 2014 by < >
-module(math_eqc).
-include_lib("eqc/include/eqc.hrl").
-include_lib("pulse/include/pulse.hrl").
-include_lib("pulse_otp/include/pulse_otp.hrl").
-compile(export_all).
-define(TREE_DEPTH, 7).
We do n't use divide since handeling the division by zery would be
%% too much pain!
op() ->
oneof(['+', '-', '*']).
runs() ->
?SUCHTHAT(N, int(), N > 0).
equasion() ->
?SIZED(Size, equasion(Size)).
equasion(Size) ->
?LAZY(oneof(
[{df_const, [int()], []} || Size == 0]
++ [?LETSHRINK(
[L, R], [equasion(Size - 1), equasion(Size - 1)],
{df_arith, [op()], [L, R]}) || Size > 0])).
setup() ->
{ok, _} = application:ensure_all_started(dflow),
otters_config:write(zipkin_collector_uri, ":9411/api/v1/spans"),
otters_config:write(filter_rules, [{[], [send_to_zipkin]}]),
fun () ->
ok
end.
prop_matches() ->
?SETUP(fun setup/0,
?FORALL(
Size, choose(1, ?TREE_DEPTH),
?FORALL(
{Eq, N}, {resize(Size, equasion()), runs()},
begin
Calculated = calculate(Eq),
?PULSE(
Result, run_and_collect(Eq, N, []),
?WHENFAIL(
io:format(user, "Eq: ~s~n~p =/= ~p~n",
[prettify(Eq), Calculated, Result]),
{Calculated, N} =:= Result))
end))).
prop_optimized() ->
?SETUP(fun setup/0,
?FORALL(
Size, choose(1, ?TREE_DEPTH),
?FORALL(
{Eq, N}, {resize(Size, equasion()), runs()},
begin
Calculated = calculate(Eq),
?PULSE(
Result, run_and_collect(Eq, N, [optimize]),
?WHENFAIL(
io:format(user, "Eq: ~s~n~p =/= ~p~n",
[prettify(Eq), Calculated, Result]),
{Calculated, N} =:= Result))
end))).
run_and_collect(Eq, N, Opts) ->
TID = otters_lib:id(),
Sp0 = otters:start(eqc, TID),
Sp1 = otters:tag(Sp0, service, qec, "eqc"),
Opts1 = [{trace_id, TID} | Opts],
Ref = make_ref(),
{ok, _, Flow} = dflow:build({dflow_send, [self(), Ref], [Eq]}, Opts1),
Sp2 = otters:log(Sp1, "build", "eqc"),
ok = dflow_graph:write_dot("./current.dot", Flow),
Sp3 = otters:log(Sp2, "write dot", "eqc"),
dflow:start(Flow, N),
Sp4 = otters:log(Sp3, "start", "eqc"),
{ok, Replies} = dflow_send:recv(Ref),
Sp5 = otters:log(Sp4, "recv", "eqc"),
ok = dflow_graph:write_dot("./current.dot", Flow),
Sp6 = otters:log(Sp5, "write new dot", "eqc"),
dflow:terminate(Flow),
Sp7 = otters:log(Sp6, "terminate", "eqc"),
[Result] = lists:usort(Replies),
otters:finish(Sp7),
{Result, length(Replies)}.
calculate({dflow_debug, [_], [C]}) ->
calculate(C);
calculate({df_const, [N], []}) ->
N;
calculate({df_arith, ['+'], [L, R]}) ->
calculate(L) + calculate(R);
calculate({df_arith, ['-'], [L, R]}) ->
calculate(L) - calculate(R);
calculate({df_arith, ['*'], [L, R]}) ->
calculate(L) * calculate(R).
prettify({dflow_debug, [_, C]}) ->
prettify(C);
prettify({df_const, [N], []}) ->
integer_to_list(N);
prettify({df_arith, ['+'], [L, R]}) ->
[$(, prettify(L), " + ", prettify(R), $)];
prettify({df_arith, ['-'], [L, R]}) ->
[$(, prettify(L), " - ", prettify(R), $)];
prettify({df_arith, ['*'], [L, R]}) ->
[$(, prettify(L), " * ", prettify(R), $)].
| null | https://raw.githubusercontent.com/dalmatinerdb/dflow/61d70b79a24c36bf72608b9fc91e91657eddd012/eqc/math_eqc.erl | erlang | @doc
@end
too much pain! | @author < >
( C ) 2014 ,
Created : 15 Dec 2014 by < >
-module(math_eqc).
-include_lib("eqc/include/eqc.hrl").
-include_lib("pulse/include/pulse.hrl").
-include_lib("pulse_otp/include/pulse_otp.hrl").
-compile(export_all).
-define(TREE_DEPTH, 7).
We do n't use divide since handeling the division by zery would be
op() ->
oneof(['+', '-', '*']).
runs() ->
?SUCHTHAT(N, int(), N > 0).
equasion() ->
?SIZED(Size, equasion(Size)).
equasion(Size) ->
?LAZY(oneof(
[{df_const, [int()], []} || Size == 0]
++ [?LETSHRINK(
[L, R], [equasion(Size - 1), equasion(Size - 1)],
{df_arith, [op()], [L, R]}) || Size > 0])).
setup() ->
{ok, _} = application:ensure_all_started(dflow),
otters_config:write(zipkin_collector_uri, ":9411/api/v1/spans"),
otters_config:write(filter_rules, [{[], [send_to_zipkin]}]),
fun () ->
ok
end.
prop_matches() ->
?SETUP(fun setup/0,
?FORALL(
Size, choose(1, ?TREE_DEPTH),
?FORALL(
{Eq, N}, {resize(Size, equasion()), runs()},
begin
Calculated = calculate(Eq),
?PULSE(
Result, run_and_collect(Eq, N, []),
?WHENFAIL(
io:format(user, "Eq: ~s~n~p =/= ~p~n",
[prettify(Eq), Calculated, Result]),
{Calculated, N} =:= Result))
end))).
prop_optimized() ->
?SETUP(fun setup/0,
?FORALL(
Size, choose(1, ?TREE_DEPTH),
?FORALL(
{Eq, N}, {resize(Size, equasion()), runs()},
begin
Calculated = calculate(Eq),
?PULSE(
Result, run_and_collect(Eq, N, [optimize]),
?WHENFAIL(
io:format(user, "Eq: ~s~n~p =/= ~p~n",
[prettify(Eq), Calculated, Result]),
{Calculated, N} =:= Result))
end))).
run_and_collect(Eq, N, Opts) ->
TID = otters_lib:id(),
Sp0 = otters:start(eqc, TID),
Sp1 = otters:tag(Sp0, service, qec, "eqc"),
Opts1 = [{trace_id, TID} | Opts],
Ref = make_ref(),
{ok, _, Flow} = dflow:build({dflow_send, [self(), Ref], [Eq]}, Opts1),
Sp2 = otters:log(Sp1, "build", "eqc"),
ok = dflow_graph:write_dot("./current.dot", Flow),
Sp3 = otters:log(Sp2, "write dot", "eqc"),
dflow:start(Flow, N),
Sp4 = otters:log(Sp3, "start", "eqc"),
{ok, Replies} = dflow_send:recv(Ref),
Sp5 = otters:log(Sp4, "recv", "eqc"),
ok = dflow_graph:write_dot("./current.dot", Flow),
Sp6 = otters:log(Sp5, "write new dot", "eqc"),
dflow:terminate(Flow),
Sp7 = otters:log(Sp6, "terminate", "eqc"),
[Result] = lists:usort(Replies),
otters:finish(Sp7),
{Result, length(Replies)}.
calculate({dflow_debug, [_], [C]}) ->
calculate(C);
calculate({df_const, [N], []}) ->
N;
calculate({df_arith, ['+'], [L, R]}) ->
calculate(L) + calculate(R);
calculate({df_arith, ['-'], [L, R]}) ->
calculate(L) - calculate(R);
calculate({df_arith, ['*'], [L, R]}) ->
calculate(L) * calculate(R).
prettify({dflow_debug, [_, C]}) ->
prettify(C);
prettify({df_const, [N], []}) ->
integer_to_list(N);
prettify({df_arith, ['+'], [L, R]}) ->
[$(, prettify(L), " + ", prettify(R), $)];
prettify({df_arith, ['-'], [L, R]}) ->
[$(, prettify(L), " - ", prettify(R), $)];
prettify({df_arith, ['*'], [L, R]}) ->
[$(, prettify(L), " * ", prettify(R), $)].
|
7d635c05bf5cf707d5dca2c60a7ddb7467502055e61b5e4c6efc8493d382a803 | Mokosha/Lambency | Utils.hs | module Lambency.Utils (
compareZero,
compareClose,
destructMat4,
clamp,
newRange,
newRangeC,
--
CyclicList(..),
advance,
cyclicLength,
cyclicFromList,
cyclicToList,
cycleSingleton,
cycles
) where
--------------------------------------------------------------------------------
import Control.Comonad
import Data.Foldable
import Linear.Epsilon
import Linear.Metric
import Prelude hiding (concat)
--------------------------------------------------------------------------------
compareZero :: (Epsilon a, Metric v) => v a -> Bool
compareZero x = nearZero $ (abs $ x `dot` x)
compareClose :: (Ord a, Epsilon a, Metric v) => v a -> v a -> Bool
compareClose x y = nearZero $ max (y `dot` y) (x `dot` x) - (x `dot` y)
destructMat4 :: (Functor f, Foldable f) => f (f a) -> [a]
destructMat4 = concat . (fmap toList)
clamp :: Ord a => a -> a -> a -> a
clamp x a b = if x < a then a else if x > b then b else x
newRange :: Floating a => a -> (a, a) -> (a, a) -> a
newRange x (omin, omax) (nmin, nmax) =
nmin + (nmax - nmin) * ((x - omin) / (omax - omin))
newRangeC :: (Ord a, Floating a) => a -> (a, a) -> (a, a) -> a
newRangeC x o n@(nmin, nmax) = clamp (newRange x o n) nmin nmax
--------------------------------------------------------------------------------
Cyclic lists
data CyclicList a = CyclicList [a] a [a]
instance Functor CyclicList where
fmap f (CyclicList p c n) = CyclicList (fmap f p) (f c) (fmap f n)
instance Foldable CyclicList where
foldr f x (CyclicList p c n) =
foldr f (f c (foldr f x $ reverse p)) n
instance Traversable CyclicList where
traverse f (CyclicList p c n) =
CyclicList <$>
(reverse <$> (traverse f $ reverse p)) <*> (f c) <*> (traverse f n)
advance :: CyclicList a -> CyclicList a
advance (CyclicList p c []) = let (r:rs) = reverse (c:p) in CyclicList [] r rs
advance (CyclicList p c (n:ns)) = CyclicList (c:p) n ns
cyclicLength :: CyclicList a -> Int
cyclicLength (CyclicList x _ z) = length x + length z + 1
cyclicFromList :: [a] -> CyclicList a
cyclicFromList [] = error "Cannot create empty cyclic list"
cyclicFromList (x:xs) = CyclicList [] x xs
cyclicToList :: CyclicList a -> [a]
cyclicToList (CyclicList p c n) = concat [reverse p, [c], n]
cycleSingleton :: a -> CyclicList a
cycleSingleton x = CyclicList [] x []
cycles :: CyclicList a -> [CyclicList a]
cycles cl = let
helper 0 _ = []
helper n cl' = cl' : (helper (n-1) $ advance cl')
in helper (cyclicLength cl) cl
instance Comonad CyclicList where
extract (CyclicList _ x _) = x
duplicate = cyclicFromList . cycles
| null | https://raw.githubusercontent.com/Mokosha/Lambency/43c58b62b9dc2c63b5f8c42248a6f7844093dac7/lib/Lambency/Utils.hs | haskell |
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | module Lambency.Utils (
compareZero,
compareClose,
destructMat4,
clamp,
newRange,
newRangeC,
CyclicList(..),
advance,
cyclicLength,
cyclicFromList,
cyclicToList,
cycleSingleton,
cycles
) where
import Control.Comonad
import Data.Foldable
import Linear.Epsilon
import Linear.Metric
import Prelude hiding (concat)
compareZero :: (Epsilon a, Metric v) => v a -> Bool
compareZero x = nearZero $ (abs $ x `dot` x)
compareClose :: (Ord a, Epsilon a, Metric v) => v a -> v a -> Bool
compareClose x y = nearZero $ max (y `dot` y) (x `dot` x) - (x `dot` y)
destructMat4 :: (Functor f, Foldable f) => f (f a) -> [a]
destructMat4 = concat . (fmap toList)
clamp :: Ord a => a -> a -> a -> a
clamp x a b = if x < a then a else if x > b then b else x
newRange :: Floating a => a -> (a, a) -> (a, a) -> a
newRange x (omin, omax) (nmin, nmax) =
nmin + (nmax - nmin) * ((x - omin) / (omax - omin))
newRangeC :: (Ord a, Floating a) => a -> (a, a) -> (a, a) -> a
newRangeC x o n@(nmin, nmax) = clamp (newRange x o n) nmin nmax
Cyclic lists
data CyclicList a = CyclicList [a] a [a]
instance Functor CyclicList where
fmap f (CyclicList p c n) = CyclicList (fmap f p) (f c) (fmap f n)
instance Foldable CyclicList where
foldr f x (CyclicList p c n) =
foldr f (f c (foldr f x $ reverse p)) n
instance Traversable CyclicList where
traverse f (CyclicList p c n) =
CyclicList <$>
(reverse <$> (traverse f $ reverse p)) <*> (f c) <*> (traverse f n)
advance :: CyclicList a -> CyclicList a
advance (CyclicList p c []) = let (r:rs) = reverse (c:p) in CyclicList [] r rs
advance (CyclicList p c (n:ns)) = CyclicList (c:p) n ns
cyclicLength :: CyclicList a -> Int
cyclicLength (CyclicList x _ z) = length x + length z + 1
cyclicFromList :: [a] -> CyclicList a
cyclicFromList [] = error "Cannot create empty cyclic list"
cyclicFromList (x:xs) = CyclicList [] x xs
cyclicToList :: CyclicList a -> [a]
cyclicToList (CyclicList p c n) = concat [reverse p, [c], n]
cycleSingleton :: a -> CyclicList a
cycleSingleton x = CyclicList [] x []
cycles :: CyclicList a -> [CyclicList a]
cycles cl = let
helper 0 _ = []
helper n cl' = cl' : (helper (n-1) $ advance cl')
in helper (cyclicLength cl) cl
instance Comonad CyclicList where
extract (CyclicList _ x _) = x
duplicate = cyclicFromList . cycles
|
ba4ef71c7dbe190cc68a801a876652dfa2a1b0341ea5816a14d5ed8d54bd8445 | bcc32/advent-of-code | a.ml | open! Core
let () =
let input =
In_channel.with_file (Sys.get_argv ()).(1) ~f:In_channel.input_all
|> String.strip
|> Int.of_string
in
let buf = ref (Array.create 0 ~len:1) in
let pos = ref 0 in
for next = 1 to 2017 do
pos := (!pos + input) % Array.length !buf;
let buf' = Array.create 0 ~len:(1 + Array.length !buf) in
Array.blit ~src:!buf ~dst:buf' ~src_pos:0 ~dst_pos:0 ~len:(!pos + 1);
buf'.(!pos + 1) <- next;
Array.blito () ~src:!buf ~dst:buf' ~src_pos:(!pos + 1) ~dst_pos:(!pos + 2);
buf := buf';
incr pos
done;
!buf.(!pos + 1) |> printf "%d\n"
;;
| null | https://raw.githubusercontent.com/bcc32/advent-of-code/653c0f130e2fb2f599d4e76804e02af54c9bb19f/2017/17/a.ml | ocaml | open! Core
let () =
let input =
In_channel.with_file (Sys.get_argv ()).(1) ~f:In_channel.input_all
|> String.strip
|> Int.of_string
in
let buf = ref (Array.create 0 ~len:1) in
let pos = ref 0 in
for next = 1 to 2017 do
pos := (!pos + input) % Array.length !buf;
let buf' = Array.create 0 ~len:(1 + Array.length !buf) in
Array.blit ~src:!buf ~dst:buf' ~src_pos:0 ~dst_pos:0 ~len:(!pos + 1);
buf'.(!pos + 1) <- next;
Array.blito () ~src:!buf ~dst:buf' ~src_pos:(!pos + 1) ~dst_pos:(!pos + 2);
buf := buf';
incr pos
done;
!buf.(!pos + 1) |> printf "%d\n"
;;
|
|
94a95a3b9628db16fef99623505ab458cee1d41396b6f3c281d9bfd41c9a6dda | AndrasKovacs/ELTE-func-lang | Lesson06_pre.hs | # LANGUAGE InstanceSigs , DeriveFoldable #
module Lesson05 where
data List a = Nil | Cons a (List a) deriving (Foldable, Show)
infixr 5 `Cons`
data BinaryTree a = Leaf a | Node (BinaryTree a) a (BinaryTree a)
data RoseTree a = RoseNode a [RoseTree a]
data Foo3 a = Foo3 a a a a a deriving Show
data Tree1 a = Leaf1 a | Node1 (Tree1 a) (Tree1 a) deriving Show
data Pair a b = Pair a b deriving Show
data Either' a b = Left' a | Right' b deriving Show
data Tree3 i a = Leaf3 a | Node3 (i -> Tree3 i a) -- i-szeres elΓ‘gazΓ‘s
newtype Id a = Id a deriving Show
newtype Const a b = Const a deriving Show
Monad : " MellΓ©khatΓ‘sok " dinamikusak , , amΓg meg nem tΓΆrtΓ©nik .
-- TΓΆrvΓ©nyek:
{-
-}
instance Monad List where
( > > =) = undefined
instance Monad BinaryTree where
( > > =) = undefined
instance Monad Foo3 where
( > > =) = undefined
instance where
( > > =) = undefined
instance Monad Pair where
( > > =) = undefined
instance ( > > =) = undefined
instance where
( > > =) = undefined
instance Monad Either ' where
( > > =) = undefined
instance I d where
( > > =) = undefined
instance where
( > > =) = undefined
instance Monad List where
(>>=) = undefined
instance Monad BinaryTree where
(>>=) = undefined
instance Monad Foo3 where
(>>=) = undefined
instance Monad Tree1 where
(>>=) = undefined
instance Monad Pair where
(>>=) = undefined
instance Monad RoseTree where
(>>=) = undefined
instance Monad Tree3 where
(>>=) = undefined
instance Monad Either' where
(>>=) = undefined
instance Monad Id where
(>>=) = undefined
instance Monad Const where
(>>=) = undefined
-}
f1 : : = > ( a - > b ) - > m a - > m b
f1 = undefined
f2 : : = > m a - > m b - > m ( a , b )
f2 = undefined
f3 : : = > m ( m a ) - > m a
f3 = undefined
f4 : : Monad m = > m ( a - > b ) - > m a - > m b
f4 = undefined
f5 : : = > ( a - > m b ) - > m a - > m b
f5 = undefined
f6 : : = > ( a - > b - > c ) - > m a - > m b - > m c
f6 = undefined
f7 : : Monad m = > ( a - > b - > c - > d ) - > m a - > m b - > m c - > m d
f7 = undefined
f8 : : = > ( a - > m b ) - > ( b - > m c ) - > a - > m c
f8 = undefined
f1 :: Monad m => (a -> b) -> m a -> m b
f1 = undefined
f2 :: Monad m => m a -> m b -> m (a, b)
f2 = undefined
f3 :: Monad m => m (m a) -> m a
f3 = undefined
f4 :: Monad m => m (a -> b) -> m a -> m b
f4 = undefined
f5 :: Monad m => (a -> m b) -> m a -> m b
f5 = undefined
f6 :: Monad m => (a -> b -> c) -> m a -> m b -> m c
f6 = undefined
f7 :: Monad m => (a -> b -> c -> d) -> m a -> m b -> m c -> m d
f7 = undefined
f8 :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
f8 = undefined
-}
| null | https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/b9855dbadacadd624d4648134733b6c4cc1ee602/2021-22-2/gyak_2/Lesson06_pre.hs | haskell | i-szeres elΓ‘gazΓ‘s
TΓΆrvΓ©nyek:
| # LANGUAGE InstanceSigs , DeriveFoldable #
module Lesson05 where
data List a = Nil | Cons a (List a) deriving (Foldable, Show)
infixr 5 `Cons`
data BinaryTree a = Leaf a | Node (BinaryTree a) a (BinaryTree a)
data RoseTree a = RoseNode a [RoseTree a]
data Foo3 a = Foo3 a a a a a deriving Show
data Tree1 a = Leaf1 a | Node1 (Tree1 a) (Tree1 a) deriving Show
data Pair a b = Pair a b deriving Show
data Either' a b = Left' a | Right' b deriving Show
newtype Id a = Id a deriving Show
newtype Const a b = Const a deriving Show
Monad : " MellΓ©khatΓ‘sok " dinamikusak , , amΓg meg nem tΓΆrtΓ©nik .
instance Monad List where
( > > =) = undefined
instance Monad BinaryTree where
( > > =) = undefined
instance Monad Foo3 where
( > > =) = undefined
instance where
( > > =) = undefined
instance Monad Pair where
( > > =) = undefined
instance ( > > =) = undefined
instance where
( > > =) = undefined
instance Monad Either ' where
( > > =) = undefined
instance I d where
( > > =) = undefined
instance where
( > > =) = undefined
instance Monad List where
(>>=) = undefined
instance Monad BinaryTree where
(>>=) = undefined
instance Monad Foo3 where
(>>=) = undefined
instance Monad Tree1 where
(>>=) = undefined
instance Monad Pair where
(>>=) = undefined
instance Monad RoseTree where
(>>=) = undefined
instance Monad Tree3 where
(>>=) = undefined
instance Monad Either' where
(>>=) = undefined
instance Monad Id where
(>>=) = undefined
instance Monad Const where
(>>=) = undefined
-}
f1 : : = > ( a - > b ) - > m a - > m b
f1 = undefined
f2 : : = > m a - > m b - > m ( a , b )
f2 = undefined
f3 : : = > m ( m a ) - > m a
f3 = undefined
f4 : : Monad m = > m ( a - > b ) - > m a - > m b
f4 = undefined
f5 : : = > ( a - > m b ) - > m a - > m b
f5 = undefined
f6 : : = > ( a - > b - > c ) - > m a - > m b - > m c
f6 = undefined
f7 : : Monad m = > ( a - > b - > c - > d ) - > m a - > m b - > m c - > m d
f7 = undefined
f8 : : = > ( a - > m b ) - > ( b - > m c ) - > a - > m c
f8 = undefined
f1 :: Monad m => (a -> b) -> m a -> m b
f1 = undefined
f2 :: Monad m => m a -> m b -> m (a, b)
f2 = undefined
f3 :: Monad m => m (m a) -> m a
f3 = undefined
f4 :: Monad m => m (a -> b) -> m a -> m b
f4 = undefined
f5 :: Monad m => (a -> m b) -> m a -> m b
f5 = undefined
f6 :: Monad m => (a -> b -> c) -> m a -> m b -> m c
f6 = undefined
f7 :: Monad m => (a -> b -> c -> d) -> m a -> m b -> m c -> m d
f7 = undefined
f8 :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
f8 = undefined
-}
|
da54a3b981b2f91355b1c383e655d61a99a875c4bfe4136e0fa54865f2d1e721 | exoscale/clojure-kubernetes-client | v1_list_meta.clj | (ns clojure-kubernetes-client.specs.v1-list-meta
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
)
(:import (java.io File)))
(declare v1-list-meta-data v1-list-meta)
(def v1-list-meta-data
{
(ds/opt :continue) string?
(ds/opt :resourceVersion) string?
(ds/opt :selfLink) string?
})
(def v1-list-meta
(ds/spec
{:name ::v1-list-meta
:spec v1-list-meta-data}))
| null | https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1_list_meta.clj | clojure | (ns clojure-kubernetes-client.specs.v1-list-meta
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
)
(:import (java.io File)))
(declare v1-list-meta-data v1-list-meta)
(def v1-list-meta-data
{
(ds/opt :continue) string?
(ds/opt :resourceVersion) string?
(ds/opt :selfLink) string?
})
(def v1-list-meta
(ds/spec
{:name ::v1-list-meta
:spec v1-list-meta-data}))
|
|
125b601c826bcd35298013c73f0bce2cf88b2cb017b285cebd5283d5a99c12b5 | CrypticButter/snoop | cljs.clj | (ns crypticbutter.snoop.impl.cljs)
| null | https://raw.githubusercontent.com/CrypticButter/snoop/4e7c820de45f811766c0164ed21e74701d27caa7/src/crypticbutter/snoop/impl/cljs.clj | clojure | (ns crypticbutter.snoop.impl.cljs)
|
|
3bd095f2b76cac56c9dba25b5ed912df45b4bcf201cd2fc10a7229423001086c | zachgk/catln | TypeCheck.hs | --------------------------------------------------------------------
-- |
Module :
Copyright : ( c ) 2019
License : MIT
-- Maintainer:
-- Stability : experimental
-- Portability: non-portable
--
-- This is the main module for typechecking. It takes a program
-- with some typing information and computes the rest of the typing
-- information. It's general goal is to narrow down types as precise
-- as possible.
--
-- The typechecking works through a constraint system. It converts
-- the code into a number of type variables and rules describing
-- relationships between those variables. Then, those relationships
-- are applied until the typing has converged (no more changes).
--------------------------------------------------------------------
# LANGUAGE NamedFieldPuns #
module TypeCheck where
import CRes
import Data.Graph
import qualified Data.HashMap.Strict as H
import qualified Data.HashSet as S
import Data.Maybe
import Semantics
import Semantics.Prgm
import TypeCheck.Common
import TypeCheck.Constrain (runConstraints)
import TypeCheck.Decode
import TypeCheck.Encode
import Utils
type TypecheckTuplePrgm = (TPrgm, VPrgm, TraceConstrain)
type FinalTypecheckTuplePrgm = (FinalTPrgm, VPrgm, TraceConstrain)
type TypecheckFileResult = H.HashMap String (GraphNodes TypecheckTuplePrgm String)
runConstraintsLimit :: Integer
runConstraintsLimit = 10
typecheckPrgms :: [PPrgm] -> [TPrgm] -> TypeCheckResult [TypecheckTuplePrgm]
typecheckPrgms pprgms typechecked = do
-- determine total classGraph
let (_, pclassGraph, _) = mergePrgms pprgms
let (_, tclassGraph, _) = mergePrgms typechecked
let classGraph = mergeClassGraphs pclassGraph tclassGraph
let baseFEnv = makeBaseFEnv classGraph
(vprgms, env@FEnv{feCons}) <- fromPrgms baseFEnv pprgms typechecked
env'@FEnv{feTrace} <- runConstraints runConstraintsLimit env feCons
tprgms <- toPrgms env' vprgms
return $ zip3 tprgms vprgms (repeat feTrace)
typecheckConnComps :: PPrgmGraphData -> TypecheckFileResult -> [SCC (GraphNodes PPrgm String)] -> TypeCheckResult TypecheckFileResult
typecheckConnComps _ res [] = return res
typecheckConnComps graphData@(prgmGraph, prgmFromNode, prgmFromName) results (curPrgm:nextPrgms) = do
let pprgms = flattenSCC curPrgm
let pprgmsNames = S.fromList $ map snd3 pprgms
let importNames = S.fromList $ map (snd3 . prgmFromNode) $ concatMap (reachable prgmGraph . fromJust . prgmFromName) pprgmsNames
let strictDepImportNames = S.difference importNames pprgmsNames
let importChecked = fromJust $ mapM (`H.lookup` results) (S.toList strictDepImportNames)
newResults <- typecheckPrgms (map fst3 pprgms) (map (fst3 . fst3) importChecked)
let results' = foldr (\((_, prgmName, prgmImports), prgm') accResults -> H.insert prgmName (prgm', prgmName, prgmImports) accResults) results (zip pprgms newResults)
typecheckConnComps graphData results' nextPrgms
typecheckPrgmWithTrace :: InitialPPrgmGraphData -> CRes (GraphData FinalTypecheckTuplePrgm String)
typecheckPrgmWithTrace initpprgms = typeCheckToRes $ do
let pprgms = fmapGraph fromExprPrgm initpprgms
let pprgmSCC = stronglyConnCompR $ graphToNodes pprgms
typechecked <- typecheckConnComps pprgms H.empty pprgmSCC
return $ fmapGraph (applyFst3 toExprPrgm) $ graphFromEdges $ H.elems typechecked
typecheckPrgm :: InitialPPrgmGraphData -> CRes (GraphData FinalTPrgm String)
typecheckPrgm pprgms = do
graph <- failOnErrorNotes $ typecheckPrgmWithTrace pprgms
return $ fmapGraph fst3 graph
| null | https://raw.githubusercontent.com/zachgk/catln/a7013bd5ab71a5034415296a009809466f9f3f69/src/TypeCheck.hs | haskell | ------------------------------------------------------------------
|
Maintainer:
Stability : experimental
Portability: non-portable
This is the main module for typechecking. It takes a program
with some typing information and computes the rest of the typing
information. It's general goal is to narrow down types as precise
as possible.
The typechecking works through a constraint system. It converts
the code into a number of type variables and rules describing
relationships between those variables. Then, those relationships
are applied until the typing has converged (no more changes).
------------------------------------------------------------------
determine total classGraph | Module :
Copyright : ( c ) 2019
License : MIT
# LANGUAGE NamedFieldPuns #
module TypeCheck where
import CRes
import Data.Graph
import qualified Data.HashMap.Strict as H
import qualified Data.HashSet as S
import Data.Maybe
import Semantics
import Semantics.Prgm
import TypeCheck.Common
import TypeCheck.Constrain (runConstraints)
import TypeCheck.Decode
import TypeCheck.Encode
import Utils
type TypecheckTuplePrgm = (TPrgm, VPrgm, TraceConstrain)
type FinalTypecheckTuplePrgm = (FinalTPrgm, VPrgm, TraceConstrain)
type TypecheckFileResult = H.HashMap String (GraphNodes TypecheckTuplePrgm String)
runConstraintsLimit :: Integer
runConstraintsLimit = 10
typecheckPrgms :: [PPrgm] -> [TPrgm] -> TypeCheckResult [TypecheckTuplePrgm]
typecheckPrgms pprgms typechecked = do
let (_, pclassGraph, _) = mergePrgms pprgms
let (_, tclassGraph, _) = mergePrgms typechecked
let classGraph = mergeClassGraphs pclassGraph tclassGraph
let baseFEnv = makeBaseFEnv classGraph
(vprgms, env@FEnv{feCons}) <- fromPrgms baseFEnv pprgms typechecked
env'@FEnv{feTrace} <- runConstraints runConstraintsLimit env feCons
tprgms <- toPrgms env' vprgms
return $ zip3 tprgms vprgms (repeat feTrace)
typecheckConnComps :: PPrgmGraphData -> TypecheckFileResult -> [SCC (GraphNodes PPrgm String)] -> TypeCheckResult TypecheckFileResult
typecheckConnComps _ res [] = return res
typecheckConnComps graphData@(prgmGraph, prgmFromNode, prgmFromName) results (curPrgm:nextPrgms) = do
let pprgms = flattenSCC curPrgm
let pprgmsNames = S.fromList $ map snd3 pprgms
let importNames = S.fromList $ map (snd3 . prgmFromNode) $ concatMap (reachable prgmGraph . fromJust . prgmFromName) pprgmsNames
let strictDepImportNames = S.difference importNames pprgmsNames
let importChecked = fromJust $ mapM (`H.lookup` results) (S.toList strictDepImportNames)
newResults <- typecheckPrgms (map fst3 pprgms) (map (fst3 . fst3) importChecked)
let results' = foldr (\((_, prgmName, prgmImports), prgm') accResults -> H.insert prgmName (prgm', prgmName, prgmImports) accResults) results (zip pprgms newResults)
typecheckConnComps graphData results' nextPrgms
typecheckPrgmWithTrace :: InitialPPrgmGraphData -> CRes (GraphData FinalTypecheckTuplePrgm String)
typecheckPrgmWithTrace initpprgms = typeCheckToRes $ do
let pprgms = fmapGraph fromExprPrgm initpprgms
let pprgmSCC = stronglyConnCompR $ graphToNodes pprgms
typechecked <- typecheckConnComps pprgms H.empty pprgmSCC
return $ fmapGraph (applyFst3 toExprPrgm) $ graphFromEdges $ H.elems typechecked
typecheckPrgm :: InitialPPrgmGraphData -> CRes (GraphData FinalTPrgm String)
typecheckPrgm pprgms = do
graph <- failOnErrorNotes $ typecheckPrgmWithTrace pprgms
return $ fmapGraph fst3 graph
|
4653bb271df25d05e39444a0237cc53c16d03bf8a87914b893a60656483a522a | modular-macros/ocaml-macros | cmt_format.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Fabrice Le Fessant, INRIA Saclay *)
(* *)
Copyright 2012 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Cmi_format
open Typedtree
Note that in Typerex , there is an awful hack to save a cmt file
together with the interface file that was generated by ( this
is because the installed version of ocaml might differ from the one
integrated in Typerex ) .
together with the interface file that was generated by ocaml (this
is because the installed version of ocaml might differ from the one
integrated in Typerex).
*)
let read_magic_number ic =
let len_magic_number = String.length Config.cmt_magic_number in
really_input_string ic len_magic_number
type binary_annots =
| Packed of Types.signature * string list
| Implementation of structure
| Interface of signature
| Partial_implementation of binary_part array
| Partial_interface of binary_part array
and binary_part =
| Partial_structure of structure
| Partial_structure_item of structure_item
| Partial_expression of expression
| Partial_pattern of pattern
| Partial_class_expr of class_expr
| Partial_signature of signature
| Partial_signature_item of signature_item
| Partial_module_type of module_type
type cmt_infos = {
cmt_modname : string;
cmt_annots : binary_annots;
cmt_value_dependencies :
(Types.value_description * Types.value_description) list;
cmt_comments : (string * Location.t) list;
cmt_args : string array;
cmt_sourcefile : string option;
cmt_builddir : string;
cmt_loadpath : string list;
cmt_source_digest : Digest.t option;
cmt_initial_env : Env.t;
cmt_imports : (string * Digest.t option) list;
cmt_interface_digest : Digest.t option;
cmt_use_summaries : bool;
}
type error =
Not_a_typedtree of string
let need_to_clear_env =
try ignore (Sys.getenv "OCAML_BINANNOT_WITHENV"); false
with Not_found -> true
let keep_only_summary = Env.keep_only_summary
open Tast_mapper
let cenv =
{Tast_mapper.default with env = fun _sub env -> keep_only_summary env}
let clear_part = function
| Partial_structure s -> Partial_structure (cenv.structure cenv s)
| Partial_structure_item s ->
Partial_structure_item (cenv.structure_item cenv s)
| Partial_expression e -> Partial_expression (cenv.expr cenv e)
| Partial_pattern p -> Partial_pattern (cenv.pat cenv p)
| Partial_class_expr ce -> Partial_class_expr (cenv.class_expr cenv ce)
| Partial_signature s -> Partial_signature (cenv.signature cenv s)
| Partial_signature_item s ->
Partial_signature_item (cenv.signature_item cenv s)
| Partial_module_type s -> Partial_module_type (cenv.module_type cenv s)
let clear_env binary_annots =
if need_to_clear_env then
match binary_annots with
| Implementation s -> Implementation (cenv.structure cenv s)
| Interface s -> Interface (cenv.signature cenv s)
| Packed _ -> binary_annots
| Partial_implementation array ->
Partial_implementation (Array.map clear_part array)
| Partial_interface array ->
Partial_interface (Array.map clear_part array)
else binary_annots
exception Error of error
let input_cmt ic = (input_value ic : cmt_infos)
let output_cmt oc cmt =
output_string oc Config.cmt_magic_number;
output_value oc (cmt : cmt_infos)
let read filename =
(* Printf.fprintf stderr "Cmt_format.read %s\n%!" filename; *)
let ic = open_in_bin filename in
try
let magic_number = read_magic_number ic in
let cmi, cmt =
if magic_number = Config.cmt_magic_number then
None, Some (input_cmt ic)
else if magic_number = Config.cmi_magic_number then
let cmi = Cmi_format.input_cmi ic in
let cmt = try
let magic_number = read_magic_number ic in
if magic_number = Config.cmt_magic_number then
let cmt = input_cmt ic in
Some cmt
else None
with _ -> None
in
Some cmi, cmt
else
raise(Cmi_format.Error(Cmi_format.Not_an_interface filename))
in
close_in ic;
Printf.fprintf stderr " Cmt_format.read done\n% ! " ;
cmi, cmt
with e ->
close_in ic;
raise e
let read_cmt filename =
match read filename with
_, None -> raise (Error (Not_a_typedtree filename))
| _, Some cmt -> cmt
let read_cmi filename =
match read filename with
None, _ ->
raise (Cmi_format.Error (Cmi_format.Not_an_interface filename))
| Some cmi, _ -> cmi
let saved_types = ref []
let value_deps = ref []
let clear () =
saved_types := [];
value_deps := []
let add_saved_type b = saved_types := b :: !saved_types
let get_saved_types () = !saved_types
let set_saved_types l = saved_types := l
let record_value_dependency vd1 vd2 =
if vd1.Types.val_loc <> vd2.Types.val_loc then
value_deps := (vd1, vd2) :: !value_deps
let save_cmt filename modname binary_annots sourcefile initial_env sg =
if !Clflags.binary_annotations && not !Clflags.print_types then begin
let imports = Env.imports () in
let flags =
List.concat [
if !Clflags.recursive_types then [Cmi_format.Rectypes] else [];
if !Clflags.opaque then [Cmi_format.Opaque] else [];
]
in
let oc = open_out_bin filename in
let this_crc =
match sg with
None -> None
| Some (sg) ->
let cmi = {
cmi_name = modname;
cmi_sign = sg;
cmi_flags = flags;
cmi_crcs = imports;
} in
Some (output_cmi filename oc cmi)
in
let source_digest = Misc.may_map Digest.file sourcefile in
let cmt = {
cmt_modname = modname;
cmt_annots = clear_env binary_annots;
cmt_value_dependencies = !value_deps;
cmt_comments = Lexer.comments ();
cmt_args = Sys.argv;
cmt_sourcefile = sourcefile;
cmt_builddir = Sys.getcwd ();
cmt_loadpath = !Config.load_path;
cmt_source_digest = source_digest;
cmt_initial_env = if need_to_clear_env then
keep_only_summary initial_env else initial_env;
cmt_imports = List.sort compare imports;
cmt_interface_digest = this_crc;
cmt_use_summaries = need_to_clear_env;
} in
output_cmt oc cmt;
close_out oc;
end;
clear ()
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/typing/cmt_format.ml | ocaml | ************************************************************************
OCaml
Fabrice Le Fessant, INRIA Saclay
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Printf.fprintf stderr "Cmt_format.read %s\n%!" filename; | Copyright 2012 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Cmi_format
open Typedtree
Note that in Typerex , there is an awful hack to save a cmt file
together with the interface file that was generated by ( this
is because the installed version of ocaml might differ from the one
integrated in Typerex ) .
together with the interface file that was generated by ocaml (this
is because the installed version of ocaml might differ from the one
integrated in Typerex).
*)
let read_magic_number ic =
let len_magic_number = String.length Config.cmt_magic_number in
really_input_string ic len_magic_number
type binary_annots =
| Packed of Types.signature * string list
| Implementation of structure
| Interface of signature
| Partial_implementation of binary_part array
| Partial_interface of binary_part array
and binary_part =
| Partial_structure of structure
| Partial_structure_item of structure_item
| Partial_expression of expression
| Partial_pattern of pattern
| Partial_class_expr of class_expr
| Partial_signature of signature
| Partial_signature_item of signature_item
| Partial_module_type of module_type
type cmt_infos = {
cmt_modname : string;
cmt_annots : binary_annots;
cmt_value_dependencies :
(Types.value_description * Types.value_description) list;
cmt_comments : (string * Location.t) list;
cmt_args : string array;
cmt_sourcefile : string option;
cmt_builddir : string;
cmt_loadpath : string list;
cmt_source_digest : Digest.t option;
cmt_initial_env : Env.t;
cmt_imports : (string * Digest.t option) list;
cmt_interface_digest : Digest.t option;
cmt_use_summaries : bool;
}
type error =
Not_a_typedtree of string
let need_to_clear_env =
try ignore (Sys.getenv "OCAML_BINANNOT_WITHENV"); false
with Not_found -> true
let keep_only_summary = Env.keep_only_summary
open Tast_mapper
let cenv =
{Tast_mapper.default with env = fun _sub env -> keep_only_summary env}
let clear_part = function
| Partial_structure s -> Partial_structure (cenv.structure cenv s)
| Partial_structure_item s ->
Partial_structure_item (cenv.structure_item cenv s)
| Partial_expression e -> Partial_expression (cenv.expr cenv e)
| Partial_pattern p -> Partial_pattern (cenv.pat cenv p)
| Partial_class_expr ce -> Partial_class_expr (cenv.class_expr cenv ce)
| Partial_signature s -> Partial_signature (cenv.signature cenv s)
| Partial_signature_item s ->
Partial_signature_item (cenv.signature_item cenv s)
| Partial_module_type s -> Partial_module_type (cenv.module_type cenv s)
let clear_env binary_annots =
if need_to_clear_env then
match binary_annots with
| Implementation s -> Implementation (cenv.structure cenv s)
| Interface s -> Interface (cenv.signature cenv s)
| Packed _ -> binary_annots
| Partial_implementation array ->
Partial_implementation (Array.map clear_part array)
| Partial_interface array ->
Partial_interface (Array.map clear_part array)
else binary_annots
exception Error of error
let input_cmt ic = (input_value ic : cmt_infos)
let output_cmt oc cmt =
output_string oc Config.cmt_magic_number;
output_value oc (cmt : cmt_infos)
let read filename =
let ic = open_in_bin filename in
try
let magic_number = read_magic_number ic in
let cmi, cmt =
if magic_number = Config.cmt_magic_number then
None, Some (input_cmt ic)
else if magic_number = Config.cmi_magic_number then
let cmi = Cmi_format.input_cmi ic in
let cmt = try
let magic_number = read_magic_number ic in
if magic_number = Config.cmt_magic_number then
let cmt = input_cmt ic in
Some cmt
else None
with _ -> None
in
Some cmi, cmt
else
raise(Cmi_format.Error(Cmi_format.Not_an_interface filename))
in
close_in ic;
Printf.fprintf stderr " Cmt_format.read done\n% ! " ;
cmi, cmt
with e ->
close_in ic;
raise e
let read_cmt filename =
match read filename with
_, None -> raise (Error (Not_a_typedtree filename))
| _, Some cmt -> cmt
let read_cmi filename =
match read filename with
None, _ ->
raise (Cmi_format.Error (Cmi_format.Not_an_interface filename))
| Some cmi, _ -> cmi
let saved_types = ref []
let value_deps = ref []
let clear () =
saved_types := [];
value_deps := []
let add_saved_type b = saved_types := b :: !saved_types
let get_saved_types () = !saved_types
let set_saved_types l = saved_types := l
let record_value_dependency vd1 vd2 =
if vd1.Types.val_loc <> vd2.Types.val_loc then
value_deps := (vd1, vd2) :: !value_deps
let save_cmt filename modname binary_annots sourcefile initial_env sg =
if !Clflags.binary_annotations && not !Clflags.print_types then begin
let imports = Env.imports () in
let flags =
List.concat [
if !Clflags.recursive_types then [Cmi_format.Rectypes] else [];
if !Clflags.opaque then [Cmi_format.Opaque] else [];
]
in
let oc = open_out_bin filename in
let this_crc =
match sg with
None -> None
| Some (sg) ->
let cmi = {
cmi_name = modname;
cmi_sign = sg;
cmi_flags = flags;
cmi_crcs = imports;
} in
Some (output_cmi filename oc cmi)
in
let source_digest = Misc.may_map Digest.file sourcefile in
let cmt = {
cmt_modname = modname;
cmt_annots = clear_env binary_annots;
cmt_value_dependencies = !value_deps;
cmt_comments = Lexer.comments ();
cmt_args = Sys.argv;
cmt_sourcefile = sourcefile;
cmt_builddir = Sys.getcwd ();
cmt_loadpath = !Config.load_path;
cmt_source_digest = source_digest;
cmt_initial_env = if need_to_clear_env then
keep_only_summary initial_env else initial_env;
cmt_imports = List.sort compare imports;
cmt_interface_digest = this_crc;
cmt_use_summaries = need_to_clear_env;
} in
output_cmt oc cmt;
close_out oc;
end;
clear ()
|
617f8edd21edbae1c3a627dbf0d17488e4fea32c1f455fbb7a3759abf63dada4 | c-cube/cconv | cConvSexp.ml |
* CSexp - interface to Copyright ( C ) 2014
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* CSexp - interface to Sexplib
* Copyright (C) 2014 Simon Cruanes
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
type 'a or_error = [ `Ok of 'a | `Error of string ]
type t = Sexplib.Sexp.t =
| Atom of string
| List of t list
let source =
let module D = CConv.Decode in
let rec src = {D.emit=fun dec s -> match s with
| Atom s -> dec.D.accept_string src s
| List l -> dec.D.accept_list src l
} in
src
let output =
let module E = CConv.Encode in
{ E.unit = List [];
bool = (fun b -> Atom (string_of_bool b));
float = (fun f -> Atom (string_of_float f));
char = (fun x -> Atom (String.make 1 x));
nativeint = (fun i -> Atom (Nativeint.to_string i));
int32 = (fun i -> Atom (Int32.to_string i));
int64 = (fun i -> Atom (Int64.to_string i));
int = (fun i -> Atom (string_of_int i));
string = (fun s -> Atom (String.escaped s));
list = (fun l -> List l);
option = (function None -> List[] | Some x -> List [x]);
record = (fun l -> List (List.map (fun (a,b) -> List [Atom a; b]) l));
tuple = (fun l -> List l);
sum = (fun name l -> match l with
| [] -> Atom name
| _::_ -> List (Atom name :: l));
}
let sexp_to_string = Sexplib.Sexp.to_string
let encode src x = CConv.encode src output x
let decode dec x = CConv.decode source dec x
let decode_exn dec x = CConv.decode_exn source dec x
let to_string src x =
sexp_to_string (encode src x)
let of_string dec s =
try
let x = Sexplib.Sexp.of_string s in
decode dec x
with Failure _ ->
`Error "invalid Sexp string"
let of_string_exn dec s =
let x = Sexplib.Sexp.of_string s in
decode_exn dec x
| null | https://raw.githubusercontent.com/c-cube/cconv/de165564973f673aacd63f53b53e230e6254eba5/src/sexp/cConvSexp.ml | ocaml |
* CSexp - interface to Copyright ( C ) 2014
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* CSexp - interface to Sexplib
* Copyright (C) 2014 Simon Cruanes
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
type 'a or_error = [ `Ok of 'a | `Error of string ]
type t = Sexplib.Sexp.t =
| Atom of string
| List of t list
let source =
let module D = CConv.Decode in
let rec src = {D.emit=fun dec s -> match s with
| Atom s -> dec.D.accept_string src s
| List l -> dec.D.accept_list src l
} in
src
let output =
let module E = CConv.Encode in
{ E.unit = List [];
bool = (fun b -> Atom (string_of_bool b));
float = (fun f -> Atom (string_of_float f));
char = (fun x -> Atom (String.make 1 x));
nativeint = (fun i -> Atom (Nativeint.to_string i));
int32 = (fun i -> Atom (Int32.to_string i));
int64 = (fun i -> Atom (Int64.to_string i));
int = (fun i -> Atom (string_of_int i));
string = (fun s -> Atom (String.escaped s));
list = (fun l -> List l);
option = (function None -> List[] | Some x -> List [x]);
record = (fun l -> List (List.map (fun (a,b) -> List [Atom a; b]) l));
tuple = (fun l -> List l);
sum = (fun name l -> match l with
| [] -> Atom name
| _::_ -> List (Atom name :: l));
}
let sexp_to_string = Sexplib.Sexp.to_string
let encode src x = CConv.encode src output x
let decode dec x = CConv.decode source dec x
let decode_exn dec x = CConv.decode_exn source dec x
let to_string src x =
sexp_to_string (encode src x)
let of_string dec s =
try
let x = Sexplib.Sexp.of_string s in
decode dec x
with Failure _ ->
`Error "invalid Sexp string"
let of_string_exn dec s =
let x = Sexplib.Sexp.of_string s in
decode_exn dec x
|
|
7691e59c5bbdbc8767d913ad3751f235035254e711d8e4e7c92b59a0b9702b85 | TomLisankie/Learning-Lisp | aoc-2018-1b.lisp | (defun open-file (file-name)
"Dumps contents of a text file into a list."
(with-open-file (file-stream file-name)
(loop for line = (read-line file-stream nil)
while line
collect line)))
(defun find-first-duplicate (list-from-file)
"Takes a list containing string representations of integers and finds the first sum that is repeated twice."
(let ((sum 0)
(seen-sums (make-hash-table)))
(dolist (an-int-string list-from-file)
(incf sum (parse-integer an-int-string))
(if (> (incf (gethash sum seen-sums 0)) 1)
(format t "~a " sum)))))
| null | https://raw.githubusercontent.com/TomLisankie/Learning-Lisp/27f9843cbb0c325a6531fd1332c6f19bebfe5a4d/code/Dec2018/10/aoc-2018-1b.lisp | lisp | (defun open-file (file-name)
"Dumps contents of a text file into a list."
(with-open-file (file-stream file-name)
(loop for line = (read-line file-stream nil)
while line
collect line)))
(defun find-first-duplicate (list-from-file)
"Takes a list containing string representations of integers and finds the first sum that is repeated twice."
(let ((sum 0)
(seen-sums (make-hash-table)))
(dolist (an-int-string list-from-file)
(incf sum (parse-integer an-int-string))
(if (> (incf (gethash sum seen-sums 0)) 1)
(format t "~a " sum)))))
|
|
9ac20d73ab201c154a0d33ca4bd92eccccfa58d20cc676fc3ca82530e912516b | zwizwa/staapl | boot.rkt | #lang staapl/pic18 \ -*- forth -*-
provide-all
\ Boot init macros for PIC18 chips.
macro
\ stack init code
: init-xs 0 movlw STKPTR movwf ; \ XS (hardware return stack / eXecute stack)
: init-ds 1 - 0 lfsr ; \ DS
\ RS ( retain stack )
\ * INDF0 the data stack pointer
\ * INDF1 the byte-sized retain stack (r) pointer
\ * STKPTR the hardware return stack (x) pointer
\ boot
\ The PIC18 has 64-byte flash erase blocks. The boot and ISR vectors
\ all reside in block 0, therefore we don't put any library code here,
\ and reserve the block for vectors only. If block 0 is cleared it
\ contains 32 #xFFFF NOP instructions, which means execution will fall
\ through to block 1 on reset. We use block 1 as the "debugger boot block".
: boot-vector! | warm |
` block1 >label | block1 |
#x0000 org-begin
block1 jw \ jump over ISR vectors if any
org-end
#x0040 org-begin
block1 enter: \ tag label for previous jump
warm i exit \ jump to setup code
org-end
;
: init-isr | action address |
address org-begin action i exit org-end ;
: init-isr-hi #x0008 init-isr ;
: init-isr-lo #x0018 init-isr ;
\ For lo-pri ISR we need to save registers manually. The tricky part
\ here is STATUS because the ordinary stack op "drop" uses MOVF, which
\ affects the flags. The code below is used "STATUS !" to make sure
\ MOVF is not used, but MOVFF is used instead (nfdrop).
: STATUS@ STATUS @ ;
: STATUS! dup STATUS ! nfdrop ;
\ fosc
: kHz 1000 * ;
: MHz kHz kHz ;
\ Misc stuff to remember when configuring chip
\ - disable watchdog timer if the code does not use CLWDT
\ - set power up timer (or use capacitor + reset enabled)
\ - disable MCLR pin, or use a reset switch with pullup resistor
\ Data memory
\ Note that the extended 18f instruction set allows the use of indexed
\ addressing relative to FSR2, which can enable cheap structs/objects.
\ however, it disables global (access bank) variables for the region
\ 0x000-0x05F, which makes that region better suited for stack memory
\ if the extensions are used, so the contiguous space after 0x80 could
\ be used as object memory, leaving the space 0x60-7F for global
\ variables.
\ in short, indexed addressing?
\ no -> stacks in 0x80 - 0xFF, globals in 0x00 - 0x7F
\ yes -> stacks in 0x00 - 0x5F, globals in 0x60 - 0x7F
\ Note that bank selecting is not used. it sucks, one can do without
forth
| null | https://raw.githubusercontent.com/zwizwa/staapl/e30e6ae6ac45de7141b97ad3cebf9b5a51bcda52/pic18/boot.rkt | racket | \ XS (hardware return stack / eXecute stack)
\ DS
| #lang staapl/pic18 \ -*- forth -*-
provide-all
\ Boot init macros for PIC18 chips.
macro
\ stack init code
\ RS ( retain stack )
\ * INDF0 the data stack pointer
\ * INDF1 the byte-sized retain stack (r) pointer
\ * STKPTR the hardware return stack (x) pointer
\ boot
\ The PIC18 has 64-byte flash erase blocks. The boot and ISR vectors
\ all reside in block 0, therefore we don't put any library code here,
\ and reserve the block for vectors only. If block 0 is cleared it
\ contains 32 #xFFFF NOP instructions, which means execution will fall
\ through to block 1 on reset. We use block 1 as the "debugger boot block".
: boot-vector! | warm |
` block1 >label | block1 |
#x0000 org-begin
block1 jw \ jump over ISR vectors if any
org-end
#x0040 org-begin
block1 enter: \ tag label for previous jump
warm i exit \ jump to setup code
org-end
: init-isr | action address |
\ For lo-pri ISR we need to save registers manually. The tricky part
\ here is STATUS because the ordinary stack op "drop" uses MOVF, which
\ affects the flags. The code below is used "STATUS !" to make sure
\ MOVF is not used, but MOVFF is used instead (nfdrop).
\ fosc
\ Misc stuff to remember when configuring chip
\ - disable watchdog timer if the code does not use CLWDT
\ - set power up timer (or use capacitor + reset enabled)
\ - disable MCLR pin, or use a reset switch with pullup resistor
\ Data memory
\ Note that the extended 18f instruction set allows the use of indexed
\ addressing relative to FSR2, which can enable cheap structs/objects.
\ however, it disables global (access bank) variables for the region
\ 0x000-0x05F, which makes that region better suited for stack memory
\ if the extensions are used, so the contiguous space after 0x80 could
\ be used as object memory, leaving the space 0x60-7F for global
\ variables.
\ in short, indexed addressing?
\ no -> stacks in 0x80 - 0xFF, globals in 0x00 - 0x7F
\ yes -> stacks in 0x00 - 0x5F, globals in 0x60 - 0x7F
\ Note that bank selecting is not used. it sucks, one can do without
forth
|
362a2564224e8a3007b21a5ab1a48675a0b26304d45ea40360396b80f65baf3c | fyquah/hardcaml_zprize | barrett_mult.ml | open Base
module Config = struct
type t =
{ multiplier_config : Karatsuba_ofman_mult.Config.t
; barrett_reduction_config : Barrett_reduction.Config.t
}
end
module With_interface (M : sig
val bits : int
end) =
struct
open M
module Karatsuba_ofman_mult = Karatsuba_ofman_mult.With_interface (M)
module Barrett_reduction = Barrett_reduction.With_interface (struct
include M
let output_bits = bits
end)
module I = struct
type 'a t =
{ clock : 'a
; enable : 'a
; x : 'a [@bits bits]
; y : 'a [@bits bits]
; valid : 'a [@rtlprefix "in_"]
}
[@@deriving sexp_of, hardcaml]
end
module O = struct
type 'a t =
{ z : 'a [@bits bits]
; valid : 'a [@rtlprefix "out_"]
}
[@@deriving sexp_of, hardcaml]
end
let create ~(config : Config.t) ~p scope { I.clock; enable; x; y; valid = valid_in } =
let mult_stage =
Karatsuba_ofman_mult.hierarchical
~config:config.multiplier_config
scope
{ clock; enable; valid = valid_in; a = x; b = y }
in
let barrett_reduction =
Barrett_reduction.hierarchical
~config:config.barrett_reduction_config
~p
scope
{ clock; enable; a = mult_stage.c; valid = mult_stage.valid }
in
{ O.z = barrett_reduction.a_mod_p; valid = barrett_reduction.valid }
;;
end
| null | https://raw.githubusercontent.com/fyquah/hardcaml_zprize/553b1be10ae9b977decbca850df6ee2d0595e7ff/libs/field_ops/src/barrett_mult.ml | ocaml | open Base
module Config = struct
type t =
{ multiplier_config : Karatsuba_ofman_mult.Config.t
; barrett_reduction_config : Barrett_reduction.Config.t
}
end
module With_interface (M : sig
val bits : int
end) =
struct
open M
module Karatsuba_ofman_mult = Karatsuba_ofman_mult.With_interface (M)
module Barrett_reduction = Barrett_reduction.With_interface (struct
include M
let output_bits = bits
end)
module I = struct
type 'a t =
{ clock : 'a
; enable : 'a
; x : 'a [@bits bits]
; y : 'a [@bits bits]
; valid : 'a [@rtlprefix "in_"]
}
[@@deriving sexp_of, hardcaml]
end
module O = struct
type 'a t =
{ z : 'a [@bits bits]
; valid : 'a [@rtlprefix "out_"]
}
[@@deriving sexp_of, hardcaml]
end
let create ~(config : Config.t) ~p scope { I.clock; enable; x; y; valid = valid_in } =
let mult_stage =
Karatsuba_ofman_mult.hierarchical
~config:config.multiplier_config
scope
{ clock; enable; valid = valid_in; a = x; b = y }
in
let barrett_reduction =
Barrett_reduction.hierarchical
~config:config.barrett_reduction_config
~p
scope
{ clock; enable; a = mult_stage.c; valid = mult_stage.valid }
in
{ O.z = barrett_reduction.a_mod_p; valid = barrett_reduction.valid }
;;
end
|
|
6eaf7c1f5efdb5733b3d3f1505991a802832d723530b1bbfb761a9649303b474 | jwaldmann/haskell-obdd | Cube.hs | {-# language FlexibleContexts #-}
# LANGUAGE TupleSections #
module OBDD.Cube where
import Prelude hiding ((&&),(||),not,and,or)
import qualified Prelude
import OBDD
import qualified Data.Bool
import Control.Monad (guard)
import Control.Applicative
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.List (partition, sortOn)
import Debug.Trace
type Cube v = M.Map v Bool
primes :: Ord v => OBDD v -> [Cube v]
primes d =
let process m = M.fromList $ do
((v,Sign), b) <- M.toList m
return (v, b)
in map process $ paths $ prime d
nice :: Show v => Cube v -> String
nice c = "(" ++ do
(v,b) <- M.toList c
(if b then " " else " -") ++ show v
++ ")"
data Check = Sign | Occurs | Original
deriving (Eq, Ord, Show)
sign v = variable (v, Sign)
occurs v = variable (v, Occurs)
original v = variable (v, Original)
process c = M.fromList $ do
((v,Occurs),True) <- M.toList c
return (v, c M.! (v,Sign))
| , :
--
prime :: Ord v => OBDD v -> OBDD (v, Check)
prime = snd
. fold ( \ b -> ( bool b, bool b ))
( \ v (fl,pl) (fr,pr) -> ( choose fl fr (variable v)
, let common = prime (fl && fr)
in not (occurs v) && common
|| occurs v && not (sign v) && pl && not common
|| occurs v && (sign v) && pr && not common
)
)
-- * naive way of finding a minimal set of clauses.
dnf f =
let ps = primes f
ms = models (variables f) f
covering = do
m <- ms
return $ S.fromList $ do
(i,p) <- zip [0..] ps
guard $ M.isSubmapOf p m
return i
cost = M.fromList $ zip [0..] $ map M.size ps
r = greed cost covering
in map (ps !!) $ S.toList r
cnf f = map (M.map Prelude.not) $ dnf $ not f
greed cost [] = S.empty
greed cost could =
let count = M.unionsWith (+) $ do
c <- could
return $ M.fromList $ zip (S.toList c) $ repeat 1
this = fst
$ head
$ sortOn snd
$ map (\(k,v) -> (k, (negate v, cost M.! k)))
$ M.toList count
in S.insert this
$ greed cost $ filter ( \p -> S.notMember this p ) could
clause c = and $ do (v,b) <- M.toList c ; return $ unit v b
| null | https://raw.githubusercontent.com/jwaldmann/haskell-obdd/537f710bc3eb6d06370659fd8c79f4da94554aeb/src/OBDD/Cube.hs | haskell | # language FlexibleContexts #
* naive way of finding a minimal set of clauses. | # LANGUAGE TupleSections #
module OBDD.Cube where
import Prelude hiding ((&&),(||),not,and,or)
import qualified Prelude
import OBDD
import qualified Data.Bool
import Control.Monad (guard)
import Control.Applicative
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.List (partition, sortOn)
import Debug.Trace
type Cube v = M.Map v Bool
primes :: Ord v => OBDD v -> [Cube v]
primes d =
let process m = M.fromList $ do
((v,Sign), b) <- M.toList m
return (v, b)
in map process $ paths $ prime d
nice :: Show v => Cube v -> String
nice c = "(" ++ do
(v,b) <- M.toList c
(if b then " " else " -") ++ show v
++ ")"
data Check = Sign | Occurs | Original
deriving (Eq, Ord, Show)
sign v = variable (v, Sign)
occurs v = variable (v, Occurs)
original v = variable (v, Original)
process c = M.fromList $ do
((v,Occurs),True) <- M.toList c
return (v, c M.! (v,Sign))
| , :
prime :: Ord v => OBDD v -> OBDD (v, Check)
prime = snd
. fold ( \ b -> ( bool b, bool b ))
( \ v (fl,pl) (fr,pr) -> ( choose fl fr (variable v)
, let common = prime (fl && fr)
in not (occurs v) && common
|| occurs v && not (sign v) && pl && not common
|| occurs v && (sign v) && pr && not common
)
)
dnf f =
let ps = primes f
ms = models (variables f) f
covering = do
m <- ms
return $ S.fromList $ do
(i,p) <- zip [0..] ps
guard $ M.isSubmapOf p m
return i
cost = M.fromList $ zip [0..] $ map M.size ps
r = greed cost covering
in map (ps !!) $ S.toList r
cnf f = map (M.map Prelude.not) $ dnf $ not f
greed cost [] = S.empty
greed cost could =
let count = M.unionsWith (+) $ do
c <- could
return $ M.fromList $ zip (S.toList c) $ repeat 1
this = fst
$ head
$ sortOn snd
$ map (\(k,v) -> (k, (negate v, cost M.! k)))
$ M.toList count
in S.insert this
$ greed cost $ filter ( \p -> S.notMember this p ) could
clause c = and $ do (v,b) <- M.toList c ; return $ unit v b
|
8ee37096744009c556d28983724532a210078d6fe806184c42f70f54f14ce6f4 | onyx-platform/onyx-examples | core.clj | (ns global-windows.core
(:require [clojure.core.async :refer [chan >!! <!! close!]]
[onyx.plugin.core-async :refer [take-segments!]]
[onyx.api])
(:gen-class))
(def id (java.util.UUID/randomUUID))
(def env-config
{:zookeeper/address "127.0.0.1:2188"
:zookeeper/server? true
:zookeeper.server/port 2188
:onyx/tenancy-id id})
(def peer-config
{:zookeeper/address "127.0.0.1:2188"
:onyx/tenancy-id id
:onyx.peer/job-scheduler :onyx.job-scheduler/balanced
:onyx.messaging/impl :aeron
:onyx.messaging/peer-port 40200
:onyx.messaging/bind-addr "localhost"})
(def batch-size 10)
(def workflow
[[:in :identity]
[:identity :out]])
(def catalog
[{:onyx/name :in
:onyx/plugin :onyx.plugin.core-async/input
:onyx/type :input
:onyx/medium :core.async
:onyx/batch-size batch-size
:onyx/max-peers 1
:onyx/doc "Reads segments from a core.async channel"}
{:onyx/name :identity
:onyx/fn :clojure.core/identity
:onyx/type :function
:onyx/batch-size batch-size}
{:onyx/name :out
:onyx/plugin :onyx.plugin.core-async/output
:onyx/type :output
:onyx/medium :core.async
:onyx/max-peers 1
:onyx/batch-size batch-size
:onyx/doc "Writes segments to a core.async channel"}])
(def capacity 1000)
(def input-chan (chan capacity))
(def input-buffer (atom {}))
(def output-chan (chan capacity))
(def input-segments
[{:n 0 :event-time #inst "2015-09-13T03:00:00.829-00:00"}
{:n 1 :event-time #inst "2015-09-13T03:03:00.829-00:00"}
{:n 2 :event-time #inst "2015-09-13T03:07:00.829-00:00"}
{:n 3 :event-time #inst "2015-09-13T03:11:00.829-00:00"}
{:n 4 :event-time #inst "2015-09-13T03:15:00.829-00:00"}
{:n 5 :event-time #inst "2015-09-13T03:02:00.829-00:00"}])
(doseq [segment input-segments]
(>!! input-chan segment))
(close! input-chan)
(def env (onyx.api/start-env env-config))
(def peer-group (onyx.api/start-peer-group peer-config))
(def n-peers (count (set (mapcat identity workflow))))
(def v-peers (onyx.api/start-peers n-peers peer-group))
(defn inject-in-ch [event lifecycle]
{:core.async/buffer input-buffer
:core.async/chan input-chan})
(defn inject-out-ch [event lifecycle]
{:core.async/chan output-chan})
(def in-calls
{:lifecycle/before-task-start inject-in-ch})
(def out-calls
{:lifecycle/before-task-start inject-out-ch})
(def lifecycles
[{:lifecycle/task :in
:lifecycle/calls ::in-calls}
{:lifecycle/task :in
:lifecycle/calls :onyx.plugin.core-async/reader-calls}
{:lifecycle/task :out
:lifecycle/calls ::out-calls}
{:lifecycle/task :out
:lifecycle/calls :onyx.plugin.core-async/writer-calls}])
(def windows
[{:window/id :collect-segments
:window/task :identity
:window/type :global
:window/aggregation :onyx.windowing.aggregation/conj}])
(def triggers
[{:trigger/window-id :collect-segments
:trigger/id :sync
:trigger/on :onyx.triggers/segment
:trigger/threshold [5 :elements]
:trigger/sync ::dump-window!}])
(defn dump-window!
[event window trigger {:keys [lower-bound upper-bound] :as window-data} state]
(println (format "Window extent [%s - %s] contents: %s"
lower-bound upper-bound state)))
(defn -main
[& args]
(let [submission (onyx.api/submit-job peer-config
{:workflow workflow
:catalog catalog
:lifecycles lifecycles
:windows windows
:triggers triggers
:task-scheduler :onyx.task-scheduler/balanced})]
(onyx.api/await-job-completion peer-config (:job-id submission)))
;; Sleep until the trigger timer fires.
(Thread/sleep 5000)
(let [results (take-segments! output-chan 50)])
(doseq [v-peer v-peers]
(onyx.api/shutdown-peer v-peer))
(onyx.api/shutdown-peer-group peer-group)
(onyx.api/shutdown-env env))
| null | https://raw.githubusercontent.com/onyx-platform/onyx-examples/668fddd26bc6b692a478fb8dc0e6d3d329879396/global-windows/src/global_windows/core.clj | clojure | Sleep until the trigger timer fires. | (ns global-windows.core
(:require [clojure.core.async :refer [chan >!! <!! close!]]
[onyx.plugin.core-async :refer [take-segments!]]
[onyx.api])
(:gen-class))
(def id (java.util.UUID/randomUUID))
(def env-config
{:zookeeper/address "127.0.0.1:2188"
:zookeeper/server? true
:zookeeper.server/port 2188
:onyx/tenancy-id id})
(def peer-config
{:zookeeper/address "127.0.0.1:2188"
:onyx/tenancy-id id
:onyx.peer/job-scheduler :onyx.job-scheduler/balanced
:onyx.messaging/impl :aeron
:onyx.messaging/peer-port 40200
:onyx.messaging/bind-addr "localhost"})
(def batch-size 10)
(def workflow
[[:in :identity]
[:identity :out]])
(def catalog
[{:onyx/name :in
:onyx/plugin :onyx.plugin.core-async/input
:onyx/type :input
:onyx/medium :core.async
:onyx/batch-size batch-size
:onyx/max-peers 1
:onyx/doc "Reads segments from a core.async channel"}
{:onyx/name :identity
:onyx/fn :clojure.core/identity
:onyx/type :function
:onyx/batch-size batch-size}
{:onyx/name :out
:onyx/plugin :onyx.plugin.core-async/output
:onyx/type :output
:onyx/medium :core.async
:onyx/max-peers 1
:onyx/batch-size batch-size
:onyx/doc "Writes segments to a core.async channel"}])
(def capacity 1000)
(def input-chan (chan capacity))
(def input-buffer (atom {}))
(def output-chan (chan capacity))
(def input-segments
[{:n 0 :event-time #inst "2015-09-13T03:00:00.829-00:00"}
{:n 1 :event-time #inst "2015-09-13T03:03:00.829-00:00"}
{:n 2 :event-time #inst "2015-09-13T03:07:00.829-00:00"}
{:n 3 :event-time #inst "2015-09-13T03:11:00.829-00:00"}
{:n 4 :event-time #inst "2015-09-13T03:15:00.829-00:00"}
{:n 5 :event-time #inst "2015-09-13T03:02:00.829-00:00"}])
(doseq [segment input-segments]
(>!! input-chan segment))
(close! input-chan)
(def env (onyx.api/start-env env-config))
(def peer-group (onyx.api/start-peer-group peer-config))
(def n-peers (count (set (mapcat identity workflow))))
(def v-peers (onyx.api/start-peers n-peers peer-group))
(defn inject-in-ch [event lifecycle]
{:core.async/buffer input-buffer
:core.async/chan input-chan})
(defn inject-out-ch [event lifecycle]
{:core.async/chan output-chan})
(def in-calls
{:lifecycle/before-task-start inject-in-ch})
(def out-calls
{:lifecycle/before-task-start inject-out-ch})
(def lifecycles
[{:lifecycle/task :in
:lifecycle/calls ::in-calls}
{:lifecycle/task :in
:lifecycle/calls :onyx.plugin.core-async/reader-calls}
{:lifecycle/task :out
:lifecycle/calls ::out-calls}
{:lifecycle/task :out
:lifecycle/calls :onyx.plugin.core-async/writer-calls}])
(def windows
[{:window/id :collect-segments
:window/task :identity
:window/type :global
:window/aggregation :onyx.windowing.aggregation/conj}])
(def triggers
[{:trigger/window-id :collect-segments
:trigger/id :sync
:trigger/on :onyx.triggers/segment
:trigger/threshold [5 :elements]
:trigger/sync ::dump-window!}])
(defn dump-window!
[event window trigger {:keys [lower-bound upper-bound] :as window-data} state]
(println (format "Window extent [%s - %s] contents: %s"
lower-bound upper-bound state)))
(defn -main
[& args]
(let [submission (onyx.api/submit-job peer-config
{:workflow workflow
:catalog catalog
:lifecycles lifecycles
:windows windows
:triggers triggers
:task-scheduler :onyx.task-scheduler/balanced})]
(onyx.api/await-job-completion peer-config (:job-id submission)))
(Thread/sleep 5000)
(let [results (take-segments! output-chan 50)])
(doseq [v-peer v-peers]
(onyx.api/shutdown-peer v-peer))
(onyx.api/shutdown-peer-group peer-group)
(onyx.api/shutdown-env env))
|
46916ce2d12887c9054be73807346fd997b364b4d85b7b1950406607807a7838 | erlang/otp | scheduler_SUITE.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2022 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%%-------------------------------------------------------------------
%%% File : scheduler_SUITE.erl
Author :
%%% Description :
%%%
Created : 27 Oct 2008 by
%%%-------------------------------------------------------------------
-module(scheduler_SUITE).
-define(line_trace , 1 ) .
-include_lib("common_test/include/ct.hrl").
%-compile(export_all).
-export([all/0, suite/0, groups/0,
init_per_suite/1, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2]).
-export([equal/1,
few_low/1,
many_low/1,
equal_with_part_time_high/1,
equal_with_part_time_max/1,
equal_and_high_with_part_time_max/1,
equal_with_high/1,
equal_with_high_max/1,
bound_process/1,
scheduler_bind_types/1,
cpu_topology/1,
update_cpu_info/1,
sct_cmd/1,
ssrct_cmd/1,
sbt_cmd/1,
scheduler_threads/1,
scheduler_suspend_basic/1,
scheduler_suspend/1,
dirty_scheduler_threads/1,
sched_poll/1,
poll_threads/1,
reader_groups/1,
otp_16446/1,
simultaneously_change_schedulers_online/1,
simultaneously_change_schedulers_online_with_exits/1]).
suite() ->
[{ct_hooks,[ts_install_cth]},
{timetrap, {minutes, 15}}].
all() ->
[equal, few_low, many_low, equal_with_part_time_high,
equal_with_part_time_max,
equal_and_high_with_part_time_max, equal_with_high,
equal_with_high_max,
bound_process,
{group, scheduler_bind}, scheduler_threads,
scheduler_suspend_basic, scheduler_suspend,
dirty_scheduler_threads,
sched_poll,
poll_threads,
reader_groups,
otp_16446,
simultaneously_change_schedulers_online,
simultaneously_change_schedulers_online_with_exits].
groups() ->
[{scheduler_bind, [],
[scheduler_bind_types, cpu_topology, update_cpu_info,
sct_cmd, sbt_cmd, ssrct_cmd]}].
init_per_suite(Config) ->
[{schedulers_online, erlang:system_info(schedulers_online)} | Config].
end_per_suite(Config) ->
catch erts_debug:set_internal_state(available_internal_state, false),
SchedOnln = proplists:get_value(schedulers_online, Config),
erlang:system_flag(schedulers_online, SchedOnln),
erlang:system_flag(dirty_cpu_schedulers_online, SchedOnln),
Config.
init_per_testcase(update_cpu_info, Config) ->
case os:find_executable("taskset") of
false ->
{skip,"Could not find 'taskset' in path"};
_ ->
init_per_tc(update_cpu_info, Config)
end;
init_per_testcase(ThreadCase, Config) when ThreadCase =:= poll_threads;
ThreadCase =:= scheduler_threads ->
case erlang:system_info(schedulers_online) of
1 -> {skip,"Needs more than one scheduler online"};
_ -> init_per_tc(ThreadCase, Config)
end;
init_per_testcase(Case, Config) when is_list(Config) ->
init_per_tc(Case, Config).
init_per_tc(Case, Config) ->
process_flag(priority, max),
erlang:display({'------------', ?MODULE, Case, '------------'}),
OkRes = ok,
[{testcase, Case}, {ok_res, OkRes} |Config].
end_per_testcase(_Case, Config) when is_list(Config) ->
erts_test_utils:ept_check_leaked_nodes(Config).
-define(ERTS_RUNQ_CHECK_BALANCE_REDS_PER_SCHED, (2000*2000)).
-define(DEFAULT_TEST_REDS_PER_SCHED, 200000000).
%%
%% Test cases
%%
equal(Config) when is_list(Config) ->
low_normal_test(Config, 500, 500).
few_low(Config) when is_list(Config) ->
low_normal_test(Config, 1000, 2*active_schedulers()).
many_low(Config) when is_list(Config) ->
low_normal_test(Config, 2*active_schedulers(), 1000).
low_normal_test(Config, NW, LW) ->
Tracer = start_tracer(),
Low = workers(LW, low),
Normal = workers(NW, normal),
Res = do_it(Tracer, Low, Normal, [], []),
chk_result(Res, LW, NW, 0, 0, true, false, false),
workers_exit([Low, Normal]),
ok(Res, Config).
equal_with_part_time_high(Config) when is_list(Config) ->
NW = 500,
LW = 500,
HW = 1,
Tracer = start_tracer(),
Normal = workers(NW, normal),
Low = workers(LW, low),
High = part_time_workers(HW, high),
Res = do_it(Tracer, Low, Normal, High, []),
chk_result(Res, LW, NW, HW, 0, true, true, false),
workers_exit([Low, Normal, High]),
ok(Res, Config).
equal_and_high_with_part_time_max(Config) when is_list(Config) ->
NW = 500,
LW = 500,
HW = 500,
MW = 1,
Tracer = start_tracer(),
Low = workers(LW, low),
Normal = workers(NW, normal),
High = workers(HW, high),
Max = part_time_workers(MW, max),
Res = do_it(Tracer, Low, Normal, High, Max),
chk_result(Res, LW, NW, HW, MW, false, true, true),
workers_exit([Low, Normal, Max]),
ok(Res, Config).
equal_with_part_time_max(Config) when is_list(Config) ->
NW = 500,
LW = 500,
MW = 1,
Tracer = start_tracer(),
Low = workers(LW, low),
Normal = workers(NW, normal),
Max = part_time_workers(MW, max),
Res = do_it(Tracer, Low, Normal, [], Max),
chk_result(Res, LW, NW, 0, MW, true, false, true),
workers_exit([Low, Normal, Max]),
ok(Res, Config).
equal_with_high(Config) when is_list(Config) ->
NW = 500,
LW = 500,
HW = 1,
Tracer = start_tracer(),
Low = workers(LW, low),
Normal = workers(NW, normal),
High = workers(HW, high),
Res = do_it(Tracer, Low, Normal, High, []),
LNExe = case active_schedulers() of
S when S =< HW -> false;
_ -> true
end,
chk_result(Res, LW, NW, HW, 0, LNExe, true, false),
workers_exit([Low, Normal, High]),
ok(Res, Config).
equal_with_high_max(Config) when is_list(Config) ->
NW = 500,
LW = 500,
HW = 1,
MW = 1,
Tracer = start_tracer(),
Normal = workers(NW, normal),
Low = workers(LW, low),
High = workers(HW, high),
Max = workers(MW, max),
Res = do_it(Tracer, Low, Normal, High, Max),
{LNExe, HExe} = case active_schedulers() of
S when S =< MW -> {false, false};
S when S =< (MW + HW) -> {false, true};
_ -> {true, true}
end,
chk_result(Res, LW, NW, HW, MW, LNExe, HExe, true),
workers_exit([Low, Normal, Max]),
ok(Res, Config).
bound_process(Config) when is_list(Config) ->
case erlang:system_info(run_queues) == erlang:system_info(schedulers) of
true ->
NStartBase = 20000,
NStart = case {erlang:system_info(debug_compiled),
erlang:system_info(lock_checking)} of
{true, true} -> NStartBase div 100;
{_, true} -> NStartBase div 10;
_ -> NStartBase
end,
MStart = 100,
Seq = lists:seq(1, 100),
Tester = self(),
Procs = lists:map(
fun (N) when N rem 2 == 0 ->
spawn_opt(fun () ->
bound_loop(NStart,
NStart,
MStart,
1),
Tester ! {self(), done}
end,
[{scheduler, 1}, link]);
(_N) ->
spawn_link(fun () ->
bound_loop(NStart,
NStart,
MStart,
false),
Tester ! {self(), done}
end)
end,
Seq),
lists:foreach(fun (P) -> receive {P, done} -> ok end end,
Procs),
ok;
false ->
{skipped, "Functionality not supported"}
end.
bound_loop(_, 0, 0, _) ->
ok;
bound_loop(NS, 0, M, false) ->
bound_loop(NS, NS, M-1, false);
bound_loop(NS, N, M, false) ->
erlang:system_info(scheduler_id),
bound_loop(NS, N-1, M, false);
bound_loop(NS, 0, M, Sched) ->
NewSched = (Sched rem erlang:system_info(schedulers_online)) + 1,
Sched = process_flag(scheduler, NewSched),
NewSched = erlang:system_info(scheduler_id),
bound_loop(NS, NS, M-1, NewSched);
bound_loop(NS, N, M, Sched) ->
Sched = erlang:system_info(scheduler_id),
bound_loop(NS, N-1, M, Sched).
-define(TOPOLOGY_A_CMD,
["+sct"
"L0-1t0-1c0p0n0"
":L2-3t0-1c1p0n0"
":L4-5t0-1c0p1n0"
":L6-7t0-1c1p1n0"
":L8-9t0-1c0p2n1"
":L10-11t0-1c1p2n1"
":L12-13t0-1c0p3n1"
":L14-15t0-1c1p3n1"]).
-define(TOPOLOGY_A_TERM,
[{node,[{processor,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]}]},
{processor,[{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]}]},
{node,[{processor,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]}]},
{processor,[{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]}]}]).
-define(TOPOLOGY_B_CMD,
["+sct"
"L0-1t0-1c0n0p0"
":L2-3t0-1c1n0p0"
":L4-5t0-1c2n1p0"
":L6-7t0-1c3n1p0"
":L8-9t0-1c0n2p1"
":L10-11t0-1c1n2p1"
":L12-13t0-1c2n3p1"
":L14-15t0-1c3n3p1"]).
-define(TOPOLOGY_B_TERM,
[{processor,[{node,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]}]},
{node,[{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]}]},
{processor,[{node,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]}]},
{node,[{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]}]}]).
-define(TOPOLOGY_C_TERM,
[{node,[{processor,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]}]},
{processor,[{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]}]},
{processor,[{node,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]}]},
{node,[{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]}]},
{node,[{processor,[{core,[{thread,{logical,16}},
{thread,{logical,17}}]},
{core,[{thread,{logical,18}},
{thread,{logical,19}}]}]},
{processor,[{core,[{thread,{logical,20}},
{thread,{logical,21}}]},
{core,[{thread,{logical,22}},
{thread,{logical,23}}]}]}]},
{processor,[{node,[{core,[{thread,{logical,24}},
{thread,{logical,25}}]},
{core,[{thread,{logical,26}},
{thread,{logical,27}}]}]},
{node,[{core,[{thread,{logical,28}},
{thread,{logical,29}}]},
{core,[{thread,{logical,30}},
{thread,{logical,31}}]}]}]}]).
-define(TOPOLOGY_C_CMD,
["+sct"
"L0-1t0-1c0p0n0"
":L2-3t0-1c1p0n0"
":L4-5t0-1c0p1n0"
":L6-7t0-1c1p1n0"
":L8-9t0-1c0n1p2"
":L10-11t0-1c1n1p2"
":L12-13t0-1c2n2p2"
":L14-15t0-1c3n2p2"
":L16-17t0-1c0p3n3"
":L18-19t0-1c1p3n3"
":L20-21t0-1c0p4n3"
":L22-23t0-1c1p4n3"
":L24-25t0-1c0n4p5"
":L26-27t0-1c1n4p5"
":L28-29t0-1c2n5p5"
":L30-31t0-1c3n5p5"]).
-define(TOPOLOGY_D_TERM,
[{processor,[{node,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]}]},
{node,[{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]}]},
{node,[{processor,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]}]},
{processor,[{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]}]},
{processor,[{node,[{core,[{thread,{logical,16}},
{thread,{logical,17}}]},
{core,[{thread,{logical,18}},
{thread,{logical,19}}]}]},
{node,[{core,[{thread,{logical,20}},
{thread,{logical,21}}]},
{core,[{thread,{logical,22}},
{thread,{logical,23}}]}]}]},
{node,[{processor,[{core,[{thread,{logical,24}},
{thread,{logical,25}}]},
{core,[{thread,{logical,26}},
{thread,{logical,27}}]}]},
{processor,[{core,[{thread,{logical,28}},
{thread,{logical,29}}]},
{core,[{thread,{logical,30}},
{thread,{logical,31}}]}]}]}]).
-define(TOPOLOGY_D_CMD,
["+sct"
"L0-1t0-1c0n0p0"
":L2-3t0-1c1n0p0"
":L4-5t0-1c2n1p0"
":L6-7t0-1c3n1p0"
":L8-9t0-1c0p1n2"
":L10-11t0-1c1p1n2"
":L12-13t0-1c0p2n2"
":L14-15t0-1c1p2n2"
":L16-17t0-1c0n3p3"
":L18-19t0-1c1n3p3"
":L20-21t0-1c2n4p3"
":L22-23t0-1c3n4p3"
":L24-25t0-1c0p4n5"
":L26-27t0-1c1p4n5"
":L28-29t0-1c0p5n5"
":L30-31t0-1c1p5n5"]).
-define(TOPOLOGY_E_CMD,
["+sct"
"L0-1t0-1c0p0n0"
":L2-3t0-1c1p0n0"
":L4-5t0-1c2p0n0"
":L6-7t0-1c3p0n0"
":L8-9t0-1c0p1n1"
":L10-11t0-1c1p1n1"
":L12-13t0-1c2p1n1"
":L14-15t0-1c3p1n1"]).
-define(TOPOLOGY_E_TERM,
[{node,[{processor,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]},
{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]}]},
{node,[{processor,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]},
{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]}]}]).
-define(TOPOLOGY_F_CMD,
["+sct"
"L0-1t0-1c0n0p0"
":L2-3t0-1c1n0p0"
":L4-5t0-1c2n0p0"
":L6-7t0-1c3n0p0"
":L8-9t0-1c4n1p0"
":L10-11t0-1c5n1p0"
":L12-13t0-1c6n1p0"
":L14-15t0-1c7n1p0"
":L16-17t0-1c8n2p0"
":L18-19t0-1c9n2p0"
":L20-21t0-1c10n2p0"
":L22-23t0-1c11n2p0"
":L24-25t0-1c12n3p0"
":L26-27t0-1c13n3p0"
":L28-29t0-1c14n3p0"
":L30-31t0-1c15n3p0"]).
-define(TOPOLOGY_F_TERM,
[{processor,[{node,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]},
{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]},
{node,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]},
{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]},
{node,[{core,[{thread,{logical,16}},
{thread,{logical,17}}]},
{core,[{thread,{logical,18}},
{thread,{logical,19}}]},
{core,[{thread,{logical,20}},
{thread,{logical,21}}]},
{core,[{thread,{logical,22}},
{thread,{logical,23}}]}]},
{node,[{core,[{thread,{logical,24}},
{thread,{logical,25}}]},
{core,[{thread,{logical,26}},
{thread,{logical,27}}]},
{core,[{thread,{logical,28}},
{thread,{logical,29}}]},
{core,[{thread,{logical,30}},
{thread,{logical,31}}]}]}]}]).
bindings(Node, BindType) ->
Parent = self(),
Ref = make_ref(),
Pid = spawn_link(Node,
fun () ->
enable_internal_state(),
Res = (catch erts_debug:get_internal_state(
{fake_scheduler_bindings,
BindType})),
Parent ! {Ref, Res}
end),
receive
{Ref, Res} ->
io:format("~p: ~p~n", [BindType, Res]),
unlink(Pid),
Res
end.
scheduler_bind_types(Config) when is_list(Config) ->
OldRelFlags = clear_erl_rel_flags(),
try
scheduler_bind_types_test(
?TOPOLOGY_A_TERM,
?TOPOLOGY_A_CMD,
a),
scheduler_bind_types_test(
?TOPOLOGY_B_TERM,
?TOPOLOGY_B_CMD,
b),
scheduler_bind_types_test(
?TOPOLOGY_C_TERM,
?TOPOLOGY_C_CMD,
c),
scheduler_bind_types_test(
?TOPOLOGY_D_TERM,
?TOPOLOGY_D_CMD,
d),
scheduler_bind_types_test(
?TOPOLOGY_E_TERM,
?TOPOLOGY_E_CMD,
e),
scheduler_bind_types_test(
?TOPOLOGY_F_TERM,
?TOPOLOGY_F_CMD,
f)
after
restore_erl_rel_flags(OldRelFlags)
end,
ok.
scheduler_bind_types_test(Topology, CmdLine, TermLetter) ->
io:format("Testing (~p): ~p~n", [TermLetter, Topology]),
{ok, Peer, Node0} = ?CT_PEER(),
_ = rpc:call(Node0, erlang, system_flag, [cpu_topology, Topology]),
cmp(Topology, rpc:call(Node0, erlang, system_info, [cpu_topology])),
check_bind_types(Node0, TermLetter),
peer:stop(Peer),
{ok, Peer1, Node1} = ?CT_PEER(CmdLine),
cmp(Topology, rpc:call(Node1, erlang, system_info, [cpu_topology])),
check_bind_types(Node1, TermLetter),
peer:stop(Peer1).
check_bind_types(Node, a) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
= bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, thread_spread),
{0,4,8,12,2,6,10,14,1,5,9,13,3,7,11,15}
= bindings(Node, processor_spread),
{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}
= bindings(Node, spread),
{0,2,4,6,1,3,5,7,8,10,12,14,9,11,13,15}
= bindings(Node, no_node_thread_spread),
{0,4,2,6,1,5,3,7,8,12,10,14,9,13,11,15}
= bindings(Node, no_node_processor_spread),
{0,4,2,6,8,12,10,14,1,5,3,7,9,13,11,15}
= bindings(Node, thread_no_node_processor_spread),
{0,4,2,6,8,12,10,14,1,5,3,7,9,13,11,15}
= bindings(Node, default_bind),
ok;
check_bind_types(Node, b) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
= bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, thread_spread),
{0,8,2,10,4,12,6,14,1,9,3,11,5,13,7,15}
= bindings(Node, processor_spread),
{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}
= bindings(Node, spread),
{0,2,1,3,4,6,5,7,8,10,9,11,12,14,13,15}
= bindings(Node, no_node_thread_spread),
{0,2,1,3,4,6,5,7,8,10,9,11,12,14,13,15}
= bindings(Node, no_node_processor_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, thread_no_node_processor_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, default_bind),
ok;
check_bind_types(Node, c) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,27,28,29,30,31} = bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,15,
17,19,21,23,25,27,29,31} = bindings(Node, thread_spread),
{0,4,8,16,20,24,2,6,10,18,22,26,12,28,14,30,1,5,9,17,21,25,
3,7,11,19,23,27,13,29,15,31} = bindings(Node, processor_spread),
{0,8,16,24,4,20,12,28,2,10,18,26,6,22,14,30,1,9,17,25,5,21,13,29,3,11,
19,27,7,23,15,31} = bindings(Node, spread),
{0,2,4,6,1,3,5,7,8,10,9,11,12,14,13,15,16,18,20,22,17,19,21,23,24,26,
25,27,28,30,29,31} = bindings(Node, no_node_thread_spread),
{0,4,2,6,1,5,3,7,8,10,9,11,12,14,13,15,16,20,18,22,17,21,19,23,24,26,
25,27,28,30,29,31} = bindings(Node, no_node_processor_spread),
{0,4,2,6,8,10,12,14,16,20,18,22,24,26,28,30,1,5,3,7,9,11,13,15,17,21,
19,23,25,27,29,31} = bindings(Node, thread_no_node_processor_spread),
{0,4,2,6,8,10,12,14,16,20,18,22,24,26,28,30,1,5,3,7,9,11,13,15,17,21,
19,23,25,27,29,31} = bindings(Node, default_bind),
ok;
check_bind_types(Node, d) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,27,28,29,30,31} = bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,15,
17,19,21,23,25,27,29,31} = bindings(Node, thread_spread),
{0,8,12,16,24,28,2,10,14,18,26,30,4,20,6,22,1,9,13,17,25,29,3,11,15,
19,27,31,5,21,7,23} = bindings(Node, processor_spread),
{0,8,16,24,12,28,4,20,2,10,18,26,14,30,6,22,1,9,17,25,13,29,5,21,3,11,
19,27,15,31,7,23} = bindings(Node, spread),
{0,2,1,3,4,6,5,7,8,10,12,14,9,11,13,15,16,18,17,19,20,22,21,23,24,26,
28,30,25,27,29,31} = bindings(Node, no_node_thread_spread),
{0,2,1,3,4,6,5,7,8,12,10,14,9,13,11,15,16,18,17,19,20,22,21,23,24,28,
26,30,25,29,27,31} = bindings(Node, no_node_processor_spread),
{0,2,4,6,8,12,10,14,16,18,20,22,24,28,26,30,1,3,5,7,9,13,11,15,17,19,
21,23,25,29,27,31} = bindings(Node, thread_no_node_processor_spread),
{0,2,4,6,8,12,10,14,16,18,20,22,24,28,26,30,1,3,5,7,9,13,11,15,17,19,
21,23,25,29,27,31} = bindings(Node, default_bind),
ok;
check_bind_types(Node, e) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
= bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, thread_spread),
{0,8,2,10,4,12,6,14,1,9,3,11,5,13,7,15}
= bindings(Node, processor_spread),
{0,8,2,10,4,12,6,14,1,9,3,11,5,13,7,15}
= bindings(Node, spread),
{0,2,4,6,1,3,5,7,8,10,12,14,9,11,13,15}
= bindings(Node, no_node_thread_spread),
{0,2,4,6,1,3,5,7,8,10,12,14,9,11,13,15}
= bindings(Node, no_node_processor_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, thread_no_node_processor_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, default_bind),
ok;
check_bind_types(Node, f) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,27,28,29,30,31} = bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,15,
17,19,21,23,25,27,29,31} = bindings(Node, thread_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,
15,17,19,21,23,25,27,29,31} = bindings(Node, processor_spread),
{0,8,16,24,2,10,18,26,4,12,20,28,6,14,22,30,1,9,17,25,3,11,19,27,5,13,
21,29,7,15,23,31} = bindings(Node, spread),
{0,2,4,6,1,3,5,7,8,10,12,14,9,11,13,15,16,18,20,22,17,19,21,23,24,26,
28,30,25,27,29,31} = bindings(Node, no_node_thread_spread),
{0,2,4,6,1,3,5,7,8,10,12,14,9,11,13,15,16,18,20,22,17,19,21,23,24,26,
28,30,25,27,29,31} = bindings(Node, no_node_processor_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,15,17,19,
21,23,25,27,29,31} = bindings(Node, thread_no_node_processor_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,15,17,19,
21,23,25,27,29,31} = bindings(Node, default_bind),
ok;
check_bind_types(Node, _) ->
bindings(Node, no_spread),
bindings(Node, thread_spread),
bindings(Node, processor_spread),
bindings(Node, spread),
bindings(Node, no_node_thread_spread),
bindings(Node, no_node_processor_spread),
bindings(Node, thread_no_node_processor_spread),
bindings(Node, default_bind),
ok.
cpu_topology(Config) when is_list(Config) ->
OldRelFlags = clear_erl_rel_flags(),
try
cpu_topology_test(
[{node,[{processor,[{core,{logical,0}},
{core,{logical,1}}]}]},
{processor,[{node,[{core,{logical,2}},
{core,{logical,3}}]}]},
{node,[{processor,[{core,{logical,4}},
{core,{logical,5}}]}]},
{processor,[{node,[{core,{logical,6}},
{core,{logical,7}}]}]}],
["+sct",
"L0-1c0-1p0n0"
":L2-3c0-1n1p1"
":L4-5c0-1p2n2"
":L6-7c0-1n3p3"]),
cpu_topology_test(
[{node,[{processor,[{core,{logical,0}},
{core,{logical,1}}]},
{processor,[{core,{logical,2}},
{core,{logical,3}}]}]},
{processor,[{node,[{core,{logical,4}},
{core,{logical,5}}]},
{node,[{core,{logical,6}},
{core,{logical,7}}]}]},
{node,[{processor,[{core,{logical,8}},
{core,{logical,9}}]},
{processor,[{core,{logical,10}},
{core,{logical,11}}]}]},
{processor,[{node,[{core,{logical,12}},
{core,{logical,13}}]},
{node,[{core,{logical,14}},
{core,{logical,15}}]}]}],
["+sct",
"L0-1c0-1p0n0"
":L2-3c0-1p1n0"
":L4-5c0-1n1p2"
":L6-7c2-3n2p2"
":L8-9c0-1p3n3"
":L10-11c0-1p4n3"
":L12-13c0-1n4p5"
":L14-15c2-3n5p5"]),
cpu_topology_test(
[{node,[{processor,[{core,{logical,0}},
{core,{logical,1}}]}]},
{processor,[{node,[{core,{logical,2}},
{core,{logical,3}}]}]},
{processor,[{node,[{core,{logical,4}},
{core,{logical,5}}]}]},
{node,[{processor,[{core,{logical,6}},
{core,{logical,7}}]}]},
{node,[{processor,[{core,{logical,8}},
{core,{logical,9}}]}]},
{processor,[{node,[{core,{logical,10}},
{core,{logical,11}}]}]}],
["+sct",
"L0-1c0-1p0n0"
":L2-3c0-1n1p1"
":L4-5c0-1n2p2"
":L6-7c0-1p3n3"
":L8-9c0-1p4n4"
":L10-11c0-1n5p5"])
after
restore_erl_rel_flags(OldRelFlags)
end,
ok.
cpu_topology_test(Topology, Cmd) ->
io:format("Testing~n ~p~n ~p~n", [Topology, Cmd]),
cpu_topology_bif_test(Topology),
cpu_topology_cmdline_test(Topology, Cmd),
ok.
cpu_topology_bif_test(false) ->
ok;
cpu_topology_bif_test(Topology) ->
{ok, Peer, Node} = ?CT_PEER(),
_ = rpc:call(Node, erlang, system_flag, [cpu_topology, Topology]),
cmp(Topology, rpc:call(Node, erlang, system_info, [cpu_topology])),
cmp(Topology,
rpc:call(Node, erlang, system_info, [{cpu_topology, defined}])),
peer:stop(Peer),
ok.
cpu_topology_cmdline_test(_Topology, false) ->
ok;
cpu_topology_cmdline_test(Topology, Cmd) ->
{ok, Peer, Node} = ?CT_PEER(Cmd),
cmp(Topology, rpc:call(Node, erlang, system_info, [cpu_topology])),
cmp(undefined,
rpc:call(Node, erlang, system_info, [{cpu_topology, detected}])),
cmp(Topology,
rpc:call(Node, erlang, system_info, [{cpu_topology, defined}])),
peer:stop(Peer),
ok.
update_cpu_info(Config) when is_list(Config) ->
OldOnline = erlang:system_info(schedulers_online),
OldAff = get_affinity_mask(),
io:format("START - Affinity mask: ~p - Schedulers online: ~p - Scheduler bindings: ~p~n",
[OldAff, OldOnline, erlang:system_info(scheduler_bindings)]),
case {erlang:system_info(logical_processors_available), OldAff} of
{Avail, _} when Avail == unknown; OldAff == unknown; OldAff == 1 ->
%% Nothing much to test; just a smoke test
case erlang:system_info(update_cpu_info) of
unchanged -> ok;
changed -> ok
end;
{_Avail, _} ->
try
adjust_schedulers_online(),
case erlang:system_info(schedulers_online) of
1 ->
%% Nothing much to test; just a smoke test
ok;
Onln0 ->
Cpus = bits_in_mask(OldAff),
RmCpus = case Cpus > Onln0 of
true -> Cpus - Onln0 + 1;
false -> Onln0 - Cpus + 1
end,
Onln1 = Cpus - RmCpus,
case Onln1 > 0 of
false ->
%% Nothing much to test; just a smoke test
ok;
true ->
Aff = restrict_affinity_mask(OldAff, RmCpus),
set_affinity_mask(Aff),
case adjust_schedulers_online() of
{Onln0, Onln1} ->
Onln1 = erlang:system_info(schedulers_online),
receive after 500 -> ok end,
io:format("TEST - Affinity mask: ~p - Schedulers online: ~p - Scheduler bindings: ~p~n",
[Aff, Onln1, erlang:system_info(scheduler_bindings)]),
unchanged = adjust_schedulers_online(),
ok;
Fail ->
ct:fail(Fail)
end
end
end
after
set_affinity_mask(OldAff),
adjust_schedulers_online(),
erlang:system_flag(schedulers_online, OldOnline),
receive after 500 -> ok end,
io:format("END - Affinity mask: ~p - Schedulers online: ~p - Scheduler bindings: ~p~n",
[get_affinity_mask(),
erlang:system_info(schedulers_online),
erlang:system_info(scheduler_bindings)])
end
end.
bits_in_mask(Mask) ->
bits_in_mask(Mask, 0, 0).
bits_in_mask(0, _Shift, N) ->
N;
bits_in_mask(Mask, Shift, N) ->
case Mask band (1 bsl Shift) of
0 -> bits_in_mask(Mask, Shift+1, N);
_ -> bits_in_mask(Mask band (bnot (1 bsl Shift)),
Shift+1, N+1)
end.
restrict_affinity_mask(Mask, N) ->
try
restrict_affinity_mask(Mask, 0, N)
catch
throw : Reason ->
exit({Reason, Mask, N})
end.
restrict_affinity_mask(Mask, _Shift, 0) ->
Mask;
restrict_affinity_mask(0, _Shift, _N) ->
throw(overresticted_affinity_mask);
restrict_affinity_mask(Mask, Shift, N) ->
case Mask band (1 bsl Shift) of
0 -> restrict_affinity_mask(Mask, Shift+1, N);
_ -> restrict_affinity_mask(Mask band (bnot (1 bsl Shift)),
Shift+1, N-1)
end.
adjust_schedulers_online() ->
case erlang:system_info(update_cpu_info) of
unchanged ->
unchanged;
changed ->
Avail = erlang:system_info(logical_processors_available),
Scheds = erlang:system_info(schedulers),
SOnln = case Avail > Scheds of
true -> Scheds;
false -> Avail
end,
{erlang:system_flag(schedulers_online, SOnln), SOnln}
end.
read_affinity(Data) ->
Exp = "pid " ++ os:getpid() ++ "'s current affinity mask",
case string:lexemes(Data, ":") of
[Exp, DirtyAffinityStr] ->
AffinityStr = string:trim(DirtyAffinityStr),
case catch erlang:list_to_integer(AffinityStr, 16) of
Affinity when is_integer(Affinity) ->
Affinity;
_ ->
bad
end;
_ ->
bad
end.
get_affinity_mask(Port, Status, Affinity) when Status == unknown;
Affinity == unknown ->
receive
{Port,{data, Data}} ->
get_affinity_mask(Port, Status, read_affinity(Data));
{Port,{exit_status,S}} ->
get_affinity_mask(Port, S, Affinity)
end;
get_affinity_mask(_Port, _Status, bad) ->
unknown;
get_affinity_mask(_Port, _Status, Affinity) ->
Affinity.
get_affinity_mask() ->
case os:type() of
{unix, linux} ->
case catch open_port({spawn, "taskset -p " ++ os:getpid()},
[exit_status]) of
Port when is_port(Port) ->
get_affinity_mask(Port, unknown, unknown);
_ ->
unknown
end;
_ ->
unknown
end.
set_affinity_mask(Port, unknown) ->
receive
{Port,{data, _}} ->
set_affinity_mask(Port, unknown);
{Port,{exit_status,Status}} ->
set_affinity_mask(Port, Status)
end;
set_affinity_mask(Port, Status) ->
receive
{Port,{data, _}} ->
set_affinity_mask(Port, unknown)
after 0 ->
Status
end.
set_affinity_mask(Mask) ->
Cmd = lists:flatten(["taskset -p ",
io_lib:format("~.16b", [Mask]),
" ",
os:getpid()]),
case catch open_port({spawn, Cmd}, [exit_status]) of
Port when is_port(Port) ->
case set_affinity_mask(Port, unknown) of
0 -> ok;
_ -> exit(failed_to_set_affinity)
end;
_ ->
exit(failed_to_set_affinity)
end.
sct_cmd(Config) when is_list(Config) ->
Topology = ?TOPOLOGY_A_TERM,
OldRelFlags = clear_erl_rel_flags(),
try
{ok, Peer, Node} = ?CT_PEER(?TOPOLOGY_A_CMD),
cmp(Topology,
rpc:call(Node, erlang, system_info, [cpu_topology])),
cmp(undefined,
rpc:call(Node, erlang, system_info, [{cpu_topology, detected}])),
cmp(Topology,
rpc:call(Node, erlang, system_info, [{cpu_topology, defined}])),
cmp(Topology,
rpc:call(Node, erlang, system_flag, [cpu_topology, Topology])),
cmp(Topology,
rpc:call(Node, erlang, system_info, [cpu_topology])),
peer:stop(Peer)
after
restore_erl_rel_flags(OldRelFlags)
end,
ok.
ssrct_cmd(Config) when is_list(Config) ->
OldRelFlags = clear_erl_rel_flags(),
try
{ok, Peer, Node} = ?CT_PEER(["+ssrct"]),
cmp(undefined,
rpc:call(Node, erlang, system_info, [cpu_topology])),
cmp(undefined,
rpc:call(Node, erlang, system_info, [{cpu_topology, detected}])),
cmp(undefined,
rpc:call(Node, erlang, system_info, [{cpu_topology, defined}])),
peer:stop(Peer)
after
restore_erl_rel_flags(OldRelFlags)
end,
ok.
-define(BIND_TYPES,
[{"u", unbound},
{"ns", no_spread},
{"ts", thread_spread},
{"ps", processor_spread},
{"s", spread},
{"nnts", no_node_thread_spread},
{"nnps", no_node_processor_spread},
{"tnnps", thread_no_node_processor_spread},
{"db", thread_no_node_processor_spread}]).
sbt_cmd(Config) when is_list(Config) ->
case sbt_check_prereqs() of
{skipped, _Reason}=Skipped ->
Skipped;
ok ->
case sbt_make_topology_args() of
false ->
{skipped, "Don't know how to create cpu topology"};
CpuTCmd ->
LP = erlang:system_info(logical_processors),
OldRelFlags = clear_erl_rel_flags(),
try
lists:foreach(fun ({ClBt, Bt}) ->
sbt_test(CpuTCmd,
ClBt, Bt, LP)
end,
?BIND_TYPES)
after
restore_erl_rel_flags(OldRelFlags)
end,
ok
end
end.
sbt_make_topology_args() ->
case erlang:system_info({cpu_topology,detected}) of
undefined ->
case os:type() of
linux ->
case erlang:system_info(logical_processors) of
1 ->
["+sctL0"];
N ->
NS = integer_to_list(N - 1),
["+sctL0-"++NS++"p0-"++NS]
end;
_ ->
false
end;
_ ->
""
end.
sbt_check_prereqs() ->
try
Available = erlang:system_info(logical_processors_available),
Quota = erlang:system_info(cpu_quota),
if
Quota =:= unknown; Quota >= Available ->
ok;
Quota < Available ->
throw({skipped, "Test requires that CPU quota is greater than "
"the number of available processors."})
end,
try
OldVal = erlang:system_flag(scheduler_bind_type, default_bind),
erlang:system_flag(scheduler_bind_type, OldVal)
catch
error:notsup ->
throw({skipped, "Scheduler binding not supported."});
error:_ ->
%% ?!
ok
end,
case erlang:system_info(logical_processors) of
Count when is_integer(Count) ->
ok;
unknown ->
throw({skipped, "Can't detect number of logical processors."})
end,
ok
catch
throw:{skip,_Reason}=Skip -> Skip
end.
sbt_test(CpuTCmd, ClBt, Bt, LP) ->
io:format("Testing +sbt ~s (~p)~n", [ClBt, Bt]),
LPS = integer_to_list(LP),
Cmd = CpuTCmd++["+sbt", ClBt, "+S"++LPS++":"++LPS],
{ok, Peer, Node} = ?CT_PEER(Cmd),
Bt = rpc:call(Node,
erlang,
system_info,
[scheduler_bind_type]),
SB = rpc:call(Node,
erlang,
system_info,
[scheduler_bindings]),
io:format("scheduler bindings: ~p~n", [SB]),
BS = case {Bt, erlang:system_info(logical_processors_available)} of
{unbound, _} -> 0;
{_, Int} when is_integer(Int) -> Int;
{_, _} -> LP
end,
lists:foldl(fun (S, 0) ->
unbound = S,
0;
(S, N) ->
true = is_integer(S),
N-1
end,
BS,
tuple_to_list(SB)),
peer:stop(Peer),
ok.
scheduler_threads(Config) when is_list(Config) ->
{Sched, SchedOnln, _} = get_sstate(""),
%% Configure half the number of both the scheduler threads and
%% the scheduler threads online.
{HalfSched, HalfSchedOnln} = {lists:max([1,Sched div 2]),
lists:max([1,SchedOnln div 2])},
{HalfSched, HalfSchedOnln, _} = get_sstate(["+SP", "50:50"]),
%% Use +S to configure 4x the number of scheduler threads and
%% 4x the number of scheduler threads online, but alter that
setting using + SP to 50 % scheduler threads and 25 % scheduler
%% threads online. The result should be 2x scheduler threads and
%% 1x scheduler threads online.
TwiceSched = Sched*2,
FourSched = integer_to_list(Sched*4),
FourSchedOnln = integer_to_list(SchedOnln*4),
CombinedCmd1 = ["+S", FourSched++":"++FourSchedOnln, "+SP50:25"],
{TwiceSched, SchedOnln, _} = get_sstate(CombinedCmd1),
Now do the same test but with the + S and + SP options in the
%% opposite order, since order shouldn't matter.
CombinedCmd2 = ["+SP50:25", "+S", FourSched++":"++FourSchedOnln],
{TwiceSched, SchedOnln, _} = get_sstate(CombinedCmd2),
Apply two + SP options to make sure the second overrides the first
TwoCmd = ["+SP", "25:25", "+SP", "100:100"],
{Sched, SchedOnln, _} = get_sstate(TwoCmd),
Configure 50 % of scheduler threads online only
{Sched, HalfSchedOnln, _} = get_sstate(["+SP:50"]),
%% Configure 2x scheduler threads only
{TwiceSched, SchedOnln, _} = get_sstate(["+SP", "200"]),
LProc = erlang:system_info(logical_processors),
LProcAvail = erlang:system_info(logical_processors_available),
Quota = erlang:system_info(cpu_quota),
if
not is_integer(LProc); not is_integer(LProcAvail) ->
{comment, "Skipped reset amount of schedulers test, and reduced "
"amount of schedulers test due to too unknown amount of "
"logical processors"};
is_integer(LProc); is_integer(LProcAvail) ->
ExpectedOnln = st_expected_onln(LProcAvail, Quota),
st_reset(LProc, ExpectedOnln, FourSched, FourSchedOnln),
if
LProc =:= 1; LProcAvail =:= 1 ->
{comment, "Skipped reduced amount of schedulers test due "
"to too few logical processors"};
LProc > 1, LProcAvail > 1 ->
st_reduced(LProc, ExpectedOnln)
end
end.
st_reset(LProc, ExpectedOnln, FourSched, FourSchedOnln) ->
%% Test resetting # of schedulers.
ResetCmd = ["+S", FourSched++":"++FourSchedOnln, "+S", "0:0"],
{LProc, ExpectedOnln, _} = get_sstate(ResetCmd),
ok.
st_reduced(LProc, ExpectedOnln) ->
%% Test negative +S settings
SchedMinus1 = LProc-1,
SchedOnlnMinus1 = ExpectedOnln-1,
{SchedMinus1, SchedOnlnMinus1, _} = get_sstate(["+S", "-1"]),
{LProc, SchedOnlnMinus1, _} = get_sstate(["+S", ":-1"]),
{SchedMinus1, SchedOnlnMinus1, _} = get_sstate(["+S", "-1:-1"]),
ok.
st_expected_onln(LProcAvail, unknown) -> LProcAvail;
st_expected_onln(LProcAvail, Quota) -> min(LProcAvail, Quota).
dirty_scheduler_threads(Config) when is_list(Config) ->
case erlang:system_info(dirty_cpu_schedulers) of
0 -> {skipped, "No dirty scheduler support"};
_ -> dirty_scheduler_threads_test(Config)
end.
dirty_scheduler_threads_test(Config) when is_list(Config) ->
{Sched, SchedOnln, _} = get_dsstate(""),
{HalfSched, HalfSchedOnln} = {lists:max([1,Sched div 2]),
lists:max([1,SchedOnln div 2])},
Cmd1 = ["+SDcpu", integer_to_list(HalfSched)++":"++
integer_to_list(HalfSchedOnln)],
{HalfSched, HalfSchedOnln, _} = get_dsstate(Cmd1),
{HalfSched, HalfSchedOnln, _} = get_dsstate(["+SDPcpu", "50:50"]),
IOSched = 20,
{_, _, IOSched} = get_dsstate(["+SDio", integer_to_list(IOSched)]),
{ok, Peer, Node} = ?CT_PEER(),
[ok] = mcall(Node, [fun() -> dirty_schedulers_online_test() end]),
peer:stop(Peer),
ok.
dirty_schedulers_online_test() ->
dirty_schedulers_online_smp_test(erlang:system_info(schedulers_online)).
dirty_schedulers_online_smp_test(SchedOnln) when SchedOnln < 4 -> ok;
dirty_schedulers_online_smp_test(SchedOnln) ->
receive after 500 -> ok end,
DirtyCPUSchedOnln = erlang:system_info(dirty_cpu_schedulers_online),
SchedOnln = DirtyCPUSchedOnln,
HalfSchedOnln = SchedOnln div 2,
SchedOnln = erlang:system_flag(schedulers_online, HalfSchedOnln),
HalfDirtyCPUSchedOnln = DirtyCPUSchedOnln div 2,
HalfDirtyCPUSchedOnln = erlang:system_flag(schedulers_online, SchedOnln),
DirtyCPUSchedOnln = erlang:system_flag(dirty_cpu_schedulers_online,
HalfDirtyCPUSchedOnln),
receive after 500 -> ok end,
HalfDirtyCPUSchedOnln = erlang:system_info(dirty_cpu_schedulers_online),
QrtrDirtyCPUSchedOnln = HalfDirtyCPUSchedOnln div 2,
SchedOnln = erlang:system_flag(schedulers_online, HalfSchedOnln),
receive after 500 -> ok end,
QrtrDirtyCPUSchedOnln = erlang:system_info(dirty_cpu_schedulers_online),
ok.
get_sstate(Cmd) ->
{ok, Peer, Node} = ?CT_PEER(#{ args => Cmd, env => [{"ERL_FLAGS",false}]}),
[SState] = mcall(Node, [fun () ->
erlang:system_info(schedulers_state)
end]),
peer:stop(Peer),
SState.
get_dsstate(Cmd) ->
{ok, Peer, Node} = ?CT_PEER(#{ args => Cmd, env => [{"ERL_FLAGS",false}]}),
[DSCPU] = mcall(Node, [fun () ->
erlang:system_info(dirty_cpu_schedulers)
end]),
[DSCPUOnln] = mcall(Node, [fun () ->
erlang:system_info(dirty_cpu_schedulers_online)
end]),
[DSIO] = mcall(Node, [fun () ->
erlang:system_info(dirty_io_schedulers)
end]),
peer:stop(Peer),
{DSCPU, DSCPUOnln, DSIO}.
scheduler_suspend_basic(Config) when is_list(Config) ->
case erlang:system_info(multi_scheduling) of
disabled ->
{skip, "Nothing to test"};
_ ->
Onln = erlang:system_info(schedulers_online),
DirtyOnln = erlang:system_info(dirty_cpu_schedulers_online),
try
scheduler_suspend_basic_test()
after
erlang:system_flag(schedulers_online, Onln),
erlang:system_flag(dirty_cpu_schedulers_online, DirtyOnln)
end
end.
scheduler_suspend_basic_test() ->
%% The receives after setting scheduler states are there
%% since the operation is not fully synchronous. For example,
%% we do not wait for dirty cpu schedulers online to complete
before returning from erlang : system_flag(schedulers_online , _ ) .
erlang:system_flag(schedulers_online,
erlang:system_info(schedulers)),
try
erlang:system_flag(dirty_cpu_schedulers_online,
erlang:system_info(dirty_cpu_schedulers)),
receive after 500 -> ok end
catch
_ : _ ->
ok
end,
S0 = sched_state(),
io:format("~p~n", [S0]),
{{normal,NTot0,NOnln0,NAct0},
{dirty_cpu,DCTot0,DCOnln0,DCAct0},
{dirty_io,DITot0,DIOnln0,DIAct0}} = S0,
enabled = erlang:system_info(multi_scheduling),
DCOne = case DCTot0 of
0 -> 0;
_ -> 1
end,
blocked_normal = erlang:system_flag(multi_scheduling, block_normal),
blocked_normal = erlang:system_info(multi_scheduling),
{{normal,NTot0,NOnln0,1},
{dirty_cpu,DCTot0,DCOnln0,DCAct0},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
NOnln0 = erlang:system_flag(schedulers_online, 1),
receive after 500 -> ok end,
{{normal,NTot0,1,1},
{dirty_cpu,DCTot0,DCOne,DCOne},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
1 = erlang:system_flag(schedulers_online, NOnln0),
receive after 500 -> ok end,
{{normal,NTot0,NOnln0,1},
{dirty_cpu,DCTot0,DCOnln0,DCAct0},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
blocked = erlang:system_flag(multi_scheduling, block),
blocked = erlang:system_info(multi_scheduling),
receive after 500 -> ok end,
{{normal,NTot0,NOnln0,1},
{dirty_cpu,DCTot0,DCOnln0,0},
{dirty_io,DITot0,DIOnln0,0}} = sched_state(),
NOnln0 = erlang:system_flag(schedulers_online, 1),
receive after 500 -> ok end,
{{normal,NTot0,1,1},
{dirty_cpu,DCTot0,DCOne,0},
{dirty_io,DITot0,DIOnln0,0}} = sched_state(),
1 = erlang:system_flag(schedulers_online, NOnln0),
receive after 500 -> ok end,
{{normal,NTot0,NOnln0,1},
{dirty_cpu,DCTot0,DCOnln0,0},
{dirty_io,DITot0,DIOnln0,0}} = sched_state(),
blocked = erlang:system_flag(multi_scheduling, unblock_normal),
blocked = erlang:system_info(multi_scheduling),
{{normal,NTot0,NOnln0,1},
{dirty_cpu,DCTot0,DCOnln0,0},
{dirty_io,DITot0,DIOnln0,0}} = sched_state(),
enabled = erlang:system_flag(multi_scheduling, unblock),
enabled = erlang:system_info(multi_scheduling),
receive after 500 -> ok end,
{{normal,NTot0,NOnln0,NAct0},
{dirty_cpu,DCTot0,DCOnln0,DCAct0},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
NOnln0 = erlang:system_flag(schedulers_online, 1),
receive after 500 -> ok end,
{{normal,NTot0,1,1},
{dirty_cpu,DCTot0,DCOne,DCOne},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
1 = erlang:system_flag(schedulers_online, NOnln0),
receive after 500 -> ok end,
{{normal,NTot0,NOnln0,NAct0},
{dirty_cpu,DCTot0,DCOnln0,DCAct0},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
ok.
scheduler_suspend(Config) when is_list(Config) ->
ct:timetrap({minutes, 5}),
lists:foreach(fun (S) -> scheduler_suspend_test(S) end,
[64, 32, 16, default]),
ok.
scheduler_suspend_test(Schedulers) ->
Cmd = case Schedulers of
default ->
"";
_ ->
S = integer_to_list(Schedulers),
["+S"++S++":"++S]
end,
{ok, Peer, Node} = ?CT_PEER(Cmd),
[SState] = mcall(Node, [fun () ->
erlang:system_info(schedulers_state)
end]),
io:format("SState=~p~n", [SState]),
{Sched, SchedOnln, _SchedAvail} = SState,
true = is_integer(Sched),
[ok] = mcall(Node, [fun () -> sst0_loop(300) end]),
[ok] = mcall(Node, [fun () -> sst1_loop(300) end]),
[ok] = mcall(Node, [fun () -> sst2_loop(300) end]),
[ok] = mcall(Node, [fun () -> sst4_loop(300) end]),
[ok] = mcall(Node, [fun () -> sst5_loop(300) end]),
[ok, ok, ok, ok,
ok, ok, ok] = mcall(Node,
[fun () -> sst0_loop(200) end,
fun () -> sst1_loop(200) end,
fun () -> sst2_loop(200) end,
fun () -> sst2_loop(200) end,
fun () -> sst3_loop(Sched, 200) end,
fun () -> sst4_loop(200) end,
fun () -> sst5_loop(200) end]),
[SState] = mcall(Node, [fun () ->
case Sched == SchedOnln of
false ->
Sched = erlang:system_flag(
schedulers_online,
SchedOnln);
true ->
ok
end,
until(fun () ->
{_A, B, C} = erlang:system_info(
schedulers_state),
B == C
end,
erlang:monotonic_time()
+ erlang:convert_time_unit(1,
seconds,
native)),
erlang:system_info(schedulers_state)
end]),
peer:stop(Peer),
ok.
until(Pred, MaxTime) ->
case Pred() of
true ->
true;
false ->
case erlang:monotonic_time() > MaxTime of
true ->
false;
false ->
receive after 100 -> ok end,
until(Pred, MaxTime)
end
end.
sst0_loop(0) ->
ok;
sst0_loop(N) ->
erlang:system_flag(multi_scheduling, block),
erlang:system_flag(multi_scheduling, unblock),
erlang:yield(),
sst0_loop(N-1).
sst1_loop(0) ->
ok;
sst1_loop(N) ->
erlang:system_flag(multi_scheduling, block),
erlang:system_flag(multi_scheduling, unblock),
sst1_loop(N-1).
sst2_loop(0) ->
ok;
sst2_loop(N) ->
erlang:system_flag(multi_scheduling, block),
erlang:system_flag(multi_scheduling, block),
erlang:system_flag(multi_scheduling, block),
erlang:system_flag(multi_scheduling, unblock),
erlang:system_flag(multi_scheduling, unblock),
erlang:system_flag(multi_scheduling, unblock),
sst2_loop(N-1).
sst3_loop(S, N) ->
case erlang:system_info(dirty_cpu_schedulers) of
0 -> sst3_loop_normal_schedulers_only(S, N);
DS -> sst3_loop_with_dirty_schedulers(S, DS, N)
end.
sst3_loop_normal_schedulers_only(_S, 0) ->
ok;
sst3_loop_normal_schedulers_only(S, N) ->
erlang:system_flag(schedulers_online, (S div 2)+1),
erlang:system_flag(schedulers_online, 1),
erlang:system_flag(schedulers_online, (S div 2)+1),
erlang:system_flag(schedulers_online, S),
erlang:system_flag(schedulers_online, 1),
erlang:system_flag(schedulers_online, S),
sst3_loop_normal_schedulers_only(S, N-1).
sst3_loop_with_dirty_schedulers(_S, _DS, 0) ->
ok;
sst3_loop_with_dirty_schedulers(S, DS, N) ->
erlang:system_flag(schedulers_online, (S div 2)+1),
erlang:system_flag(dirty_cpu_schedulers_online, (DS div 2)+1),
erlang:system_flag(schedulers_online, 1),
erlang:system_flag(schedulers_online, (S div 2)+1),
erlang:system_flag(dirty_cpu_schedulers_online, 1),
erlang:system_flag(schedulers_online, S),
erlang:system_flag(dirty_cpu_schedulers_online, DS),
erlang:system_flag(schedulers_online, 1),
erlang:system_flag(schedulers_online, S),
erlang:system_flag(dirty_cpu_schedulers_online, DS),
sst3_loop_with_dirty_schedulers(S, DS, N-1).
sst4_loop(0) ->
ok;
sst4_loop(N) ->
erlang:system_flag(multi_scheduling, block_normal),
erlang:system_flag(multi_scheduling, unblock_normal),
sst4_loop(N-1).
sst5_loop(0) ->
ok;
sst5_loop(N) ->
erlang:system_flag(multi_scheduling, block_normal),
erlang:system_flag(multi_scheduling, unblock_normal),
sst5_loop(N-1).
%% Test scheduler polling: +IOs true|false
sched_poll(Config) when is_list(Config) ->
Env = case os:getenv("ERL_AFLAGS") of
false ->
[];
AFLAGS1 ->
%% Remove any +IOs
AFLAGS2 = list_to_binary(re:replace(AFLAGS1,
"\\+IOs (true|false)",
"", [global])),
[{"ERL_AFLAGS", binary_to_list(AFLAGS2)}]
end,
[PS | _] = get_iostate(""),
HaveSchedPoll = proplists:get_value(concurrent_updates, PS),
0 = get_sched_pollsets(["+IOs", "false"]),
if
HaveSchedPoll ->
1 = get_sched_pollsets(["+IOs", "true"]),
1 = get_sched_pollsets([], Env);
not HaveSchedPoll ->
fail = get_sched_pollsets(["+IOs", "true"]),
0 = get_sched_pollsets([], Env)
end,
fail = get_sched_pollsets(["+IOs", "bad"]),
ok.
get_sched_pollsets(Cmd) ->
get_sched_pollsets(Cmd, []).
get_sched_pollsets(Cmd, Env)->
try
{ok, Peer, Node} = ?CT_PEER(#{connection => standard_io, args => Cmd,
env => [{"ERL_LIBS", false} | Env]}),
[IOStates] = mcall(Node,[fun () -> erlang:system_info(check_io) end]),
IO = [IOState || IOState <- IOStates,
%% We assume non-fallbacks without threads are scheduler pollsets
proplists:get_value(fallback, IOState) == false,
proplists:get_value(poll_threads, IOState) == 0],
peer:stop(Peer),
length(IO) % number of scheduler pollsets
catch
exit:{boot_failed, _} ->
fail
end.
poll_threads(Config) when is_list(Config) ->
[PS | _] = get_iostate(""),
Conc = proplists:get_value(concurrent_updates, PS),
[1, 1] = get_ionum(["+IOt", "2", "+IOp", "2"]),
[1, 1, 1, 1, 1] = get_ionum(["+IOt", "5", "+IOp", "5"]),
[1, 1] = get_ionum(["+S", "2", "+IOPt", "100", "+IOPp", "100"]),
if
Conc ->
[5] = get_ionum(["+IOt", "5", "+IOp", "1"]),
[3, 2] = get_ionum(["+IOt", "5", "+IOp", "2"]),
[2, 2, 2, 2, 2] = get_ionum(["+IOt", "10", "+IOPp", "50"]),
[2] = get_ionum(["+S", "2", "+IOPt", "100"]),
[4] = get_ionum(["+S", "4", "+IOPt", "100"]),
[4] = get_ionum(["+S", "4:2", "+IOPt", "100"]),
[4, 4] = get_ionum(["+S", "8", "+IOPt", "100", "+IOPp", "25"]),
fail = get_ionum(["+IOt", "1", "+IOp", "2"]),
ok;
not Conc ->
[1, 1, 1, 1, 1] = get_ionum(["+IOt", "5", "+IOp", "1"]),
[1, 1, 1, 1, 1] = get_ionum(["+IOt", "5", "+IOp", "2"]),
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] = get_ionum(["+IOt", "10", "+IOPp", "50"]),
[1, 1] = get_ionum(["+S", "2", "+IOPt", "100"]),
[1, 1, 1, 1] = get_ionum(["+S", "4", "+IOPt", "100"]),
[1, 1, 1, 1] = get_ionum(["+S", "4:2", "+IOPt", "100"]),
[1, 1, 1, 1, 1, 1, 1, 1] = get_ionum(["+S", "8", "+IOPt", "100" "+IOPp", "25"]),
[1] = get_ionum(["+IOt", "1", "+IOp", "2"]),
ok
end,
fail = get_ionum(["+IOt", "1", "+IOPp", "101"]),
fail = get_ionum(["+IOt", "0"]),
fail = get_ionum(["+IOPt", "101"]),
ok.
get_ionum(Cmd) ->
case get_iostate(Cmd) of
fail -> fail;
PSs ->
lists:reverse(
lists:sort(
[proplists:get_value(poll_threads, PS) || PS <- PSs]))
end.
get_iostate(Cmd)->
try
{ok, Peer, Node} = ?CT_PEER(#{connection => standard_io, args => Cmd,
env => [{"ERL_LIBS", false}]}),
[IOStates] = mcall(Node,[fun () -> erlang:system_info(check_io) end]),
IO = [IOState || IOState <- IOStates,
proplists:get_value(fallback, IOState) == false,
proplists:get_value(poll_threads, IOState) /= 0],
peer:stop(Peer),
IO
catch
exit:{boot_failed, _} ->
fail
end.
reader_groups(Config) when is_list(Config) ->
%% White box testing. These results are correct, but other results
%% could be too...
The actual topology
CPUT0 = [{processor,[{node,[{core,{logical,0}},
{core,{logical,1}},
{core,{logical,2}},
{core,{logical,8}},
{core,{logical,9}},
{core,{logical,10}},
{core,{logical,11}},
{core,{logical,16}},
{core,{logical,17}},
{core,{logical,18}},
{core,{logical,19}},
{core,{logical,24}},
{core,{logical,25}},
{core,{logical,27}},
{core,{logical,29}}]},
{node,[{core,{logical,3}},
{core,{logical,4}},
{core,{logical,5}},
{core,{logical,6}},
{core,{logical,7}},
{core,{logical,12}},
{core,{logical,13}},
{core,{logical,14}},
{core,{logical,15}},
{core,{logical,20}},
{core,{logical,21}},
{core,{logical,22}},
{core,{logical,23}},
{core,{logical,28}},
{core,{logical,30}}]},
{node,[{core,{logical,31}},
{core,{logical,36}},
{core,{logical,37}},
{core,{logical,38}},
{core,{logical,44}},
{core,{logical,45}},
{core,{logical,46}},
{core,{logical,47}},
{core,{logical,51}},
{core,{logical,52}},
{core,{logical,53}},
{core,{logical,54}},
{core,{logical,55}},
{core,{logical,60}},
{core,{logical,61}}]},
{node,[{core,{logical,26}},
{core,{logical,32}},
{core,{logical,33}},
{core,{logical,34}},
{core,{logical,35}},
{core,{logical,39}},
{core,{logical,40}},
{core,{logical,41}},
{core,{logical,42}},
{core,{logical,43}},
{core,{logical,48}},
{core,{logical,49}},
{core,{logical,50}},
{core,{logical,58}}]}]}],
[{0,1},{1,1},{2,1},{3,3},{4,3},{5,3},{6,3},{7,3},{8,1},{9,1},{10,1},
{11,1},{12,3},{13,3},{14,4},{15,4},{16,2},{17,2},{18,2},{19,2},
{20,4},{21,4},{22,4},{23,4},{24,2},{25,2},{26,7},{27,2},{28,4},
{29,2},{30,4},{31,5},{32,7},{33,7},{34,7},{35,7},{36,5},{37,5},
{38,5},{39,7},{40,7},{41,8},{42,8},{43,8},{44,5},{45,5},{46,5},
{47,6},{48,8},{49,8},{50,8},{51,6},{52,6},{53,6},{54,6},{55,6},
{58,8},{60,6},{61,6}]
= reader_groups_map(CPUT0, 8),
CPUT1 = [n([p([c([t(l(0)),t(l(1)),t(l(2)),t(l(3))]),
c([t(l(4)),t(l(5)),t(l(6)),t(l(7))]),
c([t(l(8)),t(l(9)),t(l(10)),t(l(11))]),
c([t(l(12)),t(l(13)),t(l(14)),t(l(15))])]),
p([c([t(l(16)),t(l(17)),t(l(18)),t(l(19))]),
c([t(l(20)),t(l(21)),t(l(22)),t(l(23))]),
c([t(l(24)),t(l(25)),t(l(26)),t(l(27))]),
c([t(l(28)),t(l(29)),t(l(30)),t(l(31))])])]),
n([p([c([t(l(32)),t(l(33)),t(l(34)),t(l(35))]),
c([t(l(36)),t(l(37)),t(l(38)),t(l(39))]),
c([t(l(40)),t(l(41)),t(l(42)),t(l(43))]),
c([t(l(44)),t(l(45)),t(l(46)),t(l(47))])]),
p([c([t(l(48)),t(l(49)),t(l(50)),t(l(51))]),
c([t(l(52)),t(l(53)),t(l(54)),t(l(55))]),
c([t(l(56)),t(l(57)),t(l(58)),t(l(59))]),
c([t(l(60)),t(l(61)),t(l(62)),t(l(63))])])]),
n([p([c([t(l(64)),t(l(65)),t(l(66)),t(l(67))]),
c([t(l(68)),t(l(69)),t(l(70)),t(l(71))]),
c([t(l(72)),t(l(73)),t(l(74)),t(l(75))]),
c([t(l(76)),t(l(77)),t(l(78)),t(l(79))])]),
p([c([t(l(80)),t(l(81)),t(l(82)),t(l(83))]),
c([t(l(84)),t(l(85)),t(l(86)),t(l(87))]),
c([t(l(88)),t(l(89)),t(l(90)),t(l(91))]),
c([t(l(92)),t(l(93)),t(l(94)),t(l(95))])])]),
n([p([c([t(l(96)),t(l(97)),t(l(98)),t(l(99))]),
c([t(l(100)),t(l(101)),t(l(102)),t(l(103))]),
c([t(l(104)),t(l(105)),t(l(106)),t(l(107))]),
c([t(l(108)),t(l(109)),t(l(110)),t(l(111))])]),
p([c([t(l(112)),t(l(113)),t(l(114)),t(l(115))]),
c([t(l(116)),t(l(117)),t(l(118)),t(l(119))]),
c([t(l(120)),t(l(121)),t(l(122)),t(l(123))]),
c([t(l(124)),t(l(125)),t(l(126)),t(l(127))])])])],
[{0,1},{1,1},{2,1},{3,1},{4,2},{5,2},{6,2},{7,2},{8,3},{9,3},
{10,3},{11,3},{12,4},{13,4},{14,4},{15,4},{16,5},{17,5},{18,5},
{19,5},{20,6},{21,6},{22,6},{23,6},{24,7},{25,7},{26,7},{27,7},
{28,8},{29,8},{30,8},{31,8},{32,9},{33,9},{34,9},{35,9},{36,10},
{37,10},{38,10},{39,10},{40,11},{41,11},{42,11},{43,11},{44,12},
{45,12},{46,12},{47,12},{48,13},{49,13},{50,13},{51,13},{52,14},
{53,14},{54,14},{55,14},{56,15},{57,15},{58,15},{59,15},{60,16},
{61,16},{62,16},{63,16},{64,17},{65,17},{66,17},{67,17},{68,18},
{69,18},{70,18},{71,18},{72,19},{73,19},{74,19},{75,19},{76,20},
{77,20},{78,20},{79,20},{80,21},{81,21},{82,21},{83,21},{84,22},
{85,22},{86,22},{87,22},{88,23},{89,23},{90,23},{91,23},{92,24},
{93,24},{94,24},{95,24},{96,25},{97,25},{98,25},{99,25},{100,26},
{101,26},{102,26},{103,26},{104,27},{105,27},{106,27},{107,27},
{108,28},{109,28},{110,28},{111,28},{112,29},{113,29},{114,29},
{115,29},{116,30},{117,30},{118,30},{119,30},{120,31},{121,31},
{122,31},{123,31},{124,32},{125,32},{126,32},{127,32}]
= reader_groups_map(CPUT1, 128),
[{0,1},{1,1},{2,1},{3,1},{4,1},{5,1},{6,1},{7,1},{8,1},{9,1},{10,1},
{11,1},{12,1},{13,1},{14,1},{15,1},{16,1},{17,1},{18,1},{19,1},
{20,1},{21,1},{22,1},{23,1},{24,1},{25,1},{26,1},{27,1},{28,1},
{29,1},{30,1},{31,1},{32,1},{33,1},{34,1},{35,1},{36,1},{37,1},
{38,1},{39,1},{40,1},{41,1},{42,1},{43,1},{44,1},{45,1},{46,1},
{47,1},{48,1},{49,1},{50,1},{51,1},{52,1},{53,1},{54,1},{55,1},
{56,1},{57,1},{58,1},{59,1},{60,1},{61,1},{62,1},{63,1},{64,2},
{65,2},{66,2},{67,2},{68,2},{69,2},{70,2},{71,2},{72,2},{73,2},
{74,2},{75,2},{76,2},{77,2},{78,2},{79,2},{80,2},{81,2},{82,2},
{83,2},{84,2},{85,2},{86,2},{87,2},{88,2},{89,2},{90,2},{91,2},
{92,2},{93,2},{94,2},{95,2},{96,2},{97,2},{98,2},{99,2},{100,2},
{101,2},{102,2},{103,2},{104,2},{105,2},{106,2},{107,2},{108,2},
{109,2},{110,2},{111,2},{112,2},{113,2},{114,2},{115,2},{116,2},
{117,2},{118,2},{119,2},{120,2},{121,2},{122,2},{123,2},{124,2},
{125,2},{126,2},{127,2}]
= reader_groups_map(CPUT1, 2),
[{0,1},{1,1},{2,1},{3,1},{4,2},{5,2},{6,2},{7,2},{8,3},{9,3},{10,3},
{11,3},{12,3},{13,3},{14,3},{15,3},{16,4},{17,4},{18,4},{19,4},
{20,4},{21,4},{22,4},{23,4},{24,5},{25,5},{26,5},{27,5},{28,5},
{29,5},{30,5},{31,5},{32,6},{33,6},{34,6},{35,6},{36,6},{37,6},
{38,6},{39,6},{40,7},{41,7},{42,7},{43,7},{44,7},{45,7},{46,7},
{47,7},{48,8},{49,8},{50,8},{51,8},{52,8},{53,8},{54,8},{55,8},
{56,9},{57,9},{58,9},{59,9},{60,9},{61,9},{62,9},{63,9},{64,10},
{65,10},{66,10},{67,10},{68,10},{69,10},{70,10},{71,10},{72,11},
{73,11},{74,11},{75,11},{76,11},{77,11},{78,11},{79,11},{80,12},
{81,12},{82,12},{83,12},{84,12},{85,12},{86,12},{87,12},{88,13},
{89,13},{90,13},{91,13},{92,13},{93,13},{94,13},{95,13},{96,14},
{97,14},{98,14},{99,14},{100,14},{101,14},{102,14},{103,14},
{104,15},{105,15},{106,15},{107,15},{108,15},{109,15},{110,15},
{111,15},{112,16},{113,16},{114,16},{115,16},{116,16},{117,16},
{118,16},{119,16},{120,17},{121,17},{122,17},{123,17},{124,17},
{125,17},{126,17},{127,17}]
= reader_groups_map(CPUT1, 17),
[{0,1},{1,1},{2,1},{3,1},{4,1},{5,1},{6,1},{7,1},{8,1},{9,1},{10,1},
{11,1},{12,1},{13,1},{14,1},{15,1},{16,2},{17,2},{18,2},{19,2},
{20,2},{21,2},{22,2},{23,2},{24,2},{25,2},{26,2},{27,2},{28,2},
{29,2},{30,2},{31,2},{32,3},{33,3},{34,3},{35,3},{36,3},{37,3},
{38,3},{39,3},{40,3},{41,3},{42,3},{43,3},{44,3},{45,3},{46,3},
{47,3},{48,4},{49,4},{50,4},{51,4},{52,4},{53,4},{54,4},{55,4},
{56,4},{57,4},{58,4},{59,4},{60,4},{61,4},{62,4},{63,4},{64,5},
{65,5},{66,5},{67,5},{68,5},{69,5},{70,5},{71,5},{72,5},{73,5},
{74,5},{75,5},{76,5},{77,5},{78,5},{79,5},{80,6},{81,6},{82,6},
{83,6},{84,6},{85,6},{86,6},{87,6},{88,6},{89,6},{90,6},{91,6},
{92,6},{93,6},{94,6},{95,6},{96,7},{97,7},{98,7},{99,7},{100,7},
{101,7},{102,7},{103,7},{104,7},{105,7},{106,7},{107,7},{108,7},
{109,7},{110,7},{111,7},{112,7},{113,7},{114,7},{115,7},{116,7},
{117,7},{118,7},{119,7},{120,7},{121,7},{122,7},{123,7},{124,7},
{125,7},{126,7},{127,7}]
= reader_groups_map(CPUT1, 7),
CPUT2 = [p([c(l(0)),c(l(1)),c(l(2)),c(l(3)),c(l(4))]),
p([t(l(5)),t(l(6)),t(l(7)),t(l(8)),t(l(9))]),
p([t(l(10))]),
p([c(l(11)),c(l(12)),c(l(13))]),
p([c(l(14)),c(l(15))])],
[{0,1},{1,1},{2,1},{3,1},{4,1},
{5,2},{6,2},{7,2},{8,2},{9,2},
{10,3},
{11,4},{12,4},{13,4},
{14,5},{15,5}] = reader_groups_map(CPUT2, 5),
[{0,1},{1,1},{2,2},{3,2},{4,2},
{5,3},{6,3},{7,3},{8,3},{9,3},
{10,4},
{11,5},{12,5},{13,5},
{14,6},{15,6}] = reader_groups_map(CPUT2, 6),
[{0,1},{1,1},{2,2},{3,2},{4,2},
{5,3},{6,3},{7,3},{8,3},{9,3},
{10,4},
{11,5},{12,6},{13,6},
{14,7},{15,7}] = reader_groups_map(CPUT2, 7),
[{0,1},{1,1},{2,2},{3,2},{4,2},
{5,3},{6,3},{7,3},{8,3},{9,3},
{10,4},
{11,5},{12,6},{13,6},
{14,7},{15,8}] = reader_groups_map(CPUT2, 8),
[{0,1},{1,2},{2,2},{3,3},{4,3},
{5,4},{6,4},{7,4},{8,4},{9,4},
{10,5},
{11,6},{12,7},{13,7},
{14,8},{15,9}] = reader_groups_map(CPUT2, 9),
[{0,1},{1,2},{2,2},{3,3},{4,3},
{5,4},{6,4},{7,4},{8,4},{9,4},
{10,5},
{11,6},{12,7},{13,8},
{14,9},{15,10}] = reader_groups_map(CPUT2, 10),
[{0,1},{1,2},{2,3},{3,4},{4,4},
{5,5},{6,5},{7,5},{8,5},{9,5},
{10,6},
{11,7},{12,8},{13,9},
{14,10},{15,11}] = reader_groups_map(CPUT2, 11),
[{0,1},{1,2},{2,3},{3,4},{4,5},
{5,6},{6,6},{7,6},{8,6},{9,6},
{10,7},
{11,8},{12,9},{13,10},
{14,11},{15,12}] = reader_groups_map(CPUT2, 100),
CPUT3 = [p([t(l(5)),t(l(6)),t(l(7)),t(l(8)),t(l(9))]),
p([t(l(10))]),
p([c(l(11)),c(l(12)),c(l(13))]),
p([c(l(14)),c(l(15))]),
p([c(l(0)),c(l(1)),c(l(2)),c(l(3)),c(l(4))])],
[{0,5},{1,5},{2,6},{3,6},{4,6},
{5,1},{6,1},{7,1},{8,1},{9,1},
{10,2},{11,3},{12,3},{13,3},
{14,4},{15,4}] = reader_groups_map(CPUT3, 6),
CPUT4 = [p([t(l(0)),t(l(1)),t(l(2)),t(l(3)),t(l(4))]),
p([t(l(5))]),
p([c(l(6)),c(l(7)),c(l(8))]),
p([c(l(9)),c(l(10))]),
p([c(l(11)),c(l(12)),c(l(13)),c(l(14)),c(l(15))])],
[{0,1},{1,1},{2,1},{3,1},{4,1},
{5,2},
{6,3},{7,3},{8,3},
{9,4},{10,4},
{11,5},{12,5},{13,6},{14,6},{15,6}] = reader_groups_map(CPUT4, 6),
[{0,1},{1,1},{2,1},{3,1},{4,1},
{5,2},
{6,3},{7,4},{8,4},
{9,5},{10,5},
{11,6},{12,6},{13,7},{14,7},{15,7}] = reader_groups_map(CPUT4, 7),
[{0,1},{65535,2}] = reader_groups_map([c(l(0)),c(l(65535))], 10),
ok.
reader_groups_map(CPUT, Groups) ->
Old = erlang:system_info({cpu_topology, defined}),
erlang:system_flag(cpu_topology, CPUT),
enable_internal_state(),
Res = erts_debug:get_internal_state({reader_groups_map, Groups}),
erlang:system_flag(cpu_topology, Old),
lists:sort(Res).
otp_16446(Config) when is_list(Config) ->
ct:timetrap({minutes, 1}),
process_flag(priority, high),
DIO = erlang:system_info(dirty_io_schedulers),
NoPrioProcs = 10*DIO,
io:format("DIO = ~p~nNoPrioProcs = ~p~n", [DIO, NoPrioProcs]),
DirtyLoop = fun Loop(P, N) ->
erts_debug:dirty_io(wait,1),
receive {get, From} -> From ! {P, N}
after 0 -> Loop(P,N+1)
end
end,
Spawn = fun SpawnLoop(_Prio, 0, Acc) ->
Acc;
SpawnLoop(Prio, N, Acc) ->
Pid = spawn_opt(fun () -> DirtyLoop(Prio, 0) end,
[link, {priority, Prio}]),
SpawnLoop(Prio, N-1, [Pid|Acc])
end,
Ns = Spawn(normal, NoPrioProcs, []),
Ls = Spawn(low, NoPrioProcs, []),
receive after 10000 -> ok end,
RequestInfo = fun (P) -> P ! {get, self()} end,
lists:foreach(RequestInfo, Ns),
lists:foreach(RequestInfo, Ls),
Collect = fun CollectFun(0, LLs, NLs) ->
{LLs, NLs};
CollectFun(N, LLs, NLs) ->
receive
{low, Calls} ->
CollectFun(N-1, LLs+Calls, NLs);
{normal, Calls} ->
CollectFun(N-1, LLs, NLs+Calls)
end
end,
{LLs, NLs} = Collect(2*NoPrioProcs, 0, 0),
expected ratio 0.125 , but this is not especially exact ...
Ratio = LLs / NLs,
io:format("LLs = ~p~nNLs = ~p~nRatio = ~p~n", [LLs, NLs, Ratio]),
true = Ratio > 0.05,
true = Ratio < 0.5,
WaitUntilDead = fun (P) ->
case is_process_alive(P) of
false ->
ok;
true ->
unlink(P),
exit(P, kill),
false = is_process_alive(P)
end
end,
lists:foreach(WaitUntilDead, Ns),
lists:foreach(WaitUntilDead, Ls),
Comment = "low/normal ratio: " ++ erlang:float_to_list(Ratio,[{decimals,4}]),
erlang:display(Comment),
{comment, Comment}.
simultaneously_change_schedulers_online(Config) when is_list(Config) ->
SchedOnline = erlang:system_info(schedulers_online),
Change = fun Change (0) ->
ok;
Change (N) ->
timer : sleep(rand : ) ) ,
erlang:system_flag(schedulers_online,
rand:uniform(erlang:system_info(schedulers))),
Change(N-1)
end,
PMs = lists:map(fun (_) ->
spawn_monitor(fun () -> Change(10) end)
end, lists:seq(1,2500)),
lists:foreach(fun ({P, M}) ->
receive
{'DOWN', M, process, P, normal} ->
ok
end
end,
PMs),
erlang:system_flag(schedulers_online, SchedOnline),
ok.
simultaneously_change_schedulers_online_with_exits(Config) when is_list(Config) ->
SchedOnline = erlang:system_info(schedulers_online),
Change = fun Change (0) ->
exit(bye);
Change (N) ->
timer : sleep(rand : ) ) ,
erlang:system_flag(schedulers_online,
rand:uniform(erlang:system_info(schedulers))),
Change(N-1)
end,
PMs = lists:map(fun (_) ->
spawn_monitor(fun () -> Change(10) end)
end, lists:seq(1,2500)),
Kill every 10 : th process ...
_ = lists:foldl(fun ({P, _M}, 0) ->
exit(P, bye),
10;
(_PM, N) ->
N-1
end,
10,
PMs),
lists:foreach(fun ({P, M}) ->
receive
{'DOWN', M, process, P, Reason} ->
bye = Reason
end
end,
PMs),
erlang:system_flag(schedulers_online, SchedOnline),
ok.
%%
Utils
%%
sched_state() ->
sched_state(erlang:system_info(all_schedulers_state),
undefined,
{dirty_cpu,0,0,0},
{dirty_io,0,0,0}).
sched_state([], N, DC, DI) ->
try
chk_basic(N),
chk_basic(DC),
chk_basic(DI),
{N, DC, DI}
catch
_ : _ ->
ct:fail({inconsisten_scheduler_state, {N, DC, DI}})
end;
sched_state([{normal, _, _, _} = S | Rest], _S, DC, DI) ->
sched_state(Rest, S, DC, DI);
sched_state([{dirty_cpu, _, _, _} = DC | Rest], S, _DC, DI) ->
sched_state(Rest, S, DC, DI);
sched_state([{dirty_io, _, _, _} = DI | Rest], S, DC, _DI) ->
sched_state(Rest, S, DC, DI).
chk_basic({_Type, Tot, Onln, Act}) ->
true = Tot >= Onln,
true = Onln >= Act.
l(Id) ->
{logical, Id}.
t(X) ->
{thread, X}.
c(X) ->
{core, X}.
p(X) ->
{processor, X}.
n(X) ->
{node, X}.
mcall(Node, Funs) ->
Parent = self(),
Refs = lists:map(fun (Fun) ->
Ref = make_ref(),
Pid = spawn(Node,
fun () ->
Res = Fun(),
unlink(Parent),
Parent ! {Ref, Res}
end),
MRef = erlang:monitor(process, Pid),
{Ref, MRef}
end, Funs),
lists:map(fun ({Ref, MRef}) ->
receive
{Ref, Res} ->
receive
{'DOWN',MRef,_,_,_} ->
Res
end;
{'DOWN',MRef,_,_,Reason} ->
Reason
end
end, Refs).
erl_rel_flag_var() ->
"ERL_OTP"++erlang:system_info(otp_release)++"_FLAGS".
clear_erl_rel_flags() ->
EnvVar = erl_rel_flag_var(),
case os:getenv(EnvVar) of
false ->
false;
Value ->
os:putenv(EnvVar, ""),
Value
end.
restore_erl_rel_flags(false) ->
ok;
restore_erl_rel_flags(OldValue) ->
os:putenv(erl_rel_flag_var(), OldValue),
ok.
ok(too_slow, _Config) ->
{comment, "Too slow system to do any actual testing..."};
ok(_Res, Config) ->
proplists:get_value(ok_res, Config).
chk_result(too_slow,
_LWorkers,
_NWorkers,
_HWorkers,
_MWorkers,
_LNShouldWork,
_HShouldWork,
_MShouldWork) ->
ok;
chk_result([{low, L, Lmin, _Lmax},
{normal, N, Nmin, _Nmax},
{high, H, Hmin, _Hmax},
{max, M, Mmin, _Mmax}] = Res,
LWorkers,
NWorkers,
HWorkers,
MWorkers,
LNShouldWork,
HShouldWork,
MShouldWork) ->
io:format("~p~n", [Res]),
Relax = relax_limits(),
case {L, N} of
{0, 0} ->
false = LNShouldWork;
_ ->
{LminRatioLim,
NminRatioLim,
LNRatioLimMin,
LNRatioLimMax} = case Relax of
false -> {0.5, 0.5, 0.05, 0.25};
true -> {0.05, 0.05, 0.01, 0.4}
end,
Lavg = L/LWorkers,
Navg = N/NWorkers,
Ratio = Lavg/Navg,
LminRatio = Lmin/Lavg,
NminRatio = Nmin/Navg,
io:format("low min ratio=~p~n"
"normal min ratio=~p~n"
"low avg=~p~n"
"normal avg=~p~n"
"low/normal ratio=~p~n",
[LminRatio, NminRatio, Lavg, Navg, Ratio]),
erlang:display({low_min_ratio, LminRatio}),
erlang:display({normal_min_ratio, NminRatio}),
erlang:display({low_avg, Lavg}),
erlang:display({normal_avg, Navg}),
erlang:display({low_normal_ratio, Ratio}),
chk_lim(LminRatioLim, LminRatio, 1.0, low_min_ratio),
chk_lim(NminRatioLim, NminRatio, 1.0, normal_min_ratio),
chk_lim(LNRatioLimMin, Ratio, LNRatioLimMax, low_normal_ratio),
true = LNShouldWork,
ok
end,
case H of
0 ->
false = HShouldWork;
_ ->
HminRatioLim = case Relax of
false -> 0.5;
true -> 0.1
end,
Havg = H/HWorkers,
HminRatio = Hmin/Havg,
erlang:display({high_min_ratio, HminRatio}),
chk_lim(HminRatioLim, HminRatio, 1.0, high_min_ratio),
true = HShouldWork,
ok
end,
case M of
0 ->
false = MShouldWork;
_ ->
MminRatioLim = case Relax of
false -> 0.5;
true -> 0.1
end,
Mavg = M/MWorkers,
MminRatio = Mmin/Mavg,
erlang:display({max_min_ratio, MminRatio}),
chk_lim(MminRatioLim, MminRatio, 1.0, max_min_ratio),
true = MShouldWork,
ok
end,
ok.
chk_lim(Min, V, Max, _What) when Min =< V, V =< Max ->
ok;
chk_lim(_Min, V, _Max, What) ->
ct:fail({bad, What, V}).
snd(_Msg, []) ->
[];
snd(Msg, [P|Ps]) ->
P ! Msg,
Ps.
relax_limits() ->
case strange_system_scale() of
Scale when Scale > 1 ->
io:format("Relaxing limits~n", []),
true;
_ ->
false
end.
strange_system_scale() ->
S0 = 1,
S1 = case erlang:system_info(schedulers_online)
> erlang:system_info(logical_processors) of
true -> S0*2;
false -> S0
end,
S2 = case erlang:system_info(debug_compiled) of
true -> S1*10;
false ->
case erlang:system_info(lock_checking) of
true -> S1*2;
false -> S1
end
end,
S3 = case lock_counting() of
true -> S2*2;
false -> S2
end,
S3.
lock_counting() ->
lock_counting(erlang:system_info(system_version)).
lock_counting([]) ->
false;
lock_counting([$[,$l,$o,$c,$k,$-,$c,$o,$u,$n,$t,$i,$n,$g,$],_]) ->
true;
lock_counting([_C|Cs]) ->
lock_counting(Cs).
go_work([], [], [], []) ->
[];
go_work(L, N, [], []) ->
go_work(snd(go_work, L), snd(go_work, N), [], []);
go_work(L, N, H, []) ->
go_work(L, N, snd(go_work, H), []);
go_work(L, N, H, M) ->
go_work(L, N, H, snd(go_work, M)).
stop_work([], [], [], []) ->
[];
stop_work([], [], [], M) ->
stop_work([], [], [], snd(stop_work, M));
stop_work([], [], H, M) ->
stop_work([], [], snd(stop_work, H), M);
stop_work(L, N, H, M) ->
stop_work(snd(stop_work, L), snd(stop_work, N), H, M).
wait_balance(N) when is_integer(N) ->
case erlang:system_info(schedulers_active) of
1 ->
done;
_ ->
erts_debug:set_internal_state(available_internal_state,true),
Start = erts_debug:get_internal_state(nbalance),
End = (Start + N) band ((1 bsl (8*erlang:system_info(wordsize)))-1),
wait_balance(Start, End),
erts_debug:set_internal_state(available_internal_state,false)
end.
wait_balance(Start, End) ->
X = erts_debug:get_internal_state(nbalance),
case End =< X of
true ->
case Start =< End of
true ->
done;
false ->
case X < Start of
true ->
done;
false ->
receive after 250 -> ok end,
wait_balance(Start, End)
end
end;
false ->
receive after 250 -> ok end,
wait_balance(Start, End)
end.
wait_reds(RedsLimit, Timeout) ->
Stop = erlang:start_timer(Timeout, self(), stop),
statistics(reductions),
wait_reds(0, RedsLimit, Stop).
wait_reds(Reds, RedsLimit, Stop) when Reds < RedsLimit ->
receive
{timeout, Stop, stop} ->
erlang:display(timeout),
erlang:display({reduction_limit, RedsLimit}),
erlang:display({reductions, Reds}),
done
after 10000 ->
{_, NewReds} = statistics(reductions),
wait_reds(NewReds+Reds, RedsLimit, Stop)
end;
wait_reds(Reds, RedsLimit, Stop) when is_reference(Stop) ->
erlang:cancel_timer(Stop),
receive {timeout, Stop, stop} -> ok after 0 -> ok end,
wait_reds(Reds, RedsLimit, false);
wait_reds(Reds, RedsLimit, _Stop) ->
erlang:display({reduction_limit, RedsLimit}),
erlang:display({reductions, Reds}),
done.
do_it(Tracer, Low, Normal, High, Max) ->
do_it(Tracer, Low, Normal, High, Max, ?DEFAULT_TEST_REDS_PER_SCHED).
do_it(Tracer, Low, Normal, High, Max, RedsPerSchedLimit) ->
OldPrio = process_flag(priority, max),
go_work(Low, Normal, High, Max),
StartWait = erlang:monotonic_time(millisecond),
%% Give the emulator a chance to balance the load...
wait_balance(5),
EndWait = erlang:monotonic_time(millisecond),
BalanceWait = EndWait-StartWait,
erlang:display({balance_wait, BalanceWait}),
Timeout = (15 - 4)*60*1000 - BalanceWait,
Res = case Timeout < 60*1000 of
true ->
stop_work(Low, Normal, High, Max),
too_slow;
false ->
set_tracing(true, Tracer, normal, Normal),
set_tracing(true, Tracer, low, Low),
set_tracing(true, Tracer, high, High),
set_tracing(true, Tracer, max, Max),
wait_reds(RedsPerSchedLimit
* erlang:system_info(schedulers_online),
Timeout),
set_tracing(false, Tracer, normal, Normal),
set_tracing(false, Tracer, low, Low),
set_tracing(false, Tracer, high, High),
set_tracing(false, Tracer, max, Max),
stop_work(Low, Normal, High, Max),
get_trace_result(Tracer)
end,
process_flag(priority, OldPrio),
Res.
workers_exit([]) ->
ok;
workers_exit([P|Ps]) when is_pid(P) ->
Mon = erlang:monitor(process, P),
unlink(P),
exit(P, kill),
workers_exit(Ps),
receive {'DOWN', Mon, process, P, _} -> ok end,
ok;
workers_exit([[]]) ->
ok;
workers_exit([Ps|Pss]) ->
workers_exit(Ps),
workers_exit(Pss).
do_work(PartTime) ->
_ = id(lists:seq(1, 50)),
receive stop_work -> receive after infinity -> ok end after 0 -> ok end,
case PartTime of
true -> receive after 1 -> ok end;
false -> ok
end,
do_work(PartTime).
id(I) -> I.
workers(N, _Prio, _PartTime) when N =< 0 ->
[];
workers(N, Prio, PartTime) ->
Parent = self(),
W = spawn_opt(fun () ->
Parent ! {ready, self()},
receive
go_work ->
do_work(PartTime)
end
end,
[{priority, Prio}, link]),
Ws = workers(N-1, Prio, PartTime),
receive {ready, W} -> ok end,
[W|Ws].
workers(N, Prio) ->
workers(N, Prio, false).
part_time_workers(N, Prio) ->
workers(N, Prio, true).
tracer(Low, Normal, High, Max) ->
receive
{tracees, Prio, Tracees} ->
save_tracees(Prio, Tracees),
case Prio of
low -> tracer(Tracees++Low, Normal, High, Max);
normal -> tracer(Low, Tracees++Normal, High, Max);
high -> tracer(Low, Normal, Tracees++High, Max);
max -> tracer(Low, Normal, High, Tracees++Max)
end;
{get_result, Ref, Who} ->
Delivered = erlang:trace_delivered(all),
receive
{trace_delivered, all, Delivered} ->
ok
end,
{Lc, Nc, Hc, Mc} = read_trace(),
GetMinMax
= fun (Prio, Procs) ->
LargeNum = 1 bsl 64,
case lists:foldl(fun (P, {Mn, Mx} = MnMx) ->
{Prio, C} = get(P),
case C < Mn of
true ->
case C > Mx of
true ->
{C, C};
false ->
{C, Mx}
end;
false ->
case C > Mx of
true -> {Mn, C};
false -> MnMx
end
end
end,
{LargeNum, 0},
Procs) of
{LargeNum, 0} -> {0, 0};
Res -> Res
end
end,
{Lmin, Lmax} = GetMinMax(low, Low),
{Nmin, Nmax} = GetMinMax(normal, Normal),
{Hmin, Hmax} = GetMinMax(high, High),
{Mmin, Mmax} = GetMinMax(max, Max),
Who ! {trace_result, Ref, [{low, Lc, Lmin, Lmax},
{normal, Nc, Nmin, Nmax},
{high, Hc, Hmin, Hmax},
{max, Mc, Mmin, Mmax}]}
end.
read_trace() ->
read_trace(0,0,0,0).
read_trace(Low, Normal, High, Max) ->
receive
{trace, Proc, in, _} ->
{Prio, Count} = get(Proc),
put(Proc, {Prio, Count+1}),
case Prio of
low -> read_trace(Low+1, Normal, High, Max);
normal -> read_trace(Low, Normal+1, High, Max);
high -> read_trace(Low, Normal, High+1, Max);
max -> read_trace(Low, Normal, High, Max+1)
end;
{trace, _Proc, out, _} ->
read_trace(Low, Normal, High, Max)
after 0 ->
{Low, Normal, High, Max}
end.
save_tracees(_Prio, []) ->
ok;
save_tracees(Prio, [T|Ts]) ->
put(T, {Prio, 0}),
save_tracees(Prio, Ts).
start_tracer() ->
Tracer = spawn_link(fun () -> tracer([], [], [], []) end),
true = erlang:suspend_process(Tracer),
Tracer.
get_trace_result(Tracer) ->
erlang:resume_process(Tracer),
Ref = make_ref(),
Tracer ! {get_result, Ref, self()},
receive
{trace_result, Ref, Res} ->
Res
end.
set_tracing(_On, _Tracer, _Prio, []) ->
ok;
set_tracing(true, Tracer, Prio, Pids) ->
Tracer ! {tracees, Prio, Pids},
set_tracing(true, Tracer, Pids);
set_tracing(false, Tracer, _Prio, Pids) ->
set_tracing(false, Tracer, Pids).
set_tracing(_On, _Tracer, []) ->
ok;
set_tracing(On, Tracer, [Pid|Pids]) ->
1 = erlang:trace(Pid, On, [running, {tracer, Tracer}]),
set_tracing(On, Tracer, Pids).
active_schedulers() ->
case erlang:system_info(schedulers_online) of
1 ->
1;
N ->
case erlang:system_info(multi_scheduling) of
blocked -> 1;
enabled -> N
end
end.
enable_internal_state() ->
case catch erts_debug:get_internal_state(available_internal_state) of
true -> true;
_ -> erts_debug:set_internal_state(available_internal_state, true)
end.
cmp(X, X) ->
ok;
cmp(X, Y) ->
io:format("cmp failed:~n X=~p~n Y=~p~n", [X,Y]),
cmp_aux(X, Y).
cmp_aux([X0|Y0], [X1|Y1]) ->
cmp_aux(X0, X1),
cmp_aux(Y0, Y1);
cmp_aux(T0, T1) when is_tuple(T0), is_tuple(T1), size(T0) == size(T1) ->
cmp_tuple(T0, T1, 1, size(T0));
cmp_aux(X, X) ->
ok;
cmp_aux(F0, F1) ->
ct:fail({no_match, F0, F1}).
cmp_tuple(_T0, _T1, N, Sz) when N > Sz ->
ok;
cmp_tuple(T0, T1, N, Sz) ->
cmp_aux(element(N, T0), element(N, T1)),
cmp_tuple(T0, T1, N+1, Sz).
| null | https://raw.githubusercontent.com/erlang/otp/f02ae58612b257d187ad030d72b9e8b67ce471ef/erts/emulator/test/scheduler_SUITE.erl | erlang |
%CopyrightBegin%
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.
%CopyrightEnd%
-------------------------------------------------------------------
File : scheduler_SUITE.erl
Description :
-------------------------------------------------------------------
-compile(export_all).
Test cases
Nothing much to test; just a smoke test
Nothing much to test; just a smoke test
Nothing much to test; just a smoke test
?!
Configure half the number of both the scheduler threads and
the scheduler threads online.
Use +S to configure 4x the number of scheduler threads and
4x the number of scheduler threads online, but alter that
scheduler threads and 25 % scheduler
threads online. The result should be 2x scheduler threads and
1x scheduler threads online.
opposite order, since order shouldn't matter.
of scheduler threads online only
Configure 2x scheduler threads only
Test resetting # of schedulers.
Test negative +S settings
The receives after setting scheduler states are there
since the operation is not fully synchronous. For example,
we do not wait for dirty cpu schedulers online to complete
Test scheduler polling: +IOs true|false
Remove any +IOs
We assume non-fallbacks without threads are scheduler pollsets
number of scheduler pollsets
White box testing. These results are correct, but other results
could be too...
Give the emulator a chance to balance the load... | Copyright Ericsson AB 2008 - 2022 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
Author :
Created : 27 Oct 2008 by
-module(scheduler_SUITE).
-define(line_trace , 1 ) .
-include_lib("common_test/include/ct.hrl").
-export([all/0, suite/0, groups/0,
init_per_suite/1, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2]).
-export([equal/1,
few_low/1,
many_low/1,
equal_with_part_time_high/1,
equal_with_part_time_max/1,
equal_and_high_with_part_time_max/1,
equal_with_high/1,
equal_with_high_max/1,
bound_process/1,
scheduler_bind_types/1,
cpu_topology/1,
update_cpu_info/1,
sct_cmd/1,
ssrct_cmd/1,
sbt_cmd/1,
scheduler_threads/1,
scheduler_suspend_basic/1,
scheduler_suspend/1,
dirty_scheduler_threads/1,
sched_poll/1,
poll_threads/1,
reader_groups/1,
otp_16446/1,
simultaneously_change_schedulers_online/1,
simultaneously_change_schedulers_online_with_exits/1]).
suite() ->
[{ct_hooks,[ts_install_cth]},
{timetrap, {minutes, 15}}].
all() ->
[equal, few_low, many_low, equal_with_part_time_high,
equal_with_part_time_max,
equal_and_high_with_part_time_max, equal_with_high,
equal_with_high_max,
bound_process,
{group, scheduler_bind}, scheduler_threads,
scheduler_suspend_basic, scheduler_suspend,
dirty_scheduler_threads,
sched_poll,
poll_threads,
reader_groups,
otp_16446,
simultaneously_change_schedulers_online,
simultaneously_change_schedulers_online_with_exits].
groups() ->
[{scheduler_bind, [],
[scheduler_bind_types, cpu_topology, update_cpu_info,
sct_cmd, sbt_cmd, ssrct_cmd]}].
init_per_suite(Config) ->
[{schedulers_online, erlang:system_info(schedulers_online)} | Config].
end_per_suite(Config) ->
catch erts_debug:set_internal_state(available_internal_state, false),
SchedOnln = proplists:get_value(schedulers_online, Config),
erlang:system_flag(schedulers_online, SchedOnln),
erlang:system_flag(dirty_cpu_schedulers_online, SchedOnln),
Config.
init_per_testcase(update_cpu_info, Config) ->
case os:find_executable("taskset") of
false ->
{skip,"Could not find 'taskset' in path"};
_ ->
init_per_tc(update_cpu_info, Config)
end;
init_per_testcase(ThreadCase, Config) when ThreadCase =:= poll_threads;
ThreadCase =:= scheduler_threads ->
case erlang:system_info(schedulers_online) of
1 -> {skip,"Needs more than one scheduler online"};
_ -> init_per_tc(ThreadCase, Config)
end;
init_per_testcase(Case, Config) when is_list(Config) ->
init_per_tc(Case, Config).
init_per_tc(Case, Config) ->
process_flag(priority, max),
erlang:display({'------------', ?MODULE, Case, '------------'}),
OkRes = ok,
[{testcase, Case}, {ok_res, OkRes} |Config].
end_per_testcase(_Case, Config) when is_list(Config) ->
erts_test_utils:ept_check_leaked_nodes(Config).
-define(ERTS_RUNQ_CHECK_BALANCE_REDS_PER_SCHED, (2000*2000)).
-define(DEFAULT_TEST_REDS_PER_SCHED, 200000000).
equal(Config) when is_list(Config) ->
low_normal_test(Config, 500, 500).
few_low(Config) when is_list(Config) ->
low_normal_test(Config, 1000, 2*active_schedulers()).
many_low(Config) when is_list(Config) ->
low_normal_test(Config, 2*active_schedulers(), 1000).
low_normal_test(Config, NW, LW) ->
Tracer = start_tracer(),
Low = workers(LW, low),
Normal = workers(NW, normal),
Res = do_it(Tracer, Low, Normal, [], []),
chk_result(Res, LW, NW, 0, 0, true, false, false),
workers_exit([Low, Normal]),
ok(Res, Config).
equal_with_part_time_high(Config) when is_list(Config) ->
NW = 500,
LW = 500,
HW = 1,
Tracer = start_tracer(),
Normal = workers(NW, normal),
Low = workers(LW, low),
High = part_time_workers(HW, high),
Res = do_it(Tracer, Low, Normal, High, []),
chk_result(Res, LW, NW, HW, 0, true, true, false),
workers_exit([Low, Normal, High]),
ok(Res, Config).
equal_and_high_with_part_time_max(Config) when is_list(Config) ->
NW = 500,
LW = 500,
HW = 500,
MW = 1,
Tracer = start_tracer(),
Low = workers(LW, low),
Normal = workers(NW, normal),
High = workers(HW, high),
Max = part_time_workers(MW, max),
Res = do_it(Tracer, Low, Normal, High, Max),
chk_result(Res, LW, NW, HW, MW, false, true, true),
workers_exit([Low, Normal, Max]),
ok(Res, Config).
equal_with_part_time_max(Config) when is_list(Config) ->
NW = 500,
LW = 500,
MW = 1,
Tracer = start_tracer(),
Low = workers(LW, low),
Normal = workers(NW, normal),
Max = part_time_workers(MW, max),
Res = do_it(Tracer, Low, Normal, [], Max),
chk_result(Res, LW, NW, 0, MW, true, false, true),
workers_exit([Low, Normal, Max]),
ok(Res, Config).
equal_with_high(Config) when is_list(Config) ->
NW = 500,
LW = 500,
HW = 1,
Tracer = start_tracer(),
Low = workers(LW, low),
Normal = workers(NW, normal),
High = workers(HW, high),
Res = do_it(Tracer, Low, Normal, High, []),
LNExe = case active_schedulers() of
S when S =< HW -> false;
_ -> true
end,
chk_result(Res, LW, NW, HW, 0, LNExe, true, false),
workers_exit([Low, Normal, High]),
ok(Res, Config).
equal_with_high_max(Config) when is_list(Config) ->
NW = 500,
LW = 500,
HW = 1,
MW = 1,
Tracer = start_tracer(),
Normal = workers(NW, normal),
Low = workers(LW, low),
High = workers(HW, high),
Max = workers(MW, max),
Res = do_it(Tracer, Low, Normal, High, Max),
{LNExe, HExe} = case active_schedulers() of
S when S =< MW -> {false, false};
S when S =< (MW + HW) -> {false, true};
_ -> {true, true}
end,
chk_result(Res, LW, NW, HW, MW, LNExe, HExe, true),
workers_exit([Low, Normal, Max]),
ok(Res, Config).
bound_process(Config) when is_list(Config) ->
case erlang:system_info(run_queues) == erlang:system_info(schedulers) of
true ->
NStartBase = 20000,
NStart = case {erlang:system_info(debug_compiled),
erlang:system_info(lock_checking)} of
{true, true} -> NStartBase div 100;
{_, true} -> NStartBase div 10;
_ -> NStartBase
end,
MStart = 100,
Seq = lists:seq(1, 100),
Tester = self(),
Procs = lists:map(
fun (N) when N rem 2 == 0 ->
spawn_opt(fun () ->
bound_loop(NStart,
NStart,
MStart,
1),
Tester ! {self(), done}
end,
[{scheduler, 1}, link]);
(_N) ->
spawn_link(fun () ->
bound_loop(NStart,
NStart,
MStart,
false),
Tester ! {self(), done}
end)
end,
Seq),
lists:foreach(fun (P) -> receive {P, done} -> ok end end,
Procs),
ok;
false ->
{skipped, "Functionality not supported"}
end.
bound_loop(_, 0, 0, _) ->
ok;
bound_loop(NS, 0, M, false) ->
bound_loop(NS, NS, M-1, false);
bound_loop(NS, N, M, false) ->
erlang:system_info(scheduler_id),
bound_loop(NS, N-1, M, false);
bound_loop(NS, 0, M, Sched) ->
NewSched = (Sched rem erlang:system_info(schedulers_online)) + 1,
Sched = process_flag(scheduler, NewSched),
NewSched = erlang:system_info(scheduler_id),
bound_loop(NS, NS, M-1, NewSched);
bound_loop(NS, N, M, Sched) ->
Sched = erlang:system_info(scheduler_id),
bound_loop(NS, N-1, M, Sched).
-define(TOPOLOGY_A_CMD,
["+sct"
"L0-1t0-1c0p0n0"
":L2-3t0-1c1p0n0"
":L4-5t0-1c0p1n0"
":L6-7t0-1c1p1n0"
":L8-9t0-1c0p2n1"
":L10-11t0-1c1p2n1"
":L12-13t0-1c0p3n1"
":L14-15t0-1c1p3n1"]).
-define(TOPOLOGY_A_TERM,
[{node,[{processor,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]}]},
{processor,[{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]}]},
{node,[{processor,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]}]},
{processor,[{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]}]}]).
-define(TOPOLOGY_B_CMD,
["+sct"
"L0-1t0-1c0n0p0"
":L2-3t0-1c1n0p0"
":L4-5t0-1c2n1p0"
":L6-7t0-1c3n1p0"
":L8-9t0-1c0n2p1"
":L10-11t0-1c1n2p1"
":L12-13t0-1c2n3p1"
":L14-15t0-1c3n3p1"]).
-define(TOPOLOGY_B_TERM,
[{processor,[{node,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]}]},
{node,[{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]}]},
{processor,[{node,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]}]},
{node,[{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]}]}]).
-define(TOPOLOGY_C_TERM,
[{node,[{processor,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]}]},
{processor,[{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]}]},
{processor,[{node,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]}]},
{node,[{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]}]},
{node,[{processor,[{core,[{thread,{logical,16}},
{thread,{logical,17}}]},
{core,[{thread,{logical,18}},
{thread,{logical,19}}]}]},
{processor,[{core,[{thread,{logical,20}},
{thread,{logical,21}}]},
{core,[{thread,{logical,22}},
{thread,{logical,23}}]}]}]},
{processor,[{node,[{core,[{thread,{logical,24}},
{thread,{logical,25}}]},
{core,[{thread,{logical,26}},
{thread,{logical,27}}]}]},
{node,[{core,[{thread,{logical,28}},
{thread,{logical,29}}]},
{core,[{thread,{logical,30}},
{thread,{logical,31}}]}]}]}]).
-define(TOPOLOGY_C_CMD,
["+sct"
"L0-1t0-1c0p0n0"
":L2-3t0-1c1p0n0"
":L4-5t0-1c0p1n0"
":L6-7t0-1c1p1n0"
":L8-9t0-1c0n1p2"
":L10-11t0-1c1n1p2"
":L12-13t0-1c2n2p2"
":L14-15t0-1c3n2p2"
":L16-17t0-1c0p3n3"
":L18-19t0-1c1p3n3"
":L20-21t0-1c0p4n3"
":L22-23t0-1c1p4n3"
":L24-25t0-1c0n4p5"
":L26-27t0-1c1n4p5"
":L28-29t0-1c2n5p5"
":L30-31t0-1c3n5p5"]).
-define(TOPOLOGY_D_TERM,
[{processor,[{node,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]}]},
{node,[{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]}]},
{node,[{processor,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]}]},
{processor,[{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]}]},
{processor,[{node,[{core,[{thread,{logical,16}},
{thread,{logical,17}}]},
{core,[{thread,{logical,18}},
{thread,{logical,19}}]}]},
{node,[{core,[{thread,{logical,20}},
{thread,{logical,21}}]},
{core,[{thread,{logical,22}},
{thread,{logical,23}}]}]}]},
{node,[{processor,[{core,[{thread,{logical,24}},
{thread,{logical,25}}]},
{core,[{thread,{logical,26}},
{thread,{logical,27}}]}]},
{processor,[{core,[{thread,{logical,28}},
{thread,{logical,29}}]},
{core,[{thread,{logical,30}},
{thread,{logical,31}}]}]}]}]).
-define(TOPOLOGY_D_CMD,
["+sct"
"L0-1t0-1c0n0p0"
":L2-3t0-1c1n0p0"
":L4-5t0-1c2n1p0"
":L6-7t0-1c3n1p0"
":L8-9t0-1c0p1n2"
":L10-11t0-1c1p1n2"
":L12-13t0-1c0p2n2"
":L14-15t0-1c1p2n2"
":L16-17t0-1c0n3p3"
":L18-19t0-1c1n3p3"
":L20-21t0-1c2n4p3"
":L22-23t0-1c3n4p3"
":L24-25t0-1c0p4n5"
":L26-27t0-1c1p4n5"
":L28-29t0-1c0p5n5"
":L30-31t0-1c1p5n5"]).
-define(TOPOLOGY_E_CMD,
["+sct"
"L0-1t0-1c0p0n0"
":L2-3t0-1c1p0n0"
":L4-5t0-1c2p0n0"
":L6-7t0-1c3p0n0"
":L8-9t0-1c0p1n1"
":L10-11t0-1c1p1n1"
":L12-13t0-1c2p1n1"
":L14-15t0-1c3p1n1"]).
-define(TOPOLOGY_E_TERM,
[{node,[{processor,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]},
{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]}]},
{node,[{processor,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]},
{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]}]}]).
-define(TOPOLOGY_F_CMD,
["+sct"
"L0-1t0-1c0n0p0"
":L2-3t0-1c1n0p0"
":L4-5t0-1c2n0p0"
":L6-7t0-1c3n0p0"
":L8-9t0-1c4n1p0"
":L10-11t0-1c5n1p0"
":L12-13t0-1c6n1p0"
":L14-15t0-1c7n1p0"
":L16-17t0-1c8n2p0"
":L18-19t0-1c9n2p0"
":L20-21t0-1c10n2p0"
":L22-23t0-1c11n2p0"
":L24-25t0-1c12n3p0"
":L26-27t0-1c13n3p0"
":L28-29t0-1c14n3p0"
":L30-31t0-1c15n3p0"]).
-define(TOPOLOGY_F_TERM,
[{processor,[{node,[{core,[{thread,{logical,0}},
{thread,{logical,1}}]},
{core,[{thread,{logical,2}},
{thread,{logical,3}}]},
{core,[{thread,{logical,4}},
{thread,{logical,5}}]},
{core,[{thread,{logical,6}},
{thread,{logical,7}}]}]},
{node,[{core,[{thread,{logical,8}},
{thread,{logical,9}}]},
{core,[{thread,{logical,10}},
{thread,{logical,11}}]},
{core,[{thread,{logical,12}},
{thread,{logical,13}}]},
{core,[{thread,{logical,14}},
{thread,{logical,15}}]}]},
{node,[{core,[{thread,{logical,16}},
{thread,{logical,17}}]},
{core,[{thread,{logical,18}},
{thread,{logical,19}}]},
{core,[{thread,{logical,20}},
{thread,{logical,21}}]},
{core,[{thread,{logical,22}},
{thread,{logical,23}}]}]},
{node,[{core,[{thread,{logical,24}},
{thread,{logical,25}}]},
{core,[{thread,{logical,26}},
{thread,{logical,27}}]},
{core,[{thread,{logical,28}},
{thread,{logical,29}}]},
{core,[{thread,{logical,30}},
{thread,{logical,31}}]}]}]}]).
bindings(Node, BindType) ->
Parent = self(),
Ref = make_ref(),
Pid = spawn_link(Node,
fun () ->
enable_internal_state(),
Res = (catch erts_debug:get_internal_state(
{fake_scheduler_bindings,
BindType})),
Parent ! {Ref, Res}
end),
receive
{Ref, Res} ->
io:format("~p: ~p~n", [BindType, Res]),
unlink(Pid),
Res
end.
scheduler_bind_types(Config) when is_list(Config) ->
OldRelFlags = clear_erl_rel_flags(),
try
scheduler_bind_types_test(
?TOPOLOGY_A_TERM,
?TOPOLOGY_A_CMD,
a),
scheduler_bind_types_test(
?TOPOLOGY_B_TERM,
?TOPOLOGY_B_CMD,
b),
scheduler_bind_types_test(
?TOPOLOGY_C_TERM,
?TOPOLOGY_C_CMD,
c),
scheduler_bind_types_test(
?TOPOLOGY_D_TERM,
?TOPOLOGY_D_CMD,
d),
scheduler_bind_types_test(
?TOPOLOGY_E_TERM,
?TOPOLOGY_E_CMD,
e),
scheduler_bind_types_test(
?TOPOLOGY_F_TERM,
?TOPOLOGY_F_CMD,
f)
after
restore_erl_rel_flags(OldRelFlags)
end,
ok.
scheduler_bind_types_test(Topology, CmdLine, TermLetter) ->
io:format("Testing (~p): ~p~n", [TermLetter, Topology]),
{ok, Peer, Node0} = ?CT_PEER(),
_ = rpc:call(Node0, erlang, system_flag, [cpu_topology, Topology]),
cmp(Topology, rpc:call(Node0, erlang, system_info, [cpu_topology])),
check_bind_types(Node0, TermLetter),
peer:stop(Peer),
{ok, Peer1, Node1} = ?CT_PEER(CmdLine),
cmp(Topology, rpc:call(Node1, erlang, system_info, [cpu_topology])),
check_bind_types(Node1, TermLetter),
peer:stop(Peer1).
check_bind_types(Node, a) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
= bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, thread_spread),
{0,4,8,12,2,6,10,14,1,5,9,13,3,7,11,15}
= bindings(Node, processor_spread),
{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}
= bindings(Node, spread),
{0,2,4,6,1,3,5,7,8,10,12,14,9,11,13,15}
= bindings(Node, no_node_thread_spread),
{0,4,2,6,1,5,3,7,8,12,10,14,9,13,11,15}
= bindings(Node, no_node_processor_spread),
{0,4,2,6,8,12,10,14,1,5,3,7,9,13,11,15}
= bindings(Node, thread_no_node_processor_spread),
{0,4,2,6,8,12,10,14,1,5,3,7,9,13,11,15}
= bindings(Node, default_bind),
ok;
check_bind_types(Node, b) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
= bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, thread_spread),
{0,8,2,10,4,12,6,14,1,9,3,11,5,13,7,15}
= bindings(Node, processor_spread),
{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15}
= bindings(Node, spread),
{0,2,1,3,4,6,5,7,8,10,9,11,12,14,13,15}
= bindings(Node, no_node_thread_spread),
{0,2,1,3,4,6,5,7,8,10,9,11,12,14,13,15}
= bindings(Node, no_node_processor_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, thread_no_node_processor_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, default_bind),
ok;
check_bind_types(Node, c) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,27,28,29,30,31} = bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,15,
17,19,21,23,25,27,29,31} = bindings(Node, thread_spread),
{0,4,8,16,20,24,2,6,10,18,22,26,12,28,14,30,1,5,9,17,21,25,
3,7,11,19,23,27,13,29,15,31} = bindings(Node, processor_spread),
{0,8,16,24,4,20,12,28,2,10,18,26,6,22,14,30,1,9,17,25,5,21,13,29,3,11,
19,27,7,23,15,31} = bindings(Node, spread),
{0,2,4,6,1,3,5,7,8,10,9,11,12,14,13,15,16,18,20,22,17,19,21,23,24,26,
25,27,28,30,29,31} = bindings(Node, no_node_thread_spread),
{0,4,2,6,1,5,3,7,8,10,9,11,12,14,13,15,16,20,18,22,17,21,19,23,24,26,
25,27,28,30,29,31} = bindings(Node, no_node_processor_spread),
{0,4,2,6,8,10,12,14,16,20,18,22,24,26,28,30,1,5,3,7,9,11,13,15,17,21,
19,23,25,27,29,31} = bindings(Node, thread_no_node_processor_spread),
{0,4,2,6,8,10,12,14,16,20,18,22,24,26,28,30,1,5,3,7,9,11,13,15,17,21,
19,23,25,27,29,31} = bindings(Node, default_bind),
ok;
check_bind_types(Node, d) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,27,28,29,30,31} = bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,15,
17,19,21,23,25,27,29,31} = bindings(Node, thread_spread),
{0,8,12,16,24,28,2,10,14,18,26,30,4,20,6,22,1,9,13,17,25,29,3,11,15,
19,27,31,5,21,7,23} = bindings(Node, processor_spread),
{0,8,16,24,12,28,4,20,2,10,18,26,14,30,6,22,1,9,17,25,13,29,5,21,3,11,
19,27,15,31,7,23} = bindings(Node, spread),
{0,2,1,3,4,6,5,7,8,10,12,14,9,11,13,15,16,18,17,19,20,22,21,23,24,26,
28,30,25,27,29,31} = bindings(Node, no_node_thread_spread),
{0,2,1,3,4,6,5,7,8,12,10,14,9,13,11,15,16,18,17,19,20,22,21,23,24,28,
26,30,25,29,27,31} = bindings(Node, no_node_processor_spread),
{0,2,4,6,8,12,10,14,16,18,20,22,24,28,26,30,1,3,5,7,9,13,11,15,17,19,
21,23,25,29,27,31} = bindings(Node, thread_no_node_processor_spread),
{0,2,4,6,8,12,10,14,16,18,20,22,24,28,26,30,1,3,5,7,9,13,11,15,17,19,
21,23,25,29,27,31} = bindings(Node, default_bind),
ok;
check_bind_types(Node, e) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
= bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, thread_spread),
{0,8,2,10,4,12,6,14,1,9,3,11,5,13,7,15}
= bindings(Node, processor_spread),
{0,8,2,10,4,12,6,14,1,9,3,11,5,13,7,15}
= bindings(Node, spread),
{0,2,4,6,1,3,5,7,8,10,12,14,9,11,13,15}
= bindings(Node, no_node_thread_spread),
{0,2,4,6,1,3,5,7,8,10,12,14,9,11,13,15}
= bindings(Node, no_node_processor_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, thread_no_node_processor_spread),
{0,2,4,6,8,10,12,14,1,3,5,7,9,11,13,15}
= bindings(Node, default_bind),
ok;
check_bind_types(Node, f) ->
{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,27,28,29,30,31} = bindings(Node, no_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,15,
17,19,21,23,25,27,29,31} = bindings(Node, thread_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,
15,17,19,21,23,25,27,29,31} = bindings(Node, processor_spread),
{0,8,16,24,2,10,18,26,4,12,20,28,6,14,22,30,1,9,17,25,3,11,19,27,5,13,
21,29,7,15,23,31} = bindings(Node, spread),
{0,2,4,6,1,3,5,7,8,10,12,14,9,11,13,15,16,18,20,22,17,19,21,23,24,26,
28,30,25,27,29,31} = bindings(Node, no_node_thread_spread),
{0,2,4,6,1,3,5,7,8,10,12,14,9,11,13,15,16,18,20,22,17,19,21,23,24,26,
28,30,25,27,29,31} = bindings(Node, no_node_processor_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,15,17,19,
21,23,25,27,29,31} = bindings(Node, thread_no_node_processor_spread),
{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,1,3,5,7,9,11,13,15,17,19,
21,23,25,27,29,31} = bindings(Node, default_bind),
ok;
check_bind_types(Node, _) ->
bindings(Node, no_spread),
bindings(Node, thread_spread),
bindings(Node, processor_spread),
bindings(Node, spread),
bindings(Node, no_node_thread_spread),
bindings(Node, no_node_processor_spread),
bindings(Node, thread_no_node_processor_spread),
bindings(Node, default_bind),
ok.
cpu_topology(Config) when is_list(Config) ->
OldRelFlags = clear_erl_rel_flags(),
try
cpu_topology_test(
[{node,[{processor,[{core,{logical,0}},
{core,{logical,1}}]}]},
{processor,[{node,[{core,{logical,2}},
{core,{logical,3}}]}]},
{node,[{processor,[{core,{logical,4}},
{core,{logical,5}}]}]},
{processor,[{node,[{core,{logical,6}},
{core,{logical,7}}]}]}],
["+sct",
"L0-1c0-1p0n0"
":L2-3c0-1n1p1"
":L4-5c0-1p2n2"
":L6-7c0-1n3p3"]),
cpu_topology_test(
[{node,[{processor,[{core,{logical,0}},
{core,{logical,1}}]},
{processor,[{core,{logical,2}},
{core,{logical,3}}]}]},
{processor,[{node,[{core,{logical,4}},
{core,{logical,5}}]},
{node,[{core,{logical,6}},
{core,{logical,7}}]}]},
{node,[{processor,[{core,{logical,8}},
{core,{logical,9}}]},
{processor,[{core,{logical,10}},
{core,{logical,11}}]}]},
{processor,[{node,[{core,{logical,12}},
{core,{logical,13}}]},
{node,[{core,{logical,14}},
{core,{logical,15}}]}]}],
["+sct",
"L0-1c0-1p0n0"
":L2-3c0-1p1n0"
":L4-5c0-1n1p2"
":L6-7c2-3n2p2"
":L8-9c0-1p3n3"
":L10-11c0-1p4n3"
":L12-13c0-1n4p5"
":L14-15c2-3n5p5"]),
cpu_topology_test(
[{node,[{processor,[{core,{logical,0}},
{core,{logical,1}}]}]},
{processor,[{node,[{core,{logical,2}},
{core,{logical,3}}]}]},
{processor,[{node,[{core,{logical,4}},
{core,{logical,5}}]}]},
{node,[{processor,[{core,{logical,6}},
{core,{logical,7}}]}]},
{node,[{processor,[{core,{logical,8}},
{core,{logical,9}}]}]},
{processor,[{node,[{core,{logical,10}},
{core,{logical,11}}]}]}],
["+sct",
"L0-1c0-1p0n0"
":L2-3c0-1n1p1"
":L4-5c0-1n2p2"
":L6-7c0-1p3n3"
":L8-9c0-1p4n4"
":L10-11c0-1n5p5"])
after
restore_erl_rel_flags(OldRelFlags)
end,
ok.
cpu_topology_test(Topology, Cmd) ->
io:format("Testing~n ~p~n ~p~n", [Topology, Cmd]),
cpu_topology_bif_test(Topology),
cpu_topology_cmdline_test(Topology, Cmd),
ok.
cpu_topology_bif_test(false) ->
ok;
cpu_topology_bif_test(Topology) ->
{ok, Peer, Node} = ?CT_PEER(),
_ = rpc:call(Node, erlang, system_flag, [cpu_topology, Topology]),
cmp(Topology, rpc:call(Node, erlang, system_info, [cpu_topology])),
cmp(Topology,
rpc:call(Node, erlang, system_info, [{cpu_topology, defined}])),
peer:stop(Peer),
ok.
cpu_topology_cmdline_test(_Topology, false) ->
ok;
cpu_topology_cmdline_test(Topology, Cmd) ->
{ok, Peer, Node} = ?CT_PEER(Cmd),
cmp(Topology, rpc:call(Node, erlang, system_info, [cpu_topology])),
cmp(undefined,
rpc:call(Node, erlang, system_info, [{cpu_topology, detected}])),
cmp(Topology,
rpc:call(Node, erlang, system_info, [{cpu_topology, defined}])),
peer:stop(Peer),
ok.
update_cpu_info(Config) when is_list(Config) ->
OldOnline = erlang:system_info(schedulers_online),
OldAff = get_affinity_mask(),
io:format("START - Affinity mask: ~p - Schedulers online: ~p - Scheduler bindings: ~p~n",
[OldAff, OldOnline, erlang:system_info(scheduler_bindings)]),
case {erlang:system_info(logical_processors_available), OldAff} of
{Avail, _} when Avail == unknown; OldAff == unknown; OldAff == 1 ->
case erlang:system_info(update_cpu_info) of
unchanged -> ok;
changed -> ok
end;
{_Avail, _} ->
try
adjust_schedulers_online(),
case erlang:system_info(schedulers_online) of
1 ->
ok;
Onln0 ->
Cpus = bits_in_mask(OldAff),
RmCpus = case Cpus > Onln0 of
true -> Cpus - Onln0 + 1;
false -> Onln0 - Cpus + 1
end,
Onln1 = Cpus - RmCpus,
case Onln1 > 0 of
false ->
ok;
true ->
Aff = restrict_affinity_mask(OldAff, RmCpus),
set_affinity_mask(Aff),
case adjust_schedulers_online() of
{Onln0, Onln1} ->
Onln1 = erlang:system_info(schedulers_online),
receive after 500 -> ok end,
io:format("TEST - Affinity mask: ~p - Schedulers online: ~p - Scheduler bindings: ~p~n",
[Aff, Onln1, erlang:system_info(scheduler_bindings)]),
unchanged = adjust_schedulers_online(),
ok;
Fail ->
ct:fail(Fail)
end
end
end
after
set_affinity_mask(OldAff),
adjust_schedulers_online(),
erlang:system_flag(schedulers_online, OldOnline),
receive after 500 -> ok end,
io:format("END - Affinity mask: ~p - Schedulers online: ~p - Scheduler bindings: ~p~n",
[get_affinity_mask(),
erlang:system_info(schedulers_online),
erlang:system_info(scheduler_bindings)])
end
end.
bits_in_mask(Mask) ->
bits_in_mask(Mask, 0, 0).
bits_in_mask(0, _Shift, N) ->
N;
bits_in_mask(Mask, Shift, N) ->
case Mask band (1 bsl Shift) of
0 -> bits_in_mask(Mask, Shift+1, N);
_ -> bits_in_mask(Mask band (bnot (1 bsl Shift)),
Shift+1, N+1)
end.
restrict_affinity_mask(Mask, N) ->
try
restrict_affinity_mask(Mask, 0, N)
catch
throw : Reason ->
exit({Reason, Mask, N})
end.
restrict_affinity_mask(Mask, _Shift, 0) ->
Mask;
restrict_affinity_mask(0, _Shift, _N) ->
throw(overresticted_affinity_mask);
restrict_affinity_mask(Mask, Shift, N) ->
case Mask band (1 bsl Shift) of
0 -> restrict_affinity_mask(Mask, Shift+1, N);
_ -> restrict_affinity_mask(Mask band (bnot (1 bsl Shift)),
Shift+1, N-1)
end.
adjust_schedulers_online() ->
case erlang:system_info(update_cpu_info) of
unchanged ->
unchanged;
changed ->
Avail = erlang:system_info(logical_processors_available),
Scheds = erlang:system_info(schedulers),
SOnln = case Avail > Scheds of
true -> Scheds;
false -> Avail
end,
{erlang:system_flag(schedulers_online, SOnln), SOnln}
end.
read_affinity(Data) ->
Exp = "pid " ++ os:getpid() ++ "'s current affinity mask",
case string:lexemes(Data, ":") of
[Exp, DirtyAffinityStr] ->
AffinityStr = string:trim(DirtyAffinityStr),
case catch erlang:list_to_integer(AffinityStr, 16) of
Affinity when is_integer(Affinity) ->
Affinity;
_ ->
bad
end;
_ ->
bad
end.
get_affinity_mask(Port, Status, Affinity) when Status == unknown;
Affinity == unknown ->
receive
{Port,{data, Data}} ->
get_affinity_mask(Port, Status, read_affinity(Data));
{Port,{exit_status,S}} ->
get_affinity_mask(Port, S, Affinity)
end;
get_affinity_mask(_Port, _Status, bad) ->
unknown;
get_affinity_mask(_Port, _Status, Affinity) ->
Affinity.
get_affinity_mask() ->
case os:type() of
{unix, linux} ->
case catch open_port({spawn, "taskset -p " ++ os:getpid()},
[exit_status]) of
Port when is_port(Port) ->
get_affinity_mask(Port, unknown, unknown);
_ ->
unknown
end;
_ ->
unknown
end.
set_affinity_mask(Port, unknown) ->
receive
{Port,{data, _}} ->
set_affinity_mask(Port, unknown);
{Port,{exit_status,Status}} ->
set_affinity_mask(Port, Status)
end;
set_affinity_mask(Port, Status) ->
receive
{Port,{data, _}} ->
set_affinity_mask(Port, unknown)
after 0 ->
Status
end.
set_affinity_mask(Mask) ->
Cmd = lists:flatten(["taskset -p ",
io_lib:format("~.16b", [Mask]),
" ",
os:getpid()]),
case catch open_port({spawn, Cmd}, [exit_status]) of
Port when is_port(Port) ->
case set_affinity_mask(Port, unknown) of
0 -> ok;
_ -> exit(failed_to_set_affinity)
end;
_ ->
exit(failed_to_set_affinity)
end.
sct_cmd(Config) when is_list(Config) ->
Topology = ?TOPOLOGY_A_TERM,
OldRelFlags = clear_erl_rel_flags(),
try
{ok, Peer, Node} = ?CT_PEER(?TOPOLOGY_A_CMD),
cmp(Topology,
rpc:call(Node, erlang, system_info, [cpu_topology])),
cmp(undefined,
rpc:call(Node, erlang, system_info, [{cpu_topology, detected}])),
cmp(Topology,
rpc:call(Node, erlang, system_info, [{cpu_topology, defined}])),
cmp(Topology,
rpc:call(Node, erlang, system_flag, [cpu_topology, Topology])),
cmp(Topology,
rpc:call(Node, erlang, system_info, [cpu_topology])),
peer:stop(Peer)
after
restore_erl_rel_flags(OldRelFlags)
end,
ok.
ssrct_cmd(Config) when is_list(Config) ->
OldRelFlags = clear_erl_rel_flags(),
try
{ok, Peer, Node} = ?CT_PEER(["+ssrct"]),
cmp(undefined,
rpc:call(Node, erlang, system_info, [cpu_topology])),
cmp(undefined,
rpc:call(Node, erlang, system_info, [{cpu_topology, detected}])),
cmp(undefined,
rpc:call(Node, erlang, system_info, [{cpu_topology, defined}])),
peer:stop(Peer)
after
restore_erl_rel_flags(OldRelFlags)
end,
ok.
-define(BIND_TYPES,
[{"u", unbound},
{"ns", no_spread},
{"ts", thread_spread},
{"ps", processor_spread},
{"s", spread},
{"nnts", no_node_thread_spread},
{"nnps", no_node_processor_spread},
{"tnnps", thread_no_node_processor_spread},
{"db", thread_no_node_processor_spread}]).
sbt_cmd(Config) when is_list(Config) ->
case sbt_check_prereqs() of
{skipped, _Reason}=Skipped ->
Skipped;
ok ->
case sbt_make_topology_args() of
false ->
{skipped, "Don't know how to create cpu topology"};
CpuTCmd ->
LP = erlang:system_info(logical_processors),
OldRelFlags = clear_erl_rel_flags(),
try
lists:foreach(fun ({ClBt, Bt}) ->
sbt_test(CpuTCmd,
ClBt, Bt, LP)
end,
?BIND_TYPES)
after
restore_erl_rel_flags(OldRelFlags)
end,
ok
end
end.
sbt_make_topology_args() ->
case erlang:system_info({cpu_topology,detected}) of
undefined ->
case os:type() of
linux ->
case erlang:system_info(logical_processors) of
1 ->
["+sctL0"];
N ->
NS = integer_to_list(N - 1),
["+sctL0-"++NS++"p0-"++NS]
end;
_ ->
false
end;
_ ->
""
end.
sbt_check_prereqs() ->
try
Available = erlang:system_info(logical_processors_available),
Quota = erlang:system_info(cpu_quota),
if
Quota =:= unknown; Quota >= Available ->
ok;
Quota < Available ->
throw({skipped, "Test requires that CPU quota is greater than "
"the number of available processors."})
end,
try
OldVal = erlang:system_flag(scheduler_bind_type, default_bind),
erlang:system_flag(scheduler_bind_type, OldVal)
catch
error:notsup ->
throw({skipped, "Scheduler binding not supported."});
error:_ ->
ok
end,
case erlang:system_info(logical_processors) of
Count when is_integer(Count) ->
ok;
unknown ->
throw({skipped, "Can't detect number of logical processors."})
end,
ok
catch
throw:{skip,_Reason}=Skip -> Skip
end.
sbt_test(CpuTCmd, ClBt, Bt, LP) ->
io:format("Testing +sbt ~s (~p)~n", [ClBt, Bt]),
LPS = integer_to_list(LP),
Cmd = CpuTCmd++["+sbt", ClBt, "+S"++LPS++":"++LPS],
{ok, Peer, Node} = ?CT_PEER(Cmd),
Bt = rpc:call(Node,
erlang,
system_info,
[scheduler_bind_type]),
SB = rpc:call(Node,
erlang,
system_info,
[scheduler_bindings]),
io:format("scheduler bindings: ~p~n", [SB]),
BS = case {Bt, erlang:system_info(logical_processors_available)} of
{unbound, _} -> 0;
{_, Int} when is_integer(Int) -> Int;
{_, _} -> LP
end,
lists:foldl(fun (S, 0) ->
unbound = S,
0;
(S, N) ->
true = is_integer(S),
N-1
end,
BS,
tuple_to_list(SB)),
peer:stop(Peer),
ok.
scheduler_threads(Config) when is_list(Config) ->
{Sched, SchedOnln, _} = get_sstate(""),
{HalfSched, HalfSchedOnln} = {lists:max([1,Sched div 2]),
lists:max([1,SchedOnln div 2])},
{HalfSched, HalfSchedOnln, _} = get_sstate(["+SP", "50:50"]),
TwiceSched = Sched*2,
FourSched = integer_to_list(Sched*4),
FourSchedOnln = integer_to_list(SchedOnln*4),
CombinedCmd1 = ["+S", FourSched++":"++FourSchedOnln, "+SP50:25"],
{TwiceSched, SchedOnln, _} = get_sstate(CombinedCmd1),
Now do the same test but with the + S and + SP options in the
CombinedCmd2 = ["+SP50:25", "+S", FourSched++":"++FourSchedOnln],
{TwiceSched, SchedOnln, _} = get_sstate(CombinedCmd2),
Apply two + SP options to make sure the second overrides the first
TwoCmd = ["+SP", "25:25", "+SP", "100:100"],
{Sched, SchedOnln, _} = get_sstate(TwoCmd),
{Sched, HalfSchedOnln, _} = get_sstate(["+SP:50"]),
{TwiceSched, SchedOnln, _} = get_sstate(["+SP", "200"]),
LProc = erlang:system_info(logical_processors),
LProcAvail = erlang:system_info(logical_processors_available),
Quota = erlang:system_info(cpu_quota),
if
not is_integer(LProc); not is_integer(LProcAvail) ->
{comment, "Skipped reset amount of schedulers test, and reduced "
"amount of schedulers test due to too unknown amount of "
"logical processors"};
is_integer(LProc); is_integer(LProcAvail) ->
ExpectedOnln = st_expected_onln(LProcAvail, Quota),
st_reset(LProc, ExpectedOnln, FourSched, FourSchedOnln),
if
LProc =:= 1; LProcAvail =:= 1 ->
{comment, "Skipped reduced amount of schedulers test due "
"to too few logical processors"};
LProc > 1, LProcAvail > 1 ->
st_reduced(LProc, ExpectedOnln)
end
end.
st_reset(LProc, ExpectedOnln, FourSched, FourSchedOnln) ->
ResetCmd = ["+S", FourSched++":"++FourSchedOnln, "+S", "0:0"],
{LProc, ExpectedOnln, _} = get_sstate(ResetCmd),
ok.
st_reduced(LProc, ExpectedOnln) ->
SchedMinus1 = LProc-1,
SchedOnlnMinus1 = ExpectedOnln-1,
{SchedMinus1, SchedOnlnMinus1, _} = get_sstate(["+S", "-1"]),
{LProc, SchedOnlnMinus1, _} = get_sstate(["+S", ":-1"]),
{SchedMinus1, SchedOnlnMinus1, _} = get_sstate(["+S", "-1:-1"]),
ok.
st_expected_onln(LProcAvail, unknown) -> LProcAvail;
st_expected_onln(LProcAvail, Quota) -> min(LProcAvail, Quota).
dirty_scheduler_threads(Config) when is_list(Config) ->
case erlang:system_info(dirty_cpu_schedulers) of
0 -> {skipped, "No dirty scheduler support"};
_ -> dirty_scheduler_threads_test(Config)
end.
dirty_scheduler_threads_test(Config) when is_list(Config) ->
{Sched, SchedOnln, _} = get_dsstate(""),
{HalfSched, HalfSchedOnln} = {lists:max([1,Sched div 2]),
lists:max([1,SchedOnln div 2])},
Cmd1 = ["+SDcpu", integer_to_list(HalfSched)++":"++
integer_to_list(HalfSchedOnln)],
{HalfSched, HalfSchedOnln, _} = get_dsstate(Cmd1),
{HalfSched, HalfSchedOnln, _} = get_dsstate(["+SDPcpu", "50:50"]),
IOSched = 20,
{_, _, IOSched} = get_dsstate(["+SDio", integer_to_list(IOSched)]),
{ok, Peer, Node} = ?CT_PEER(),
[ok] = mcall(Node, [fun() -> dirty_schedulers_online_test() end]),
peer:stop(Peer),
ok.
dirty_schedulers_online_test() ->
dirty_schedulers_online_smp_test(erlang:system_info(schedulers_online)).
dirty_schedulers_online_smp_test(SchedOnln) when SchedOnln < 4 -> ok;
dirty_schedulers_online_smp_test(SchedOnln) ->
receive after 500 -> ok end,
DirtyCPUSchedOnln = erlang:system_info(dirty_cpu_schedulers_online),
SchedOnln = DirtyCPUSchedOnln,
HalfSchedOnln = SchedOnln div 2,
SchedOnln = erlang:system_flag(schedulers_online, HalfSchedOnln),
HalfDirtyCPUSchedOnln = DirtyCPUSchedOnln div 2,
HalfDirtyCPUSchedOnln = erlang:system_flag(schedulers_online, SchedOnln),
DirtyCPUSchedOnln = erlang:system_flag(dirty_cpu_schedulers_online,
HalfDirtyCPUSchedOnln),
receive after 500 -> ok end,
HalfDirtyCPUSchedOnln = erlang:system_info(dirty_cpu_schedulers_online),
QrtrDirtyCPUSchedOnln = HalfDirtyCPUSchedOnln div 2,
SchedOnln = erlang:system_flag(schedulers_online, HalfSchedOnln),
receive after 500 -> ok end,
QrtrDirtyCPUSchedOnln = erlang:system_info(dirty_cpu_schedulers_online),
ok.
get_sstate(Cmd) ->
{ok, Peer, Node} = ?CT_PEER(#{ args => Cmd, env => [{"ERL_FLAGS",false}]}),
[SState] = mcall(Node, [fun () ->
erlang:system_info(schedulers_state)
end]),
peer:stop(Peer),
SState.
get_dsstate(Cmd) ->
{ok, Peer, Node} = ?CT_PEER(#{ args => Cmd, env => [{"ERL_FLAGS",false}]}),
[DSCPU] = mcall(Node, [fun () ->
erlang:system_info(dirty_cpu_schedulers)
end]),
[DSCPUOnln] = mcall(Node, [fun () ->
erlang:system_info(dirty_cpu_schedulers_online)
end]),
[DSIO] = mcall(Node, [fun () ->
erlang:system_info(dirty_io_schedulers)
end]),
peer:stop(Peer),
{DSCPU, DSCPUOnln, DSIO}.
scheduler_suspend_basic(Config) when is_list(Config) ->
case erlang:system_info(multi_scheduling) of
disabled ->
{skip, "Nothing to test"};
_ ->
Onln = erlang:system_info(schedulers_online),
DirtyOnln = erlang:system_info(dirty_cpu_schedulers_online),
try
scheduler_suspend_basic_test()
after
erlang:system_flag(schedulers_online, Onln),
erlang:system_flag(dirty_cpu_schedulers_online, DirtyOnln)
end
end.
scheduler_suspend_basic_test() ->
before returning from erlang : system_flag(schedulers_online , _ ) .
erlang:system_flag(schedulers_online,
erlang:system_info(schedulers)),
try
erlang:system_flag(dirty_cpu_schedulers_online,
erlang:system_info(dirty_cpu_schedulers)),
receive after 500 -> ok end
catch
_ : _ ->
ok
end,
S0 = sched_state(),
io:format("~p~n", [S0]),
{{normal,NTot0,NOnln0,NAct0},
{dirty_cpu,DCTot0,DCOnln0,DCAct0},
{dirty_io,DITot0,DIOnln0,DIAct0}} = S0,
enabled = erlang:system_info(multi_scheduling),
DCOne = case DCTot0 of
0 -> 0;
_ -> 1
end,
blocked_normal = erlang:system_flag(multi_scheduling, block_normal),
blocked_normal = erlang:system_info(multi_scheduling),
{{normal,NTot0,NOnln0,1},
{dirty_cpu,DCTot0,DCOnln0,DCAct0},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
NOnln0 = erlang:system_flag(schedulers_online, 1),
receive after 500 -> ok end,
{{normal,NTot0,1,1},
{dirty_cpu,DCTot0,DCOne,DCOne},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
1 = erlang:system_flag(schedulers_online, NOnln0),
receive after 500 -> ok end,
{{normal,NTot0,NOnln0,1},
{dirty_cpu,DCTot0,DCOnln0,DCAct0},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
blocked = erlang:system_flag(multi_scheduling, block),
blocked = erlang:system_info(multi_scheduling),
receive after 500 -> ok end,
{{normal,NTot0,NOnln0,1},
{dirty_cpu,DCTot0,DCOnln0,0},
{dirty_io,DITot0,DIOnln0,0}} = sched_state(),
NOnln0 = erlang:system_flag(schedulers_online, 1),
receive after 500 -> ok end,
{{normal,NTot0,1,1},
{dirty_cpu,DCTot0,DCOne,0},
{dirty_io,DITot0,DIOnln0,0}} = sched_state(),
1 = erlang:system_flag(schedulers_online, NOnln0),
receive after 500 -> ok end,
{{normal,NTot0,NOnln0,1},
{dirty_cpu,DCTot0,DCOnln0,0},
{dirty_io,DITot0,DIOnln0,0}} = sched_state(),
blocked = erlang:system_flag(multi_scheduling, unblock_normal),
blocked = erlang:system_info(multi_scheduling),
{{normal,NTot0,NOnln0,1},
{dirty_cpu,DCTot0,DCOnln0,0},
{dirty_io,DITot0,DIOnln0,0}} = sched_state(),
enabled = erlang:system_flag(multi_scheduling, unblock),
enabled = erlang:system_info(multi_scheduling),
receive after 500 -> ok end,
{{normal,NTot0,NOnln0,NAct0},
{dirty_cpu,DCTot0,DCOnln0,DCAct0},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
NOnln0 = erlang:system_flag(schedulers_online, 1),
receive after 500 -> ok end,
{{normal,NTot0,1,1},
{dirty_cpu,DCTot0,DCOne,DCOne},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
1 = erlang:system_flag(schedulers_online, NOnln0),
receive after 500 -> ok end,
{{normal,NTot0,NOnln0,NAct0},
{dirty_cpu,DCTot0,DCOnln0,DCAct0},
{dirty_io,DITot0,DIOnln0,DIAct0}} = sched_state(),
ok.
scheduler_suspend(Config) when is_list(Config) ->
ct:timetrap({minutes, 5}),
lists:foreach(fun (S) -> scheduler_suspend_test(S) end,
[64, 32, 16, default]),
ok.
scheduler_suspend_test(Schedulers) ->
Cmd = case Schedulers of
default ->
"";
_ ->
S = integer_to_list(Schedulers),
["+S"++S++":"++S]
end,
{ok, Peer, Node} = ?CT_PEER(Cmd),
[SState] = mcall(Node, [fun () ->
erlang:system_info(schedulers_state)
end]),
io:format("SState=~p~n", [SState]),
{Sched, SchedOnln, _SchedAvail} = SState,
true = is_integer(Sched),
[ok] = mcall(Node, [fun () -> sst0_loop(300) end]),
[ok] = mcall(Node, [fun () -> sst1_loop(300) end]),
[ok] = mcall(Node, [fun () -> sst2_loop(300) end]),
[ok] = mcall(Node, [fun () -> sst4_loop(300) end]),
[ok] = mcall(Node, [fun () -> sst5_loop(300) end]),
[ok, ok, ok, ok,
ok, ok, ok] = mcall(Node,
[fun () -> sst0_loop(200) end,
fun () -> sst1_loop(200) end,
fun () -> sst2_loop(200) end,
fun () -> sst2_loop(200) end,
fun () -> sst3_loop(Sched, 200) end,
fun () -> sst4_loop(200) end,
fun () -> sst5_loop(200) end]),
[SState] = mcall(Node, [fun () ->
case Sched == SchedOnln of
false ->
Sched = erlang:system_flag(
schedulers_online,
SchedOnln);
true ->
ok
end,
until(fun () ->
{_A, B, C} = erlang:system_info(
schedulers_state),
B == C
end,
erlang:monotonic_time()
+ erlang:convert_time_unit(1,
seconds,
native)),
erlang:system_info(schedulers_state)
end]),
peer:stop(Peer),
ok.
until(Pred, MaxTime) ->
case Pred() of
true ->
true;
false ->
case erlang:monotonic_time() > MaxTime of
true ->
false;
false ->
receive after 100 -> ok end,
until(Pred, MaxTime)
end
end.
sst0_loop(0) ->
ok;
sst0_loop(N) ->
erlang:system_flag(multi_scheduling, block),
erlang:system_flag(multi_scheduling, unblock),
erlang:yield(),
sst0_loop(N-1).
sst1_loop(0) ->
ok;
sst1_loop(N) ->
erlang:system_flag(multi_scheduling, block),
erlang:system_flag(multi_scheduling, unblock),
sst1_loop(N-1).
sst2_loop(0) ->
ok;
sst2_loop(N) ->
erlang:system_flag(multi_scheduling, block),
erlang:system_flag(multi_scheduling, block),
erlang:system_flag(multi_scheduling, block),
erlang:system_flag(multi_scheduling, unblock),
erlang:system_flag(multi_scheduling, unblock),
erlang:system_flag(multi_scheduling, unblock),
sst2_loop(N-1).
sst3_loop(S, N) ->
case erlang:system_info(dirty_cpu_schedulers) of
0 -> sst3_loop_normal_schedulers_only(S, N);
DS -> sst3_loop_with_dirty_schedulers(S, DS, N)
end.
sst3_loop_normal_schedulers_only(_S, 0) ->
ok;
sst3_loop_normal_schedulers_only(S, N) ->
erlang:system_flag(schedulers_online, (S div 2)+1),
erlang:system_flag(schedulers_online, 1),
erlang:system_flag(schedulers_online, (S div 2)+1),
erlang:system_flag(schedulers_online, S),
erlang:system_flag(schedulers_online, 1),
erlang:system_flag(schedulers_online, S),
sst3_loop_normal_schedulers_only(S, N-1).
sst3_loop_with_dirty_schedulers(_S, _DS, 0) ->
ok;
sst3_loop_with_dirty_schedulers(S, DS, N) ->
erlang:system_flag(schedulers_online, (S div 2)+1),
erlang:system_flag(dirty_cpu_schedulers_online, (DS div 2)+1),
erlang:system_flag(schedulers_online, 1),
erlang:system_flag(schedulers_online, (S div 2)+1),
erlang:system_flag(dirty_cpu_schedulers_online, 1),
erlang:system_flag(schedulers_online, S),
erlang:system_flag(dirty_cpu_schedulers_online, DS),
erlang:system_flag(schedulers_online, 1),
erlang:system_flag(schedulers_online, S),
erlang:system_flag(dirty_cpu_schedulers_online, DS),
sst3_loop_with_dirty_schedulers(S, DS, N-1).
sst4_loop(0) ->
ok;
sst4_loop(N) ->
erlang:system_flag(multi_scheduling, block_normal),
erlang:system_flag(multi_scheduling, unblock_normal),
sst4_loop(N-1).
sst5_loop(0) ->
ok;
sst5_loop(N) ->
erlang:system_flag(multi_scheduling, block_normal),
erlang:system_flag(multi_scheduling, unblock_normal),
sst5_loop(N-1).
sched_poll(Config) when is_list(Config) ->
Env = case os:getenv("ERL_AFLAGS") of
false ->
[];
AFLAGS1 ->
AFLAGS2 = list_to_binary(re:replace(AFLAGS1,
"\\+IOs (true|false)",
"", [global])),
[{"ERL_AFLAGS", binary_to_list(AFLAGS2)}]
end,
[PS | _] = get_iostate(""),
HaveSchedPoll = proplists:get_value(concurrent_updates, PS),
0 = get_sched_pollsets(["+IOs", "false"]),
if
HaveSchedPoll ->
1 = get_sched_pollsets(["+IOs", "true"]),
1 = get_sched_pollsets([], Env);
not HaveSchedPoll ->
fail = get_sched_pollsets(["+IOs", "true"]),
0 = get_sched_pollsets([], Env)
end,
fail = get_sched_pollsets(["+IOs", "bad"]),
ok.
get_sched_pollsets(Cmd) ->
get_sched_pollsets(Cmd, []).
get_sched_pollsets(Cmd, Env)->
try
{ok, Peer, Node} = ?CT_PEER(#{connection => standard_io, args => Cmd,
env => [{"ERL_LIBS", false} | Env]}),
[IOStates] = mcall(Node,[fun () -> erlang:system_info(check_io) end]),
IO = [IOState || IOState <- IOStates,
proplists:get_value(fallback, IOState) == false,
proplists:get_value(poll_threads, IOState) == 0],
peer:stop(Peer),
catch
exit:{boot_failed, _} ->
fail
end.
poll_threads(Config) when is_list(Config) ->
[PS | _] = get_iostate(""),
Conc = proplists:get_value(concurrent_updates, PS),
[1, 1] = get_ionum(["+IOt", "2", "+IOp", "2"]),
[1, 1, 1, 1, 1] = get_ionum(["+IOt", "5", "+IOp", "5"]),
[1, 1] = get_ionum(["+S", "2", "+IOPt", "100", "+IOPp", "100"]),
if
Conc ->
[5] = get_ionum(["+IOt", "5", "+IOp", "1"]),
[3, 2] = get_ionum(["+IOt", "5", "+IOp", "2"]),
[2, 2, 2, 2, 2] = get_ionum(["+IOt", "10", "+IOPp", "50"]),
[2] = get_ionum(["+S", "2", "+IOPt", "100"]),
[4] = get_ionum(["+S", "4", "+IOPt", "100"]),
[4] = get_ionum(["+S", "4:2", "+IOPt", "100"]),
[4, 4] = get_ionum(["+S", "8", "+IOPt", "100", "+IOPp", "25"]),
fail = get_ionum(["+IOt", "1", "+IOp", "2"]),
ok;
not Conc ->
[1, 1, 1, 1, 1] = get_ionum(["+IOt", "5", "+IOp", "1"]),
[1, 1, 1, 1, 1] = get_ionum(["+IOt", "5", "+IOp", "2"]),
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] = get_ionum(["+IOt", "10", "+IOPp", "50"]),
[1, 1] = get_ionum(["+S", "2", "+IOPt", "100"]),
[1, 1, 1, 1] = get_ionum(["+S", "4", "+IOPt", "100"]),
[1, 1, 1, 1] = get_ionum(["+S", "4:2", "+IOPt", "100"]),
[1, 1, 1, 1, 1, 1, 1, 1] = get_ionum(["+S", "8", "+IOPt", "100" "+IOPp", "25"]),
[1] = get_ionum(["+IOt", "1", "+IOp", "2"]),
ok
end,
fail = get_ionum(["+IOt", "1", "+IOPp", "101"]),
fail = get_ionum(["+IOt", "0"]),
fail = get_ionum(["+IOPt", "101"]),
ok.
get_ionum(Cmd) ->
case get_iostate(Cmd) of
fail -> fail;
PSs ->
lists:reverse(
lists:sort(
[proplists:get_value(poll_threads, PS) || PS <- PSs]))
end.
get_iostate(Cmd)->
try
{ok, Peer, Node} = ?CT_PEER(#{connection => standard_io, args => Cmd,
env => [{"ERL_LIBS", false}]}),
[IOStates] = mcall(Node,[fun () -> erlang:system_info(check_io) end]),
IO = [IOState || IOState <- IOStates,
proplists:get_value(fallback, IOState) == false,
proplists:get_value(poll_threads, IOState) /= 0],
peer:stop(Peer),
IO
catch
exit:{boot_failed, _} ->
fail
end.
reader_groups(Config) when is_list(Config) ->
The actual topology
CPUT0 = [{processor,[{node,[{core,{logical,0}},
{core,{logical,1}},
{core,{logical,2}},
{core,{logical,8}},
{core,{logical,9}},
{core,{logical,10}},
{core,{logical,11}},
{core,{logical,16}},
{core,{logical,17}},
{core,{logical,18}},
{core,{logical,19}},
{core,{logical,24}},
{core,{logical,25}},
{core,{logical,27}},
{core,{logical,29}}]},
{node,[{core,{logical,3}},
{core,{logical,4}},
{core,{logical,5}},
{core,{logical,6}},
{core,{logical,7}},
{core,{logical,12}},
{core,{logical,13}},
{core,{logical,14}},
{core,{logical,15}},
{core,{logical,20}},
{core,{logical,21}},
{core,{logical,22}},
{core,{logical,23}},
{core,{logical,28}},
{core,{logical,30}}]},
{node,[{core,{logical,31}},
{core,{logical,36}},
{core,{logical,37}},
{core,{logical,38}},
{core,{logical,44}},
{core,{logical,45}},
{core,{logical,46}},
{core,{logical,47}},
{core,{logical,51}},
{core,{logical,52}},
{core,{logical,53}},
{core,{logical,54}},
{core,{logical,55}},
{core,{logical,60}},
{core,{logical,61}}]},
{node,[{core,{logical,26}},
{core,{logical,32}},
{core,{logical,33}},
{core,{logical,34}},
{core,{logical,35}},
{core,{logical,39}},
{core,{logical,40}},
{core,{logical,41}},
{core,{logical,42}},
{core,{logical,43}},
{core,{logical,48}},
{core,{logical,49}},
{core,{logical,50}},
{core,{logical,58}}]}]}],
[{0,1},{1,1},{2,1},{3,3},{4,3},{5,3},{6,3},{7,3},{8,1},{9,1},{10,1},
{11,1},{12,3},{13,3},{14,4},{15,4},{16,2},{17,2},{18,2},{19,2},
{20,4},{21,4},{22,4},{23,4},{24,2},{25,2},{26,7},{27,2},{28,4},
{29,2},{30,4},{31,5},{32,7},{33,7},{34,7},{35,7},{36,5},{37,5},
{38,5},{39,7},{40,7},{41,8},{42,8},{43,8},{44,5},{45,5},{46,5},
{47,6},{48,8},{49,8},{50,8},{51,6},{52,6},{53,6},{54,6},{55,6},
{58,8},{60,6},{61,6}]
= reader_groups_map(CPUT0, 8),
CPUT1 = [n([p([c([t(l(0)),t(l(1)),t(l(2)),t(l(3))]),
c([t(l(4)),t(l(5)),t(l(6)),t(l(7))]),
c([t(l(8)),t(l(9)),t(l(10)),t(l(11))]),
c([t(l(12)),t(l(13)),t(l(14)),t(l(15))])]),
p([c([t(l(16)),t(l(17)),t(l(18)),t(l(19))]),
c([t(l(20)),t(l(21)),t(l(22)),t(l(23))]),
c([t(l(24)),t(l(25)),t(l(26)),t(l(27))]),
c([t(l(28)),t(l(29)),t(l(30)),t(l(31))])])]),
n([p([c([t(l(32)),t(l(33)),t(l(34)),t(l(35))]),
c([t(l(36)),t(l(37)),t(l(38)),t(l(39))]),
c([t(l(40)),t(l(41)),t(l(42)),t(l(43))]),
c([t(l(44)),t(l(45)),t(l(46)),t(l(47))])]),
p([c([t(l(48)),t(l(49)),t(l(50)),t(l(51))]),
c([t(l(52)),t(l(53)),t(l(54)),t(l(55))]),
c([t(l(56)),t(l(57)),t(l(58)),t(l(59))]),
c([t(l(60)),t(l(61)),t(l(62)),t(l(63))])])]),
n([p([c([t(l(64)),t(l(65)),t(l(66)),t(l(67))]),
c([t(l(68)),t(l(69)),t(l(70)),t(l(71))]),
c([t(l(72)),t(l(73)),t(l(74)),t(l(75))]),
c([t(l(76)),t(l(77)),t(l(78)),t(l(79))])]),
p([c([t(l(80)),t(l(81)),t(l(82)),t(l(83))]),
c([t(l(84)),t(l(85)),t(l(86)),t(l(87))]),
c([t(l(88)),t(l(89)),t(l(90)),t(l(91))]),
c([t(l(92)),t(l(93)),t(l(94)),t(l(95))])])]),
n([p([c([t(l(96)),t(l(97)),t(l(98)),t(l(99))]),
c([t(l(100)),t(l(101)),t(l(102)),t(l(103))]),
c([t(l(104)),t(l(105)),t(l(106)),t(l(107))]),
c([t(l(108)),t(l(109)),t(l(110)),t(l(111))])]),
p([c([t(l(112)),t(l(113)),t(l(114)),t(l(115))]),
c([t(l(116)),t(l(117)),t(l(118)),t(l(119))]),
c([t(l(120)),t(l(121)),t(l(122)),t(l(123))]),
c([t(l(124)),t(l(125)),t(l(126)),t(l(127))])])])],
[{0,1},{1,1},{2,1},{3,1},{4,2},{5,2},{6,2},{7,2},{8,3},{9,3},
{10,3},{11,3},{12,4},{13,4},{14,4},{15,4},{16,5},{17,5},{18,5},
{19,5},{20,6},{21,6},{22,6},{23,6},{24,7},{25,7},{26,7},{27,7},
{28,8},{29,8},{30,8},{31,8},{32,9},{33,9},{34,9},{35,9},{36,10},
{37,10},{38,10},{39,10},{40,11},{41,11},{42,11},{43,11},{44,12},
{45,12},{46,12},{47,12},{48,13},{49,13},{50,13},{51,13},{52,14},
{53,14},{54,14},{55,14},{56,15},{57,15},{58,15},{59,15},{60,16},
{61,16},{62,16},{63,16},{64,17},{65,17},{66,17},{67,17},{68,18},
{69,18},{70,18},{71,18},{72,19},{73,19},{74,19},{75,19},{76,20},
{77,20},{78,20},{79,20},{80,21},{81,21},{82,21},{83,21},{84,22},
{85,22},{86,22},{87,22},{88,23},{89,23},{90,23},{91,23},{92,24},
{93,24},{94,24},{95,24},{96,25},{97,25},{98,25},{99,25},{100,26},
{101,26},{102,26},{103,26},{104,27},{105,27},{106,27},{107,27},
{108,28},{109,28},{110,28},{111,28},{112,29},{113,29},{114,29},
{115,29},{116,30},{117,30},{118,30},{119,30},{120,31},{121,31},
{122,31},{123,31},{124,32},{125,32},{126,32},{127,32}]
= reader_groups_map(CPUT1, 128),
[{0,1},{1,1},{2,1},{3,1},{4,1},{5,1},{6,1},{7,1},{8,1},{9,1},{10,1},
{11,1},{12,1},{13,1},{14,1},{15,1},{16,1},{17,1},{18,1},{19,1},
{20,1},{21,1},{22,1},{23,1},{24,1},{25,1},{26,1},{27,1},{28,1},
{29,1},{30,1},{31,1},{32,1},{33,1},{34,1},{35,1},{36,1},{37,1},
{38,1},{39,1},{40,1},{41,1},{42,1},{43,1},{44,1},{45,1},{46,1},
{47,1},{48,1},{49,1},{50,1},{51,1},{52,1},{53,1},{54,1},{55,1},
{56,1},{57,1},{58,1},{59,1},{60,1},{61,1},{62,1},{63,1},{64,2},
{65,2},{66,2},{67,2},{68,2},{69,2},{70,2},{71,2},{72,2},{73,2},
{74,2},{75,2},{76,2},{77,2},{78,2},{79,2},{80,2},{81,2},{82,2},
{83,2},{84,2},{85,2},{86,2},{87,2},{88,2},{89,2},{90,2},{91,2},
{92,2},{93,2},{94,2},{95,2},{96,2},{97,2},{98,2},{99,2},{100,2},
{101,2},{102,2},{103,2},{104,2},{105,2},{106,2},{107,2},{108,2},
{109,2},{110,2},{111,2},{112,2},{113,2},{114,2},{115,2},{116,2},
{117,2},{118,2},{119,2},{120,2},{121,2},{122,2},{123,2},{124,2},
{125,2},{126,2},{127,2}]
= reader_groups_map(CPUT1, 2),
[{0,1},{1,1},{2,1},{3,1},{4,2},{5,2},{6,2},{7,2},{8,3},{9,3},{10,3},
{11,3},{12,3},{13,3},{14,3},{15,3},{16,4},{17,4},{18,4},{19,4},
{20,4},{21,4},{22,4},{23,4},{24,5},{25,5},{26,5},{27,5},{28,5},
{29,5},{30,5},{31,5},{32,6},{33,6},{34,6},{35,6},{36,6},{37,6},
{38,6},{39,6},{40,7},{41,7},{42,7},{43,7},{44,7},{45,7},{46,7},
{47,7},{48,8},{49,8},{50,8},{51,8},{52,8},{53,8},{54,8},{55,8},
{56,9},{57,9},{58,9},{59,9},{60,9},{61,9},{62,9},{63,9},{64,10},
{65,10},{66,10},{67,10},{68,10},{69,10},{70,10},{71,10},{72,11},
{73,11},{74,11},{75,11},{76,11},{77,11},{78,11},{79,11},{80,12},
{81,12},{82,12},{83,12},{84,12},{85,12},{86,12},{87,12},{88,13},
{89,13},{90,13},{91,13},{92,13},{93,13},{94,13},{95,13},{96,14},
{97,14},{98,14},{99,14},{100,14},{101,14},{102,14},{103,14},
{104,15},{105,15},{106,15},{107,15},{108,15},{109,15},{110,15},
{111,15},{112,16},{113,16},{114,16},{115,16},{116,16},{117,16},
{118,16},{119,16},{120,17},{121,17},{122,17},{123,17},{124,17},
{125,17},{126,17},{127,17}]
= reader_groups_map(CPUT1, 17),
[{0,1},{1,1},{2,1},{3,1},{4,1},{5,1},{6,1},{7,1},{8,1},{9,1},{10,1},
{11,1},{12,1},{13,1},{14,1},{15,1},{16,2},{17,2},{18,2},{19,2},
{20,2},{21,2},{22,2},{23,2},{24,2},{25,2},{26,2},{27,2},{28,2},
{29,2},{30,2},{31,2},{32,3},{33,3},{34,3},{35,3},{36,3},{37,3},
{38,3},{39,3},{40,3},{41,3},{42,3},{43,3},{44,3},{45,3},{46,3},
{47,3},{48,4},{49,4},{50,4},{51,4},{52,4},{53,4},{54,4},{55,4},
{56,4},{57,4},{58,4},{59,4},{60,4},{61,4},{62,4},{63,4},{64,5},
{65,5},{66,5},{67,5},{68,5},{69,5},{70,5},{71,5},{72,5},{73,5},
{74,5},{75,5},{76,5},{77,5},{78,5},{79,5},{80,6},{81,6},{82,6},
{83,6},{84,6},{85,6},{86,6},{87,6},{88,6},{89,6},{90,6},{91,6},
{92,6},{93,6},{94,6},{95,6},{96,7},{97,7},{98,7},{99,7},{100,7},
{101,7},{102,7},{103,7},{104,7},{105,7},{106,7},{107,7},{108,7},
{109,7},{110,7},{111,7},{112,7},{113,7},{114,7},{115,7},{116,7},
{117,7},{118,7},{119,7},{120,7},{121,7},{122,7},{123,7},{124,7},
{125,7},{126,7},{127,7}]
= reader_groups_map(CPUT1, 7),
CPUT2 = [p([c(l(0)),c(l(1)),c(l(2)),c(l(3)),c(l(4))]),
p([t(l(5)),t(l(6)),t(l(7)),t(l(8)),t(l(9))]),
p([t(l(10))]),
p([c(l(11)),c(l(12)),c(l(13))]),
p([c(l(14)),c(l(15))])],
[{0,1},{1,1},{2,1},{3,1},{4,1},
{5,2},{6,2},{7,2},{8,2},{9,2},
{10,3},
{11,4},{12,4},{13,4},
{14,5},{15,5}] = reader_groups_map(CPUT2, 5),
[{0,1},{1,1},{2,2},{3,2},{4,2},
{5,3},{6,3},{7,3},{8,3},{9,3},
{10,4},
{11,5},{12,5},{13,5},
{14,6},{15,6}] = reader_groups_map(CPUT2, 6),
[{0,1},{1,1},{2,2},{3,2},{4,2},
{5,3},{6,3},{7,3},{8,3},{9,3},
{10,4},
{11,5},{12,6},{13,6},
{14,7},{15,7}] = reader_groups_map(CPUT2, 7),
[{0,1},{1,1},{2,2},{3,2},{4,2},
{5,3},{6,3},{7,3},{8,3},{9,3},
{10,4},
{11,5},{12,6},{13,6},
{14,7},{15,8}] = reader_groups_map(CPUT2, 8),
[{0,1},{1,2},{2,2},{3,3},{4,3},
{5,4},{6,4},{7,4},{8,4},{9,4},
{10,5},
{11,6},{12,7},{13,7},
{14,8},{15,9}] = reader_groups_map(CPUT2, 9),
[{0,1},{1,2},{2,2},{3,3},{4,3},
{5,4},{6,4},{7,4},{8,4},{9,4},
{10,5},
{11,6},{12,7},{13,8},
{14,9},{15,10}] = reader_groups_map(CPUT2, 10),
[{0,1},{1,2},{2,3},{3,4},{4,4},
{5,5},{6,5},{7,5},{8,5},{9,5},
{10,6},
{11,7},{12,8},{13,9},
{14,10},{15,11}] = reader_groups_map(CPUT2, 11),
[{0,1},{1,2},{2,3},{3,4},{4,5},
{5,6},{6,6},{7,6},{8,6},{9,6},
{10,7},
{11,8},{12,9},{13,10},
{14,11},{15,12}] = reader_groups_map(CPUT2, 100),
CPUT3 = [p([t(l(5)),t(l(6)),t(l(7)),t(l(8)),t(l(9))]),
p([t(l(10))]),
p([c(l(11)),c(l(12)),c(l(13))]),
p([c(l(14)),c(l(15))]),
p([c(l(0)),c(l(1)),c(l(2)),c(l(3)),c(l(4))])],
[{0,5},{1,5},{2,6},{3,6},{4,6},
{5,1},{6,1},{7,1},{8,1},{9,1},
{10,2},{11,3},{12,3},{13,3},
{14,4},{15,4}] = reader_groups_map(CPUT3, 6),
CPUT4 = [p([t(l(0)),t(l(1)),t(l(2)),t(l(3)),t(l(4))]),
p([t(l(5))]),
p([c(l(6)),c(l(7)),c(l(8))]),
p([c(l(9)),c(l(10))]),
p([c(l(11)),c(l(12)),c(l(13)),c(l(14)),c(l(15))])],
[{0,1},{1,1},{2,1},{3,1},{4,1},
{5,2},
{6,3},{7,3},{8,3},
{9,4},{10,4},
{11,5},{12,5},{13,6},{14,6},{15,6}] = reader_groups_map(CPUT4, 6),
[{0,1},{1,1},{2,1},{3,1},{4,1},
{5,2},
{6,3},{7,4},{8,4},
{9,5},{10,5},
{11,6},{12,6},{13,7},{14,7},{15,7}] = reader_groups_map(CPUT4, 7),
[{0,1},{65535,2}] = reader_groups_map([c(l(0)),c(l(65535))], 10),
ok.
reader_groups_map(CPUT, Groups) ->
Old = erlang:system_info({cpu_topology, defined}),
erlang:system_flag(cpu_topology, CPUT),
enable_internal_state(),
Res = erts_debug:get_internal_state({reader_groups_map, Groups}),
erlang:system_flag(cpu_topology, Old),
lists:sort(Res).
otp_16446(Config) when is_list(Config) ->
ct:timetrap({minutes, 1}),
process_flag(priority, high),
DIO = erlang:system_info(dirty_io_schedulers),
NoPrioProcs = 10*DIO,
io:format("DIO = ~p~nNoPrioProcs = ~p~n", [DIO, NoPrioProcs]),
DirtyLoop = fun Loop(P, N) ->
erts_debug:dirty_io(wait,1),
receive {get, From} -> From ! {P, N}
after 0 -> Loop(P,N+1)
end
end,
Spawn = fun SpawnLoop(_Prio, 0, Acc) ->
Acc;
SpawnLoop(Prio, N, Acc) ->
Pid = spawn_opt(fun () -> DirtyLoop(Prio, 0) end,
[link, {priority, Prio}]),
SpawnLoop(Prio, N-1, [Pid|Acc])
end,
Ns = Spawn(normal, NoPrioProcs, []),
Ls = Spawn(low, NoPrioProcs, []),
receive after 10000 -> ok end,
RequestInfo = fun (P) -> P ! {get, self()} end,
lists:foreach(RequestInfo, Ns),
lists:foreach(RequestInfo, Ls),
Collect = fun CollectFun(0, LLs, NLs) ->
{LLs, NLs};
CollectFun(N, LLs, NLs) ->
receive
{low, Calls} ->
CollectFun(N-1, LLs+Calls, NLs);
{normal, Calls} ->
CollectFun(N-1, LLs, NLs+Calls)
end
end,
{LLs, NLs} = Collect(2*NoPrioProcs, 0, 0),
expected ratio 0.125 , but this is not especially exact ...
Ratio = LLs / NLs,
io:format("LLs = ~p~nNLs = ~p~nRatio = ~p~n", [LLs, NLs, Ratio]),
true = Ratio > 0.05,
true = Ratio < 0.5,
WaitUntilDead = fun (P) ->
case is_process_alive(P) of
false ->
ok;
true ->
unlink(P),
exit(P, kill),
false = is_process_alive(P)
end
end,
lists:foreach(WaitUntilDead, Ns),
lists:foreach(WaitUntilDead, Ls),
Comment = "low/normal ratio: " ++ erlang:float_to_list(Ratio,[{decimals,4}]),
erlang:display(Comment),
{comment, Comment}.
simultaneously_change_schedulers_online(Config) when is_list(Config) ->
SchedOnline = erlang:system_info(schedulers_online),
Change = fun Change (0) ->
ok;
Change (N) ->
timer : sleep(rand : ) ) ,
erlang:system_flag(schedulers_online,
rand:uniform(erlang:system_info(schedulers))),
Change(N-1)
end,
PMs = lists:map(fun (_) ->
spawn_monitor(fun () -> Change(10) end)
end, lists:seq(1,2500)),
lists:foreach(fun ({P, M}) ->
receive
{'DOWN', M, process, P, normal} ->
ok
end
end,
PMs),
erlang:system_flag(schedulers_online, SchedOnline),
ok.
simultaneously_change_schedulers_online_with_exits(Config) when is_list(Config) ->
SchedOnline = erlang:system_info(schedulers_online),
Change = fun Change (0) ->
exit(bye);
Change (N) ->
timer : sleep(rand : ) ) ,
erlang:system_flag(schedulers_online,
rand:uniform(erlang:system_info(schedulers))),
Change(N-1)
end,
PMs = lists:map(fun (_) ->
spawn_monitor(fun () -> Change(10) end)
end, lists:seq(1,2500)),
Kill every 10 : th process ...
_ = lists:foldl(fun ({P, _M}, 0) ->
exit(P, bye),
10;
(_PM, N) ->
N-1
end,
10,
PMs),
lists:foreach(fun ({P, M}) ->
receive
{'DOWN', M, process, P, Reason} ->
bye = Reason
end
end,
PMs),
erlang:system_flag(schedulers_online, SchedOnline),
ok.
Utils
sched_state() ->
sched_state(erlang:system_info(all_schedulers_state),
undefined,
{dirty_cpu,0,0,0},
{dirty_io,0,0,0}).
sched_state([], N, DC, DI) ->
try
chk_basic(N),
chk_basic(DC),
chk_basic(DI),
{N, DC, DI}
catch
_ : _ ->
ct:fail({inconsisten_scheduler_state, {N, DC, DI}})
end;
sched_state([{normal, _, _, _} = S | Rest], _S, DC, DI) ->
sched_state(Rest, S, DC, DI);
sched_state([{dirty_cpu, _, _, _} = DC | Rest], S, _DC, DI) ->
sched_state(Rest, S, DC, DI);
sched_state([{dirty_io, _, _, _} = DI | Rest], S, DC, _DI) ->
sched_state(Rest, S, DC, DI).
chk_basic({_Type, Tot, Onln, Act}) ->
true = Tot >= Onln,
true = Onln >= Act.
l(Id) ->
{logical, Id}.
t(X) ->
{thread, X}.
c(X) ->
{core, X}.
p(X) ->
{processor, X}.
n(X) ->
{node, X}.
mcall(Node, Funs) ->
Parent = self(),
Refs = lists:map(fun (Fun) ->
Ref = make_ref(),
Pid = spawn(Node,
fun () ->
Res = Fun(),
unlink(Parent),
Parent ! {Ref, Res}
end),
MRef = erlang:monitor(process, Pid),
{Ref, MRef}
end, Funs),
lists:map(fun ({Ref, MRef}) ->
receive
{Ref, Res} ->
receive
{'DOWN',MRef,_,_,_} ->
Res
end;
{'DOWN',MRef,_,_,Reason} ->
Reason
end
end, Refs).
erl_rel_flag_var() ->
"ERL_OTP"++erlang:system_info(otp_release)++"_FLAGS".
clear_erl_rel_flags() ->
EnvVar = erl_rel_flag_var(),
case os:getenv(EnvVar) of
false ->
false;
Value ->
os:putenv(EnvVar, ""),
Value
end.
restore_erl_rel_flags(false) ->
ok;
restore_erl_rel_flags(OldValue) ->
os:putenv(erl_rel_flag_var(), OldValue),
ok.
ok(too_slow, _Config) ->
{comment, "Too slow system to do any actual testing..."};
ok(_Res, Config) ->
proplists:get_value(ok_res, Config).
chk_result(too_slow,
_LWorkers,
_NWorkers,
_HWorkers,
_MWorkers,
_LNShouldWork,
_HShouldWork,
_MShouldWork) ->
ok;
chk_result([{low, L, Lmin, _Lmax},
{normal, N, Nmin, _Nmax},
{high, H, Hmin, _Hmax},
{max, M, Mmin, _Mmax}] = Res,
LWorkers,
NWorkers,
HWorkers,
MWorkers,
LNShouldWork,
HShouldWork,
MShouldWork) ->
io:format("~p~n", [Res]),
Relax = relax_limits(),
case {L, N} of
{0, 0} ->
false = LNShouldWork;
_ ->
{LminRatioLim,
NminRatioLim,
LNRatioLimMin,
LNRatioLimMax} = case Relax of
false -> {0.5, 0.5, 0.05, 0.25};
true -> {0.05, 0.05, 0.01, 0.4}
end,
Lavg = L/LWorkers,
Navg = N/NWorkers,
Ratio = Lavg/Navg,
LminRatio = Lmin/Lavg,
NminRatio = Nmin/Navg,
io:format("low min ratio=~p~n"
"normal min ratio=~p~n"
"low avg=~p~n"
"normal avg=~p~n"
"low/normal ratio=~p~n",
[LminRatio, NminRatio, Lavg, Navg, Ratio]),
erlang:display({low_min_ratio, LminRatio}),
erlang:display({normal_min_ratio, NminRatio}),
erlang:display({low_avg, Lavg}),
erlang:display({normal_avg, Navg}),
erlang:display({low_normal_ratio, Ratio}),
chk_lim(LminRatioLim, LminRatio, 1.0, low_min_ratio),
chk_lim(NminRatioLim, NminRatio, 1.0, normal_min_ratio),
chk_lim(LNRatioLimMin, Ratio, LNRatioLimMax, low_normal_ratio),
true = LNShouldWork,
ok
end,
case H of
0 ->
false = HShouldWork;
_ ->
HminRatioLim = case Relax of
false -> 0.5;
true -> 0.1
end,
Havg = H/HWorkers,
HminRatio = Hmin/Havg,
erlang:display({high_min_ratio, HminRatio}),
chk_lim(HminRatioLim, HminRatio, 1.0, high_min_ratio),
true = HShouldWork,
ok
end,
case M of
0 ->
false = MShouldWork;
_ ->
MminRatioLim = case Relax of
false -> 0.5;
true -> 0.1
end,
Mavg = M/MWorkers,
MminRatio = Mmin/Mavg,
erlang:display({max_min_ratio, MminRatio}),
chk_lim(MminRatioLim, MminRatio, 1.0, max_min_ratio),
true = MShouldWork,
ok
end,
ok.
chk_lim(Min, V, Max, _What) when Min =< V, V =< Max ->
ok;
chk_lim(_Min, V, _Max, What) ->
ct:fail({bad, What, V}).
snd(_Msg, []) ->
[];
snd(Msg, [P|Ps]) ->
P ! Msg,
Ps.
relax_limits() ->
case strange_system_scale() of
Scale when Scale > 1 ->
io:format("Relaxing limits~n", []),
true;
_ ->
false
end.
strange_system_scale() ->
S0 = 1,
S1 = case erlang:system_info(schedulers_online)
> erlang:system_info(logical_processors) of
true -> S0*2;
false -> S0
end,
S2 = case erlang:system_info(debug_compiled) of
true -> S1*10;
false ->
case erlang:system_info(lock_checking) of
true -> S1*2;
false -> S1
end
end,
S3 = case lock_counting() of
true -> S2*2;
false -> S2
end,
S3.
lock_counting() ->
lock_counting(erlang:system_info(system_version)).
lock_counting([]) ->
false;
lock_counting([$[,$l,$o,$c,$k,$-,$c,$o,$u,$n,$t,$i,$n,$g,$],_]) ->
true;
lock_counting([_C|Cs]) ->
lock_counting(Cs).
go_work([], [], [], []) ->
[];
go_work(L, N, [], []) ->
go_work(snd(go_work, L), snd(go_work, N), [], []);
go_work(L, N, H, []) ->
go_work(L, N, snd(go_work, H), []);
go_work(L, N, H, M) ->
go_work(L, N, H, snd(go_work, M)).
stop_work([], [], [], []) ->
[];
stop_work([], [], [], M) ->
stop_work([], [], [], snd(stop_work, M));
stop_work([], [], H, M) ->
stop_work([], [], snd(stop_work, H), M);
stop_work(L, N, H, M) ->
stop_work(snd(stop_work, L), snd(stop_work, N), H, M).
wait_balance(N) when is_integer(N) ->
case erlang:system_info(schedulers_active) of
1 ->
done;
_ ->
erts_debug:set_internal_state(available_internal_state,true),
Start = erts_debug:get_internal_state(nbalance),
End = (Start + N) band ((1 bsl (8*erlang:system_info(wordsize)))-1),
wait_balance(Start, End),
erts_debug:set_internal_state(available_internal_state,false)
end.
wait_balance(Start, End) ->
X = erts_debug:get_internal_state(nbalance),
case End =< X of
true ->
case Start =< End of
true ->
done;
false ->
case X < Start of
true ->
done;
false ->
receive after 250 -> ok end,
wait_balance(Start, End)
end
end;
false ->
receive after 250 -> ok end,
wait_balance(Start, End)
end.
wait_reds(RedsLimit, Timeout) ->
Stop = erlang:start_timer(Timeout, self(), stop),
statistics(reductions),
wait_reds(0, RedsLimit, Stop).
wait_reds(Reds, RedsLimit, Stop) when Reds < RedsLimit ->
receive
{timeout, Stop, stop} ->
erlang:display(timeout),
erlang:display({reduction_limit, RedsLimit}),
erlang:display({reductions, Reds}),
done
after 10000 ->
{_, NewReds} = statistics(reductions),
wait_reds(NewReds+Reds, RedsLimit, Stop)
end;
wait_reds(Reds, RedsLimit, Stop) when is_reference(Stop) ->
erlang:cancel_timer(Stop),
receive {timeout, Stop, stop} -> ok after 0 -> ok end,
wait_reds(Reds, RedsLimit, false);
wait_reds(Reds, RedsLimit, _Stop) ->
erlang:display({reduction_limit, RedsLimit}),
erlang:display({reductions, Reds}),
done.
do_it(Tracer, Low, Normal, High, Max) ->
do_it(Tracer, Low, Normal, High, Max, ?DEFAULT_TEST_REDS_PER_SCHED).
do_it(Tracer, Low, Normal, High, Max, RedsPerSchedLimit) ->
OldPrio = process_flag(priority, max),
go_work(Low, Normal, High, Max),
StartWait = erlang:monotonic_time(millisecond),
wait_balance(5),
EndWait = erlang:monotonic_time(millisecond),
BalanceWait = EndWait-StartWait,
erlang:display({balance_wait, BalanceWait}),
Timeout = (15 - 4)*60*1000 - BalanceWait,
Res = case Timeout < 60*1000 of
true ->
stop_work(Low, Normal, High, Max),
too_slow;
false ->
set_tracing(true, Tracer, normal, Normal),
set_tracing(true, Tracer, low, Low),
set_tracing(true, Tracer, high, High),
set_tracing(true, Tracer, max, Max),
wait_reds(RedsPerSchedLimit
* erlang:system_info(schedulers_online),
Timeout),
set_tracing(false, Tracer, normal, Normal),
set_tracing(false, Tracer, low, Low),
set_tracing(false, Tracer, high, High),
set_tracing(false, Tracer, max, Max),
stop_work(Low, Normal, High, Max),
get_trace_result(Tracer)
end,
process_flag(priority, OldPrio),
Res.
workers_exit([]) ->
ok;
workers_exit([P|Ps]) when is_pid(P) ->
Mon = erlang:monitor(process, P),
unlink(P),
exit(P, kill),
workers_exit(Ps),
receive {'DOWN', Mon, process, P, _} -> ok end,
ok;
workers_exit([[]]) ->
ok;
workers_exit([Ps|Pss]) ->
workers_exit(Ps),
workers_exit(Pss).
do_work(PartTime) ->
_ = id(lists:seq(1, 50)),
receive stop_work -> receive after infinity -> ok end after 0 -> ok end,
case PartTime of
true -> receive after 1 -> ok end;
false -> ok
end,
do_work(PartTime).
id(I) -> I.
workers(N, _Prio, _PartTime) when N =< 0 ->
[];
workers(N, Prio, PartTime) ->
Parent = self(),
W = spawn_opt(fun () ->
Parent ! {ready, self()},
receive
go_work ->
do_work(PartTime)
end
end,
[{priority, Prio}, link]),
Ws = workers(N-1, Prio, PartTime),
receive {ready, W} -> ok end,
[W|Ws].
workers(N, Prio) ->
workers(N, Prio, false).
part_time_workers(N, Prio) ->
workers(N, Prio, true).
tracer(Low, Normal, High, Max) ->
receive
{tracees, Prio, Tracees} ->
save_tracees(Prio, Tracees),
case Prio of
low -> tracer(Tracees++Low, Normal, High, Max);
normal -> tracer(Low, Tracees++Normal, High, Max);
high -> tracer(Low, Normal, Tracees++High, Max);
max -> tracer(Low, Normal, High, Tracees++Max)
end;
{get_result, Ref, Who} ->
Delivered = erlang:trace_delivered(all),
receive
{trace_delivered, all, Delivered} ->
ok
end,
{Lc, Nc, Hc, Mc} = read_trace(),
GetMinMax
= fun (Prio, Procs) ->
LargeNum = 1 bsl 64,
case lists:foldl(fun (P, {Mn, Mx} = MnMx) ->
{Prio, C} = get(P),
case C < Mn of
true ->
case C > Mx of
true ->
{C, C};
false ->
{C, Mx}
end;
false ->
case C > Mx of
true -> {Mn, C};
false -> MnMx
end
end
end,
{LargeNum, 0},
Procs) of
{LargeNum, 0} -> {0, 0};
Res -> Res
end
end,
{Lmin, Lmax} = GetMinMax(low, Low),
{Nmin, Nmax} = GetMinMax(normal, Normal),
{Hmin, Hmax} = GetMinMax(high, High),
{Mmin, Mmax} = GetMinMax(max, Max),
Who ! {trace_result, Ref, [{low, Lc, Lmin, Lmax},
{normal, Nc, Nmin, Nmax},
{high, Hc, Hmin, Hmax},
{max, Mc, Mmin, Mmax}]}
end.
read_trace() ->
read_trace(0,0,0,0).
read_trace(Low, Normal, High, Max) ->
receive
{trace, Proc, in, _} ->
{Prio, Count} = get(Proc),
put(Proc, {Prio, Count+1}),
case Prio of
low -> read_trace(Low+1, Normal, High, Max);
normal -> read_trace(Low, Normal+1, High, Max);
high -> read_trace(Low, Normal, High+1, Max);
max -> read_trace(Low, Normal, High, Max+1)
end;
{trace, _Proc, out, _} ->
read_trace(Low, Normal, High, Max)
after 0 ->
{Low, Normal, High, Max}
end.
save_tracees(_Prio, []) ->
ok;
save_tracees(Prio, [T|Ts]) ->
put(T, {Prio, 0}),
save_tracees(Prio, Ts).
start_tracer() ->
Tracer = spawn_link(fun () -> tracer([], [], [], []) end),
true = erlang:suspend_process(Tracer),
Tracer.
get_trace_result(Tracer) ->
erlang:resume_process(Tracer),
Ref = make_ref(),
Tracer ! {get_result, Ref, self()},
receive
{trace_result, Ref, Res} ->
Res
end.
set_tracing(_On, _Tracer, _Prio, []) ->
ok;
set_tracing(true, Tracer, Prio, Pids) ->
Tracer ! {tracees, Prio, Pids},
set_tracing(true, Tracer, Pids);
set_tracing(false, Tracer, _Prio, Pids) ->
set_tracing(false, Tracer, Pids).
set_tracing(_On, _Tracer, []) ->
ok;
set_tracing(On, Tracer, [Pid|Pids]) ->
1 = erlang:trace(Pid, On, [running, {tracer, Tracer}]),
set_tracing(On, Tracer, Pids).
active_schedulers() ->
case erlang:system_info(schedulers_online) of
1 ->
1;
N ->
case erlang:system_info(multi_scheduling) of
blocked -> 1;
enabled -> N
end
end.
enable_internal_state() ->
case catch erts_debug:get_internal_state(available_internal_state) of
true -> true;
_ -> erts_debug:set_internal_state(available_internal_state, true)
end.
cmp(X, X) ->
ok;
cmp(X, Y) ->
io:format("cmp failed:~n X=~p~n Y=~p~n", [X,Y]),
cmp_aux(X, Y).
cmp_aux([X0|Y0], [X1|Y1]) ->
cmp_aux(X0, X1),
cmp_aux(Y0, Y1);
cmp_aux(T0, T1) when is_tuple(T0), is_tuple(T1), size(T0) == size(T1) ->
cmp_tuple(T0, T1, 1, size(T0));
cmp_aux(X, X) ->
ok;
cmp_aux(F0, F1) ->
ct:fail({no_match, F0, F1}).
cmp_tuple(_T0, _T1, N, Sz) when N > Sz ->
ok;
cmp_tuple(T0, T1, N, Sz) ->
cmp_aux(element(N, T0), element(N, T1)),
cmp_tuple(T0, T1, N+1, Sz).
|
669203a5a7b8fc6f94b33757ccd2fcdd9010cc6235817d55938c56b687dc456e | aaltodsg/instans | debug.lisp | ;;; -*- Mode: Lisp -*-
;;; -------------------- Debug messages --------------------
(in-package #:instans)
(proclaim '(optimize safety))
(defvar *dbg-stream* *error-output*)
(defvar *dbg-indent* 0)
(defun dbginc (inc)
(incf *dbg-indent* inc))
(defvar *dbgp* nil)
(eval-when (:compile-toplevel :load-toplevel :execute)
(setq *dbgp* nil))
(defmacro dbg (&rest args)
(cond ((not *dbgp*)
nil)
(t
`(format *dbg-stream* (concatenate 'string "~%~V@T" ,(first args)) *dbg-indent* ,@(rest args)))))
(defmacro dbgblock (&body body)
(cond ((not *dbgp*)
nil)
(t
`(progn ,@body))))
| null | https://raw.githubusercontent.com/aaltodsg/instans/5ffc90e733e76ab911165f205ba57a7b3b200945/src/cl-ll1/debug.lisp | lisp | -*- Mode: Lisp -*-
-------------------- Debug messages -------------------- |
(in-package #:instans)
(proclaim '(optimize safety))
(defvar *dbg-stream* *error-output*)
(defvar *dbg-indent* 0)
(defun dbginc (inc)
(incf *dbg-indent* inc))
(defvar *dbgp* nil)
(eval-when (:compile-toplevel :load-toplevel :execute)
(setq *dbgp* nil))
(defmacro dbg (&rest args)
(cond ((not *dbgp*)
nil)
(t
`(format *dbg-stream* (concatenate 'string "~%~V@T" ,(first args)) *dbg-indent* ,@(rest args)))))
(defmacro dbgblock (&body body)
(cond ((not *dbgp*)
nil)
(t
`(progn ,@body))))
|
6a7df94afc7405c9ebcc2baf7046fb549a49bbb0ea90f61cc533b6c0c44a0cda | williamleferrand/accretio | pa_operators.ml |
* Accretio is an API , a sandbox and a runtime for social playbooks
*
* Copyright ( C ) 2015
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation , either version 3 of the
* License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Affero General Public License for more details .
*
* You should have received a copy of the GNU Affero General Public License
* along with this program . If not , see < / > .
* Accretio is an API, a sandbox and a runtime for social playbooks
*
* Copyright (C) 2015 William Le Ferrand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see </>.
*)
open Camlp4
module Id : Sig.Id =
struct
let name = "pa_operators"
let version = "0.1"
end
module Make (Syntax : Sig.Camlp4Syntax) =
struct
open Camlp4.PreCast
include Syntax
(* this is a duplicate, but I don't want to depend on pa_vertex outside of
/graph *)
let wrap_field _loc uid field =
<:expr< (Ys_uid.to_string_padded $uid$) ^ "_" ^ $str:field$ >>
EXTEND Gram
expr: LAST
[
[
(* get fields with a lwt argument*)
"$$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "->" ; field = LIDENT ->
let obj = "Object_"^obj in
<:expr< Lwt.bind ($uid$) $uid:obj$.Store.$lid:"get_"^field$ >>
(* get fields *)
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "->" ;
field = LIDENT ->
let obj = "Object_"^obj in
<:expr< $uid:obj$.Store.$lid:"get_"^field$ $uid$ >>
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "->" ;
"(" ; fields = LIST1 [ f = LIDENT -> f ] SEP "," ; ")" ->
Printf.eprintf " hit rule 1\n " ; flush stdout ;
let obj = "Object_"^obj in
(match fields with
| [ field ] ->
(* singleton case need to be handled separately *)
<:expr< $uid:obj$.Store.$lid:"get_"^field$ $uid$ >>
| _ as fields ->
let keys = List.map (wrap_field _loc uid) fields in
(* optimisation? we could use an iterator & skip the keys we're
not interested in *)
let idents = List.map (fun field -> <:expr< $lid:field$ >>) fields in
let _, bindings =
List.fold_left
(fun (cnt, acc) field ->
(cnt + 1),
<:expr<
Lwt.bind
($uid:obj$.Store.$lid:"raw_"^field$ $uid$ data_options.($int:(string_of_int cnt)$))
(fun [ $lid:field$ -> $acc$ ])
>>)
(0,
<:expr<
Lwt.return $tup:Ast.exCom_of_list idents$
>>)
fields
in
<:expr<
Lwt.bind
(Ys_persistency.Store.Batch.get $uid:obj$.Store.db [| $list:keys$ |])
(fun data_options ->
(* now we need to remap this array to a tuple of results
which isn't super trivial to do in parallel *)
$bindings$)
>>)
(* set a field. no need to batch as it is asynchrounous *)
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"=" ; e = expr LEVEL "top" ->
Printf.eprintf " hit rule 2\n " ; flush stdout ;
let obj = "Object_"^obj in
<:expr<
($uid:obj$.Store.$lid:"set_"^field$ $uid$ $e$)
>>
(* patch a field lwt. no need to batch because we never patch several fields, but risk of deadlock *)
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"%%%" ; p = expr LEVEL "simple" ->
Printf.eprintf " hit rule 3\n " ; flush stdout ;
let obj = "Object_"^obj in
<:expr<
$uid:obj$.Store.$lid:"patch_lwt_"^field$ $uid$ $p$
>>
(* patch a field. no need to batch because we never patch several fields *)
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"%%" ; p = expr LEVEL "simple" ->
Printf.eprintf " hit rule 3\n " ; flush stdout ;
let obj = "Object_"^obj in
<:expr<
$uid:obj$.Store.$lid:"patch_"^field$ $uid$ $p$
>>
(* attach an edge *)
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"+=" ; p = expr LEVEL "simple" ->
Printf.eprintf " hit rule 4\n " ; flush stdout ;
let obj = "Object_"^obj in
<:expr<
$uid:obj$.Store.$lid:"attach_to_"^field$ $uid$ $p$
>>
(* attach an edge, check unicity *)
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"+=!" ; p = expr LEVEL "simple" ->
let obj = "Object_"^obj in
<:expr<
$uid:obj$.Store.$lid:"attach_to_"^field^"_check_unicity"$ $uid$ $p$
>>
(* detach an edge *)
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"-=" ; p = expr LEVEL "simple" ->
Printf.eprintf " hit rule 5\n " ; flush stdout ;
let obj = "Object_"^obj in
<:expr<
$uid:obj$.Store.$lid:"detach_from_"^field$ $uid$ $p$
>>
(* the scala _ *)
| "_" ; "." ; m = OPT [ m = UIDENT ; "." -> m ] ; lid = LIDENT ->
Printf.eprintf " hit rule 6\n " ; flush stdout ;
match m with
None -> <:expr< fun e -> e.$lid:lid$ >>
| Some m -> <:expr< fun e -> e.$uid:m$.$lid:lid$ >>
]
];
END
end
module M = Register.OCamlSyntaxExtension(Id)(Make)
| null | https://raw.githubusercontent.com/williamleferrand/accretio/394f855e9c2a6a18f0c2da35058d5a01aacf6586/library/syntax/pa_operators.ml | ocaml | this is a duplicate, but I don't want to depend on pa_vertex outside of
/graph
get fields with a lwt argument
get fields
singleton case need to be handled separately
optimisation? we could use an iterator & skip the keys we're
not interested in
now we need to remap this array to a tuple of results
which isn't super trivial to do in parallel
set a field. no need to batch as it is asynchrounous
patch a field lwt. no need to batch because we never patch several fields, but risk of deadlock
patch a field. no need to batch because we never patch several fields
attach an edge
attach an edge, check unicity
detach an edge
the scala _ |
* Accretio is an API , a sandbox and a runtime for social playbooks
*
* Copyright ( C ) 2015
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation , either version 3 of the
* License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Affero General Public License for more details .
*
* You should have received a copy of the GNU Affero General Public License
* along with this program . If not , see < / > .
* Accretio is an API, a sandbox and a runtime for social playbooks
*
* Copyright (C) 2015 William Le Ferrand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see </>.
*)
open Camlp4
module Id : Sig.Id =
struct
let name = "pa_operators"
let version = "0.1"
end
module Make (Syntax : Sig.Camlp4Syntax) =
struct
open Camlp4.PreCast
include Syntax
let wrap_field _loc uid field =
<:expr< (Ys_uid.to_string_padded $uid$) ^ "_" ^ $str:field$ >>
EXTEND Gram
expr: LAST
[
[
"$$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "->" ; field = LIDENT ->
let obj = "Object_"^obj in
<:expr< Lwt.bind ($uid$) $uid:obj$.Store.$lid:"get_"^field$ >>
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "->" ;
field = LIDENT ->
let obj = "Object_"^obj in
<:expr< $uid:obj$.Store.$lid:"get_"^field$ $uid$ >>
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "->" ;
"(" ; fields = LIST1 [ f = LIDENT -> f ] SEP "," ; ")" ->
Printf.eprintf " hit rule 1\n " ; flush stdout ;
let obj = "Object_"^obj in
(match fields with
| [ field ] ->
<:expr< $uid:obj$.Store.$lid:"get_"^field$ $uid$ >>
| _ as fields ->
let keys = List.map (wrap_field _loc uid) fields in
let idents = List.map (fun field -> <:expr< $lid:field$ >>) fields in
let _, bindings =
List.fold_left
(fun (cnt, acc) field ->
(cnt + 1),
<:expr<
Lwt.bind
($uid:obj$.Store.$lid:"raw_"^field$ $uid$ data_options.($int:(string_of_int cnt)$))
(fun [ $lid:field$ -> $acc$ ])
>>)
(0,
<:expr<
Lwt.return $tup:Ast.exCom_of_list idents$
>>)
fields
in
<:expr<
Lwt.bind
(Ys_persistency.Store.Batch.get $uid:obj$.Store.db [| $list:keys$ |])
(fun data_options ->
$bindings$)
>>)
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"=" ; e = expr LEVEL "top" ->
Printf.eprintf " hit rule 2\n " ; flush stdout ;
let obj = "Object_"^obj in
<:expr<
($uid:obj$.Store.$lid:"set_"^field$ $uid$ $e$)
>>
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"%%%" ; p = expr LEVEL "simple" ->
Printf.eprintf " hit rule 3\n " ; flush stdout ;
let obj = "Object_"^obj in
<:expr<
$uid:obj$.Store.$lid:"patch_lwt_"^field$ $uid$ $p$
>>
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"%%" ; p = expr LEVEL "simple" ->
Printf.eprintf " hit rule 3\n " ; flush stdout ;
let obj = "Object_"^obj in
<:expr<
$uid:obj$.Store.$lid:"patch_"^field$ $uid$ $p$
>>
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"+=" ; p = expr LEVEL "simple" ->
Printf.eprintf " hit rule 4\n " ; flush stdout ;
let obj = "Object_"^obj in
<:expr<
$uid:obj$.Store.$lid:"attach_to_"^field$ $uid$ $p$
>>
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"+=!" ; p = expr LEVEL "simple" ->
let obj = "Object_"^obj in
<:expr<
$uid:obj$.Store.$lid:"attach_to_"^field^"_check_unicity"$ $uid$ $p$
>>
| "$" ; obj = LIDENT ; "(" ; uid = expr ; ")" ; "<-" ; field = LIDENT ;
"-=" ; p = expr LEVEL "simple" ->
Printf.eprintf " hit rule 5\n " ; flush stdout ;
let obj = "Object_"^obj in
<:expr<
$uid:obj$.Store.$lid:"detach_from_"^field$ $uid$ $p$
>>
| "_" ; "." ; m = OPT [ m = UIDENT ; "." -> m ] ; lid = LIDENT ->
Printf.eprintf " hit rule 6\n " ; flush stdout ;
match m with
None -> <:expr< fun e -> e.$lid:lid$ >>
| Some m -> <:expr< fun e -> e.$uid:m$.$lid:lid$ >>
]
];
END
end
module M = Register.OCamlSyntaxExtension(Id)(Make)
|
571f3606c51cd6d5f352d02cbfce4b0382936a600d299787a460ba8b49beaaa2 | Frozenlock/wacnet | repl.clj | (ns wacnet.api.repl
(:require [clojure.stacktrace :refer [root-cause]]
[wacnet.api.bacnet.common :as co]
[wacnet.nrepl :as wnrepl]
[yada.resource :refer [resource]]
[schema.core :as s])
(:import java.io.StringWriter
[java.util.concurrent TimeoutException TimeUnit FutureTask]))
(def users-namespaces (atom {}))
(defn remove-ns-future
"Unmap a namespace after `delay' in ms."
[delay]
24 hours ( * 60000 60 24 )
(-> *ns* .getName remove-ns)))
(defmacro new-namespace
"Create a new newspace and return it." []
(let [ns-name# (symbol (gensym "user-"))]
`(binding [*ns* *ns*]
(ns ~ns-name#)
*ns*)))
(defn throwable-ns
"Creates a new ns that will expire after `delay' in ms. If init is
provided, it will be evaluated when the namespace is created."
[&{:keys [delay init]}]
(let [new-ns (new-namespace)]
(binding [*ns* new-ns]
(when init (eval init))
(remove-ns-future delay))
new-ns))
(defn make-user-ns! [session-id]
24 hours
ns (throwable-ns :delay delay-ms
:init wnrepl/repl-init)]
(swap! users-namespaces assoc session-id ns)
(future (Thread/sleep delay-ms)
(swap! users-namespaces dissoc session-id))
ns))
;; from clojail
(def ^{:doc "Create a map of pretty keywords to ugly TimeUnits"}
uglify-time-unit
(into {} (for [[enum aliases] {TimeUnit/NANOSECONDS [:ns :nanoseconds]
TimeUnit/MICROSECONDS [:us :microseconds]
TimeUnit/MILLISECONDS [:ms :milliseconds]
TimeUnit/SECONDS [:s :sec :seconds]}
alias aliases]
{alias enum})))
(defn thunk-timeout
"Takes a function and an amount of time to wait for those function to finish
executing. The sandbox can do this for you. unit is any of :ns, :us, :ms,
or :s which correspond to TimeUnit/NANOSECONDS, MICROSECONDS, MILLISECONDS,
and SECONDS respectively."
([thunk ms]
(thunk-timeout thunk ms :ms nil)) ; Default to milliseconds, because that's pretty common.
([thunk time unit]
(thunk-timeout thunk time unit nil))
([thunk time unit tg]
(let [task (FutureTask. thunk)
thr (if tg (Thread. tg task) (Thread. task))]
(try
(.start thr)
(.get task time (or (uglify-time-unit unit) unit))
(catch TimeoutException e
(.cancel task true)
(.stop thr)
(throw (TimeoutException. "Execution timed out.")))
(catch Exception e
(.cancel task true)
(.stop thr)
(throw e))
(finally (when tg (.stop tg)))))))
(defn eval-form [form namespace]
(with-open [out (StringWriter.)]
(binding [*out* out
*ns* namespace]
(let [result (eval form)]
{:expr form
:result [out result]}))))
(defn eval-string [expr namespace]
(let [form (binding [*read-eval* false] (read-string expr))]
(thunk-timeout #(eval-form form namespace) (* 60000 5))))
(defn get-ns!
"Return a namespace associated with the given session. If nothing is
found, initiate the namespace."
[session-id]
(or (get @users-namespaces session-id)
(make-user-ns! session-id)))
(defn eval-request
([expr] (eval-request expr "web-repl"))
([expr session-id]
(try
(eval-string expr (get-ns! session-id))
(catch TimeoutException _
{:error true :message "Execution Timed Out!"})
(catch Exception e
{:error true :message (str (root-cause e))}))))
(def eval-resource
(resource
{:produces [{:media-type co/produced-types
:charset "UTF-8"}]
:consumes [{:media-type #{}
:charset "UTF-8"}]
:access-control {:allow-origin "*"}
:swagger/tags ["REPL"]
:methods {:get {:summary "Devices list"
:parameters {:query {:expr s/Str}}
:description "Evaluate the given expression in a Clojure repl."
:response (fn [ctx]
(let [session (some-> ctx :request :session)
expr (some-> ctx :parameters :query :expr)
{:keys [expr result error message] :as res} (eval-request expr session)
data (if error
res
(let [[out res] result]
{:expr (pr-str expr)
:result (str out (pr-str res))}))]
data))}}}))
| null | https://raw.githubusercontent.com/Frozenlock/wacnet/4a4c21d423a9eeaaa70ec5c0ac4203a6978d3db9/src/clj/wacnet/api/repl.clj | clojure | from clojail
Default to milliseconds, because that's pretty common. | (ns wacnet.api.repl
(:require [clojure.stacktrace :refer [root-cause]]
[wacnet.api.bacnet.common :as co]
[wacnet.nrepl :as wnrepl]
[yada.resource :refer [resource]]
[schema.core :as s])
(:import java.io.StringWriter
[java.util.concurrent TimeoutException TimeUnit FutureTask]))
(def users-namespaces (atom {}))
(defn remove-ns-future
"Unmap a namespace after `delay' in ms."
[delay]
24 hours ( * 60000 60 24 )
(-> *ns* .getName remove-ns)))
(defmacro new-namespace
"Create a new newspace and return it." []
(let [ns-name# (symbol (gensym "user-"))]
`(binding [*ns* *ns*]
(ns ~ns-name#)
*ns*)))
(defn throwable-ns
"Creates a new ns that will expire after `delay' in ms. If init is
provided, it will be evaluated when the namespace is created."
[&{:keys [delay init]}]
(let [new-ns (new-namespace)]
(binding [*ns* new-ns]
(when init (eval init))
(remove-ns-future delay))
new-ns))
(defn make-user-ns! [session-id]
24 hours
ns (throwable-ns :delay delay-ms
:init wnrepl/repl-init)]
(swap! users-namespaces assoc session-id ns)
(future (Thread/sleep delay-ms)
(swap! users-namespaces dissoc session-id))
ns))
(def ^{:doc "Create a map of pretty keywords to ugly TimeUnits"}
uglify-time-unit
(into {} (for [[enum aliases] {TimeUnit/NANOSECONDS [:ns :nanoseconds]
TimeUnit/MICROSECONDS [:us :microseconds]
TimeUnit/MILLISECONDS [:ms :milliseconds]
TimeUnit/SECONDS [:s :sec :seconds]}
alias aliases]
{alias enum})))
(defn thunk-timeout
"Takes a function and an amount of time to wait for those function to finish
executing. The sandbox can do this for you. unit is any of :ns, :us, :ms,
or :s which correspond to TimeUnit/NANOSECONDS, MICROSECONDS, MILLISECONDS,
and SECONDS respectively."
([thunk ms]
([thunk time unit]
(thunk-timeout thunk time unit nil))
([thunk time unit tg]
(let [task (FutureTask. thunk)
thr (if tg (Thread. tg task) (Thread. task))]
(try
(.start thr)
(.get task time (or (uglify-time-unit unit) unit))
(catch TimeoutException e
(.cancel task true)
(.stop thr)
(throw (TimeoutException. "Execution timed out.")))
(catch Exception e
(.cancel task true)
(.stop thr)
(throw e))
(finally (when tg (.stop tg)))))))
(defn eval-form [form namespace]
(with-open [out (StringWriter.)]
(binding [*out* out
*ns* namespace]
(let [result (eval form)]
{:expr form
:result [out result]}))))
(defn eval-string [expr namespace]
(let [form (binding [*read-eval* false] (read-string expr))]
(thunk-timeout #(eval-form form namespace) (* 60000 5))))
(defn get-ns!
"Return a namespace associated with the given session. If nothing is
found, initiate the namespace."
[session-id]
(or (get @users-namespaces session-id)
(make-user-ns! session-id)))
(defn eval-request
([expr] (eval-request expr "web-repl"))
([expr session-id]
(try
(eval-string expr (get-ns! session-id))
(catch TimeoutException _
{:error true :message "Execution Timed Out!"})
(catch Exception e
{:error true :message (str (root-cause e))}))))
(def eval-resource
(resource
{:produces [{:media-type co/produced-types
:charset "UTF-8"}]
:consumes [{:media-type #{}
:charset "UTF-8"}]
:access-control {:allow-origin "*"}
:swagger/tags ["REPL"]
:methods {:get {:summary "Devices list"
:parameters {:query {:expr s/Str}}
:description "Evaluate the given expression in a Clojure repl."
:response (fn [ctx]
(let [session (some-> ctx :request :session)
expr (some-> ctx :parameters :query :expr)
{:keys [expr result error message] :as res} (eval-request expr session)
data (if error
res
(let [[out res] result]
{:expr (pr-str expr)
:result (str out (pr-str res))}))]
data))}}}))
|
668414fe22fe63cbf20face2c255e9727840b4cead045b45359bc3662fefa733 | ygmpkk/house | ObjectIO.hs | -----------------------------------------------------------------------------
-- |
-- Module : ObjectIO
Copyright : ( c ) 2002
-- License : BSD-style
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
ObjectIO contains all definition modules of the Object I\/O library .
--
-----------------------------------------------------------------------------
module Graphics.UI.ObjectIO
( module Graphics.UI.ObjectIO.StdId
, module Graphics.UI.ObjectIO.StdIOBasic
, module Graphics.UI.ObjectIO.StdIOCommon
, module Graphics.UI.ObjectIO.StdKey
, module Graphics.UI.ObjectIO.StdGUI
, module Graphics.UI.ObjectIO.StdPicture
, module Graphics.UI.ObjectIO.StdBitmap
, module Graphics.UI.ObjectIO.StdProcess
, module Graphics.UI.ObjectIO.StdControl
, module Graphics.UI.ObjectIO.StdControlReceiver
, module Graphics.UI.ObjectIO.StdReceiver
, module Graphics.UI.ObjectIO.StdWindow
, module Graphics.UI.ObjectIO.StdMenu
, module Graphics.UI.ObjectIO.StdMenuReceiver
, module Graphics.UI.ObjectIO.StdMenuElement
, module Graphics.UI.ObjectIO.StdTimer
, module Graphics.UI.ObjectIO.StdTimerReceiver
, module Graphics.UI.ObjectIO.StdFileSelect
, module Graphics.UI.ObjectIO.StdSound
, module Graphics.UI.ObjectIO.StdClipboard
, module Graphics.UI.ObjectIO.StdSystem
) where
import Graphics.UI.ObjectIO.StdId -- The operations that generate identification values
import Graphics.UI.ObjectIO.StdIOBasic -- Function and type definitions used in the library
import Graphics.UI.ObjectIO.StdIOCommon -- Function and type definitions used in the library
import Graphics.UI.ObjectIO.StdKey -- Function and type definitions on keyboard
import Graphics.UI.ObjectIO.StdGUI -- Type definitions used in the library
import Graphics.UI.ObjectIO.StdPicture -- Picture handling operations
import Graphics.UI.ObjectIO.StdBitmap -- Defines an instance for drawing bitmaps
import Graphics.UI.ObjectIO.StdProcess -- Process handling operations
import Graphics.UI.ObjectIO.StdControl -- Control handling operations
import Graphics.UI.ObjectIO.StdControlReceiver
import Graphics.UI.ObjectIO.StdReceiver -- Receiver handling operations
import Graphics.UI.ObjectIO.StdWindow -- Window handling operations
import Graphics.UI.ObjectIO.StdMenu
import Graphics.UI.ObjectIO.StdMenuReceiver
import Graphics.UI.ObjectIO.StdMenuElement
import Graphics.UI.ObjectIO.StdTimer
import Graphics.UI.ObjectIO.StdTimerReceiver
import Graphics.UI.ObjectIO.StdFileSelect
import Graphics.UI.ObjectIO.StdSound
import Graphics.UI.ObjectIO.StdClipboard
import Graphics.UI.ObjectIO.StdSystem
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/ObjectIO/Graphics/UI/ObjectIO.hs | haskell | ---------------------------------------------------------------------------
|
Module : ObjectIO
License : BSD-style
Maintainer :
Stability : provisional
Portability : portable
---------------------------------------------------------------------------
The operations that generate identification values
Function and type definitions used in the library
Function and type definitions used in the library
Function and type definitions on keyboard
Type definitions used in the library
Picture handling operations
Defines an instance for drawing bitmaps
Process handling operations
Control handling operations
Receiver handling operations
Window handling operations | Copyright : ( c ) 2002
ObjectIO contains all definition modules of the Object I\/O library .
module Graphics.UI.ObjectIO
( module Graphics.UI.ObjectIO.StdId
, module Graphics.UI.ObjectIO.StdIOBasic
, module Graphics.UI.ObjectIO.StdIOCommon
, module Graphics.UI.ObjectIO.StdKey
, module Graphics.UI.ObjectIO.StdGUI
, module Graphics.UI.ObjectIO.StdPicture
, module Graphics.UI.ObjectIO.StdBitmap
, module Graphics.UI.ObjectIO.StdProcess
, module Graphics.UI.ObjectIO.StdControl
, module Graphics.UI.ObjectIO.StdControlReceiver
, module Graphics.UI.ObjectIO.StdReceiver
, module Graphics.UI.ObjectIO.StdWindow
, module Graphics.UI.ObjectIO.StdMenu
, module Graphics.UI.ObjectIO.StdMenuReceiver
, module Graphics.UI.ObjectIO.StdMenuElement
, module Graphics.UI.ObjectIO.StdTimer
, module Graphics.UI.ObjectIO.StdTimerReceiver
, module Graphics.UI.ObjectIO.StdFileSelect
, module Graphics.UI.ObjectIO.StdSound
, module Graphics.UI.ObjectIO.StdClipboard
, module Graphics.UI.ObjectIO.StdSystem
) where
import Graphics.UI.ObjectIO.StdControlReceiver
import Graphics.UI.ObjectIO.StdMenu
import Graphics.UI.ObjectIO.StdMenuReceiver
import Graphics.UI.ObjectIO.StdMenuElement
import Graphics.UI.ObjectIO.StdTimer
import Graphics.UI.ObjectIO.StdTimerReceiver
import Graphics.UI.ObjectIO.StdFileSelect
import Graphics.UI.ObjectIO.StdSound
import Graphics.UI.ObjectIO.StdClipboard
import Graphics.UI.ObjectIO.StdSystem
|
e48ec15596e33528b91bc7bcf9d211a0b8f173b97b6c37d7dd8c7853a63afbd1 | rixed/ramen | RamenAtomic.ml | open Batteries
let with_mutex m f x =
Mutex.lock m ;
finally
(fun () -> Mutex.unlock m)
f x
module Base = struct
type 'a t = { mutex : Mutex.t ; x : 'a }
let make x =
{ mutex = Mutex.create () ; x }
let with_lock t f =
with_mutex t.mutex f t.x
end
module Flag = struct
type t = bool Base.t
let make (x : bool) = Base.make (ref x)
let is_set t = Base.with_lock t (!)
let is_unset = not % is_set
let set t = Base.with_lock t (fun b -> b := true)
let clear t = Base.with_lock t (fun b -> b := false)
end
module Counter = struct
type t = int Base.t
let make (x : int) = Base.make (ref x)
let get t = Base.with_lock t (!)
let set t x = Base.with_lock t (fun r -> r := x)
let incr t = Base.with_lock t incr
let decr t = Base.with_lock t decr
end
module Set = struct
type 'a t = 'a Set.t ref Base.t
let make () = Base.make (ref Set.empty)
let is_empty t = Base.with_lock t (fun s -> Set.is_empty !s)
let cardinal t = Base.with_lock t (fun s -> Set.cardinal !s)
let iter t f = Base.with_lock t (fun s -> Set.iter f !s)
let filter t f = Base.with_lock t (fun s -> s := Set.filter f !s)
let add t x = Base.with_lock t (fun s -> s := Set.add x !s)
end
| null | https://raw.githubusercontent.com/rixed/ramen/11b1b34c3bf73ee6c69d7eb5c5fbf30e6dd2df4f/src/RamenAtomic.ml | ocaml | open Batteries
let with_mutex m f x =
Mutex.lock m ;
finally
(fun () -> Mutex.unlock m)
f x
module Base = struct
type 'a t = { mutex : Mutex.t ; x : 'a }
let make x =
{ mutex = Mutex.create () ; x }
let with_lock t f =
with_mutex t.mutex f t.x
end
module Flag = struct
type t = bool Base.t
let make (x : bool) = Base.make (ref x)
let is_set t = Base.with_lock t (!)
let is_unset = not % is_set
let set t = Base.with_lock t (fun b -> b := true)
let clear t = Base.with_lock t (fun b -> b := false)
end
module Counter = struct
type t = int Base.t
let make (x : int) = Base.make (ref x)
let get t = Base.with_lock t (!)
let set t x = Base.with_lock t (fun r -> r := x)
let incr t = Base.with_lock t incr
let decr t = Base.with_lock t decr
end
module Set = struct
type 'a t = 'a Set.t ref Base.t
let make () = Base.make (ref Set.empty)
let is_empty t = Base.with_lock t (fun s -> Set.is_empty !s)
let cardinal t = Base.with_lock t (fun s -> Set.cardinal !s)
let iter t f = Base.with_lock t (fun s -> Set.iter f !s)
let filter t f = Base.with_lock t (fun s -> s := Set.filter f !s)
let add t x = Base.with_lock t (fun s -> s := Set.add x !s)
end
|
|
fef8b0bf213638eb8f9860790ce999f4de16145504b8c12ba6962697fd105aa7 | pedropramos/PyonR | strings.rkt | (module strings racket
(provide (all-defined-out))
(require "engine.rkt"
"exceptions.rkt"
(only-in srfi/13 string-contains))
(define (py-string-hash x)
(let ([bytes (string->bytes/utf-8 x)])
(remainder (for/fold ([result 0]) ([byte bytes])
(+ (* result 256) byte))
2147483647)))
(define (py-string-contains outer inner)
(if (string-contains outer inner) #t #f))
(define (py-string-str x)
(string-append "'" x "'"))
(define (py-string-new typ . args)
(if (empty? args)
""
(let ([str (mro-lookup (first args) '__str__)])
(or (and str (str (first args)))
(mro-method-call (first args) '__repr__)))))
(define (py-string-replace str old new [count -1])
(if (< count 0)
(string-replace str old new)
(let loop ([i 0]
[res str])
(if (< i count)
(loop (add1 i) (string-replace res old new #:all? #f))
res))))
(define (py-string-mod str args)
(let loop ([str str]
[args (if (vector? args)
(vector->list args)
(list args))])
(let ([%-location (string-contains str "%")])
(when (and (not %-location) (not (empty? args)))
(exn-raise py-TypeError "not all arguments converted during string formatting"))
(when (and %-location (empty? args))
(exn-raise py-TypeError "not enough arguments for format string"))
(cond
[(and (not %-location) (empty? args)) str]
[else (let* ([pattern (substring str %-location (+ %-location 2))]
[value (first args)]
[replacement (case pattern
[("%s") (py-string-new py-string value)]
[("%r") (repr value)]
[("%d" "%i" "%u") (number->string (inexact->exact (floor value)))]
[("%e" "%E" "%f" "%F" "%g" "%G") (number->string (exact->inexact value))]
[("%%") "%"]
[else (exn-raise py-TypeError "'~a' pattern not recoginized or not implemented" pattern)])])
(loop (string-replace str pattern replacement #:all? #f)
(rest args)))]))))
(define py-string
(make-type "str"
(vector py-object)
(hasheq '__add__ string-append
'__contains__ py-string-contains
'__doc__ #f
'__eq__ equal?
'__format__ #f
'__ge__ string>=?
'__getattribute__ #f
'__getitem__ (compose string string-ref)
'__getnewargs__ #f
'__getslice__ #f
'__gt__ string>?
'__hash__ equal-hash-code
'__le__ string<=?
'__len__ string-length
'__lt__ string<?
'__mod__ py-string-mod
'__mul__ #f
'__ne__ (compose not equal?)
'__new__ py-string-new
'__repr__ py-string-str
'__rmod__ #f
'__rmul__ #f
'__sizeof__ #f
'__str__ identity
'_formatter_field_name_split #f
'_formatter_parser #f
'capitalize #f
'center #f
'count #f
'decode #f
'encode #f
'endswith #f
'expandtabs #f
'find #f
'format #f
'index #f
'isalnum #f
'isalpha #f
'isdigit #f
'islower #f
'isspace #f
'istitle #f
'isupper #f
'join #f
'ljust #f
'lower string-downcase
'lstrip #f
'partition #f
'replace py-string-replace
'rfind #f
'rindex #f
'rjust #f
'rpartition #f
'rsplit #f
'rstrip #f
'split #f
'splitlines #f
'startswith #f
'strip #f
'swapcase #f
'title #f
'translate #f
'upper string-upcase
'zfill #f)))
(define-syntax-rule (make-py-string x) x)
) | null | https://raw.githubusercontent.com/pedropramos/PyonR/16edd14f3950fd5a01f8b0237e023536ef48d17b/engine/strings.rkt | racket | (module strings racket
(provide (all-defined-out))
(require "engine.rkt"
"exceptions.rkt"
(only-in srfi/13 string-contains))
(define (py-string-hash x)
(let ([bytes (string->bytes/utf-8 x)])
(remainder (for/fold ([result 0]) ([byte bytes])
(+ (* result 256) byte))
2147483647)))
(define (py-string-contains outer inner)
(if (string-contains outer inner) #t #f))
(define (py-string-str x)
(string-append "'" x "'"))
(define (py-string-new typ . args)
(if (empty? args)
""
(let ([str (mro-lookup (first args) '__str__)])
(or (and str (str (first args)))
(mro-method-call (first args) '__repr__)))))
(define (py-string-replace str old new [count -1])
(if (< count 0)
(string-replace str old new)
(let loop ([i 0]
[res str])
(if (< i count)
(loop (add1 i) (string-replace res old new #:all? #f))
res))))
(define (py-string-mod str args)
(let loop ([str str]
[args (if (vector? args)
(vector->list args)
(list args))])
(let ([%-location (string-contains str "%")])
(when (and (not %-location) (not (empty? args)))
(exn-raise py-TypeError "not all arguments converted during string formatting"))
(when (and %-location (empty? args))
(exn-raise py-TypeError "not enough arguments for format string"))
(cond
[(and (not %-location) (empty? args)) str]
[else (let* ([pattern (substring str %-location (+ %-location 2))]
[value (first args)]
[replacement (case pattern
[("%s") (py-string-new py-string value)]
[("%r") (repr value)]
[("%d" "%i" "%u") (number->string (inexact->exact (floor value)))]
[("%e" "%E" "%f" "%F" "%g" "%G") (number->string (exact->inexact value))]
[("%%") "%"]
[else (exn-raise py-TypeError "'~a' pattern not recoginized or not implemented" pattern)])])
(loop (string-replace str pattern replacement #:all? #f)
(rest args)))]))))
(define py-string
(make-type "str"
(vector py-object)
(hasheq '__add__ string-append
'__contains__ py-string-contains
'__doc__ #f
'__eq__ equal?
'__format__ #f
'__ge__ string>=?
'__getattribute__ #f
'__getitem__ (compose string string-ref)
'__getnewargs__ #f
'__getslice__ #f
'__gt__ string>?
'__hash__ equal-hash-code
'__le__ string<=?
'__len__ string-length
'__lt__ string<?
'__mod__ py-string-mod
'__mul__ #f
'__ne__ (compose not equal?)
'__new__ py-string-new
'__repr__ py-string-str
'__rmod__ #f
'__rmul__ #f
'__sizeof__ #f
'__str__ identity
'_formatter_field_name_split #f
'_formatter_parser #f
'capitalize #f
'center #f
'count #f
'decode #f
'encode #f
'endswith #f
'expandtabs #f
'find #f
'format #f
'index #f
'isalnum #f
'isalpha #f
'isdigit #f
'islower #f
'isspace #f
'istitle #f
'isupper #f
'join #f
'ljust #f
'lower string-downcase
'lstrip #f
'partition #f
'replace py-string-replace
'rfind #f
'rindex #f
'rjust #f
'rpartition #f
'rsplit #f
'rstrip #f
'split #f
'splitlines #f
'startswith #f
'strip #f
'swapcase #f
'title #f
'translate #f
'upper string-upcase
'zfill #f)))
(define-syntax-rule (make-py-string x) x)
) |
|
dbe1b204b9dbde3a7bdbb618f32a3afd2761aecc106f4ce4a5f39e2ae493582a | RefactoringTools/HaRe | Demote.hs | module MoveDef.Demote where
toplevel :: Integer -> Integer
toplevel x = c * x
-- c,d :: Integer
c = 7
d = 9
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/MoveDef/Demote.hs | haskell | c,d :: Integer | module MoveDef.Demote where
toplevel :: Integer -> Integer
toplevel x = c * x
c = 7
d = 9
|
dd98f1988a87bbf6577c198ee80c9650f52dd3c6f60f29529d134c905ac2c907 | nitrogen/NitrogenProject.com | demos_notices.erl | -module (demos_notices).
-include_lib ("nitrogen_core/include/wf.hrl").
-compile(export_all).
main() -> #template { file="./templates/demos46.html" }.
title() -> "User Notices".
headline() -> "User Notices".
left() ->
[
"
<p>
Nitrogen provides you with a variety of ways to notify a user
of information.
<p>
<h2>Flash Message</h2>
<p>
A flash message is an HTML box that slides into the page at a
point specified by the <code>#flash{}</code> element. The flash
message can be a simple text-message, or can contain other controls.
To display a flash message, call <code>wf:flash(TextOrElements)</code>.
<p>
Flash messages are stored in session until they are displayed. This
allows your application to set a flash message on one page in response
to user action and then redirect the user to another page, at which
the message is displayed.
<p>
<h2>Alert Box</h2>
<p>
The <code>#alert {}</code> action displays a simple
Javascript alert to the user.
<p>
<h2>Confirm Box</h2>
<p>
The <code>#confirm {}</code> action displays a Javascript
confirm box to the user, and posts back if the 'OK' button is
clicked.
",
linecount:render()
].
right() ->
[
#flash{},
#p{},
#button { text="Show Flash Message", postback=show_flash },
#p{},
#button { text="Show Advanced Flash Message", postback=show_advanced_flash },
#p{},
#button { text="Show Javascript Alert", postback=show_alert },
#p{},
#button { text="Show Javascript Confirm", postback=show_confirm }
].
event(show_flash) ->
wf:flash("This is a flash message.");
event(show_advanced_flash) ->
FlashID = wf:temp_id(),
wf:flash(FlashID, [
#span { text="Flash messages can contain nested controls." },
#p{},
#button { text="Click Me", postback={advanced_flash_click, FlashID} }
]);
event({advanced_flash_click, FlashID}) ->
wf:flash("You clicked the button."),
wf:wire(FlashID, #hide { effect=blind, speed=100 });
event(show_alert) ->
wf:wire(#alert { text="This is a Javascript Alert" });
event(show_confirm) ->
wf:wire(#confirm { text="This is a Javascript Confirm", postback=confirm_ok });
event(confirm_ok) ->
wf:wire(#alert { text="You pressed the OK button." });
event(_) -> ok.
| null | https://raw.githubusercontent.com/nitrogen/NitrogenProject.com/b4b3a0dbe17394608d2ee6eaa089e3ece1285075/src/demos/demos_notices.erl | erlang | -module (demos_notices).
-include_lib ("nitrogen_core/include/wf.hrl").
-compile(export_all).
main() -> #template { file="./templates/demos46.html" }.
title() -> "User Notices".
headline() -> "User Notices".
left() ->
[
"
<p>
Nitrogen provides you with a variety of ways to notify a user
of information.
<p>
<h2>Flash Message</h2>
<p>
A flash message is an HTML box that slides into the page at a
point specified by the <code>#flash{}</code> element. The flash
message can be a simple text-message, or can contain other controls.
To display a flash message, call <code>wf:flash(TextOrElements)</code>.
<p>
Flash messages are stored in session until they are displayed. This
allows your application to set a flash message on one page in response
to user action and then redirect the user to another page, at which
the message is displayed.
<p>
<h2>Alert Box</h2>
<p>
The <code>#alert {}</code> action displays a simple
Javascript alert to the user.
<p>
<h2>Confirm Box</h2>
<p>
The <code>#confirm {}</code> action displays a Javascript
confirm box to the user, and posts back if the 'OK' button is
clicked.
",
linecount:render()
].
right() ->
[
#flash{},
#p{},
#button { text="Show Flash Message", postback=show_flash },
#p{},
#button { text="Show Advanced Flash Message", postback=show_advanced_flash },
#p{},
#button { text="Show Javascript Alert", postback=show_alert },
#p{},
#button { text="Show Javascript Confirm", postback=show_confirm }
].
event(show_flash) ->
wf:flash("This is a flash message.");
event(show_advanced_flash) ->
FlashID = wf:temp_id(),
wf:flash(FlashID, [
#span { text="Flash messages can contain nested controls." },
#p{},
#button { text="Click Me", postback={advanced_flash_click, FlashID} }
]);
event({advanced_flash_click, FlashID}) ->
wf:flash("You clicked the button."),
wf:wire(FlashID, #hide { effect=blind, speed=100 });
event(show_alert) ->
wf:wire(#alert { text="This is a Javascript Alert" });
event(show_confirm) ->
wf:wire(#confirm { text="This is a Javascript Confirm", postback=confirm_ok });
event(confirm_ok) ->
wf:wire(#alert { text="You pressed the OK button." });
event(_) -> ok.
|
|
2fc42290497c664e9622054ecbe5cb69ff437ce2fe63a930d71b7728c22134ce | lambdacube3d/lambdacube-edsl | LC_GADT_DSLType.hs | module LC_GADT_DSLType where
import Data.Int
import Data.Word
import Data.Typeable
import LCType
import LC_GADT_APIType
-- IsScalar means here that the related type is not a tuple, but a GPU primitive type
class GPU a => IsScalar a where
toValue :: a -> Value
toType :: a -> InputType
instance (Typeable dim, Typeable sh, Typeable t, Typeable ar) => IsScalar (Sampler dim sh t ar) where
TODO
TODO
instance IsScalar Int32 where
toValue v = VInt v
toType _ = ITInt
instance IsScalar Word32 where
toValue v = VWord v
toType _ = ITWord
instance IsScalar Float where
toValue v = VFloat v
toType _ = ITFloat
instance IsScalar Bool where
toValue v = VBool v
toType _ = ITBool
instance IsScalar M22F where
toValue v = VM22F v
toType _ = ITM22F
instance IsScalar M23F where
toValue v = VM23F v
toType _ = ITM23F
instance IsScalar M24F where
toValue v = VM24F v
toType _ = ITM24F
instance IsScalar M32F where
toValue v = VM32F v
toType _ = ITM32F
instance IsScalar M33F where
toValue v = VM33F v
toType _ = ITM33F
instance IsScalar M34F where
toValue v = VM34F v
toType _ = ITM34F
instance IsScalar M42F where
toValue v = VM42F v
toType _ = ITM42F
instance IsScalar M43F where
toValue v = VM43F v
toType _ = ITM43F
instance IsScalar M44F where
toValue v = VM44F v
toType _ = ITM44F
instance IsScalar V2F where
toValue v = VV2F v
toType _ = ITV2F
instance IsScalar V3F where
toValue v = VV3F v
toType _ = ITV3F
instance IsScalar V4F where
toValue v = VV4F v
toType _ = ITV4F
instance IsScalar V2I where
toValue v = VV2I v
toType _ = ITV2I
instance IsScalar V3I where
toValue v = VV3I v
toType _ = ITV3I
instance IsScalar V4I where
toValue v = VV4I v
toType _ = ITV4I
instance IsScalar V2U where
toValue v = VV2U v
toType _ = ITV2U
instance IsScalar V3U where
toValue v = VV3U v
toType _ = ITV3U
instance IsScalar V4U where
toValue v = VV4U v
toType _ = ITV4U
instance IsScalar V2B where
toValue v = VV2B v
toType _ = ITV2B
instance IsScalar V3B where
toValue v = VV3B v
toType _ = ITV3B
instance IsScalar V4B where
toValue v = VV4B v
toType _ = ITV4B
GPU type value reification , needed for shader
data Value
= VBool !Bool
| VV2B !V2B
| VV3B !V3B
| VV4B !V4B
| VWord !Word32
| VV2U !V2U
| VV3U !V3U
| VV4U !V4U
| VInt !Int32
| VV2I !V2I
| VV3I !V3I
| VV4I !V4I
| VFloat !Float
| VV2F !V2F
| VV3F !V3F
| VV4F !V4F
| VM22F !M22F
| VM23F !M23F
| VM24F !M24F
| VM32F !M32F
| VM33F !M33F
| VM34F !M34F
| VM42F !M42F
| VM43F !M43F
| VM44F !M44F
deriving (Show,Eq,Ord)
singletonScalarType :: IsScalar a => a -> TupleType ((), a)
singletonScalarType a = PairTuple UnitTuple (SingleTuple a)
GPU type restriction , the functions are used in shader
class (Show a, Typeable a, Typeable (EltRepr a), Typeable (EltRepr' a)) => GPU a where
tupleType :: a -> TupleType (EltRepr a)
tupleType' :: a -> TupleType (EltRepr' a)
instance (Typeable dim, Typeable sh, Typeable t, Typeable ar) => GPU (Sampler dim sh t ar) where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU () where
tupleType _ = UnitTuple
tupleType' _ = UnitTuple
instance GPU Bool where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU Float where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU Int32 where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU Word32 where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V2B where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V2F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V2I where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V2U where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V3B where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V3F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V3I where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V3U where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V4B where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V4F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V4I where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V4U where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M22F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M23F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M24F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M32F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M33F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M34F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M42F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M43F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M44F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance (GPU a, GPU b) => GPU (a, b) where
tupleType (_::(a, b))
= PairTuple (tupleType (undefined :: a)) (tupleType' (undefined :: b))
tupleType' (_::(a, b))
= PairTuple (tupleType (undefined :: a)) (tupleType' (undefined :: b))
instance (GPU a, GPU b, GPU c) => GPU (a, b, c) where
tupleType (_::(a, b, c))
= PairTuple (tupleType (undefined :: (a, b))) (tupleType' (undefined :: c))
tupleType' (_::(a, b, c))
= PairTuple (tupleType (undefined :: (a, b))) (tupleType' (undefined :: c))
instance (GPU a, GPU b, GPU c, GPU d) => GPU (a, b, c, d) where
tupleType (_::(a, b, c, d))
= PairTuple (tupleType (undefined :: (a, b, c))) (tupleType' (undefined :: d))
tupleType' (_::(a, b, c, d))
= PairTuple (tupleType (undefined :: (a, b, c))) (tupleType' (undefined :: d))
instance (GPU a, GPU b, GPU c, GPU d, GPU e) => GPU (a, b, c, d, e) where
tupleType (_::(a, b, c, d, e))
= PairTuple (tupleType (undefined :: (a, b, c, d)))
(tupleType' (undefined :: e))
tupleType' (_::(a, b, c, d, e))
= PairTuple (tupleType (undefined :: (a, b, c, d)))
(tupleType' (undefined :: e))
instance (GPU a, GPU b, GPU c, GPU d, GPU e, GPU f) => GPU (a, b, c, d, e, f) where
tupleType (_::(a, b, c, d, e, f))
= PairTuple (tupleType (undefined :: (a, b, c, d, e)))
(tupleType' (undefined :: f))
tupleType' (_::(a, b, c, d, e, f))
= PairTuple (tupleType (undefined :: (a, b, c, d, e)))
(tupleType' (undefined :: f))
instance (GPU a, GPU b, GPU c, GPU d, GPU e, GPU f, GPU g) => GPU (a, b, c, d, e, f, g) where
tupleType (_::(a, b, c, d, e, f, g))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f)))
(tupleType' (undefined :: g))
tupleType' (_::(a, b, c, d, e, f, g))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f)))
(tupleType' (undefined :: g))
instance (GPU a, GPU b, GPU c, GPU d, GPU e, GPU f, GPU g, GPU h) => GPU (a, b, c, d, e, f, g, h) where
tupleType (_::(a, b, c, d, e, f, g, h))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f, g)))
(tupleType' (undefined :: h))
tupleType' (_::(a, b, c, d, e, f, g, h))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f, g)))
(tupleType' (undefined :: h))
instance (GPU a, GPU b, GPU c, GPU d, GPU e, GPU f, GPU g, GPU h, GPU i) => GPU (a, b, c, d, e, f, g, h, i) where
tupleType (_::(a, b, c, d, e, f, g, h, i))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f, g, h)))
(tupleType' (undefined :: i))
tupleType' (_::(a, b, c, d, e, f, g, h, i))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f, g, h)))
(tupleType' (undefined :: i))
-- stream type restriction, these types can be used in vertex shader input
class GPU a => SGPU a
instance SGPU Int32
instance SGPU Word32
instance SGPU Float
instance SGPU M22F
instance SGPU M23F
instance SGPU M24F
instance SGPU M32F
instance SGPU M33F
instance SGPU M34F
instance SGPU M42F
instance SGPU M43F
instance SGPU M44F
instance SGPU V2F
instance SGPU V3F
instance SGPU V4F
instance SGPU V2I
instance SGPU V3I
instance SGPU V4I
instance SGPU V2U
instance SGPU V3U
instance SGPU V4U
instance (SGPU a, SGPU b) => SGPU (a, b)
instance (SGPU a, SGPU b, SGPU c) => SGPU (a, b, c)
instance (SGPU a, SGPU b, SGPU c, SGPU d) => SGPU (a, b, c, d)
instance (SGPU a, SGPU b, SGPU c, SGPU d, SGPU e) => SGPU (a, b, c, d, e)
instance (SGPU a, SGPU b, SGPU c, SGPU d, SGPU e, SGPU f) => SGPU (a, b, c, d, e, f)
instance (SGPU a, SGPU b, SGPU c, SGPU d, SGPU e, SGPU f, SGPU g) => SGPU (a, b, c, d, e, f, g)
instance (SGPU a, SGPU b, SGPU c, SGPU d, SGPU e, SGPU f, SGPU g, SGPU h) => SGPU (a, b, c, d, e, f, g, h)
instance (SGPU a, SGPU b, SGPU c, SGPU d, SGPU e, SGPU f, SGPU g, SGPU h, SGPU i) => SGPU (a, b, c, d, e, f, g, h, i)
-- uniform type restriction
hint : EltRepr stands for Elementary Type Representation
type family EltRepr a :: *
type instance EltRepr (Sampler dim sh t ar) = ((), Sampler dim sh t ar)
type instance EltRepr () = ()
type instance EltRepr Int32 = ((), Int32)
type instance EltRepr Word32 = ((), Word32)
type instance EltRepr Float = ((), Float)
type instance EltRepr Bool = ((), Bool)
type instance EltRepr V2F = ((), V2F)
type instance EltRepr V2I = ((), V2I)
type instance EltRepr V2U = ((), V2U)
type instance EltRepr V2B = ((), V2B)
type instance EltRepr M22F = ((), M22F)
type instance EltRepr M23F = ((), M23F)
type instance EltRepr M24F = ((), M24F)
type instance EltRepr V3F = ((), V3F)
type instance EltRepr V3I = ((), V3I)
type instance EltRepr V3U = ((), V3U)
type instance EltRepr V3B = ((), V3B)
type instance EltRepr M32F = ((), M32F)
type instance EltRepr M33F = ((), M33F)
type instance EltRepr M34F = ((), M34F)
type instance EltRepr V4F = ((), V4F)
type instance EltRepr V4I = ((), V4I)
type instance EltRepr V4U = ((), V4U)
type instance EltRepr V4B = ((), V4B)
type instance EltRepr M42F = ((), M42F)
type instance EltRepr M43F = ((), M43F)
type instance EltRepr M44F = ((), M44F)
type instance EltRepr (a, b) = (EltRepr a, EltRepr' b)
type instance EltRepr (a, b, c) = (EltRepr (a, b), EltRepr' c)
type instance EltRepr (a, b, c, d) = (EltRepr (a, b, c), EltRepr' d)
type instance EltRepr (a, b, c, d, e) = (EltRepr (a, b, c, d), EltRepr' e)
type instance EltRepr (a, b, c, d, e, f) = (EltRepr (a, b, c, d, e), EltRepr' f)
type instance EltRepr (a, b, c, d, e, f, g) = (EltRepr (a, b, c, d, e, f), EltRepr' g)
type instance EltRepr (a, b, c, d, e, f, g, h) = (EltRepr (a, b, c, d, e, f, g), EltRepr' h)
type instance EltRepr (a, b, c, d, e, f, g, h, i) = (EltRepr (a, b, c, d, e, f, g, h), EltRepr' i)
type family EltRepr' a :: *
type instance EltRepr' (Sampler dim sh t ar) = Sampler dim sh t ar
type instance EltRepr' () = ()
type instance EltRepr' Int32 = Int32
type instance EltRepr' Word32 = Word32
type instance EltRepr' Float = Float
type instance EltRepr' Bool = Bool
type instance EltRepr' V2F = V2F
type instance EltRepr' V2I = V2I
type instance EltRepr' V2U = V2U
type instance EltRepr' V2B = V2B
type instance EltRepr' M22F = M22F
type instance EltRepr' M23F = M23F
type instance EltRepr' M24F = M24F
type instance EltRepr' V3F = V3F
type instance EltRepr' V3I = V3I
type instance EltRepr' V3U = V3U
type instance EltRepr' V3B = V3B
type instance EltRepr' M32F = M32F
type instance EltRepr' M33F = M33F
type instance EltRepr' M34F = M34F
type instance EltRepr' V4F = V4F
type instance EltRepr' V4I = V4I
type instance EltRepr' V4U = V4U
type instance EltRepr' V4B = V4B
type instance EltRepr' M42F = M42F
type instance EltRepr' M43F = M43F
type instance EltRepr' M44F = M44F
type instance EltRepr' (a, b) = (EltRepr a, EltRepr' b)
type instance EltRepr' (a, b, c) = (EltRepr (a, b), EltRepr' c)
type instance EltRepr' (a, b, c, d) = (EltRepr (a, b, c), EltRepr' d)
type instance EltRepr' (a, b, c, d, e) = (EltRepr (a, b, c, d), EltRepr' e)
type instance EltRepr' (a, b, c, d, e, f) = (EltRepr (a, b, c, d, e), EltRepr' f)
type instance EltRepr' (a, b, c, d, e, f, g) = (EltRepr (a, b, c, d, e, f), EltRepr' g)
type instance EltRepr' (a, b, c, d, e, f, g, h) = (EltRepr (a, b, c, d, e, f, g), EltRepr' h)
type instance EltRepr' (a, b, c, d, e, f, g, h, i) = (EltRepr (a, b, c, d, e, f, g, h), EltRepr' i)
-- |Conversion between surface n-tuples and our tuple representation.
--
-- our language uses nested tuple representation
class IsTuple tup where
type TupleRepr tup
fromTuple :: tup -> TupleRepr tup
toTuple :: TupleRepr tup -> tup
instance IsTuple () where
type TupleRepr () = ()
fromTuple = id
toTuple = id
instance IsTuple (a, b) where
type TupleRepr (a, b) = (((), a), b)
fromTuple (x, y) = (((), x), y)
toTuple (((), x), y) = (x, y)
instance IsTuple (a, b, c) where
type TupleRepr (a, b, c) = (TupleRepr (a, b), c)
fromTuple (x, y, z) = ((((), x), y), z)
toTuple ((((), x), y), z) = (x, y, z)
instance IsTuple (a, b, c, d) where
type TupleRepr (a, b, c, d) = (TupleRepr (a, b, c), d)
fromTuple (x, y, z, v) = (((((), x), y), z), v)
toTuple (((((), x), y), z), v) = (x, y, z, v)
instance IsTuple (a, b, c, d, e) where
type TupleRepr (a, b, c, d, e) = (TupleRepr (a, b, c, d), e)
fromTuple (x, y, z, v, w) = ((((((), x), y), z), v), w)
toTuple ((((((), x), y), z), v), w) = (x, y, z, v, w)
instance IsTuple (a, b, c, d, e, f) where
type TupleRepr (a, b, c, d, e, f) = (TupleRepr (a, b, c, d, e), f)
fromTuple (x, y, z, v, w, r) = (((((((), x), y), z), v), w), r)
toTuple (((((((), x), y), z), v), w), r) = (x, y, z, v, w, r)
instance IsTuple (a, b, c, d, e, f, g) where
type TupleRepr (a, b, c, d, e, f, g) = (TupleRepr (a, b, c, d, e, f), g)
fromTuple (x, y, z, v, w, r, s) = ((((((((), x), y), z), v), w), r), s)
toTuple ((((((((), x), y), z), v), w), r), s) = (x, y, z, v, w, r, s)
instance IsTuple (a, b, c, d, e, f, g, h) where
type TupleRepr (a, b, c, d, e, f, g, h) = (TupleRepr (a, b, c, d, e, f, g), h)
fromTuple (x, y, z, v, w, r, s, t) = (((((((((), x), y), z), v), w), r), s), t)
toTuple (((((((((), x), y), z), v), w), r), s), t) = (x, y, z, v, w, r, s, t)
instance IsTuple (a, b, c, d, e, f, g, h, i) where
type TupleRepr (a, b, c, d, e, f, g, h, i) = (TupleRepr (a, b, c, d, e, f, g, h), i)
fromTuple (x, y, z, v, w, r, s, t, u) = ((((((((((), x), y), z), v), w), r), s), t), u)
toTuple ((((((((((), x), y), z), v), w), r), s), t), u) = (x, y, z, v, w, r, s, t, u)
-- Tuple representation
-- --------------------
-- |We represent tuples as heterogenous lists, typed by a type list.
--
data Tuple c t where
NilTup :: Tuple c ()
SnocTup :: GPU t => Tuple c s -> c t -> Tuple c (s, t)
-- |Type-safe projection indicies for tuples.
--
NB : We index tuples by starting to count from the * right * !
--
data TupleIdx t e where
ZeroTupIdx :: GPU s => TupleIdx (t, s) s
SuccTupIdx :: TupleIdx t e -> TupleIdx (t, s) e
-- Auxiliary tuple index constants
--
tix0 :: GPU s => TupleIdx (t, s) s
tix0 = ZeroTupIdx
tix1 :: GPU s => TupleIdx ((t, s), s1) s
tix1 = SuccTupIdx tix0
tix2 :: GPU s => TupleIdx (((t, s), s1), s2) s
tix2 = SuccTupIdx tix1
tix3 :: GPU s => TupleIdx ((((t, s), s1), s2), s3) s
tix3 = SuccTupIdx tix2
tix4 :: GPU s => TupleIdx (((((t, s), s1), s2), s3), s4) s
tix4 = SuccTupIdx tix3
tix5 :: GPU s => TupleIdx ((((((t, s), s1), s2), s3), s4), s5) s
tix5 = SuccTupIdx tix4
tix6 :: GPU s => TupleIdx (((((((t, s), s1), s2), s3), s4), s5), s6) s
tix6 = SuccTupIdx tix5
tix7 :: GPU s => TupleIdx ((((((((t, s), s1), s2), s3), s4), s5), s6), s7) s
tix7 = SuccTupIdx tix6
tix8 :: GPU s => TupleIdx (((((((((t, s), s1), s2), s3), s4), s5), s6), s7), s8) s
tix8 = SuccTupIdx tix7
used in shader
data TupleType a where
UnitTuple :: TupleType ()
SingleTuple :: IsScalar a => a -> TupleType a
PairTuple :: TupleType a -> TupleType b -> TupleType (a, b)
Extend Typeable support for 8- and 9 - tuple
-- ------------------------------------------
myMkTyCon :: String -> TyCon
myMkTyCon = mkTyCon
class Typeable8 t where
typeOf8 :: t a b c d e f g h -> TypeRep
instance Typeable8 (,,,,,,,) where
typeOf8 _ = myMkTyCon "(,,,,,,,)" `mkTyConApp` []
typeOf7Default :: (Typeable8 t, Typeable a) => t a b c d e f g h -> TypeRep
typeOf7Default x = typeOf7 x `mkAppTy` typeOf (argType x)
where
argType :: t a b c d e f g h -> a
argType = undefined
instance (Typeable8 s, Typeable a) => Typeable7 (s a) where
typeOf7 = typeOf7Default
class Typeable9 t where
typeOf9 :: t a b c d e f g h i -> TypeRep
instance Typeable9 (,,,,,,,,) where
typeOf9 _ = myMkTyCon "(,,,,,,,,)" `mkTyConApp` []
typeOf8Default :: (Typeable9 t, Typeable a) => t a b c d e f g h i -> TypeRep
typeOf8Default x = typeOf8 x `mkAppTy` typeOf (argType x)
where
argType :: t a b c d e f g h i -> a
argType = undefined
instance (Typeable9 s, Typeable a) => Typeable8 (s a) where
typeOf8 = typeOf8Default
| null | https://raw.githubusercontent.com/lambdacube3d/lambdacube-edsl/4347bb0ed344e71c0333136cf2e162aec5941df7/lambdacube-core/tmp/sandbox/LC_GADT_DSLType.hs | haskell | IsScalar means here that the related type is not a tuple, but a GPU primitive type
stream type restriction, these types can be used in vertex shader input
uniform type restriction
|Conversion between surface n-tuples and our tuple representation.
our language uses nested tuple representation
Tuple representation
--------------------
|We represent tuples as heterogenous lists, typed by a type list.
|Type-safe projection indicies for tuples.
Auxiliary tuple index constants
------------------------------------------ | module LC_GADT_DSLType where
import Data.Int
import Data.Word
import Data.Typeable
import LCType
import LC_GADT_APIType
class GPU a => IsScalar a where
toValue :: a -> Value
toType :: a -> InputType
instance (Typeable dim, Typeable sh, Typeable t, Typeable ar) => IsScalar (Sampler dim sh t ar) where
TODO
TODO
instance IsScalar Int32 where
toValue v = VInt v
toType _ = ITInt
instance IsScalar Word32 where
toValue v = VWord v
toType _ = ITWord
instance IsScalar Float where
toValue v = VFloat v
toType _ = ITFloat
instance IsScalar Bool where
toValue v = VBool v
toType _ = ITBool
instance IsScalar M22F where
toValue v = VM22F v
toType _ = ITM22F
instance IsScalar M23F where
toValue v = VM23F v
toType _ = ITM23F
instance IsScalar M24F where
toValue v = VM24F v
toType _ = ITM24F
instance IsScalar M32F where
toValue v = VM32F v
toType _ = ITM32F
instance IsScalar M33F where
toValue v = VM33F v
toType _ = ITM33F
instance IsScalar M34F where
toValue v = VM34F v
toType _ = ITM34F
instance IsScalar M42F where
toValue v = VM42F v
toType _ = ITM42F
instance IsScalar M43F where
toValue v = VM43F v
toType _ = ITM43F
instance IsScalar M44F where
toValue v = VM44F v
toType _ = ITM44F
instance IsScalar V2F where
toValue v = VV2F v
toType _ = ITV2F
instance IsScalar V3F where
toValue v = VV3F v
toType _ = ITV3F
instance IsScalar V4F where
toValue v = VV4F v
toType _ = ITV4F
instance IsScalar V2I where
toValue v = VV2I v
toType _ = ITV2I
instance IsScalar V3I where
toValue v = VV3I v
toType _ = ITV3I
instance IsScalar V4I where
toValue v = VV4I v
toType _ = ITV4I
instance IsScalar V2U where
toValue v = VV2U v
toType _ = ITV2U
instance IsScalar V3U where
toValue v = VV3U v
toType _ = ITV3U
instance IsScalar V4U where
toValue v = VV4U v
toType _ = ITV4U
instance IsScalar V2B where
toValue v = VV2B v
toType _ = ITV2B
instance IsScalar V3B where
toValue v = VV3B v
toType _ = ITV3B
instance IsScalar V4B where
toValue v = VV4B v
toType _ = ITV4B
GPU type value reification , needed for shader
data Value
= VBool !Bool
| VV2B !V2B
| VV3B !V3B
| VV4B !V4B
| VWord !Word32
| VV2U !V2U
| VV3U !V3U
| VV4U !V4U
| VInt !Int32
| VV2I !V2I
| VV3I !V3I
| VV4I !V4I
| VFloat !Float
| VV2F !V2F
| VV3F !V3F
| VV4F !V4F
| VM22F !M22F
| VM23F !M23F
| VM24F !M24F
| VM32F !M32F
| VM33F !M33F
| VM34F !M34F
| VM42F !M42F
| VM43F !M43F
| VM44F !M44F
deriving (Show,Eq,Ord)
singletonScalarType :: IsScalar a => a -> TupleType ((), a)
singletonScalarType a = PairTuple UnitTuple (SingleTuple a)
GPU type restriction , the functions are used in shader
class (Show a, Typeable a, Typeable (EltRepr a), Typeable (EltRepr' a)) => GPU a where
tupleType :: a -> TupleType (EltRepr a)
tupleType' :: a -> TupleType (EltRepr' a)
instance (Typeable dim, Typeable sh, Typeable t, Typeable ar) => GPU (Sampler dim sh t ar) where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU () where
tupleType _ = UnitTuple
tupleType' _ = UnitTuple
instance GPU Bool where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU Float where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU Int32 where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU Word32 where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V2B where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V2F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V2I where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V2U where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V3B where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V3F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V3I where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V3U where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V4B where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V4F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V4I where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU V4U where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M22F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M23F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M24F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M32F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M33F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M34F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M42F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M43F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance GPU M44F where
tupleType v = singletonScalarType v
tupleType' v = SingleTuple v
instance (GPU a, GPU b) => GPU (a, b) where
tupleType (_::(a, b))
= PairTuple (tupleType (undefined :: a)) (tupleType' (undefined :: b))
tupleType' (_::(a, b))
= PairTuple (tupleType (undefined :: a)) (tupleType' (undefined :: b))
instance (GPU a, GPU b, GPU c) => GPU (a, b, c) where
tupleType (_::(a, b, c))
= PairTuple (tupleType (undefined :: (a, b))) (tupleType' (undefined :: c))
tupleType' (_::(a, b, c))
= PairTuple (tupleType (undefined :: (a, b))) (tupleType' (undefined :: c))
instance (GPU a, GPU b, GPU c, GPU d) => GPU (a, b, c, d) where
tupleType (_::(a, b, c, d))
= PairTuple (tupleType (undefined :: (a, b, c))) (tupleType' (undefined :: d))
tupleType' (_::(a, b, c, d))
= PairTuple (tupleType (undefined :: (a, b, c))) (tupleType' (undefined :: d))
instance (GPU a, GPU b, GPU c, GPU d, GPU e) => GPU (a, b, c, d, e) where
tupleType (_::(a, b, c, d, e))
= PairTuple (tupleType (undefined :: (a, b, c, d)))
(tupleType' (undefined :: e))
tupleType' (_::(a, b, c, d, e))
= PairTuple (tupleType (undefined :: (a, b, c, d)))
(tupleType' (undefined :: e))
instance (GPU a, GPU b, GPU c, GPU d, GPU e, GPU f) => GPU (a, b, c, d, e, f) where
tupleType (_::(a, b, c, d, e, f))
= PairTuple (tupleType (undefined :: (a, b, c, d, e)))
(tupleType' (undefined :: f))
tupleType' (_::(a, b, c, d, e, f))
= PairTuple (tupleType (undefined :: (a, b, c, d, e)))
(tupleType' (undefined :: f))
instance (GPU a, GPU b, GPU c, GPU d, GPU e, GPU f, GPU g) => GPU (a, b, c, d, e, f, g) where
tupleType (_::(a, b, c, d, e, f, g))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f)))
(tupleType' (undefined :: g))
tupleType' (_::(a, b, c, d, e, f, g))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f)))
(tupleType' (undefined :: g))
instance (GPU a, GPU b, GPU c, GPU d, GPU e, GPU f, GPU g, GPU h) => GPU (a, b, c, d, e, f, g, h) where
tupleType (_::(a, b, c, d, e, f, g, h))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f, g)))
(tupleType' (undefined :: h))
tupleType' (_::(a, b, c, d, e, f, g, h))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f, g)))
(tupleType' (undefined :: h))
instance (GPU a, GPU b, GPU c, GPU d, GPU e, GPU f, GPU g, GPU h, GPU i) => GPU (a, b, c, d, e, f, g, h, i) where
tupleType (_::(a, b, c, d, e, f, g, h, i))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f, g, h)))
(tupleType' (undefined :: i))
tupleType' (_::(a, b, c, d, e, f, g, h, i))
= PairTuple (tupleType (undefined :: (a, b, c, d, e, f, g, h)))
(tupleType' (undefined :: i))
class GPU a => SGPU a
instance SGPU Int32
instance SGPU Word32
instance SGPU Float
instance SGPU M22F
instance SGPU M23F
instance SGPU M24F
instance SGPU M32F
instance SGPU M33F
instance SGPU M34F
instance SGPU M42F
instance SGPU M43F
instance SGPU M44F
instance SGPU V2F
instance SGPU V3F
instance SGPU V4F
instance SGPU V2I
instance SGPU V3I
instance SGPU V4I
instance SGPU V2U
instance SGPU V3U
instance SGPU V4U
instance (SGPU a, SGPU b) => SGPU (a, b)
instance (SGPU a, SGPU b, SGPU c) => SGPU (a, b, c)
instance (SGPU a, SGPU b, SGPU c, SGPU d) => SGPU (a, b, c, d)
instance (SGPU a, SGPU b, SGPU c, SGPU d, SGPU e) => SGPU (a, b, c, d, e)
instance (SGPU a, SGPU b, SGPU c, SGPU d, SGPU e, SGPU f) => SGPU (a, b, c, d, e, f)
instance (SGPU a, SGPU b, SGPU c, SGPU d, SGPU e, SGPU f, SGPU g) => SGPU (a, b, c, d, e, f, g)
instance (SGPU a, SGPU b, SGPU c, SGPU d, SGPU e, SGPU f, SGPU g, SGPU h) => SGPU (a, b, c, d, e, f, g, h)
instance (SGPU a, SGPU b, SGPU c, SGPU d, SGPU e, SGPU f, SGPU g, SGPU h, SGPU i) => SGPU (a, b, c, d, e, f, g, h, i)
hint : EltRepr stands for Elementary Type Representation
type family EltRepr a :: *
type instance EltRepr (Sampler dim sh t ar) = ((), Sampler dim sh t ar)
type instance EltRepr () = ()
type instance EltRepr Int32 = ((), Int32)
type instance EltRepr Word32 = ((), Word32)
type instance EltRepr Float = ((), Float)
type instance EltRepr Bool = ((), Bool)
type instance EltRepr V2F = ((), V2F)
type instance EltRepr V2I = ((), V2I)
type instance EltRepr V2U = ((), V2U)
type instance EltRepr V2B = ((), V2B)
type instance EltRepr M22F = ((), M22F)
type instance EltRepr M23F = ((), M23F)
type instance EltRepr M24F = ((), M24F)
type instance EltRepr V3F = ((), V3F)
type instance EltRepr V3I = ((), V3I)
type instance EltRepr V3U = ((), V3U)
type instance EltRepr V3B = ((), V3B)
type instance EltRepr M32F = ((), M32F)
type instance EltRepr M33F = ((), M33F)
type instance EltRepr M34F = ((), M34F)
type instance EltRepr V4F = ((), V4F)
type instance EltRepr V4I = ((), V4I)
type instance EltRepr V4U = ((), V4U)
type instance EltRepr V4B = ((), V4B)
type instance EltRepr M42F = ((), M42F)
type instance EltRepr M43F = ((), M43F)
type instance EltRepr M44F = ((), M44F)
type instance EltRepr (a, b) = (EltRepr a, EltRepr' b)
type instance EltRepr (a, b, c) = (EltRepr (a, b), EltRepr' c)
type instance EltRepr (a, b, c, d) = (EltRepr (a, b, c), EltRepr' d)
type instance EltRepr (a, b, c, d, e) = (EltRepr (a, b, c, d), EltRepr' e)
type instance EltRepr (a, b, c, d, e, f) = (EltRepr (a, b, c, d, e), EltRepr' f)
type instance EltRepr (a, b, c, d, e, f, g) = (EltRepr (a, b, c, d, e, f), EltRepr' g)
type instance EltRepr (a, b, c, d, e, f, g, h) = (EltRepr (a, b, c, d, e, f, g), EltRepr' h)
type instance EltRepr (a, b, c, d, e, f, g, h, i) = (EltRepr (a, b, c, d, e, f, g, h), EltRepr' i)
type family EltRepr' a :: *
type instance EltRepr' (Sampler dim sh t ar) = Sampler dim sh t ar
type instance EltRepr' () = ()
type instance EltRepr' Int32 = Int32
type instance EltRepr' Word32 = Word32
type instance EltRepr' Float = Float
type instance EltRepr' Bool = Bool
type instance EltRepr' V2F = V2F
type instance EltRepr' V2I = V2I
type instance EltRepr' V2U = V2U
type instance EltRepr' V2B = V2B
type instance EltRepr' M22F = M22F
type instance EltRepr' M23F = M23F
type instance EltRepr' M24F = M24F
type instance EltRepr' V3F = V3F
type instance EltRepr' V3I = V3I
type instance EltRepr' V3U = V3U
type instance EltRepr' V3B = V3B
type instance EltRepr' M32F = M32F
type instance EltRepr' M33F = M33F
type instance EltRepr' M34F = M34F
type instance EltRepr' V4F = V4F
type instance EltRepr' V4I = V4I
type instance EltRepr' V4U = V4U
type instance EltRepr' V4B = V4B
type instance EltRepr' M42F = M42F
type instance EltRepr' M43F = M43F
type instance EltRepr' M44F = M44F
type instance EltRepr' (a, b) = (EltRepr a, EltRepr' b)
type instance EltRepr' (a, b, c) = (EltRepr (a, b), EltRepr' c)
type instance EltRepr' (a, b, c, d) = (EltRepr (a, b, c), EltRepr' d)
type instance EltRepr' (a, b, c, d, e) = (EltRepr (a, b, c, d), EltRepr' e)
type instance EltRepr' (a, b, c, d, e, f) = (EltRepr (a, b, c, d, e), EltRepr' f)
type instance EltRepr' (a, b, c, d, e, f, g) = (EltRepr (a, b, c, d, e, f), EltRepr' g)
type instance EltRepr' (a, b, c, d, e, f, g, h) = (EltRepr (a, b, c, d, e, f, g), EltRepr' h)
type instance EltRepr' (a, b, c, d, e, f, g, h, i) = (EltRepr (a, b, c, d, e, f, g, h), EltRepr' i)
class IsTuple tup where
type TupleRepr tup
fromTuple :: tup -> TupleRepr tup
toTuple :: TupleRepr tup -> tup
instance IsTuple () where
type TupleRepr () = ()
fromTuple = id
toTuple = id
instance IsTuple (a, b) where
type TupleRepr (a, b) = (((), a), b)
fromTuple (x, y) = (((), x), y)
toTuple (((), x), y) = (x, y)
instance IsTuple (a, b, c) where
type TupleRepr (a, b, c) = (TupleRepr (a, b), c)
fromTuple (x, y, z) = ((((), x), y), z)
toTuple ((((), x), y), z) = (x, y, z)
instance IsTuple (a, b, c, d) where
type TupleRepr (a, b, c, d) = (TupleRepr (a, b, c), d)
fromTuple (x, y, z, v) = (((((), x), y), z), v)
toTuple (((((), x), y), z), v) = (x, y, z, v)
instance IsTuple (a, b, c, d, e) where
type TupleRepr (a, b, c, d, e) = (TupleRepr (a, b, c, d), e)
fromTuple (x, y, z, v, w) = ((((((), x), y), z), v), w)
toTuple ((((((), x), y), z), v), w) = (x, y, z, v, w)
instance IsTuple (a, b, c, d, e, f) where
type TupleRepr (a, b, c, d, e, f) = (TupleRepr (a, b, c, d, e), f)
fromTuple (x, y, z, v, w, r) = (((((((), x), y), z), v), w), r)
toTuple (((((((), x), y), z), v), w), r) = (x, y, z, v, w, r)
instance IsTuple (a, b, c, d, e, f, g) where
type TupleRepr (a, b, c, d, e, f, g) = (TupleRepr (a, b, c, d, e, f), g)
fromTuple (x, y, z, v, w, r, s) = ((((((((), x), y), z), v), w), r), s)
toTuple ((((((((), x), y), z), v), w), r), s) = (x, y, z, v, w, r, s)
instance IsTuple (a, b, c, d, e, f, g, h) where
type TupleRepr (a, b, c, d, e, f, g, h) = (TupleRepr (a, b, c, d, e, f, g), h)
fromTuple (x, y, z, v, w, r, s, t) = (((((((((), x), y), z), v), w), r), s), t)
toTuple (((((((((), x), y), z), v), w), r), s), t) = (x, y, z, v, w, r, s, t)
instance IsTuple (a, b, c, d, e, f, g, h, i) where
type TupleRepr (a, b, c, d, e, f, g, h, i) = (TupleRepr (a, b, c, d, e, f, g, h), i)
fromTuple (x, y, z, v, w, r, s, t, u) = ((((((((((), x), y), z), v), w), r), s), t), u)
toTuple ((((((((((), x), y), z), v), w), r), s), t), u) = (x, y, z, v, w, r, s, t, u)
data Tuple c t where
NilTup :: Tuple c ()
SnocTup :: GPU t => Tuple c s -> c t -> Tuple c (s, t)
NB : We index tuples by starting to count from the * right * !
data TupleIdx t e where
ZeroTupIdx :: GPU s => TupleIdx (t, s) s
SuccTupIdx :: TupleIdx t e -> TupleIdx (t, s) e
tix0 :: GPU s => TupleIdx (t, s) s
tix0 = ZeroTupIdx
tix1 :: GPU s => TupleIdx ((t, s), s1) s
tix1 = SuccTupIdx tix0
tix2 :: GPU s => TupleIdx (((t, s), s1), s2) s
tix2 = SuccTupIdx tix1
tix3 :: GPU s => TupleIdx ((((t, s), s1), s2), s3) s
tix3 = SuccTupIdx tix2
tix4 :: GPU s => TupleIdx (((((t, s), s1), s2), s3), s4) s
tix4 = SuccTupIdx tix3
tix5 :: GPU s => TupleIdx ((((((t, s), s1), s2), s3), s4), s5) s
tix5 = SuccTupIdx tix4
tix6 :: GPU s => TupleIdx (((((((t, s), s1), s2), s3), s4), s5), s6) s
tix6 = SuccTupIdx tix5
tix7 :: GPU s => TupleIdx ((((((((t, s), s1), s2), s3), s4), s5), s6), s7) s
tix7 = SuccTupIdx tix6
tix8 :: GPU s => TupleIdx (((((((((t, s), s1), s2), s3), s4), s5), s6), s7), s8) s
tix8 = SuccTupIdx tix7
used in shader
data TupleType a where
UnitTuple :: TupleType ()
SingleTuple :: IsScalar a => a -> TupleType a
PairTuple :: TupleType a -> TupleType b -> TupleType (a, b)
Extend Typeable support for 8- and 9 - tuple
myMkTyCon :: String -> TyCon
myMkTyCon = mkTyCon
class Typeable8 t where
typeOf8 :: t a b c d e f g h -> TypeRep
instance Typeable8 (,,,,,,,) where
typeOf8 _ = myMkTyCon "(,,,,,,,)" `mkTyConApp` []
typeOf7Default :: (Typeable8 t, Typeable a) => t a b c d e f g h -> TypeRep
typeOf7Default x = typeOf7 x `mkAppTy` typeOf (argType x)
where
argType :: t a b c d e f g h -> a
argType = undefined
instance (Typeable8 s, Typeable a) => Typeable7 (s a) where
typeOf7 = typeOf7Default
class Typeable9 t where
typeOf9 :: t a b c d e f g h i -> TypeRep
instance Typeable9 (,,,,,,,,) where
typeOf9 _ = myMkTyCon "(,,,,,,,,)" `mkTyConApp` []
typeOf8Default :: (Typeable9 t, Typeable a) => t a b c d e f g h i -> TypeRep
typeOf8Default x = typeOf8 x `mkAppTy` typeOf (argType x)
where
argType :: t a b c d e f g h i -> a
argType = undefined
instance (Typeable9 s, Typeable a) => Typeable8 (s a) where
typeOf8 = typeOf8Default
|
c8d3af22615797d1990e62fbe674ffec7ae839d2e551298e1b8c0bea21cd90da | Kakadu/fp2022 | save.ml | * Copyright 2022 - 2023 , and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
open Rep
open Printf
open Type
exception Type of string
" /Users / akabynda / fp2022 / SQLyd "
let conc_comma = String.concat ","
let conc_line = String.concat "\n"
let rec type_to_string = function
| [] -> []
| h :: t ->
let type_helper = function
| (Int : Type.data_type) -> "Int"
| (Float : Type.data_type) -> "Float"
| (String : Type.data_type) -> "String"
in
type_helper h :: type_to_string t
;;
let rec string_to_type = function
| [] -> []
| h :: t ->
let string_helper = function
| "Int" -> (Int : Type.data_type)
| "Float" -> (Float : Type.data_type)
| "String" -> (String : Type.data_type)
| _ -> raise (Type "Type Error: Type does not exist")
in
string_helper h :: string_to_type t
;;
let rec get_main_table db table_name = function
| h :: t ->
(get_column_data db table_name h |> conc_comma) :: get_main_table db table_name t
| [] -> []
;;
let get_file db table_name =
let field_names_pair = get_field_name_list db table_name |> List.split in
let field_name_lst = field_names_pair |> fst in
let field_name_string = field_name_lst |> conc_comma in
let field_name_type = field_names_pair |> snd |> type_to_string |> conc_comma in
let main_table = get_main_table db table_name field_name_lst in
let table_title = [ field_name_string; field_name_type ] in
[ table_title |> conc_line; main_table |> conc_line ]
;;
let save_file db table_name =
let ecsv_title = Csv.input_all (Csv.of_string (List.nth (get_file db table_name) 0)) in
let ecsv_main' = Csv.input_all (Csv.of_string (List.nth (get_file db table_name) 1)) in
let ecsv_main = Csv.transpose ecsv_main' in
let fname_title =
let file = String.concat "" [ "csv_files/"; table_name; "_title.csv" ] in
Filename.concat path_to_csv_dir file
in
Csv.save fname_title ecsv_title;
let fname_main =
let file = String.concat "" [ "csv_files/"; table_name; "_main.csv" ] in
Filename.concat path_to_csv_dir file
in
Csv.save fname_main ecsv_main;
printf "Saved CSV to file %S and %S.\n" fname_title fname_main
;;
let csvs table_name =
let tfile = String.concat "" [ "csv_files/"; table_name; "_title.csv" ] in
let mfile = String.concat "" [ "csv_files/"; table_name; "_main.csv" ] in
List.map
(fun name -> Csv.load name)
[ Filename.concat path_to_csv_dir tfile; Filename.concat path_to_csv_dir mfile ]
;;
let file_to_db db table_name =
let csv = csvs table_name in
let csv_title = List.nth csv 0 |> Csv.to_array in
let csv_main = List.nth csv 1 |> Csv.to_array in
let csv_title1 = csv_title.(0) |> Array.to_list in
let csv_title2 = csv_title.(1) |> Array.to_list |> string_to_type in
let combine_func_1 str typ = str, typ in
let combine_title = List.map2 combine_func_1 csv_title1 csv_title2 in
let db' = create_table db table_name combine_title in
let array_to_db db (str_arr : string array) : database =
let str_lst = str_arr |> Array.to_list in
let combine_func_2 str1 str2 = str1, str2 in
let combine_row = List.map2 combine_func_2 csv_title1 str_lst in
let db' = insert_row db table_name combine_row in
db'
in
let db_final = Array.fold_left array_to_db db' csv_main in
db_final
;;
let rec print_2d_array lst =
let rec print_array = function
| [] -> ""
| h :: t -> String.concat " " [ h; print_array t ]
in
match lst with
| [] -> ""
| h :: t -> String.concat "\n" [ print_array (Array.to_list h); print_2d_array t ]
;;
| null | https://raw.githubusercontent.com/Kakadu/fp2022/0eb49bf60d173287607678159465c425cdf699be/SQLyd/lib/save.ml | ocaml | * Copyright 2022 - 2023 , and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
open Rep
open Printf
open Type
exception Type of string
" /Users / akabynda / fp2022 / SQLyd "
let conc_comma = String.concat ","
let conc_line = String.concat "\n"
let rec type_to_string = function
| [] -> []
| h :: t ->
let type_helper = function
| (Int : Type.data_type) -> "Int"
| (Float : Type.data_type) -> "Float"
| (String : Type.data_type) -> "String"
in
type_helper h :: type_to_string t
;;
let rec string_to_type = function
| [] -> []
| h :: t ->
let string_helper = function
| "Int" -> (Int : Type.data_type)
| "Float" -> (Float : Type.data_type)
| "String" -> (String : Type.data_type)
| _ -> raise (Type "Type Error: Type does not exist")
in
string_helper h :: string_to_type t
;;
let rec get_main_table db table_name = function
| h :: t ->
(get_column_data db table_name h |> conc_comma) :: get_main_table db table_name t
| [] -> []
;;
let get_file db table_name =
let field_names_pair = get_field_name_list db table_name |> List.split in
let field_name_lst = field_names_pair |> fst in
let field_name_string = field_name_lst |> conc_comma in
let field_name_type = field_names_pair |> snd |> type_to_string |> conc_comma in
let main_table = get_main_table db table_name field_name_lst in
let table_title = [ field_name_string; field_name_type ] in
[ table_title |> conc_line; main_table |> conc_line ]
;;
let save_file db table_name =
let ecsv_title = Csv.input_all (Csv.of_string (List.nth (get_file db table_name) 0)) in
let ecsv_main' = Csv.input_all (Csv.of_string (List.nth (get_file db table_name) 1)) in
let ecsv_main = Csv.transpose ecsv_main' in
let fname_title =
let file = String.concat "" [ "csv_files/"; table_name; "_title.csv" ] in
Filename.concat path_to_csv_dir file
in
Csv.save fname_title ecsv_title;
let fname_main =
let file = String.concat "" [ "csv_files/"; table_name; "_main.csv" ] in
Filename.concat path_to_csv_dir file
in
Csv.save fname_main ecsv_main;
printf "Saved CSV to file %S and %S.\n" fname_title fname_main
;;
let csvs table_name =
let tfile = String.concat "" [ "csv_files/"; table_name; "_title.csv" ] in
let mfile = String.concat "" [ "csv_files/"; table_name; "_main.csv" ] in
List.map
(fun name -> Csv.load name)
[ Filename.concat path_to_csv_dir tfile; Filename.concat path_to_csv_dir mfile ]
;;
let file_to_db db table_name =
let csv = csvs table_name in
let csv_title = List.nth csv 0 |> Csv.to_array in
let csv_main = List.nth csv 1 |> Csv.to_array in
let csv_title1 = csv_title.(0) |> Array.to_list in
let csv_title2 = csv_title.(1) |> Array.to_list |> string_to_type in
let combine_func_1 str typ = str, typ in
let combine_title = List.map2 combine_func_1 csv_title1 csv_title2 in
let db' = create_table db table_name combine_title in
let array_to_db db (str_arr : string array) : database =
let str_lst = str_arr |> Array.to_list in
let combine_func_2 str1 str2 = str1, str2 in
let combine_row = List.map2 combine_func_2 csv_title1 str_lst in
let db' = insert_row db table_name combine_row in
db'
in
let db_final = Array.fold_left array_to_db db' csv_main in
db_final
;;
let rec print_2d_array lst =
let rec print_array = function
| [] -> ""
| h :: t -> String.concat " " [ h; print_array t ]
in
match lst with
| [] -> ""
| h :: t -> String.concat "\n" [ print_array (Array.to_list h); print_2d_array t ]
;;
|
|
36c0fbab1d2732b3e272643b119fdcc9dc18325339525d84880c0697fb7be62d | acieroid/scala-am | pcounter14.scm | (letrec ((counter (atom 0))
(thread (lambda (n)
(letrec ((old (deref counter))
(new (+ old 1)))
(if (compare-and-set! counter old new)
#t
(thread n)))))
(t1 (future (thread 1)))
(t2 (future (thread 2)))
(t3 (future (thread 3)))
(t4 (future (thread 4)))
(t5 (future (thread 5)))
(t6 (future (thread 6)))
(t7 (future (thread 7)))
(t8 (future (thread 8)))
(t9 (future (thread 9)))
(t10 (future (thread 10)))
(t11 (future (thread 11)))
(t12 (future (thread 12)))
(t13 (future (thread 13)))
(t14 (future (thread 14))))
(deref t1)
(deref t2)
(deref t3)
(deref t4)
(deref t5)
(deref t6)
(deref t7)
(deref t8)
(deref t9)
(deref t10)
(deref t11)
(deref t12)
(deref t13)
(deref t14)
(= counter 14)) | null | https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/concurrentScheme/futures/variations/pcounter14.scm | scheme | (letrec ((counter (atom 0))
(thread (lambda (n)
(letrec ((old (deref counter))
(new (+ old 1)))
(if (compare-and-set! counter old new)
#t
(thread n)))))
(t1 (future (thread 1)))
(t2 (future (thread 2)))
(t3 (future (thread 3)))
(t4 (future (thread 4)))
(t5 (future (thread 5)))
(t6 (future (thread 6)))
(t7 (future (thread 7)))
(t8 (future (thread 8)))
(t9 (future (thread 9)))
(t10 (future (thread 10)))
(t11 (future (thread 11)))
(t12 (future (thread 12)))
(t13 (future (thread 13)))
(t14 (future (thread 14))))
(deref t1)
(deref t2)
(deref t3)
(deref t4)
(deref t5)
(deref t6)
(deref t7)
(deref t8)
(deref t9)
(deref t10)
(deref t11)
(deref t12)
(deref t13)
(deref t14)
(= counter 14)) |
|
d9c66e759abf50fbe2e0ec3011f2f8db020dea809037b7b7d86bf9cad1cbed7b | cedlemo/OCaml-GLib2 | DLList.ml |
* Copyright 2018 ,
* This file is part of .
*
* OCaml - GLib2 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
* any later version .
*
* OCaml - GLib2 is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with . If not , see < / > .
* Copyright 2018 Cedric LE MOIGNE,
* This file is part of OCaml-GLib2.
*
* OCaml-GLib2 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
* any later version.
*
* OCaml-GLib2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OCaml-GLib2. If not, see </>.
*)
open Ctypes
open Foreign
(** GLib Doubly Linked List
-Doubly-Linked-Lists.html
*)
module type DataTypes = sig
type t
val t_typ : t Ctypes.typ
val free_func : (t ptr -> unit) option
end
module Make(Data : DataTypes) = struct
type glist
let glist : glist structure typ = structure "GList"
type data = Data.t
let data = Data.t_typ
let free_func = Data.free_func
module Comp_func =
GCallback.CompareFunc.Make(struct
type t = data
let t_typ = data
end)
module GDestroy_notify =
GCallback.GDestroyNotify.Make(struct
type t = data
let t_typ = data
end)
module GFunc =
GCallback.GFunc.Make(struct
type t = data
let t_typ = data
end)
let glist_data = field glist "data" (ptr data)
let glist_next = field glist "next" (ptr_opt glist)
let glist_prev = field glist "prev" (ptr_opt glist)
let () = seal glist
let free =
foreign "g_list_free" (ptr_opt glist @-> returning void)
let free_full =
foreign "g_list_free_full" (ptr_opt glist @-> GDestroy_notify.funptr @-> returning void)
let finalise dllist =
match free_func with
| None -> Gc.finalise free dllist
| Some fn ->
let free_full' sl = free_full sl fn in
Gc.finalise free_full' dllist
let append dllist element =
let append_raw =
foreign "g_list_append" (ptr_opt glist @-> ptr data @-> returning (ptr_opt glist))
in
match dllist with
| Some _ -> append_raw dllist element
| None -> let dllist' = append_raw dllist element in
let () = finalise dllist' in
dllist'
let prepend dllist element =
let is_start = match dllist with
| None -> true
| Some node -> match getf (!@node) glist_prev with
| None -> true
| Some _ -> false
in
if is_start then begin
let prepend_raw =
foreign "g_list_prepend" (ptr_opt glist @-> ptr data @-> returning (ptr_opt glist))
in
match dllist with
| Some _ -> prepend_raw dllist element
| None -> let dllist' = prepend_raw dllist element in
let () = finalise dllist' in
dllist'
end
else
raise (Invalid_argument "The element is not the start of the list")
let remove =
foreign "g_list_remove" (ptr_opt glist @-> ptr data @-> returning (ptr_opt glist))
let first =
foreign "g_list_first" (ptr_opt glist @-> returning (ptr_opt glist))
let last =
foreign "g_list_last" (ptr_opt glist @-> returning (ptr_opt glist))
let length =
foreign "g_list_length" (ptr_opt glist @-> returning uint)
let reverse =
foreign "g_list_reverse" (ptr_opt glist @-> returning (ptr_opt glist))
let get_previous = function
| None -> None
| Some dllist_ptr ->
getf (!@dllist_ptr) glist_prev
let get_next = function
| None -> None
| Some dllist_ptr ->
getf (!@dllist_ptr) glist_next
let get_data = function
| None -> None
| Some dllist_ptr ->
let data_ptr = getf (!@dllist_ptr) glist_data in
Some data_ptr
let sort =
foreign "g_list_sort" (ptr_opt glist @-> Comp_func.funptr @-> returning (ptr_opt glist))
let nth =
foreign "g_list_nth" (ptr_opt glist @-> int @-> returning (ptr_opt glist))
let concat =
foreign "g_list_concat" (ptr_opt glist @-> ptr_opt glist @-> returning (ptr_opt glist))
let foreach dllist f =
let foreign_raw =
foreign "g_list_foreach" (ptr_opt glist @-> GFunc.funptr @-> returning void)
in
the following function wrapper is used to ignore the ' gpointer user_data '
* of the C callback .
* In C , ' gpointer user_data ' are used to pass variables defined in other
* environment to the callback body .
* In OCaml a function can be a closure .
* Closures are functions which carry around some of the " environment " in
* which they were defined . In particular , a closure can reference variables
* which were available at the point of its definition .
* I just have to pass a function that can carry variables from other environment
* than the callback itself .
*
* absolutly want the same signature than in C , using f_raw allows
* user to define the callback to foreach with a signature like
* ptr data @- > returning void instead of
* ptr data @- > ptr_opt void @- > returning void .
* of the C callback.
* In C, 'gpointer user_data' are used to pass variables defined in other
* environment to the callback body.
* In OCaml a function can be a closure.
* Closures are functions which carry around some of the "environment" in
* which they were defined. In particular, a closure can reference variables
* which were available at the point of its definition.
* I just have to pass a function that can carry variables from other environment
* than the callback itself.
*
* Ctypes absolutly want the same signature than in C, using f_raw allows
* user to define the callback to foreach with a signature like
* ptr data @-> returning void instead of
* ptr data @-> ptr_opt void @-> returning void.
*)
let f_raw a b = f a in
foreign_raw dllist f_raw
end
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GLib2/084a148faa4f18d0ddf78315d57c1d623aa9522c/lib/DLList.ml | ocaml | * GLib Doubly Linked List
-Doubly-Linked-Lists.html
|
* Copyright 2018 ,
* This file is part of .
*
* OCaml - GLib2 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
* any later version .
*
* OCaml - GLib2 is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with . If not , see < / > .
* Copyright 2018 Cedric LE MOIGNE,
* This file is part of OCaml-GLib2.
*
* OCaml-GLib2 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
* any later version.
*
* OCaml-GLib2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OCaml-GLib2. If not, see </>.
*)
open Ctypes
open Foreign
module type DataTypes = sig
type t
val t_typ : t Ctypes.typ
val free_func : (t ptr -> unit) option
end
module Make(Data : DataTypes) = struct
type glist
let glist : glist structure typ = structure "GList"
type data = Data.t
let data = Data.t_typ
let free_func = Data.free_func
module Comp_func =
GCallback.CompareFunc.Make(struct
type t = data
let t_typ = data
end)
module GDestroy_notify =
GCallback.GDestroyNotify.Make(struct
type t = data
let t_typ = data
end)
module GFunc =
GCallback.GFunc.Make(struct
type t = data
let t_typ = data
end)
let glist_data = field glist "data" (ptr data)
let glist_next = field glist "next" (ptr_opt glist)
let glist_prev = field glist "prev" (ptr_opt glist)
let () = seal glist
let free =
foreign "g_list_free" (ptr_opt glist @-> returning void)
let free_full =
foreign "g_list_free_full" (ptr_opt glist @-> GDestroy_notify.funptr @-> returning void)
let finalise dllist =
match free_func with
| None -> Gc.finalise free dllist
| Some fn ->
let free_full' sl = free_full sl fn in
Gc.finalise free_full' dllist
let append dllist element =
let append_raw =
foreign "g_list_append" (ptr_opt glist @-> ptr data @-> returning (ptr_opt glist))
in
match dllist with
| Some _ -> append_raw dllist element
| None -> let dllist' = append_raw dllist element in
let () = finalise dllist' in
dllist'
let prepend dllist element =
let is_start = match dllist with
| None -> true
| Some node -> match getf (!@node) glist_prev with
| None -> true
| Some _ -> false
in
if is_start then begin
let prepend_raw =
foreign "g_list_prepend" (ptr_opt glist @-> ptr data @-> returning (ptr_opt glist))
in
match dllist with
| Some _ -> prepend_raw dllist element
| None -> let dllist' = prepend_raw dllist element in
let () = finalise dllist' in
dllist'
end
else
raise (Invalid_argument "The element is not the start of the list")
let remove =
foreign "g_list_remove" (ptr_opt glist @-> ptr data @-> returning (ptr_opt glist))
let first =
foreign "g_list_first" (ptr_opt glist @-> returning (ptr_opt glist))
let last =
foreign "g_list_last" (ptr_opt glist @-> returning (ptr_opt glist))
let length =
foreign "g_list_length" (ptr_opt glist @-> returning uint)
let reverse =
foreign "g_list_reverse" (ptr_opt glist @-> returning (ptr_opt glist))
let get_previous = function
| None -> None
| Some dllist_ptr ->
getf (!@dllist_ptr) glist_prev
let get_next = function
| None -> None
| Some dllist_ptr ->
getf (!@dllist_ptr) glist_next
let get_data = function
| None -> None
| Some dllist_ptr ->
let data_ptr = getf (!@dllist_ptr) glist_data in
Some data_ptr
let sort =
foreign "g_list_sort" (ptr_opt glist @-> Comp_func.funptr @-> returning (ptr_opt glist))
let nth =
foreign "g_list_nth" (ptr_opt glist @-> int @-> returning (ptr_opt glist))
let concat =
foreign "g_list_concat" (ptr_opt glist @-> ptr_opt glist @-> returning (ptr_opt glist))
let foreach dllist f =
let foreign_raw =
foreign "g_list_foreach" (ptr_opt glist @-> GFunc.funptr @-> returning void)
in
the following function wrapper is used to ignore the ' gpointer user_data '
* of the C callback .
* In C , ' gpointer user_data ' are used to pass variables defined in other
* environment to the callback body .
* In OCaml a function can be a closure .
* Closures are functions which carry around some of the " environment " in
* which they were defined . In particular , a closure can reference variables
* which were available at the point of its definition .
* I just have to pass a function that can carry variables from other environment
* than the callback itself .
*
* absolutly want the same signature than in C , using f_raw allows
* user to define the callback to foreach with a signature like
* ptr data @- > returning void instead of
* ptr data @- > ptr_opt void @- > returning void .
* of the C callback.
* In C, 'gpointer user_data' are used to pass variables defined in other
* environment to the callback body.
* In OCaml a function can be a closure.
* Closures are functions which carry around some of the "environment" in
* which they were defined. In particular, a closure can reference variables
* which were available at the point of its definition.
* I just have to pass a function that can carry variables from other environment
* than the callback itself.
*
* Ctypes absolutly want the same signature than in C, using f_raw allows
* user to define the callback to foreach with a signature like
* ptr data @-> returning void instead of
* ptr data @-> ptr_opt void @-> returning void.
*)
let f_raw a b = f a in
foreign_raw dllist f_raw
end
|
c07a591bf028f8ace07bf5b1eb3b230b90dade81ce314b69681f4b2673bb4194 | anton-k/sharc-timbre | Viola.hs | module Sharc.Instruments.Viola (viola) where
import Sharc.Types
viola :: Instr
viola = Instr
"viola_vibrato"
"Viola"
(Legend "McGill" "1" "6")
(Range
(InstrRange
(HarmonicFreq 1 (Pitch 130.81 36 "c3"))
(Pitch 130.81 36 "c3")
(Amplitude 8372.03 (HarmonicFreq 64 (Pitch 130.813 36 "c3")) 0.13))
(InstrRange
(HarmonicFreq 58 (Pitch 10127.61 41 "f3"))
(Pitch 1174.66 74 "d6")
(Amplitude 233.08 (HarmonicFreq 1 (Pitch 233.082 46 "a#3")) 15064.0)))
[note0
,note1
,note2
,note3
,note4
,note5
,note6
,note7
,note8
,note9
,note10
,note11
,note12
,note13
,note14
,note15
,note16
,note17
,note18
,note19
,note20
,note21
,note22
,note23
,note24
,note25
,note26
,note27
,note28
,note29
,note30
,note31
,note32
,note33
,note34
,note35
,note36
,note37
,note38]
note0 :: Note
note0 = Note
(Pitch 130.813 36 "c3")
1
(Range
(NoteRange
(NoteRangeAmplitude 8372.03 64 0.13)
(NoteRangeHarmonicFreq 1 130.81))
(NoteRange
(NoteRangeAmplitude 261.62 2 6050.0)
(NoteRangeHarmonicFreq 76 9941.78)))
[Harmonic 1 (-1.737) 143.33
,Harmonic 2 (-0.361) 6050.0
,Harmonic 3 (-1.376) 4471.52
,Harmonic 4 (-3.095) 3116.69
,Harmonic 5 (-1.708) 2813.13
,Harmonic 6 (-1.712) 3094.79
,Harmonic 7 (-1.402) 823.26
,Harmonic 8 3.096 4538.32
,Harmonic 9 0.716 1644.78
,Harmonic 10 (-2.288) 1971.2
,Harmonic 11 (-1.953) 1790.56
,Harmonic 12 (-1.976) 1535.71
,Harmonic 13 (-2.834) 456.34
,Harmonic 14 (-0.418) 1698.59
,Harmonic 15 0.448 1109.26
,Harmonic 16 (-1.771) 1055.89
,Harmonic 17 3.091 675.94
,Harmonic 18 2.688 281.65
,Harmonic 19 1.122 133.54
,Harmonic 20 1.266 323.49
,Harmonic 21 (-0.231) 534.58
,Harmonic 22 (-2.582) 312.86
,Harmonic 23 (-0.508) 78.28
,Harmonic 24 (-3.066) 185.09
,Harmonic 25 1.527 81.84
,Harmonic 26 0.323 52.88
,Harmonic 27 1.041 58.49
,Harmonic 28 1.483 128.93
,Harmonic 29 (-0.383) 235.71
,Harmonic 30 (-1.999) 199.47
,Harmonic 31 (-1.399) 94.82
,Harmonic 32 (-3.137) 72.25
,Harmonic 33 1.045 22.95
,Harmonic 34 6.4e-2 26.22
,Harmonic 35 (-0.509) 18.03
,Harmonic 36 2.65 22.63
,Harmonic 37 0.631 51.42
,Harmonic 38 1.766 47.95
,Harmonic 39 (-1.833) 36.2
,Harmonic 40 2.236 36.85
,Harmonic 41 0.358 16.08
,Harmonic 42 (-0.427) 5.42
,Harmonic 43 2.76 26.67
,Harmonic 44 1.4 29.1
,Harmonic 45 1.7e-2 18.2
,Harmonic 46 (-0.871) 15.15
,Harmonic 47 (-1.892) 16.48
,Harmonic 48 (-1.645) 1.28
,Harmonic 49 2.771 10.84
,Harmonic 50 1.705 6.4
,Harmonic 51 0.861 4.87
,Harmonic 52 (-1.572) 3.59
,Harmonic 53 (-2.172) 4.72
,Harmonic 54 (-2.228) 3.61
,Harmonic 55 2.928 10.46
,Harmonic 56 0.712 4.25
,Harmonic 57 0.342 5.22
,Harmonic 58 (-7.0e-3) 11.81
,Harmonic 59 (-0.641) 13.31
,Harmonic 60 (-1.002) 9.35
,Harmonic 61 (-1.449) 7.17
,Harmonic 62 (-2.112) 4.1
,Harmonic 63 2.493 2.23
,Harmonic 64 (-1.735) 0.13
,Harmonic 65 (-1.922) 2.59
,Harmonic 66 1.499 1.13
,Harmonic 67 (-8.0e-2) 1.31
,Harmonic 68 (-1.463) 3.17
,Harmonic 69 (-2.433) 3.35
,Harmonic 70 (-3.056) 4.41
,Harmonic 71 2.39 7.2
,Harmonic 72 1.665 10.61
,Harmonic 73 0.965 9.37
,Harmonic 74 0.525 4.63
,Harmonic 75 1.151 3.47
,Harmonic 76 2.351 2.3]
note1 :: Note
note1 = Note
(Pitch 138.591 37 "c#3")
2
(Range
(NoteRange
(NoteRangeAmplitude 8731.23 63 2.47)
(NoteRangeHarmonicFreq 1 138.59))
(NoteRange
(NoteRangeAmplitude 692.95 5 7155.0)
(NoteRangeHarmonicFreq 72 9978.55)))
[Harmonic 1 (-1.366) 339.29
,Harmonic 2 2.541 6245.16
,Harmonic 3 1.512 5420.62
,Harmonic 4 0.506 7117.55
,Harmonic 5 2.116 7155.0
,Harmonic 6 2.865 6795.0
,Harmonic 7 (-0.978) 4657.18
,Harmonic 8 1.648 2281.12
,Harmonic 9 1.553 6013.29
,Harmonic 10 0.846 4558.98
,Harmonic 11 0.734 2667.41
,Harmonic 12 2.488 1877.8
,Harmonic 13 0.472 1662.64
,Harmonic 14 1.555 741.53
,Harmonic 15 1.17 2128.55
,Harmonic 16 (-4.5e-2) 1310.88
,Harmonic 17 (-0.456) 145.48
,Harmonic 18 3.134 164.67
,Harmonic 19 1.327 257.88
,Harmonic 20 0.312 667.32
,Harmonic 21 (-2.213) 476.89
,Harmonic 22 0.422 580.86
,Harmonic 23 (-0.207) 409.94
,Harmonic 24 (-0.896) 339.64
,Harmonic 25 2.169 245.94
,Harmonic 26 0.89 579.16
,Harmonic 27 0.124 790.47
,Harmonic 28 (-0.21) 535.37
,Harmonic 29 (-0.654) 130.35
,Harmonic 30 0.109 61.82
,Harmonic 31 1.061 146.09
,Harmonic 32 1.782 131.01
,Harmonic 33 1.745 73.99
,Harmonic 34 2.895 37.3
,Harmonic 35 (-1.63) 23.14
,Harmonic 36 (-2.723) 29.25
,Harmonic 37 0.171 40.0
,Harmonic 38 0.294 18.51
,Harmonic 39 (-2.874) 26.58
,Harmonic 40 (-2.646) 43.69
,Harmonic 41 1.6e-2 9.16
,Harmonic 42 (-1.631) 12.86
,Harmonic 43 (-0.433) 8.26
,Harmonic 44 2.82 4.84
,Harmonic 45 (-0.914) 7.52
,Harmonic 46 (-2.512) 6.68
,Harmonic 47 2.903 3.43
,Harmonic 48 (-1.314) 9.12
,Harmonic 49 (-0.122) 16.59
,Harmonic 50 0.515 13.63
,Harmonic 51 2.471 10.42
,Harmonic 52 (-1.801) 7.09
,Harmonic 53 (-0.719) 3.42
,Harmonic 54 0.559 18.31
,Harmonic 55 1.557 26.59
,Harmonic 56 2.307 24.72
,Harmonic 57 (-2.894) 32.41
,Harmonic 58 (-2.968) 21.84
,Harmonic 59 3.002 9.16
,Harmonic 60 2.577 4.05
,Harmonic 61 2.803 3.87
,Harmonic 62 9.0e-2 3.16
,Harmonic 63 (-1.151) 2.47
,Harmonic 64 (-1.035) 6.33
,Harmonic 65 (-2.8e-2) 7.14
,Harmonic 66 0.69 5.32
,Harmonic 67 2.082 6.18
,Harmonic 68 (-3.056) 9.71
,Harmonic 69 (-2.059) 10.52
,Harmonic 70 (-1.277) 11.72
,Harmonic 71 (-2.3e-2) 6.92
,Harmonic 72 0.736 7.92]
note2 :: Note
note2 = Note
(Pitch 146.832 38 "d3")
3
(Range
(NoteRange
(NoteRangeAmplitude 8809.92 60 0.74)
(NoteRangeHarmonicFreq 1 146.83))
(NoteRange
(NoteRangeAmplitude 293.66 2 7702.0)
(NoteRangeHarmonicFreq 68 9984.57)))
[Harmonic 1 2.964 267.42
,Harmonic 2 (-1.338) 7702.0
,Harmonic 3 3.075 4292.1
,Harmonic 4 0.388 884.14
,Harmonic 5 1.104 3113.29
,Harmonic 6 (-0.492) 1823.19
,Harmonic 7 (-0.884) 2545.5
,Harmonic 8 1.416 1139.72
,Harmonic 9 (-1.081) 1505.61
,Harmonic 10 (-2.734) 2574.99
,Harmonic 11 2.878 985.19
,Harmonic 12 (-0.886) 144.89
,Harmonic 13 3.113 315.67
,Harmonic 14 2.975 1173.4
,Harmonic 15 1.3 334.39
,Harmonic 16 (-1.088) 296.83
,Harmonic 17 (-0.641) 195.09
,Harmonic 18 (-2.721) 92.4
,Harmonic 19 0.176 226.08
,Harmonic 20 1.528 177.68
,Harmonic 21 2.438 211.04
,Harmonic 22 0.67 379.87
,Harmonic 23 (-0.181) 138.67
,Harmonic 24 (-0.893) 281.81
,Harmonic 25 (-2.711) 267.94
,Harmonic 26 1.427 227.46
,Harmonic 27 (-1.83) 313.65
,Harmonic 28 (-2.861) 165.69
,Harmonic 29 2.432 107.83
,Harmonic 30 1.472 55.82
,Harmonic 31 (-2.715) 39.01
,Harmonic 32 1.999 29.31
,Harmonic 33 0.627 48.49
,Harmonic 34 (-1.462) 41.17
,Harmonic 35 (-0.789) 30.69
,Harmonic 36 2.869 50.57
,Harmonic 37 1.071 15.23
,Harmonic 38 (-1.076) 4.74
,Harmonic 39 (-0.772) 6.48
,Harmonic 40 (-1.858) 7.65
,Harmonic 41 (-2.521) 13.38
,Harmonic 42 2.579 19.86
,Harmonic 43 0.89 18.18
,Harmonic 44 1.364 4.44
,Harmonic 45 (-1.437) 11.76
,Harmonic 46 (-3.115) 9.11
,Harmonic 47 0.379 6.69
,Harmonic 48 (-2.189) 2.92
,Harmonic 49 2.887 2.16
,Harmonic 50 0.797 4.23
,Harmonic 51 (-2.963) 9.53
,Harmonic 52 1.84 7.41
,Harmonic 53 2.097 6.46
,Harmonic 54 0.17 7.96
,Harmonic 55 (-1.709) 4.66
,Harmonic 56 (-1.923) 2.91
,Harmonic 57 (-2.652) 3.52
,Harmonic 58 2.246 2.48
,Harmonic 59 (-1.615) 1.08
,Harmonic 60 (-1.784) 0.74
,Harmonic 61 2.16 3.25
,Harmonic 62 1.081 1.92
,Harmonic 63 (-0.38) 3.39
,Harmonic 64 (-1.428) 3.95
,Harmonic 65 (-2.925) 2.72
,Harmonic 66 (-3.015) 4.11
,Harmonic 67 2.107 2.77
,Harmonic 68 2.475 2.26]
note3 :: Note
note3 = Note
(Pitch 155.563 39 "d#3")
4
(Range
(NoteRange
(NoteRangeAmplitude 7155.89 46 0.25)
(NoteRangeHarmonicFreq 1 155.56))
(NoteRange
(NoteRangeAmplitude 466.68 3 9957.0)
(NoteRangeHarmonicFreq 64 9956.03)))
[Harmonic 1 (-2.798) 508.38
,Harmonic 2 (-0.302) 5737.84
,Harmonic 3 (-1.76) 9957.0
,Harmonic 4 (-1.64) 3843.32
,Harmonic 5 (-2.718) 3575.43
,Harmonic 6 (-2.539) 903.49
,Harmonic 7 (-0.238) 1450.92
,Harmonic 8 (-2.034) 2701.61
,Harmonic 9 2.976 1953.81
,Harmonic 10 2.453 678.73
,Harmonic 11 1.17 755.25
,Harmonic 12 (-2.054) 1979.05
,Harmonic 13 (-1.813) 2207.36
,Harmonic 14 2.132 1333.44
,Harmonic 15 1.435 277.64
,Harmonic 16 (-2.221) 71.68
,Harmonic 17 0.179 230.39
,Harmonic 18 (-1.562) 282.81
,Harmonic 19 (-0.519) 490.79
,Harmonic 20 1.076 553.6
,Harmonic 21 (-0.641) 229.89
,Harmonic 22 (-9.0e-2) 108.47
,Harmonic 23 (-0.949) 221.27
,Harmonic 24 (-1.976) 154.96
,Harmonic 25 2.465 155.07
,Harmonic 26 0.879 271.89
,Harmonic 27 (-4.7e-2) 214.75
,Harmonic 28 (-1.324) 80.69
,Harmonic 29 1.787 19.97
,Harmonic 30 0.107 43.72
,Harmonic 31 (-0.324) 34.21
,Harmonic 32 (-1.63) 14.53
,Harmonic 33 0.974 51.32
,Harmonic 34 (-0.974) 28.13
,Harmonic 35 (-2.626) 15.56
,Harmonic 36 1.429 10.66
,Harmonic 37 2.066 22.34
,Harmonic 38 1.458 54.09
,Harmonic 39 0.463 34.84
,Harmonic 40 (-0.54) 22.49
,Harmonic 41 1.429 6.91
,Harmonic 42 0.343 10.54
,Harmonic 43 (-2.759) 5.24
,Harmonic 44 0.936 0.85
,Harmonic 45 (-2.118) 1.48
,Harmonic 46 2.468 0.25
,Harmonic 47 (-2.36) 5.16
,Harmonic 48 2.693 6.64
,Harmonic 49 1.443 4.53
,Harmonic 50 1.038 6.18
,Harmonic 51 1.431 3.94
,Harmonic 52 0.576 8.15
,Harmonic 53 (-0.532) 7.66
,Harmonic 54 (-0.974) 1.52
,Harmonic 55 (-1.277) 2.32
,Harmonic 56 2.01 2.98
,Harmonic 57 2.281 9.57
,Harmonic 58 1.884 10.47
,Harmonic 59 1.728 5.7
,Harmonic 60 0.474 1.64
,Harmonic 61 (-1.458) 1.79
,Harmonic 62 (-3.09) 1.95
,Harmonic 63 (-1.084) 3.63
,Harmonic 64 (-1.608) 2.67]
note4 :: Note
note4 = Note
(Pitch 164.814 40 "e3")
5
(Range
(NoteRange
(NoteRangeAmplitude 7746.25 47 0.98)
(NoteRangeHarmonicFreq 1 164.81))
(NoteRange
(NoteRangeAmplitude 494.44 3 5938.0)
(NoteRangeHarmonicFreq 61 10053.65)))
[Harmonic 1 (-0.424) 262.27
,Harmonic 2 (-1.771) 4565.41
,Harmonic 3 (-1.636) 5938.0
,Harmonic 4 1.679 2034.66
,Harmonic 5 (-3.115) 2889.35
,Harmonic 6 (-8.0e-3) 2638.09
,Harmonic 7 (-2.857) 972.25
,Harmonic 8 (-1.23) 2068.71
,Harmonic 9 (-0.129) 2055.18
,Harmonic 10 1.454 1009.68
,Harmonic 11 1.36 381.33
,Harmonic 12 (-2.752) 423.1
,Harmonic 13 (-2.009) 1490.52
,Harmonic 14 (-0.87) 466.34
,Harmonic 15 (-1.762) 355.48
,Harmonic 16 0.775 161.62
,Harmonic 17 2.403 348.0
,Harmonic 18 (-0.155) 275.44
,Harmonic 19 (-2.922) 284.27
,Harmonic 20 (-1.847) 118.35
,Harmonic 21 (-0.693) 35.89
,Harmonic 22 (-2.548) 152.71
,Harmonic 23 (-2.127) 179.31
,Harmonic 24 (-2.404) 211.03
,Harmonic 25 (-0.335) 164.56
,Harmonic 26 0.72 138.04
,Harmonic 27 2.514 24.61
,Harmonic 28 0.273 9.18
,Harmonic 29 3.094 18.83
,Harmonic 30 (-2.648) 11.63
,Harmonic 31 3.011 33.82
,Harmonic 32 2.594 29.24
,Harmonic 33 2.957 12.27
,Harmonic 34 (-2.247) 28.85
,Harmonic 35 2.797 12.95
,Harmonic 36 (-2.528) 17.32
,Harmonic 37 (-0.505) 21.07
,Harmonic 38 1.556 14.12
,Harmonic 39 (-2.133) 5.55
,Harmonic 40 (-2.908) 13.69
,Harmonic 41 2.932 6.16
,Harmonic 42 (-0.42) 6.49
,Harmonic 43 2.196 2.81
,Harmonic 44 0.963 2.97
,Harmonic 45 2.813 2.83
,Harmonic 46 (-0.54) 3.47
,Harmonic 47 (-2.032) 0.98
,Harmonic 48 (-1.381) 7.87
,Harmonic 49 0.313 8.54
,Harmonic 50 1.583 5.46
,Harmonic 51 (-2.738) 2.68
,Harmonic 52 4.2e-2 1.62
,Harmonic 53 1.803 3.08
,Harmonic 54 1.876 1.91
,Harmonic 55 (-2.623) 3.65
,Harmonic 56 (-0.228) 3.07
,Harmonic 57 0.736 4.56
,Harmonic 58 2.283 8.67
,Harmonic 59 (-2.563) 8.21
,Harmonic 60 (-0.937) 3.98
,Harmonic 61 1.487 1.18]
note5 :: Note
note5 = Note
(Pitch 174.614 41 "f3")
6
(Range
(NoteRange
(NoteRangeAmplitude 9079.92 52 0.32)
(NoteRangeHarmonicFreq 1 174.61))
(NoteRange
(NoteRangeAmplitude 349.22 2 7094.0)
(NoteRangeHarmonicFreq 58 10127.61)))
[Harmonic 1 (-1.393) 854.97
,Harmonic 2 2.19 7094.0
,Harmonic 3 0.547 6922.78
,Harmonic 4 2.477 4224.62
,Harmonic 5 2.65 2694.58
,Harmonic 6 (-2.072) 2630.57
,Harmonic 7 1.23 2560.33
,Harmonic 8 0.843 3483.79
,Harmonic 9 0.181 585.14
,Harmonic 10 0.185 229.73
,Harmonic 11 (-1.558) 593.0
,Harmonic 12 2.8e-2 1644.98
,Harmonic 13 0.169 718.4
,Harmonic 14 (-1.856) 116.74
,Harmonic 15 (-1.375) 318.73
,Harmonic 16 (-1.209) 423.99
,Harmonic 17 (-2.95) 328.75
,Harmonic 18 (-1.624) 235.46
,Harmonic 19 (-2.763) 371.93
,Harmonic 20 (-2.716) 82.3
,Harmonic 21 (-8.9e-2) 273.2
,Harmonic 22 (-0.714) 376.1
,Harmonic 23 (-1.625) 357.95
,Harmonic 24 (-1.522) 167.16
,Harmonic 25 (-1.218) 75.13
,Harmonic 26 (-1.49) 59.43
,Harmonic 27 (-2.968) 55.02
,Harmonic 28 2.358 50.03
,Harmonic 29 2.523 18.12
,Harmonic 30 (-0.824) 44.43
,Harmonic 31 (-2.557) 26.38
,Harmonic 32 (-1.665) 21.09
,Harmonic 33 (-0.743) 38.03
,Harmonic 34 0.161 54.93
,Harmonic 35 0.643 84.52
,Harmonic 36 0.713 62.11
,Harmonic 37 1.264 13.64
,Harmonic 38 2.158 34.06
,Harmonic 39 1.249 16.98
,Harmonic 40 1.005 7.28
,Harmonic 41 0.552 0.97
,Harmonic 42 (-0.61) 10.05
,Harmonic 43 0.507 4.35
,Harmonic 44 1.522 4.77
,Harmonic 45 2.036 4.77
,Harmonic 46 (-1.455) 7.87
,Harmonic 47 (-1.417) 9.33
,Harmonic 48 (-0.839) 10.03
,Harmonic 49 0.331 4.97
,Harmonic 50 1.427 5.6
,Harmonic 51 1.975 3.86
,Harmonic 52 (-1.955) 0.32
,Harmonic 53 (-1.817) 0.51
,Harmonic 54 2.151 1.33
,Harmonic 55 0.654 1.69
,Harmonic 56 (-0.74) 0.35
,Harmonic 57 (-2.39) 3.78
,Harmonic 58 (-2.418) 5.7]
note6 :: Note
note6 = Note
(Pitch 184.997 42 "f#3")
7
(Range
(NoteRange
(NoteRangeAmplitude 7399.88 40 1.65)
(NoteRangeHarmonicFreq 1 184.99))
(NoteRange
(NoteRangeAmplitude 369.99 2 6497.0)
(NoteRangeHarmonicFreq 54 9989.83)))
[Harmonic 1 2.826 995.6
,Harmonic 2 (-2.094) 6497.0
,Harmonic 3 1.203 1591.48
,Harmonic 4 1.089 1324.48
,Harmonic 5 1.703 760.49
,Harmonic 6 2.832 647.22
,Harmonic 7 (-0.565) 2256.7
,Harmonic 8 (-1.462) 1007.36
,Harmonic 9 (-2.161) 552.29
,Harmonic 10 (-1.03) 1219.27
,Harmonic 11 (-1.382) 822.24
,Harmonic 12 2.426 275.73
,Harmonic 13 (-0.179) 105.31
,Harmonic 14 (-2.415) 145.23
,Harmonic 15 2.466 190.65
,Harmonic 16 1.821 126.73
,Harmonic 17 (-1.892) 218.23
,Harmonic 18 (-3.08) 135.12
,Harmonic 19 1.153 221.19
,Harmonic 20 (-0.934) 204.79
,Harmonic 21 (-2.776) 54.57
,Harmonic 22 2.457 62.78
,Harmonic 23 8.3e-2 43.09
,Harmonic 24 (-0.442) 50.37
,Harmonic 25 (-0.624) 57.56
,Harmonic 26 (-2.633) 24.97
,Harmonic 27 0.277 31.55
,Harmonic 28 3.034 6.14
,Harmonic 29 (-3.061) 13.34
,Harmonic 30 1.081 32.52
,Harmonic 31 (-1.066) 48.8
,Harmonic 32 (-3.063) 33.21
,Harmonic 33 1.644 17.54
,Harmonic 34 0.826 3.99
,Harmonic 35 0.196 8.25
,Harmonic 36 (-1.356) 11.54
,Harmonic 37 (-2.466) 12.25
,Harmonic 38 2.221 4.0
,Harmonic 39 0.983 9.7
,Harmonic 40 (-1.655) 1.65
,Harmonic 41 1.437 1.68
,Harmonic 42 0.103 8.38
,Harmonic 43 (-2.871) 2.93
,Harmonic 44 0.693 3.31
,Harmonic 45 (-0.634) 2.77
,Harmonic 46 (-1.177) 3.25
,Harmonic 47 2.667 1.73
,Harmonic 48 1.389 4.13
,Harmonic 49 0.301 3.93
,Harmonic 50 (-0.49) 5.57
,Harmonic 51 (-2.35) 5.86
,Harmonic 52 1.369 6.33
,Harmonic 53 (-1.008) 2.1
,Harmonic 54 0.189 2.1]
note7 :: Note
note7 = Note
(Pitch 195.998 43 "g3")
8
(Range
(NoteRange
(NoteRangeAmplitude 9211.9 47 2.03)
(NoteRangeHarmonicFreq 1 195.99))
(NoteRange
(NoteRangeAmplitude 1371.98 7 6214.0)
(NoteRangeHarmonicFreq 50 9799.9)))
[Harmonic 1 (-2.832) 2304.17
,Harmonic 2 0.441 3061.32
,Harmonic 3 (-0.879) 2019.25
,Harmonic 4 (-0.314) 2284.87
,Harmonic 5 0.897 2199.32
,Harmonic 6 2.461 4359.08
,Harmonic 7 1.278 6214.0
,Harmonic 8 1.605 4300.0
,Harmonic 9 3.059 446.43
,Harmonic 10 2.606 484.21
,Harmonic 11 1.603 1738.72
,Harmonic 12 0.526 564.41
,Harmonic 13 0.205 484.24
,Harmonic 14 (-1.174) 941.42
,Harmonic 15 2.027 500.14
,Harmonic 16 (-2.699) 485.74
,Harmonic 17 1.381 492.54
,Harmonic 18 (-2.104) 1078.88
,Harmonic 19 1.485 775.07
,Harmonic 20 (-0.745) 347.18
,Harmonic 21 (-1.044) 130.81
,Harmonic 22 (-0.504) 104.9
,Harmonic 23 2.661 68.22
,Harmonic 24 (-1.942) 46.22
,Harmonic 25 1.102 208.31
,Harmonic 26 (-2.162) 131.56
,Harmonic 27 1.44 111.76
,Harmonic 28 (-0.521) 92.83
,Harmonic 29 (-3.004) 77.13
,Harmonic 30 (-2.872) 48.19
,Harmonic 31 (-2.815) 64.59
,Harmonic 32 (-1.369) 6.36
,Harmonic 33 (-1.862) 51.57
,Harmonic 34 (-1.71) 45.79
,Harmonic 35 1.632 17.37
,Harmonic 36 1.493 44.58
,Harmonic 37 0.728 55.62
,Harmonic 38 (-0.231) 6.23
,Harmonic 39 2.403 26.12
,Harmonic 40 (-2.762) 12.08
,Harmonic 41 1.309 5.32
,Harmonic 42 (-0.49) 24.44
,Harmonic 43 (-2.858) 9.14
,Harmonic 44 1.576 12.07
,Harmonic 45 (-0.979) 15.58
,Harmonic 46 (-2.463) 13.18
,Harmonic 47 0.79 2.03
,Harmonic 48 (-1.143) 9.19
,Harmonic 49 (-2.136) 4.74
,Harmonic 50 2.412 4.6]
note8 :: Note
note8 = Note
(Pitch 207.652 44 "g#3")
9
(Range
(NoteRange
(NoteRangeAmplitude 9967.29 48 3.88)
(NoteRangeHarmonicFreq 1 207.65))
(NoteRange
(NoteRangeAmplitude 1453.56 7 9195.0)
(NoteRangeHarmonicFreq 48 9967.29)))
[Harmonic 1 (-1.91) 2981.66
,Harmonic 2 2.629 6517.51
,Harmonic 3 (-2.933) 3444.14
,Harmonic 4 (-1.555) 6146.84
,Harmonic 5 0.235 3706.13
,Harmonic 6 (-2.698) 5602.03
,Harmonic 7 (-1.471) 9195.0
,Harmonic 8 (-0.668) 7525.02
,Harmonic 9 1.632 2311.11
,Harmonic 10 (-2.442) 2455.59
,Harmonic 11 2.718 1749.65
,Harmonic 12 1.534 615.81
,Harmonic 13 (-2.313) 639.75
,Harmonic 14 2.83 1476.63
,Harmonic 15 (-1.424) 1640.57
,Harmonic 16 (-2.623) 991.31
,Harmonic 17 0.113 1298.03
,Harmonic 18 (-0.474) 1150.64
,Harmonic 19 (-0.932) 941.21
,Harmonic 20 (-1.192) 627.89
,Harmonic 21 (-2.337) 214.84
,Harmonic 22 (-0.774) 65.46
,Harmonic 23 0.788 394.73
,Harmonic 24 0.358 412.56
,Harmonic 25 1.594 364.58
,Harmonic 26 2.654 325.41
,Harmonic 27 (-1.939) 419.93
,Harmonic 28 1.914 38.99
,Harmonic 29 2.239 98.38
,Harmonic 30 (-2.887) 119.1
,Harmonic 31 1.86 52.33
,Harmonic 32 (-2.239) 87.74
,Harmonic 33 (-0.3) 82.17
,Harmonic 34 1.551 78.01
,Harmonic 35 (-3.002) 151.71
,Harmonic 36 (-1.889) 103.22
,Harmonic 37 0.474 34.53
,Harmonic 38 2.89 28.58
,Harmonic 39 (-2.413) 41.98
,Harmonic 40 0.918 37.48
,Harmonic 41 1.324 49.38
,Harmonic 42 (-1.95) 22.87
,Harmonic 43 (-0.728) 21.03
,Harmonic 44 (-0.421) 32.72
,Harmonic 45 (-0.251) 19.23
,Harmonic 46 (-0.489) 16.55
,Harmonic 47 1.5 12.1
,Harmonic 48 (-2.864) 3.88]
note9 :: Note
note9 = Note
(Pitch 220.0 45 "a3")
10
(Range
(NoteRange
(NoteRangeAmplitude 9900.0 45 3.13)
(NoteRangeHarmonicFreq 1 220.0))
(NoteRange
(NoteRangeAmplitude 440.0 2 11549.0)
(NoteRangeHarmonicFreq 45 9900.0)))
[Harmonic 1 (-0.553) 6617.65
,Harmonic 2 (-1.981) 11549.0
,Harmonic 3 (-2.7e-2) 1815.72
,Harmonic 4 2.0 1498.02
,Harmonic 5 2.593 696.85
,Harmonic 6 2.499 4561.23
,Harmonic 7 (-2.436) 1616.94
,Harmonic 8 (-1.302) 1322.31
,Harmonic 9 (-0.51) 2172.62
,Harmonic 10 (-0.557) 1887.24
,Harmonic 11 (-1.248) 287.03
,Harmonic 12 1.803 165.62
,Harmonic 13 1.317 1224.55
,Harmonic 14 (-2.128) 645.69
,Harmonic 15 (-2.318) 602.62
,Harmonic 16 2.413 393.01
,Harmonic 17 1.78 701.89
,Harmonic 18 1.653 349.11
,Harmonic 19 3.085 300.94
,Harmonic 20 1.087 58.08
,Harmonic 21 6.0e-2 19.57
,Harmonic 22 1.158 41.24
,Harmonic 23 2.166 55.96
,Harmonic 24 (-3.086) 100.65
,Harmonic 25 0.242 192.03
,Harmonic 26 (-0.112) 108.32
,Harmonic 27 0.337 168.41
,Harmonic 28 2.918 144.42
,Harmonic 29 0.69 50.74
,Harmonic 30 1.592 23.59
,Harmonic 31 (-0.117) 17.68
,Harmonic 32 (-0.991) 7.94
,Harmonic 33 0.108 33.72
,Harmonic 34 2.885 36.25
,Harmonic 35 0.594 27.1
,Harmonic 36 (-2.851) 57.96
,Harmonic 37 (-0.768) 24.22
,Harmonic 38 2.419 15.2
,Harmonic 39 0.252 7.14
,Harmonic 40 2.384 21.16
,Harmonic 41 (-2.258) 15.53
,Harmonic 42 (-2.2) 5.33
,Harmonic 43 1.41 7.18
,Harmonic 44 2.422 17.95
,Harmonic 45 0.336 3.13]
note10 :: Note
note10 = Note
(Pitch 233.082 46 "a#3")
11
(Range
(NoteRange
(NoteRangeAmplitude 8857.11 38 1.77)
(NoteRangeHarmonicFreq 1 233.08))
(NoteRange
(NoteRangeAmplitude 233.08 1 15064.0)
(NoteRangeHarmonicFreq 43 10022.52)))
[Harmonic 1 (-1.72) 15064.0
,Harmonic 2 (-1.697) 12962.84
,Harmonic 3 0.138 1493.03
,Harmonic 4 (-1.125) 1242.65
,Harmonic 5 (-3.138) 2215.9
,Harmonic 6 (-2.179) 4530.49
,Harmonic 7 0.176 3934.23
,Harmonic 8 (-2.1) 3321.89
,Harmonic 9 0.913 1790.0
,Harmonic 10 1.695 211.64
,Harmonic 11 3.098 422.0
,Harmonic 12 (-1.878) 1223.09
,Harmonic 13 1.182 568.0
,Harmonic 14 7.0e-3 369.81
,Harmonic 15 (-2.719) 568.37
,Harmonic 16 (-1.545) 654.24
,Harmonic 17 (-1.014) 176.28
,Harmonic 18 (-0.481) 225.2
,Harmonic 19 (-2.813) 86.54
,Harmonic 20 2.375 54.56
,Harmonic 21 (-2.336) 60.06
,Harmonic 22 (-8.4e-2) 241.36
,Harmonic 23 2.346 79.96
,Harmonic 24 (-1.732) 124.84
,Harmonic 25 (-1.628) 106.1
,Harmonic 26 6.9e-2 86.04
,Harmonic 27 2.781 26.52
,Harmonic 28 (-2.044) 4.35
,Harmonic 29 (-0.779) 39.12
,Harmonic 30 2.438 16.66
,Harmonic 31 (-0.913) 72.25
,Harmonic 32 2.894 5.28
,Harmonic 33 (-0.194) 73.23
,Harmonic 34 1.798 49.6
,Harmonic 35 (-1.486) 5.85
,Harmonic 36 0.208 12.53
,Harmonic 37 1.193 10.71
,Harmonic 38 (-0.856) 1.77
,Harmonic 39 (-3.074) 7.25
,Harmonic 40 0.335 13.43
,Harmonic 41 1.714 13.2
,Harmonic 42 (-1.742) 12.93
,Harmonic 43 0.868 6.53]
note11 :: Note
note11 = Note
(Pitch 246.942 47 "b3")
12
(Range
(NoteRange
(NoteRangeAmplitude 9383.79 38 1.4)
(NoteRangeHarmonicFreq 1 246.94))
(NoteRange
(NoteRangeAmplitude 493.88 2 7831.0)
(NoteRangeHarmonicFreq 41 10124.62)))
[Harmonic 1 (-1.098) 6459.96
,Harmonic 2 (-3.3e-2) 7831.0
,Harmonic 3 (-2.743) 2405.56
,Harmonic 4 3.03 3284.59
,Harmonic 5 2.541 4562.92
,Harmonic 6 (-1.471) 4359.22
,Harmonic 7 (-1.313) 1611.04
,Harmonic 8 2.864 2198.42
,Harmonic 9 (-1.511) 2577.71
,Harmonic 10 1.496 273.86
,Harmonic 11 2.579 1141.0
,Harmonic 12 2.049 482.26
,Harmonic 13 1.876 432.4
,Harmonic 14 1.471 332.35
,Harmonic 15 0.735 72.02
,Harmonic 16 1.704 735.64
,Harmonic 17 (-1.02) 267.59
,Harmonic 18 (-2.385) 35.89
,Harmonic 19 (-4.0e-3) 138.29
,Harmonic 20 (-2.497) 89.98
,Harmonic 21 0.512 67.61
,Harmonic 22 0.329 47.6
,Harmonic 23 (-0.364) 54.8
,Harmonic 24 2.445 53.82
,Harmonic 25 0.513 79.34
,Harmonic 26 2.426 31.3
,Harmonic 27 0.967 67.46
,Harmonic 28 (-2.244) 42.2
,Harmonic 29 0.22 32.63
,Harmonic 30 (-2.334) 41.18
,Harmonic 31 (-0.111) 35.55
,Harmonic 32 (-0.736) 34.27
,Harmonic 33 2.576 35.69
,Harmonic 34 (-0.317) 17.55
,Harmonic 35 (-1.074) 7.92
,Harmonic 36 (-3.008) 11.29
,Harmonic 37 0.9 9.91
,Harmonic 38 (-1.425) 1.4
,Harmonic 39 0.14 13.53
,Harmonic 40 (-1.879) 8.55
,Harmonic 41 1.827 11.9]
note12 :: Note
note12 = Note
(Pitch 261.626 48 "c4")
13
(Range
(NoteRange
(NoteRangeAmplitude 9680.16 37 8.29)
(NoteRangeHarmonicFreq 1 261.62))
(NoteRange
(NoteRangeAmplitude 261.62 1 8531.0)
(NoteRangeHarmonicFreq 38 9941.78)))
[Harmonic 1 1.849 8531.0
,Harmonic 2 2.0 3012.87
,Harmonic 3 0.367 1271.51
,Harmonic 4 1.789 2745.79
,Harmonic 5 (-0.51) 3151.96
,Harmonic 6 1.135 1352.91
,Harmonic 7 (-0.506) 1502.43
,Harmonic 8 1.14 2921.29
,Harmonic 9 1.047 1124.29
,Harmonic 10 2.202 877.91
,Harmonic 11 0.174 690.14
,Harmonic 12 2.709 419.18
,Harmonic 13 1.354 182.35
,Harmonic 14 (-1.282) 123.15
,Harmonic 15 (-2.103) 252.51
,Harmonic 16 0.323 61.42
,Harmonic 17 (-1.764) 31.5
,Harmonic 18 2.673 103.55
,Harmonic 19 (-1.63) 34.69
,Harmonic 20 (-2.817) 37.4
,Harmonic 21 0.151 113.61
,Harmonic 22 1.302 35.3
,Harmonic 23 (-1.849) 10.51
,Harmonic 24 (-3.118) 29.38
,Harmonic 25 (-1.976) 82.57
,Harmonic 26 0.373 40.73
,Harmonic 27 1.839 21.6
,Harmonic 28 2.97 10.48
,Harmonic 29 (-1.094) 31.83
,Harmonic 30 0.83 40.33
,Harmonic 31 2.494 24.35
,Harmonic 32 1.974 9.01
,Harmonic 33 (-1.592) 18.85
,Harmonic 34 (-0.232) 17.17
,Harmonic 35 1.346 11.24
,Harmonic 36 (-2.491) 19.7
,Harmonic 37 1.197 8.29
,Harmonic 38 2.661 15.7]
note13 :: Note
note13 = Note
(Pitch 277.183 49 "c#4")
14
(Range
(NoteRange
(NoteRangeAmplitude 8869.85 32 8.19)
(NoteRangeHarmonicFreq 1 277.18))
(NoteRange
(NoteRangeAmplitude 1385.91 5 6263.0)
(NoteRangeHarmonicFreq 36 9978.58)))
[Harmonic 1 1.969 4509.09
,Harmonic 2 (-0.872) 3526.63
,Harmonic 3 0.919 4387.78
,Harmonic 4 (-0.949) 2660.26
,Harmonic 5 (-2.375) 6263.0
,Harmonic 6 (-1.754) 4006.26
,Harmonic 7 (-3.037) 2661.3
,Harmonic 8 (-7.0e-3) 1148.94
,Harmonic 9 (-2.503) 370.52
,Harmonic 10 (-2.593) 907.38
,Harmonic 11 (-0.439) 819.06
,Harmonic 12 1.579 470.04
,Harmonic 13 2.735 793.17
,Harmonic 14 1.077 1403.06
,Harmonic 15 (-0.213) 238.99
,Harmonic 16 (-0.527) 67.72
,Harmonic 17 1.062 59.71
,Harmonic 18 3.087 172.41
,Harmonic 19 (-2.237) 125.86
,Harmonic 20 (-2.097) 103.46
,Harmonic 21 1.419 186.03
,Harmonic 22 1.73 153.13
,Harmonic 23 (-2.541) 112.95
,Harmonic 24 (-2.026) 41.49
,Harmonic 25 (-0.513) 23.87
,Harmonic 26 2.427 47.49
,Harmonic 27 (-1.954) 40.27
,Harmonic 28 (-0.529) 79.67
,Harmonic 29 (-0.581) 29.68
,Harmonic 30 0.735 25.66
,Harmonic 31 (-2.855) 22.26
,Harmonic 32 (-2.347) 8.19
,Harmonic 33 1.634 11.7
,Harmonic 34 (-2.988) 16.08
,Harmonic 35 (-2.574) 22.05
,Harmonic 36 (-1.521) 8.81]
note14 :: Note
note14 = Note
(Pitch 293.665 50 "d4")
15
(Range
(NoteRange
(NoteRangeAmplitude 9690.94 33 34.15)
(NoteRangeHarmonicFreq 1 293.66))
(NoteRange
(NoteRangeAmplitude 293.66 1 10821.0)
(NoteRangeHarmonicFreq 34 9984.61)))
[Harmonic 1 2.574 10821.0
,Harmonic 2 1.88 4804.88
,Harmonic 3 0.134 1267.58
,Harmonic 4 (-2.87) 4013.97
,Harmonic 5 (-0.864) 9345.71
,Harmonic 6 (-0.936) 2702.97
,Harmonic 7 (-1.411) 7831.49
,Harmonic 8 (-1.893) 1602.29
,Harmonic 9 (-1.436) 3950.3
,Harmonic 10 2.72 1084.73
,Harmonic 11 (-1.471) 3043.56
,Harmonic 12 1.422 1978.05
,Harmonic 13 0.739 1129.55
,Harmonic 14 1.89 364.76
,Harmonic 15 (-1.321) 325.05
,Harmonic 16 (-3.084) 349.39
,Harmonic 17 2.667 124.81
,Harmonic 18 (-0.634) 126.91
,Harmonic 19 (-0.151) 118.67
,Harmonic 20 1.883 238.95
,Harmonic 21 1.172 276.89
,Harmonic 22 (-0.465) 56.24
,Harmonic 23 (-1.336) 51.5
,Harmonic 24 (-0.7) 60.27
,Harmonic 25 3.131 67.57
,Harmonic 26 2.36 78.05
,Harmonic 27 (-1.035) 79.9
,Harmonic 28 0.461 35.66
,Harmonic 29 1.261 41.59
,Harmonic 30 (-2.182) 37.44
,Harmonic 31 1.816 39.83
,Harmonic 32 (-1.923) 66.6
,Harmonic 33 0.394 34.15
,Harmonic 34 (-2.028) 55.28]
note15 :: Note
note15 = Note
(Pitch 311.127 51 "d#4")
16
(Range
(NoteRange
(NoteRangeAmplitude 9022.68 29 5.99)
(NoteRangeHarmonicFreq 1 311.12))
(NoteRange
(NoteRangeAmplitude 2177.88 7 10586.0)
(NoteRangeHarmonicFreq 32 9956.06)))
[Harmonic 1 0.488 4236.58
,Harmonic 2 (-1.211) 2438.15
,Harmonic 3 1.942 1378.7
,Harmonic 4 1.702 3578.54
,Harmonic 5 0.17 1247.74
,Harmonic 6 2.03 3360.82
,Harmonic 7 1.178 10586.0
,Harmonic 8 0.348 346.51
,Harmonic 9 2.621 995.81
,Harmonic 10 1.951 1437.14
,Harmonic 11 (-2.177) 432.39
,Harmonic 12 (-0.718) 745.44
,Harmonic 13 (-2.717) 195.72
,Harmonic 14 (-2.471) 286.14
,Harmonic 15 2.946 173.15
,Harmonic 16 1.422 63.93
,Harmonic 17 1.877 203.54
,Harmonic 18 (-3.129) 51.93
,Harmonic 19 2.4 192.15
,Harmonic 20 2.553 77.73
,Harmonic 21 (-1.098) 58.5
,Harmonic 22 0.707 15.29
,Harmonic 23 (-0.221) 43.45
,Harmonic 24 (-1.916) 65.44
,Harmonic 25 (-2.328) 59.88
,Harmonic 26 (-2.906) 96.56
,Harmonic 27 2.957 51.0
,Harmonic 28 0.874 25.61
,Harmonic 29 0.527 5.99
,Harmonic 30 3.003 16.52
,Harmonic 31 (-2.626) 30.48
,Harmonic 32 (-1.453) 28.44]
note16 :: Note
note16 = Note
(Pitch 329.628 52 "e4")
17
(Range
(NoteRange
(NoteRangeAmplitude 8899.95 27 19.31)
(NoteRangeHarmonicFreq 1 329.62))
(NoteRange
(NoteRangeAmplitude 329.62 1 7162.0)
(NoteRangeHarmonicFreq 30 9888.84)))
[Harmonic 1 (-2.05) 7162.0
,Harmonic 2 (-0.209) 2500.43
,Harmonic 3 (-1.619) 1935.05
,Harmonic 4 (-2.366) 6058.87
,Harmonic 5 (-0.66) 3178.81
,Harmonic 6 1.627 2100.45
,Harmonic 7 2.314 2368.58
,Harmonic 8 (-1.668) 1808.14
,Harmonic 9 (-2.395) 854.49
,Harmonic 10 (-0.277) 348.2
,Harmonic 11 (-1.573) 1206.81
,Harmonic 12 (-1.127) 1271.52
,Harmonic 13 (-2.64) 423.32
,Harmonic 14 9.4e-2 425.97
,Harmonic 15 (-1.896) 27.31
,Harmonic 16 (-0.195) 221.32
,Harmonic 17 (-2.246) 515.39
,Harmonic 18 0.333 195.46
,Harmonic 19 2.627 128.13
,Harmonic 20 (-0.354) 130.72
,Harmonic 21 (-2.616) 113.99
,Harmonic 22 3.059 51.09
,Harmonic 23 (-2.336) 86.23
,Harmonic 24 1.601 141.64
,Harmonic 25 (-0.649) 51.95
,Harmonic 26 1.258 57.75
,Harmonic 27 (-2.891) 19.31
,Harmonic 28 (-2.647) 22.58
,Harmonic 29 1.842 148.45
,Harmonic 30 (-0.669) 39.78]
note17 :: Note
note17 = Note
(Pitch 349.228 53 "f4")
18
(Range
(NoteRange
(NoteRangeAmplitude 8730.7 25 10.47)
(NoteRangeHarmonicFreq 1 349.22))
(NoteRange
(NoteRangeAmplitude 349.22 1 9001.0)
(NoteRangeHarmonicFreq 28 9778.38)))
[Harmonic 1 (-0.76) 9001.0
,Harmonic 2 3.107 1108.5
,Harmonic 3 1.21 2633.15
,Harmonic 4 2.187 3968.97
,Harmonic 5 0.53 1287.12
,Harmonic 6 2.293 3185.73
,Harmonic 7 3.034 576.2
,Harmonic 8 0.954 1985.66
,Harmonic 9 (-1.948) 732.58
,Harmonic 10 (-2.871) 511.76
,Harmonic 11 (-1.803) 642.03
,Harmonic 12 (-1.061) 193.68
,Harmonic 13 2.58 124.51
,Harmonic 14 1.172 191.53
,Harmonic 15 (-0.65) 85.22
,Harmonic 16 (-2.275) 289.82
,Harmonic 17 (-2.944) 132.67
,Harmonic 18 1.906 106.65
,Harmonic 19 (-1.234) 102.74
,Harmonic 20 1.384 38.72
,Harmonic 21 (-2.974) 33.25
,Harmonic 22 2.513 41.59
,Harmonic 23 1.054 35.67
,Harmonic 24 (-2.215) 37.29
,Harmonic 25 0.827 10.47
,Harmonic 26 0.462 61.63
,Harmonic 27 0.139 43.86
,Harmonic 28 (-8.3e-2) 21.85]
note18 :: Note
note18 = Note
(Pitch 369.994 54 "f#4")
19
(Range
(NoteRange
(NoteRangeAmplitude 8879.85 24 7.43)
(NoteRangeHarmonicFreq 1 369.99))
(NoteRange
(NoteRangeAmplitude 1479.97 4 7675.0)
(NoteRangeHarmonicFreq 26 9619.84)))
[Harmonic 1 2.219 7591.78
,Harmonic 2 1.026 1324.87
,Harmonic 3 (-2.264) 1335.54
,Harmonic 4 (-1.062) 7675.0
,Harmonic 5 (-3.051) 1719.38
,Harmonic 6 (-1.706) 3738.3
,Harmonic 7 (-0.73) 1080.39
,Harmonic 8 (-1.65) 111.77
,Harmonic 9 2.936 316.49
,Harmonic 10 0.469 396.42
,Harmonic 11 3.037 531.54
,Harmonic 12 0.906 216.47
,Harmonic 13 (-2.819) 151.12
,Harmonic 14 (-2.974) 235.26
,Harmonic 15 0.429 115.38
,Harmonic 16 1.201 64.39
,Harmonic 17 (-2.932) 20.39
,Harmonic 18 (-0.133) 38.5
,Harmonic 19 (-1.239) 9.31
,Harmonic 20 2.181 58.37
,Harmonic 21 (-0.722) 30.39
,Harmonic 22 2.611 29.51
,Harmonic 23 1.606 28.26
,Harmonic 24 (-3.106) 7.43
,Harmonic 25 (-0.599) 15.39
,Harmonic 26 2.371 37.24]
note19 :: Note
note19 = Note
(Pitch 391.995 55 "g4")
20
(Range
(NoteRange
(NoteRangeAmplitude 7055.91 18 17.01)
(NoteRangeHarmonicFreq 1 391.99))
(NoteRange
(NoteRangeAmplitude 391.99 1 6129.0)
(NoteRangeHarmonicFreq 25 9799.87)))
[Harmonic 1 (-1.608) 6129.0
,Harmonic 2 0.496 1388.75
,Harmonic 3 2.047 3283.16
,Harmonic 4 0.55 5569.24
,Harmonic 5 (-2.572) 3979.83
,Harmonic 6 (-8.1e-2) 1567.27
,Harmonic 7 2.402 1409.07
,Harmonic 8 1.185 1191.46
,Harmonic 9 (-0.114) 1156.36
,Harmonic 10 2.378 1098.84
,Harmonic 11 2.772 368.14
,Harmonic 12 (-2.575) 181.44
,Harmonic 13 2.832 250.63
,Harmonic 14 1.217 203.72
,Harmonic 15 (-1.132) 25.79
,Harmonic 16 2.966 68.67
,Harmonic 17 (-1.314) 102.22
,Harmonic 18 2.523 17.01
,Harmonic 19 0.474 113.16
,Harmonic 20 2.9e-2 55.76
,Harmonic 21 (-2.031) 69.82
,Harmonic 22 (-2.29) 27.5
,Harmonic 23 7.0e-2 52.9
,Harmonic 24 1.35 62.34
,Harmonic 25 (-2.16) 28.26]
note20 :: Note
note20 = Note
(Pitch 415.305 56 "g#4")
21
(Range
(NoteRange
(NoteRangeAmplitude 7475.49 18 2.14)
(NoteRangeHarmonicFreq 1 415.3))
(NoteRange
(NoteRangeAmplitude 1245.91 3 6522.0)
(NoteRangeHarmonicFreq 23 9552.01)))
[Harmonic 1 (-0.97) 5184.39
,Harmonic 2 2.723 1538.56
,Harmonic 3 3.112 6522.0
,Harmonic 4 0.609 3871.29
,Harmonic 5 1.504 3033.58
,Harmonic 6 (-2.681) 1783.49
,Harmonic 7 (-2.638) 2625.95
,Harmonic 8 (-0.558) 232.59
,Harmonic 9 (-2.651) 1316.22
,Harmonic 10 1.743 309.75
,Harmonic 11 0.663 264.46
,Harmonic 12 (-2.361) 257.17
,Harmonic 13 (-0.202) 44.15
,Harmonic 14 2.825 184.83
,Harmonic 15 2.306 35.95
,Harmonic 16 2.125 57.46
,Harmonic 17 (-2.91) 32.95
,Harmonic 18 (-2.772) 2.14
,Harmonic 19 2.297 17.8
,Harmonic 20 (-1.166) 6.96
,Harmonic 21 0.995 14.45
,Harmonic 22 (-2.66) 10.58
,Harmonic 23 (-2.047) 10.57]
note21 :: Note
note21 = Note
(Pitch 440.0 57 "a4")
22
(Range
(NoteRange
(NoteRangeAmplitude 9240.0 21 18.52)
(NoteRangeHarmonicFreq 1 440.0))
(NoteRange
(NoteRangeAmplitude 440.0 1 5433.0)
(NoteRangeHarmonicFreq 22 9680.0)))
[Harmonic 1 (-2.408) 5433.0
,Harmonic 2 2.659 1020.55
,Harmonic 3 1.457 2541.88
,Harmonic 4 (-2.744) 998.74
,Harmonic 5 (-1.573) 4585.86
,Harmonic 6 (-0.558) 2102.96
,Harmonic 7 0.342 1178.77
,Harmonic 8 (-0.188) 1287.95
,Harmonic 9 (-0.435) 1599.37
,Harmonic 10 1.496 441.93
,Harmonic 11 (-2.485) 219.43
,Harmonic 12 (-0.507) 370.0
,Harmonic 13 0.35 70.1
,Harmonic 14 0.605 88.45
,Harmonic 15 (-1.377) 109.58
,Harmonic 16 0.131 40.15
,Harmonic 17 (-1.859) 60.03
,Harmonic 18 (-1.004) 113.08
,Harmonic 19 (-2.998) 69.64
,Harmonic 20 (-1.159) 111.67
,Harmonic 21 (-0.243) 18.52
,Harmonic 22 (-2.58) 44.34]
note22 :: Note
note22 = Note
(Pitch 466.164 58 "a#4")
23
(Range
(NoteRange
(NoteRangeAmplitude 9789.44 21 30.01)
(NoteRangeHarmonicFreq 1 466.16))
(NoteRange
(NoteRangeAmplitude 466.16 1 8241.0)
(NoteRangeHarmonicFreq 21 9789.44)))
[Harmonic 1 1.719 8241.0
,Harmonic 2 4.4e-2 1040.23
,Harmonic 3 2.599 1695.66
,Harmonic 4 (-0.406) 2248.4
,Harmonic 5 2.248 1040.75
,Harmonic 6 0.626 2052.03
,Harmonic 7 1.787 366.76
,Harmonic 8 1.83 1015.79
,Harmonic 9 (-1.685) 582.08
,Harmonic 10 (-1.558) 277.45
,Harmonic 11 1.337 66.38
,Harmonic 12 0.909 200.23
,Harmonic 13 (-2.988) 256.95
,Harmonic 14 (-1.499) 114.04
,Harmonic 15 1.422 36.25
,Harmonic 16 0.474 83.51
,Harmonic 17 2.861 39.34
,Harmonic 18 (-1.9) 51.06
,Harmonic 19 1.615 97.7
,Harmonic 20 0.971 46.11
,Harmonic 21 1.917 30.01]
note23 :: Note
note23 = Note
(Pitch 493.883 59 "b4")
24
(Range
(NoteRange
(NoteRangeAmplitude 8396.01 17 11.78)
(NoteRangeHarmonicFreq 1 493.88))
(NoteRange
(NoteRangeAmplitude 493.88 1 7498.0)
(NoteRangeHarmonicFreq 20 9877.66)))
[Harmonic 1 (-2.161) 7498.0
,Harmonic 2 (-0.726) 1638.17
,Harmonic 3 (-1.448) 6237.67
,Harmonic 4 3.116 3204.73
,Harmonic 5 (-1.043) 1186.58
,Harmonic 6 (-1.279) 1748.25
,Harmonic 7 2.023 420.44
,Harmonic 8 (-7.6e-2) 1370.7
,Harmonic 9 (-0.597) 505.84
,Harmonic 10 (-1.24) 548.75
,Harmonic 11 (-2.155) 186.13
,Harmonic 12 (-1.586) 173.18
,Harmonic 13 (-1.583) 305.74
,Harmonic 14 2.453 98.6
,Harmonic 15 (-0.737) 31.75
,Harmonic 16 (-0.749) 97.04
,Harmonic 17 3.04 11.78
,Harmonic 18 (-2.907) 24.69
,Harmonic 19 1.8 37.81
,Harmonic 20 (-1.514) 45.4]
note24 :: Note
note24 = Note
(Pitch 523.251 60 "c5")
25
(Range
(NoteRange
(NoteRangeAmplitude 7848.76 15 7.47)
(NoteRangeHarmonicFreq 1 523.25))
(NoteRange
(NoteRangeAmplitude 1569.75 3 6561.0)
(NoteRangeHarmonicFreq 19 9941.76)))
[Harmonic 1 2.216 2658.8
,Harmonic 2 0.751 3080.38
,Harmonic 3 1.14 6561.0
,Harmonic 4 1.241 4529.37
,Harmonic 5 (-0.353) 507.46
,Harmonic 6 2.847 1503.43
,Harmonic 7 (-2.105) 1053.57
,Harmonic 8 1.264 680.26
,Harmonic 9 2.151 241.65
,Harmonic 10 2.007 406.73
,Harmonic 11 0.683 636.65
,Harmonic 12 (-1.682) 677.39
,Harmonic 13 (-1.193) 138.13
,Harmonic 14 2.211 131.81
,Harmonic 15 2.591 7.47
,Harmonic 16 (-1.105) 24.53
,Harmonic 17 0.745 47.39
,Harmonic 18 (-1.861) 23.11
,Harmonic 19 (-1.434) 14.09]
note25 :: Note
note25 = Note
(Pitch 554.365 61 "c#5")
26
(Range
(NoteRange
(NoteRangeAmplitude 9424.2 17 13.77)
(NoteRangeHarmonicFreq 1 554.36))
(NoteRange
(NoteRangeAmplitude 1663.09 3 3873.0)
(NoteRangeHarmonicFreq 18 9978.57)))
[Harmonic 1 1.988 914.19
,Harmonic 2 (-2.412) 1805.84
,Harmonic 3 (-1.24) 3873.0
,Harmonic 4 (-2.407) 1980.98
,Harmonic 5 (-2.193) 2383.19
,Harmonic 6 1.517 616.16
,Harmonic 7 (-0.539) 1337.55
,Harmonic 8 (-3.103) 634.16
,Harmonic 9 0.452 605.15
,Harmonic 10 0.506 214.27
,Harmonic 11 2.23 233.94
,Harmonic 12 (-1.72) 90.11
,Harmonic 13 1.852 142.24
,Harmonic 14 (-0.481) 195.77
,Harmonic 15 (-0.584) 18.93
,Harmonic 16 2.335 105.44
,Harmonic 17 (-2.869) 13.77
,Harmonic 18 1.171 130.05]
note26 :: Note
note26 = Note
(Pitch 587.33 62 "d5")
27
(Range
(NoteRange
(NoteRangeAmplitude 8809.95 15 29.85)
(NoteRangeHarmonicFreq 1 587.33))
(NoteRange
(NoteRangeAmplitude 1174.66 2 3815.0)
(NoteRangeHarmonicFreq 17 9984.61)))
[Harmonic 1 (-2.753) 2881.62
,Harmonic 2 (-8.9e-2) 3815.0
,Harmonic 3 (-3.139) 3488.34
,Harmonic 4 (-1.163) 1879.4
,Harmonic 5 (-1.972) 2400.28
,Harmonic 6 (-2.642) 703.07
,Harmonic 7 1.083 320.77
,Harmonic 8 (-2.661) 898.26
,Harmonic 9 (-2.893) 891.15
,Harmonic 10 (-2.287) 609.16
,Harmonic 11 (-3.092) 306.91
,Harmonic 12 (-1.828) 117.91
,Harmonic 13 1.763 150.46
,Harmonic 14 (-1.889) 43.46
,Harmonic 15 0.138 29.85
,Harmonic 16 0.519 66.36
,Harmonic 17 2.682 52.65]
note27 :: Note
note27 = Note
(Pitch 622.254 63 "d#5")
28
(Range
(NoteRange
(NoteRangeAmplitude 8711.55 14 6.97)
(NoteRangeHarmonicFreq 1 622.25))
(NoteRange
(NoteRangeAmplitude 1244.5 2 5801.0)
(NoteRangeHarmonicFreq 16 9956.06)))
[Harmonic 1 2.448 3152.14
,Harmonic 2 2.042 5801.0
,Harmonic 3 (-0.332) 3357.98
,Harmonic 4 1.658 3124.3
,Harmonic 5 0.932 340.75
,Harmonic 6 (-7.0e-2) 3081.96
,Harmonic 7 2.041 1313.03
,Harmonic 8 (-0.924) 1179.4
,Harmonic 9 1.606 269.07
,Harmonic 10 (-1.976) 137.27
,Harmonic 11 (-1.07) 89.47
,Harmonic 12 0.711 190.19
,Harmonic 13 (-2.383) 221.3
,Harmonic 14 (-2.663) 6.97
,Harmonic 15 (-3.12) 47.94
,Harmonic 16 1.898 104.9]
note28 :: Note
note28 = Note
(Pitch 659.255 64 "e5")
29
(Range
(NoteRange
(NoteRangeAmplitude 9888.82 15 25.37)
(NoteRangeHarmonicFreq 1 659.25))
(NoteRange
(NoteRangeAmplitude 1318.51 2 5079.0)
(NoteRangeHarmonicFreq 15 9888.82)))
[Harmonic 1 (-0.738) 2878.03
,Harmonic 2 (-2.502) 5079.0
,Harmonic 3 1.368 3714.07
,Harmonic 4 (-1.653) 1502.53
,Harmonic 5 0.693 515.56
,Harmonic 6 (-0.254) 1731.13
,Harmonic 7 (-0.237) 657.64
,Harmonic 8 0.809 652.02
,Harmonic 9 (-2.779) 353.49
,Harmonic 10 0.903 183.65
,Harmonic 11 (-0.206) 82.73
,Harmonic 12 2.642 112.56
,Harmonic 13 1.082 76.27
,Harmonic 14 2.608 25.38
,Harmonic 15 (-2.327) 25.37]
note29 :: Note
note29 = Note
(Pitch 698.456 65 "f5")
30
(Range
(NoteRange
(NoteRangeAmplitude 9778.38 14 8.34)
(NoteRangeHarmonicFreq 1 698.45))
(NoteRange
(NoteRangeAmplitude 2095.36 3 3019.0)
(NoteRangeHarmonicFreq 14 9778.38)))
[Harmonic 1 (-1.611) 287.27
,Harmonic 2 (-1.955) 2094.7
,Harmonic 3 (-1.04) 3019.0
,Harmonic 4 (-1.914) 2477.51
,Harmonic 5 3.033 1189.66
,Harmonic 6 (-2.139) 833.07
,Harmonic 7 2.314 264.84
,Harmonic 8 2.002 126.98
,Harmonic 9 (-0.856) 59.03
,Harmonic 10 1.193 201.53
,Harmonic 11 0.374 66.62
,Harmonic 12 1.501 50.35
,Harmonic 13 0.402 17.76
,Harmonic 14 2.585 8.34]
note30 :: Note
note30 = Note
(Pitch 739.989 66 "f#5")
31
(Range
(NoteRange
(NoteRangeAmplitude 9619.85 13 90.07)
(NoteRangeHarmonicFreq 1 739.98))
(NoteRange
(NoteRangeAmplitude 1479.97 2 5275.0)
(NoteRangeHarmonicFreq 13 9619.85)))
[Harmonic 1 2.215 2914.6
,Harmonic 2 (-1.076) 5275.0
,Harmonic 3 (-2.089) 4251.75
,Harmonic 4 (-2.267) 1883.68
,Harmonic 5 0.434 3193.9
,Harmonic 6 (-1.781) 1236.65
,Harmonic 7 (-2.839) 843.44
,Harmonic 8 2.792 640.09
,Harmonic 9 0.853 266.03
,Harmonic 10 2.618 495.05
,Harmonic 11 1.839 98.93
,Harmonic 12 (-0.791) 96.66
,Harmonic 13 1.122 90.07]
note31 :: Note
note31 = Note
(Pitch 783.991 67 "g5")
32
(Range
(NoteRange
(NoteRangeAmplitude 8623.9 11 29.31)
(NoteRangeHarmonicFreq 1 783.99))
(NoteRange
(NoteRangeAmplitude 1567.98 2 9526.0)
(NoteRangeHarmonicFreq 12 9407.89)))
[Harmonic 1 2.919 162.38
,Harmonic 2 1.409 9526.0
,Harmonic 3 1.725 735.93
,Harmonic 4 (-2.464) 1232.79
,Harmonic 5 0.392 1473.24
,Harmonic 6 (-1.565) 326.76
,Harmonic 7 0.827 524.14
,Harmonic 8 2.442 433.83
,Harmonic 9 (-1.811) 417.2
,Harmonic 10 (-2.53) 118.08
,Harmonic 11 (-2.748) 29.31
,Harmonic 12 (-1.069) 36.13]
note32 :: Note
note32 = Note
(Pitch 830.609 68 "g#5")
33
(Range
(NoteRange
(NoteRangeAmplitude 8306.09 10 11.02)
(NoteRangeHarmonicFreq 1 830.6))
(NoteRange
(NoteRangeAmplitude 1661.21 2 3256.0)
(NoteRangeHarmonicFreq 12 9967.3)))
[Harmonic 1 (-1.602) 639.54
,Harmonic 2 (-1.523) 3256.0
,Harmonic 3 3.091 665.41
,Harmonic 4 2.212 439.47
,Harmonic 5 1.679 715.64
,Harmonic 6 (-1.872) 445.58
,Harmonic 7 1.49 273.09
,Harmonic 8 1.9e-2 120.89
,Harmonic 9 (-1.184) 84.44
,Harmonic 10 1.716 11.02
,Harmonic 11 (-0.486) 57.28
,Harmonic 12 1.729 59.97]
note33 :: Note
note33 = Note
(Pitch 880.0 69 "a5")
34
(Range
(NoteRange
(NoteRangeAmplitude 7920.0 9 20.37)
(NoteRangeHarmonicFreq 1 880.0))
(NoteRange
(NoteRangeAmplitude 2640.0 3 1686.0)
(NoteRangeHarmonicFreq 11 9680.0)))
[Harmonic 1 (-1.18) 661.8
,Harmonic 2 3.017 1230.51
,Harmonic 3 (-1.57) 1686.0
,Harmonic 4 (-1.239) 65.5
,Harmonic 5 2.702 602.05
,Harmonic 6 (-1.857) 478.9
,Harmonic 7 (-2.967) 326.2
,Harmonic 8 (-0.507) 177.24
,Harmonic 9 (-1.436) 20.37
,Harmonic 10 (-2.033) 24.82
,Harmonic 11 (-1.593) 21.62]
note34 :: Note
note34 = Note
(Pitch 932.328 70 "a#5")
35
(Range
(NoteRange
(NoteRangeAmplitude 8390.95 9 31.0)
(NoteRangeHarmonicFreq 1 932.32))
(NoteRange
(NoteRangeAmplitude 2796.98 3 3827.0)
(NoteRangeHarmonicFreq 10 9323.27)))
[Harmonic 1 2.729 1739.76
,Harmonic 2 0.618 3022.85
,Harmonic 3 0.959 3827.0
,Harmonic 4 1.165 1403.38
,Harmonic 5 2.288 213.53
,Harmonic 6 0.168 89.82
,Harmonic 7 (-3.5e-2) 94.02
,Harmonic 8 2.837 111.27
,Harmonic 9 (-2.376) 31.0
,Harmonic 10 (-2.092) 39.66]
note35 :: Note
note35 = Note
(Pitch 987.767 71 "b5")
36
(Range
(NoteRange
(NoteRangeAmplitude 9877.67 10 46.26)
(NoteRangeHarmonicFreq 1 987.76))
(NoteRange
(NoteRangeAmplitude 1975.53 2 2994.0)
(NoteRangeHarmonicFreq 10 9877.67)))
[Harmonic 1 (-0.956) 2257.56
,Harmonic 2 2.173 2994.0
,Harmonic 3 (-1.816) 615.05
,Harmonic 4 (-1.856) 1793.92
,Harmonic 5 (-1.694) 1012.59
,Harmonic 6 (-2.69) 1012.24
,Harmonic 7 2.548 107.07
,Harmonic 8 (-0.671) 145.76
,Harmonic 9 (-0.819) 132.18
,Harmonic 10 0.467 46.26]
note36 :: Note
note36 = Note
(Pitch 1046.5 72 "c6")
37
(Range
(NoteRange
(NoteRangeAmplitude 7325.5 7 67.6)
(NoteRangeHarmonicFreq 1 1046.5))
(NoteRange
(NoteRangeAmplitude 2093.0 2 4242.0)
(NoteRangeHarmonicFreq 9 9418.5)))
[Harmonic 1 (-0.873) 2617.16
,Harmonic 2 (-2.35) 4242.0
,Harmonic 3 (-1.181) 1356.33
,Harmonic 4 2.775 1125.42
,Harmonic 5 1.449 580.39
,Harmonic 6 2.022 431.31
,Harmonic 7 (-0.927) 67.6
,Harmonic 8 1.932 333.39
,Harmonic 9 2.219 259.1]
note37 :: Note
note37 = Note
(Pitch 1108.73 73 "c#6")
38
(Range
(NoteRange
(NoteRangeAmplitude 9978.57 9 2.7)
(NoteRangeHarmonicFreq 1 1108.73))
(NoteRange
(NoteRangeAmplitude 2217.46 2 2180.0)
(NoteRangeHarmonicFreq 9 9978.57)))
[Harmonic 1 1.417 1029.56
,Harmonic 2 (-1.859) 2180.0
,Harmonic 3 (-2.662) 482.16
,Harmonic 4 (-1.211) 295.94
,Harmonic 5 (-1.738) 108.27
,Harmonic 6 1.321 166.75
,Harmonic 7 2.461 91.77
,Harmonic 8 (-0.359) 98.52
,Harmonic 9 2.175 2.7]
note38 :: Note
note38 = Note
(Pitch 1174.66 74 "d6")
39
(Range
(NoteRange
(NoteRangeAmplitude 9397.28 8 13.99)
(NoteRangeHarmonicFreq 1 1174.66))
(NoteRange
(NoteRangeAmplitude 1174.66 1 2549.0)
(NoteRangeHarmonicFreq 8 9397.28)))
[Harmonic 1 (-1.896) 2549.0
,Harmonic 2 1.206 1060.86
,Harmonic 3 (-2.321) 404.24
,Harmonic 4 (-2.006) 180.37
,Harmonic 5 (-2.603) 404.86
,Harmonic 6 9.9e-2 85.92
,Harmonic 7 0.685 55.07
,Harmonic 8 (-1.956) 13.99] | null | https://raw.githubusercontent.com/anton-k/sharc-timbre/14be260021c02f31905b3e63269f582030a45c8d/src/Sharc/Instruments/Viola.hs | haskell | module Sharc.Instruments.Viola (viola) where
import Sharc.Types
viola :: Instr
viola = Instr
"viola_vibrato"
"Viola"
(Legend "McGill" "1" "6")
(Range
(InstrRange
(HarmonicFreq 1 (Pitch 130.81 36 "c3"))
(Pitch 130.81 36 "c3")
(Amplitude 8372.03 (HarmonicFreq 64 (Pitch 130.813 36 "c3")) 0.13))
(InstrRange
(HarmonicFreq 58 (Pitch 10127.61 41 "f3"))
(Pitch 1174.66 74 "d6")
(Amplitude 233.08 (HarmonicFreq 1 (Pitch 233.082 46 "a#3")) 15064.0)))
[note0
,note1
,note2
,note3
,note4
,note5
,note6
,note7
,note8
,note9
,note10
,note11
,note12
,note13
,note14
,note15
,note16
,note17
,note18
,note19
,note20
,note21
,note22
,note23
,note24
,note25
,note26
,note27
,note28
,note29
,note30
,note31
,note32
,note33
,note34
,note35
,note36
,note37
,note38]
note0 :: Note
note0 = Note
(Pitch 130.813 36 "c3")
1
(Range
(NoteRange
(NoteRangeAmplitude 8372.03 64 0.13)
(NoteRangeHarmonicFreq 1 130.81))
(NoteRange
(NoteRangeAmplitude 261.62 2 6050.0)
(NoteRangeHarmonicFreq 76 9941.78)))
[Harmonic 1 (-1.737) 143.33
,Harmonic 2 (-0.361) 6050.0
,Harmonic 3 (-1.376) 4471.52
,Harmonic 4 (-3.095) 3116.69
,Harmonic 5 (-1.708) 2813.13
,Harmonic 6 (-1.712) 3094.79
,Harmonic 7 (-1.402) 823.26
,Harmonic 8 3.096 4538.32
,Harmonic 9 0.716 1644.78
,Harmonic 10 (-2.288) 1971.2
,Harmonic 11 (-1.953) 1790.56
,Harmonic 12 (-1.976) 1535.71
,Harmonic 13 (-2.834) 456.34
,Harmonic 14 (-0.418) 1698.59
,Harmonic 15 0.448 1109.26
,Harmonic 16 (-1.771) 1055.89
,Harmonic 17 3.091 675.94
,Harmonic 18 2.688 281.65
,Harmonic 19 1.122 133.54
,Harmonic 20 1.266 323.49
,Harmonic 21 (-0.231) 534.58
,Harmonic 22 (-2.582) 312.86
,Harmonic 23 (-0.508) 78.28
,Harmonic 24 (-3.066) 185.09
,Harmonic 25 1.527 81.84
,Harmonic 26 0.323 52.88
,Harmonic 27 1.041 58.49
,Harmonic 28 1.483 128.93
,Harmonic 29 (-0.383) 235.71
,Harmonic 30 (-1.999) 199.47
,Harmonic 31 (-1.399) 94.82
,Harmonic 32 (-3.137) 72.25
,Harmonic 33 1.045 22.95
,Harmonic 34 6.4e-2 26.22
,Harmonic 35 (-0.509) 18.03
,Harmonic 36 2.65 22.63
,Harmonic 37 0.631 51.42
,Harmonic 38 1.766 47.95
,Harmonic 39 (-1.833) 36.2
,Harmonic 40 2.236 36.85
,Harmonic 41 0.358 16.08
,Harmonic 42 (-0.427) 5.42
,Harmonic 43 2.76 26.67
,Harmonic 44 1.4 29.1
,Harmonic 45 1.7e-2 18.2
,Harmonic 46 (-0.871) 15.15
,Harmonic 47 (-1.892) 16.48
,Harmonic 48 (-1.645) 1.28
,Harmonic 49 2.771 10.84
,Harmonic 50 1.705 6.4
,Harmonic 51 0.861 4.87
,Harmonic 52 (-1.572) 3.59
,Harmonic 53 (-2.172) 4.72
,Harmonic 54 (-2.228) 3.61
,Harmonic 55 2.928 10.46
,Harmonic 56 0.712 4.25
,Harmonic 57 0.342 5.22
,Harmonic 58 (-7.0e-3) 11.81
,Harmonic 59 (-0.641) 13.31
,Harmonic 60 (-1.002) 9.35
,Harmonic 61 (-1.449) 7.17
,Harmonic 62 (-2.112) 4.1
,Harmonic 63 2.493 2.23
,Harmonic 64 (-1.735) 0.13
,Harmonic 65 (-1.922) 2.59
,Harmonic 66 1.499 1.13
,Harmonic 67 (-8.0e-2) 1.31
,Harmonic 68 (-1.463) 3.17
,Harmonic 69 (-2.433) 3.35
,Harmonic 70 (-3.056) 4.41
,Harmonic 71 2.39 7.2
,Harmonic 72 1.665 10.61
,Harmonic 73 0.965 9.37
,Harmonic 74 0.525 4.63
,Harmonic 75 1.151 3.47
,Harmonic 76 2.351 2.3]
note1 :: Note
note1 = Note
(Pitch 138.591 37 "c#3")
2
(Range
(NoteRange
(NoteRangeAmplitude 8731.23 63 2.47)
(NoteRangeHarmonicFreq 1 138.59))
(NoteRange
(NoteRangeAmplitude 692.95 5 7155.0)
(NoteRangeHarmonicFreq 72 9978.55)))
[Harmonic 1 (-1.366) 339.29
,Harmonic 2 2.541 6245.16
,Harmonic 3 1.512 5420.62
,Harmonic 4 0.506 7117.55
,Harmonic 5 2.116 7155.0
,Harmonic 6 2.865 6795.0
,Harmonic 7 (-0.978) 4657.18
,Harmonic 8 1.648 2281.12
,Harmonic 9 1.553 6013.29
,Harmonic 10 0.846 4558.98
,Harmonic 11 0.734 2667.41
,Harmonic 12 2.488 1877.8
,Harmonic 13 0.472 1662.64
,Harmonic 14 1.555 741.53
,Harmonic 15 1.17 2128.55
,Harmonic 16 (-4.5e-2) 1310.88
,Harmonic 17 (-0.456) 145.48
,Harmonic 18 3.134 164.67
,Harmonic 19 1.327 257.88
,Harmonic 20 0.312 667.32
,Harmonic 21 (-2.213) 476.89
,Harmonic 22 0.422 580.86
,Harmonic 23 (-0.207) 409.94
,Harmonic 24 (-0.896) 339.64
,Harmonic 25 2.169 245.94
,Harmonic 26 0.89 579.16
,Harmonic 27 0.124 790.47
,Harmonic 28 (-0.21) 535.37
,Harmonic 29 (-0.654) 130.35
,Harmonic 30 0.109 61.82
,Harmonic 31 1.061 146.09
,Harmonic 32 1.782 131.01
,Harmonic 33 1.745 73.99
,Harmonic 34 2.895 37.3
,Harmonic 35 (-1.63) 23.14
,Harmonic 36 (-2.723) 29.25
,Harmonic 37 0.171 40.0
,Harmonic 38 0.294 18.51
,Harmonic 39 (-2.874) 26.58
,Harmonic 40 (-2.646) 43.69
,Harmonic 41 1.6e-2 9.16
,Harmonic 42 (-1.631) 12.86
,Harmonic 43 (-0.433) 8.26
,Harmonic 44 2.82 4.84
,Harmonic 45 (-0.914) 7.52
,Harmonic 46 (-2.512) 6.68
,Harmonic 47 2.903 3.43
,Harmonic 48 (-1.314) 9.12
,Harmonic 49 (-0.122) 16.59
,Harmonic 50 0.515 13.63
,Harmonic 51 2.471 10.42
,Harmonic 52 (-1.801) 7.09
,Harmonic 53 (-0.719) 3.42
,Harmonic 54 0.559 18.31
,Harmonic 55 1.557 26.59
,Harmonic 56 2.307 24.72
,Harmonic 57 (-2.894) 32.41
,Harmonic 58 (-2.968) 21.84
,Harmonic 59 3.002 9.16
,Harmonic 60 2.577 4.05
,Harmonic 61 2.803 3.87
,Harmonic 62 9.0e-2 3.16
,Harmonic 63 (-1.151) 2.47
,Harmonic 64 (-1.035) 6.33
,Harmonic 65 (-2.8e-2) 7.14
,Harmonic 66 0.69 5.32
,Harmonic 67 2.082 6.18
,Harmonic 68 (-3.056) 9.71
,Harmonic 69 (-2.059) 10.52
,Harmonic 70 (-1.277) 11.72
,Harmonic 71 (-2.3e-2) 6.92
,Harmonic 72 0.736 7.92]
note2 :: Note
note2 = Note
(Pitch 146.832 38 "d3")
3
(Range
(NoteRange
(NoteRangeAmplitude 8809.92 60 0.74)
(NoteRangeHarmonicFreq 1 146.83))
(NoteRange
(NoteRangeAmplitude 293.66 2 7702.0)
(NoteRangeHarmonicFreq 68 9984.57)))
[Harmonic 1 2.964 267.42
,Harmonic 2 (-1.338) 7702.0
,Harmonic 3 3.075 4292.1
,Harmonic 4 0.388 884.14
,Harmonic 5 1.104 3113.29
,Harmonic 6 (-0.492) 1823.19
,Harmonic 7 (-0.884) 2545.5
,Harmonic 8 1.416 1139.72
,Harmonic 9 (-1.081) 1505.61
,Harmonic 10 (-2.734) 2574.99
,Harmonic 11 2.878 985.19
,Harmonic 12 (-0.886) 144.89
,Harmonic 13 3.113 315.67
,Harmonic 14 2.975 1173.4
,Harmonic 15 1.3 334.39
,Harmonic 16 (-1.088) 296.83
,Harmonic 17 (-0.641) 195.09
,Harmonic 18 (-2.721) 92.4
,Harmonic 19 0.176 226.08
,Harmonic 20 1.528 177.68
,Harmonic 21 2.438 211.04
,Harmonic 22 0.67 379.87
,Harmonic 23 (-0.181) 138.67
,Harmonic 24 (-0.893) 281.81
,Harmonic 25 (-2.711) 267.94
,Harmonic 26 1.427 227.46
,Harmonic 27 (-1.83) 313.65
,Harmonic 28 (-2.861) 165.69
,Harmonic 29 2.432 107.83
,Harmonic 30 1.472 55.82
,Harmonic 31 (-2.715) 39.01
,Harmonic 32 1.999 29.31
,Harmonic 33 0.627 48.49
,Harmonic 34 (-1.462) 41.17
,Harmonic 35 (-0.789) 30.69
,Harmonic 36 2.869 50.57
,Harmonic 37 1.071 15.23
,Harmonic 38 (-1.076) 4.74
,Harmonic 39 (-0.772) 6.48
,Harmonic 40 (-1.858) 7.65
,Harmonic 41 (-2.521) 13.38
,Harmonic 42 2.579 19.86
,Harmonic 43 0.89 18.18
,Harmonic 44 1.364 4.44
,Harmonic 45 (-1.437) 11.76
,Harmonic 46 (-3.115) 9.11
,Harmonic 47 0.379 6.69
,Harmonic 48 (-2.189) 2.92
,Harmonic 49 2.887 2.16
,Harmonic 50 0.797 4.23
,Harmonic 51 (-2.963) 9.53
,Harmonic 52 1.84 7.41
,Harmonic 53 2.097 6.46
,Harmonic 54 0.17 7.96
,Harmonic 55 (-1.709) 4.66
,Harmonic 56 (-1.923) 2.91
,Harmonic 57 (-2.652) 3.52
,Harmonic 58 2.246 2.48
,Harmonic 59 (-1.615) 1.08
,Harmonic 60 (-1.784) 0.74
,Harmonic 61 2.16 3.25
,Harmonic 62 1.081 1.92
,Harmonic 63 (-0.38) 3.39
,Harmonic 64 (-1.428) 3.95
,Harmonic 65 (-2.925) 2.72
,Harmonic 66 (-3.015) 4.11
,Harmonic 67 2.107 2.77
,Harmonic 68 2.475 2.26]
note3 :: Note
note3 = Note
(Pitch 155.563 39 "d#3")
4
(Range
(NoteRange
(NoteRangeAmplitude 7155.89 46 0.25)
(NoteRangeHarmonicFreq 1 155.56))
(NoteRange
(NoteRangeAmplitude 466.68 3 9957.0)
(NoteRangeHarmonicFreq 64 9956.03)))
[Harmonic 1 (-2.798) 508.38
,Harmonic 2 (-0.302) 5737.84
,Harmonic 3 (-1.76) 9957.0
,Harmonic 4 (-1.64) 3843.32
,Harmonic 5 (-2.718) 3575.43
,Harmonic 6 (-2.539) 903.49
,Harmonic 7 (-0.238) 1450.92
,Harmonic 8 (-2.034) 2701.61
,Harmonic 9 2.976 1953.81
,Harmonic 10 2.453 678.73
,Harmonic 11 1.17 755.25
,Harmonic 12 (-2.054) 1979.05
,Harmonic 13 (-1.813) 2207.36
,Harmonic 14 2.132 1333.44
,Harmonic 15 1.435 277.64
,Harmonic 16 (-2.221) 71.68
,Harmonic 17 0.179 230.39
,Harmonic 18 (-1.562) 282.81
,Harmonic 19 (-0.519) 490.79
,Harmonic 20 1.076 553.6
,Harmonic 21 (-0.641) 229.89
,Harmonic 22 (-9.0e-2) 108.47
,Harmonic 23 (-0.949) 221.27
,Harmonic 24 (-1.976) 154.96
,Harmonic 25 2.465 155.07
,Harmonic 26 0.879 271.89
,Harmonic 27 (-4.7e-2) 214.75
,Harmonic 28 (-1.324) 80.69
,Harmonic 29 1.787 19.97
,Harmonic 30 0.107 43.72
,Harmonic 31 (-0.324) 34.21
,Harmonic 32 (-1.63) 14.53
,Harmonic 33 0.974 51.32
,Harmonic 34 (-0.974) 28.13
,Harmonic 35 (-2.626) 15.56
,Harmonic 36 1.429 10.66
,Harmonic 37 2.066 22.34
,Harmonic 38 1.458 54.09
,Harmonic 39 0.463 34.84
,Harmonic 40 (-0.54) 22.49
,Harmonic 41 1.429 6.91
,Harmonic 42 0.343 10.54
,Harmonic 43 (-2.759) 5.24
,Harmonic 44 0.936 0.85
,Harmonic 45 (-2.118) 1.48
,Harmonic 46 2.468 0.25
,Harmonic 47 (-2.36) 5.16
,Harmonic 48 2.693 6.64
,Harmonic 49 1.443 4.53
,Harmonic 50 1.038 6.18
,Harmonic 51 1.431 3.94
,Harmonic 52 0.576 8.15
,Harmonic 53 (-0.532) 7.66
,Harmonic 54 (-0.974) 1.52
,Harmonic 55 (-1.277) 2.32
,Harmonic 56 2.01 2.98
,Harmonic 57 2.281 9.57
,Harmonic 58 1.884 10.47
,Harmonic 59 1.728 5.7
,Harmonic 60 0.474 1.64
,Harmonic 61 (-1.458) 1.79
,Harmonic 62 (-3.09) 1.95
,Harmonic 63 (-1.084) 3.63
,Harmonic 64 (-1.608) 2.67]
note4 :: Note
note4 = Note
(Pitch 164.814 40 "e3")
5
(Range
(NoteRange
(NoteRangeAmplitude 7746.25 47 0.98)
(NoteRangeHarmonicFreq 1 164.81))
(NoteRange
(NoteRangeAmplitude 494.44 3 5938.0)
(NoteRangeHarmonicFreq 61 10053.65)))
[Harmonic 1 (-0.424) 262.27
,Harmonic 2 (-1.771) 4565.41
,Harmonic 3 (-1.636) 5938.0
,Harmonic 4 1.679 2034.66
,Harmonic 5 (-3.115) 2889.35
,Harmonic 6 (-8.0e-3) 2638.09
,Harmonic 7 (-2.857) 972.25
,Harmonic 8 (-1.23) 2068.71
,Harmonic 9 (-0.129) 2055.18
,Harmonic 10 1.454 1009.68
,Harmonic 11 1.36 381.33
,Harmonic 12 (-2.752) 423.1
,Harmonic 13 (-2.009) 1490.52
,Harmonic 14 (-0.87) 466.34
,Harmonic 15 (-1.762) 355.48
,Harmonic 16 0.775 161.62
,Harmonic 17 2.403 348.0
,Harmonic 18 (-0.155) 275.44
,Harmonic 19 (-2.922) 284.27
,Harmonic 20 (-1.847) 118.35
,Harmonic 21 (-0.693) 35.89
,Harmonic 22 (-2.548) 152.71
,Harmonic 23 (-2.127) 179.31
,Harmonic 24 (-2.404) 211.03
,Harmonic 25 (-0.335) 164.56
,Harmonic 26 0.72 138.04
,Harmonic 27 2.514 24.61
,Harmonic 28 0.273 9.18
,Harmonic 29 3.094 18.83
,Harmonic 30 (-2.648) 11.63
,Harmonic 31 3.011 33.82
,Harmonic 32 2.594 29.24
,Harmonic 33 2.957 12.27
,Harmonic 34 (-2.247) 28.85
,Harmonic 35 2.797 12.95
,Harmonic 36 (-2.528) 17.32
,Harmonic 37 (-0.505) 21.07
,Harmonic 38 1.556 14.12
,Harmonic 39 (-2.133) 5.55
,Harmonic 40 (-2.908) 13.69
,Harmonic 41 2.932 6.16
,Harmonic 42 (-0.42) 6.49
,Harmonic 43 2.196 2.81
,Harmonic 44 0.963 2.97
,Harmonic 45 2.813 2.83
,Harmonic 46 (-0.54) 3.47
,Harmonic 47 (-2.032) 0.98
,Harmonic 48 (-1.381) 7.87
,Harmonic 49 0.313 8.54
,Harmonic 50 1.583 5.46
,Harmonic 51 (-2.738) 2.68
,Harmonic 52 4.2e-2 1.62
,Harmonic 53 1.803 3.08
,Harmonic 54 1.876 1.91
,Harmonic 55 (-2.623) 3.65
,Harmonic 56 (-0.228) 3.07
,Harmonic 57 0.736 4.56
,Harmonic 58 2.283 8.67
,Harmonic 59 (-2.563) 8.21
,Harmonic 60 (-0.937) 3.98
,Harmonic 61 1.487 1.18]
note5 :: Note
note5 = Note
(Pitch 174.614 41 "f3")
6
(Range
(NoteRange
(NoteRangeAmplitude 9079.92 52 0.32)
(NoteRangeHarmonicFreq 1 174.61))
(NoteRange
(NoteRangeAmplitude 349.22 2 7094.0)
(NoteRangeHarmonicFreq 58 10127.61)))
[Harmonic 1 (-1.393) 854.97
,Harmonic 2 2.19 7094.0
,Harmonic 3 0.547 6922.78
,Harmonic 4 2.477 4224.62
,Harmonic 5 2.65 2694.58
,Harmonic 6 (-2.072) 2630.57
,Harmonic 7 1.23 2560.33
,Harmonic 8 0.843 3483.79
,Harmonic 9 0.181 585.14
,Harmonic 10 0.185 229.73
,Harmonic 11 (-1.558) 593.0
,Harmonic 12 2.8e-2 1644.98
,Harmonic 13 0.169 718.4
,Harmonic 14 (-1.856) 116.74
,Harmonic 15 (-1.375) 318.73
,Harmonic 16 (-1.209) 423.99
,Harmonic 17 (-2.95) 328.75
,Harmonic 18 (-1.624) 235.46
,Harmonic 19 (-2.763) 371.93
,Harmonic 20 (-2.716) 82.3
,Harmonic 21 (-8.9e-2) 273.2
,Harmonic 22 (-0.714) 376.1
,Harmonic 23 (-1.625) 357.95
,Harmonic 24 (-1.522) 167.16
,Harmonic 25 (-1.218) 75.13
,Harmonic 26 (-1.49) 59.43
,Harmonic 27 (-2.968) 55.02
,Harmonic 28 2.358 50.03
,Harmonic 29 2.523 18.12
,Harmonic 30 (-0.824) 44.43
,Harmonic 31 (-2.557) 26.38
,Harmonic 32 (-1.665) 21.09
,Harmonic 33 (-0.743) 38.03
,Harmonic 34 0.161 54.93
,Harmonic 35 0.643 84.52
,Harmonic 36 0.713 62.11
,Harmonic 37 1.264 13.64
,Harmonic 38 2.158 34.06
,Harmonic 39 1.249 16.98
,Harmonic 40 1.005 7.28
,Harmonic 41 0.552 0.97
,Harmonic 42 (-0.61) 10.05
,Harmonic 43 0.507 4.35
,Harmonic 44 1.522 4.77
,Harmonic 45 2.036 4.77
,Harmonic 46 (-1.455) 7.87
,Harmonic 47 (-1.417) 9.33
,Harmonic 48 (-0.839) 10.03
,Harmonic 49 0.331 4.97
,Harmonic 50 1.427 5.6
,Harmonic 51 1.975 3.86
,Harmonic 52 (-1.955) 0.32
,Harmonic 53 (-1.817) 0.51
,Harmonic 54 2.151 1.33
,Harmonic 55 0.654 1.69
,Harmonic 56 (-0.74) 0.35
,Harmonic 57 (-2.39) 3.78
,Harmonic 58 (-2.418) 5.7]
note6 :: Note
note6 = Note
(Pitch 184.997 42 "f#3")
7
(Range
(NoteRange
(NoteRangeAmplitude 7399.88 40 1.65)
(NoteRangeHarmonicFreq 1 184.99))
(NoteRange
(NoteRangeAmplitude 369.99 2 6497.0)
(NoteRangeHarmonicFreq 54 9989.83)))
[Harmonic 1 2.826 995.6
,Harmonic 2 (-2.094) 6497.0
,Harmonic 3 1.203 1591.48
,Harmonic 4 1.089 1324.48
,Harmonic 5 1.703 760.49
,Harmonic 6 2.832 647.22
,Harmonic 7 (-0.565) 2256.7
,Harmonic 8 (-1.462) 1007.36
,Harmonic 9 (-2.161) 552.29
,Harmonic 10 (-1.03) 1219.27
,Harmonic 11 (-1.382) 822.24
,Harmonic 12 2.426 275.73
,Harmonic 13 (-0.179) 105.31
,Harmonic 14 (-2.415) 145.23
,Harmonic 15 2.466 190.65
,Harmonic 16 1.821 126.73
,Harmonic 17 (-1.892) 218.23
,Harmonic 18 (-3.08) 135.12
,Harmonic 19 1.153 221.19
,Harmonic 20 (-0.934) 204.79
,Harmonic 21 (-2.776) 54.57
,Harmonic 22 2.457 62.78
,Harmonic 23 8.3e-2 43.09
,Harmonic 24 (-0.442) 50.37
,Harmonic 25 (-0.624) 57.56
,Harmonic 26 (-2.633) 24.97
,Harmonic 27 0.277 31.55
,Harmonic 28 3.034 6.14
,Harmonic 29 (-3.061) 13.34
,Harmonic 30 1.081 32.52
,Harmonic 31 (-1.066) 48.8
,Harmonic 32 (-3.063) 33.21
,Harmonic 33 1.644 17.54
,Harmonic 34 0.826 3.99
,Harmonic 35 0.196 8.25
,Harmonic 36 (-1.356) 11.54
,Harmonic 37 (-2.466) 12.25
,Harmonic 38 2.221 4.0
,Harmonic 39 0.983 9.7
,Harmonic 40 (-1.655) 1.65
,Harmonic 41 1.437 1.68
,Harmonic 42 0.103 8.38
,Harmonic 43 (-2.871) 2.93
,Harmonic 44 0.693 3.31
,Harmonic 45 (-0.634) 2.77
,Harmonic 46 (-1.177) 3.25
,Harmonic 47 2.667 1.73
,Harmonic 48 1.389 4.13
,Harmonic 49 0.301 3.93
,Harmonic 50 (-0.49) 5.57
,Harmonic 51 (-2.35) 5.86
,Harmonic 52 1.369 6.33
,Harmonic 53 (-1.008) 2.1
,Harmonic 54 0.189 2.1]
note7 :: Note
note7 = Note
(Pitch 195.998 43 "g3")
8
(Range
(NoteRange
(NoteRangeAmplitude 9211.9 47 2.03)
(NoteRangeHarmonicFreq 1 195.99))
(NoteRange
(NoteRangeAmplitude 1371.98 7 6214.0)
(NoteRangeHarmonicFreq 50 9799.9)))
[Harmonic 1 (-2.832) 2304.17
,Harmonic 2 0.441 3061.32
,Harmonic 3 (-0.879) 2019.25
,Harmonic 4 (-0.314) 2284.87
,Harmonic 5 0.897 2199.32
,Harmonic 6 2.461 4359.08
,Harmonic 7 1.278 6214.0
,Harmonic 8 1.605 4300.0
,Harmonic 9 3.059 446.43
,Harmonic 10 2.606 484.21
,Harmonic 11 1.603 1738.72
,Harmonic 12 0.526 564.41
,Harmonic 13 0.205 484.24
,Harmonic 14 (-1.174) 941.42
,Harmonic 15 2.027 500.14
,Harmonic 16 (-2.699) 485.74
,Harmonic 17 1.381 492.54
,Harmonic 18 (-2.104) 1078.88
,Harmonic 19 1.485 775.07
,Harmonic 20 (-0.745) 347.18
,Harmonic 21 (-1.044) 130.81
,Harmonic 22 (-0.504) 104.9
,Harmonic 23 2.661 68.22
,Harmonic 24 (-1.942) 46.22
,Harmonic 25 1.102 208.31
,Harmonic 26 (-2.162) 131.56
,Harmonic 27 1.44 111.76
,Harmonic 28 (-0.521) 92.83
,Harmonic 29 (-3.004) 77.13
,Harmonic 30 (-2.872) 48.19
,Harmonic 31 (-2.815) 64.59
,Harmonic 32 (-1.369) 6.36
,Harmonic 33 (-1.862) 51.57
,Harmonic 34 (-1.71) 45.79
,Harmonic 35 1.632 17.37
,Harmonic 36 1.493 44.58
,Harmonic 37 0.728 55.62
,Harmonic 38 (-0.231) 6.23
,Harmonic 39 2.403 26.12
,Harmonic 40 (-2.762) 12.08
,Harmonic 41 1.309 5.32
,Harmonic 42 (-0.49) 24.44
,Harmonic 43 (-2.858) 9.14
,Harmonic 44 1.576 12.07
,Harmonic 45 (-0.979) 15.58
,Harmonic 46 (-2.463) 13.18
,Harmonic 47 0.79 2.03
,Harmonic 48 (-1.143) 9.19
,Harmonic 49 (-2.136) 4.74
,Harmonic 50 2.412 4.6]
note8 :: Note
note8 = Note
(Pitch 207.652 44 "g#3")
9
(Range
(NoteRange
(NoteRangeAmplitude 9967.29 48 3.88)
(NoteRangeHarmonicFreq 1 207.65))
(NoteRange
(NoteRangeAmplitude 1453.56 7 9195.0)
(NoteRangeHarmonicFreq 48 9967.29)))
[Harmonic 1 (-1.91) 2981.66
,Harmonic 2 2.629 6517.51
,Harmonic 3 (-2.933) 3444.14
,Harmonic 4 (-1.555) 6146.84
,Harmonic 5 0.235 3706.13
,Harmonic 6 (-2.698) 5602.03
,Harmonic 7 (-1.471) 9195.0
,Harmonic 8 (-0.668) 7525.02
,Harmonic 9 1.632 2311.11
,Harmonic 10 (-2.442) 2455.59
,Harmonic 11 2.718 1749.65
,Harmonic 12 1.534 615.81
,Harmonic 13 (-2.313) 639.75
,Harmonic 14 2.83 1476.63
,Harmonic 15 (-1.424) 1640.57
,Harmonic 16 (-2.623) 991.31
,Harmonic 17 0.113 1298.03
,Harmonic 18 (-0.474) 1150.64
,Harmonic 19 (-0.932) 941.21
,Harmonic 20 (-1.192) 627.89
,Harmonic 21 (-2.337) 214.84
,Harmonic 22 (-0.774) 65.46
,Harmonic 23 0.788 394.73
,Harmonic 24 0.358 412.56
,Harmonic 25 1.594 364.58
,Harmonic 26 2.654 325.41
,Harmonic 27 (-1.939) 419.93
,Harmonic 28 1.914 38.99
,Harmonic 29 2.239 98.38
,Harmonic 30 (-2.887) 119.1
,Harmonic 31 1.86 52.33
,Harmonic 32 (-2.239) 87.74
,Harmonic 33 (-0.3) 82.17
,Harmonic 34 1.551 78.01
,Harmonic 35 (-3.002) 151.71
,Harmonic 36 (-1.889) 103.22
,Harmonic 37 0.474 34.53
,Harmonic 38 2.89 28.58
,Harmonic 39 (-2.413) 41.98
,Harmonic 40 0.918 37.48
,Harmonic 41 1.324 49.38
,Harmonic 42 (-1.95) 22.87
,Harmonic 43 (-0.728) 21.03
,Harmonic 44 (-0.421) 32.72
,Harmonic 45 (-0.251) 19.23
,Harmonic 46 (-0.489) 16.55
,Harmonic 47 1.5 12.1
,Harmonic 48 (-2.864) 3.88]
note9 :: Note
note9 = Note
(Pitch 220.0 45 "a3")
10
(Range
(NoteRange
(NoteRangeAmplitude 9900.0 45 3.13)
(NoteRangeHarmonicFreq 1 220.0))
(NoteRange
(NoteRangeAmplitude 440.0 2 11549.0)
(NoteRangeHarmonicFreq 45 9900.0)))
[Harmonic 1 (-0.553) 6617.65
,Harmonic 2 (-1.981) 11549.0
,Harmonic 3 (-2.7e-2) 1815.72
,Harmonic 4 2.0 1498.02
,Harmonic 5 2.593 696.85
,Harmonic 6 2.499 4561.23
,Harmonic 7 (-2.436) 1616.94
,Harmonic 8 (-1.302) 1322.31
,Harmonic 9 (-0.51) 2172.62
,Harmonic 10 (-0.557) 1887.24
,Harmonic 11 (-1.248) 287.03
,Harmonic 12 1.803 165.62
,Harmonic 13 1.317 1224.55
,Harmonic 14 (-2.128) 645.69
,Harmonic 15 (-2.318) 602.62
,Harmonic 16 2.413 393.01
,Harmonic 17 1.78 701.89
,Harmonic 18 1.653 349.11
,Harmonic 19 3.085 300.94
,Harmonic 20 1.087 58.08
,Harmonic 21 6.0e-2 19.57
,Harmonic 22 1.158 41.24
,Harmonic 23 2.166 55.96
,Harmonic 24 (-3.086) 100.65
,Harmonic 25 0.242 192.03
,Harmonic 26 (-0.112) 108.32
,Harmonic 27 0.337 168.41
,Harmonic 28 2.918 144.42
,Harmonic 29 0.69 50.74
,Harmonic 30 1.592 23.59
,Harmonic 31 (-0.117) 17.68
,Harmonic 32 (-0.991) 7.94
,Harmonic 33 0.108 33.72
,Harmonic 34 2.885 36.25
,Harmonic 35 0.594 27.1
,Harmonic 36 (-2.851) 57.96
,Harmonic 37 (-0.768) 24.22
,Harmonic 38 2.419 15.2
,Harmonic 39 0.252 7.14
,Harmonic 40 2.384 21.16
,Harmonic 41 (-2.258) 15.53
,Harmonic 42 (-2.2) 5.33
,Harmonic 43 1.41 7.18
,Harmonic 44 2.422 17.95
,Harmonic 45 0.336 3.13]
note10 :: Note
note10 = Note
(Pitch 233.082 46 "a#3")
11
(Range
(NoteRange
(NoteRangeAmplitude 8857.11 38 1.77)
(NoteRangeHarmonicFreq 1 233.08))
(NoteRange
(NoteRangeAmplitude 233.08 1 15064.0)
(NoteRangeHarmonicFreq 43 10022.52)))
[Harmonic 1 (-1.72) 15064.0
,Harmonic 2 (-1.697) 12962.84
,Harmonic 3 0.138 1493.03
,Harmonic 4 (-1.125) 1242.65
,Harmonic 5 (-3.138) 2215.9
,Harmonic 6 (-2.179) 4530.49
,Harmonic 7 0.176 3934.23
,Harmonic 8 (-2.1) 3321.89
,Harmonic 9 0.913 1790.0
,Harmonic 10 1.695 211.64
,Harmonic 11 3.098 422.0
,Harmonic 12 (-1.878) 1223.09
,Harmonic 13 1.182 568.0
,Harmonic 14 7.0e-3 369.81
,Harmonic 15 (-2.719) 568.37
,Harmonic 16 (-1.545) 654.24
,Harmonic 17 (-1.014) 176.28
,Harmonic 18 (-0.481) 225.2
,Harmonic 19 (-2.813) 86.54
,Harmonic 20 2.375 54.56
,Harmonic 21 (-2.336) 60.06
,Harmonic 22 (-8.4e-2) 241.36
,Harmonic 23 2.346 79.96
,Harmonic 24 (-1.732) 124.84
,Harmonic 25 (-1.628) 106.1
,Harmonic 26 6.9e-2 86.04
,Harmonic 27 2.781 26.52
,Harmonic 28 (-2.044) 4.35
,Harmonic 29 (-0.779) 39.12
,Harmonic 30 2.438 16.66
,Harmonic 31 (-0.913) 72.25
,Harmonic 32 2.894 5.28
,Harmonic 33 (-0.194) 73.23
,Harmonic 34 1.798 49.6
,Harmonic 35 (-1.486) 5.85
,Harmonic 36 0.208 12.53
,Harmonic 37 1.193 10.71
,Harmonic 38 (-0.856) 1.77
,Harmonic 39 (-3.074) 7.25
,Harmonic 40 0.335 13.43
,Harmonic 41 1.714 13.2
,Harmonic 42 (-1.742) 12.93
,Harmonic 43 0.868 6.53]
note11 :: Note
note11 = Note
(Pitch 246.942 47 "b3")
12
(Range
(NoteRange
(NoteRangeAmplitude 9383.79 38 1.4)
(NoteRangeHarmonicFreq 1 246.94))
(NoteRange
(NoteRangeAmplitude 493.88 2 7831.0)
(NoteRangeHarmonicFreq 41 10124.62)))
[Harmonic 1 (-1.098) 6459.96
,Harmonic 2 (-3.3e-2) 7831.0
,Harmonic 3 (-2.743) 2405.56
,Harmonic 4 3.03 3284.59
,Harmonic 5 2.541 4562.92
,Harmonic 6 (-1.471) 4359.22
,Harmonic 7 (-1.313) 1611.04
,Harmonic 8 2.864 2198.42
,Harmonic 9 (-1.511) 2577.71
,Harmonic 10 1.496 273.86
,Harmonic 11 2.579 1141.0
,Harmonic 12 2.049 482.26
,Harmonic 13 1.876 432.4
,Harmonic 14 1.471 332.35
,Harmonic 15 0.735 72.02
,Harmonic 16 1.704 735.64
,Harmonic 17 (-1.02) 267.59
,Harmonic 18 (-2.385) 35.89
,Harmonic 19 (-4.0e-3) 138.29
,Harmonic 20 (-2.497) 89.98
,Harmonic 21 0.512 67.61
,Harmonic 22 0.329 47.6
,Harmonic 23 (-0.364) 54.8
,Harmonic 24 2.445 53.82
,Harmonic 25 0.513 79.34
,Harmonic 26 2.426 31.3
,Harmonic 27 0.967 67.46
,Harmonic 28 (-2.244) 42.2
,Harmonic 29 0.22 32.63
,Harmonic 30 (-2.334) 41.18
,Harmonic 31 (-0.111) 35.55
,Harmonic 32 (-0.736) 34.27
,Harmonic 33 2.576 35.69
,Harmonic 34 (-0.317) 17.55
,Harmonic 35 (-1.074) 7.92
,Harmonic 36 (-3.008) 11.29
,Harmonic 37 0.9 9.91
,Harmonic 38 (-1.425) 1.4
,Harmonic 39 0.14 13.53
,Harmonic 40 (-1.879) 8.55
,Harmonic 41 1.827 11.9]
note12 :: Note
note12 = Note
(Pitch 261.626 48 "c4")
13
(Range
(NoteRange
(NoteRangeAmplitude 9680.16 37 8.29)
(NoteRangeHarmonicFreq 1 261.62))
(NoteRange
(NoteRangeAmplitude 261.62 1 8531.0)
(NoteRangeHarmonicFreq 38 9941.78)))
[Harmonic 1 1.849 8531.0
,Harmonic 2 2.0 3012.87
,Harmonic 3 0.367 1271.51
,Harmonic 4 1.789 2745.79
,Harmonic 5 (-0.51) 3151.96
,Harmonic 6 1.135 1352.91
,Harmonic 7 (-0.506) 1502.43
,Harmonic 8 1.14 2921.29
,Harmonic 9 1.047 1124.29
,Harmonic 10 2.202 877.91
,Harmonic 11 0.174 690.14
,Harmonic 12 2.709 419.18
,Harmonic 13 1.354 182.35
,Harmonic 14 (-1.282) 123.15
,Harmonic 15 (-2.103) 252.51
,Harmonic 16 0.323 61.42
,Harmonic 17 (-1.764) 31.5
,Harmonic 18 2.673 103.55
,Harmonic 19 (-1.63) 34.69
,Harmonic 20 (-2.817) 37.4
,Harmonic 21 0.151 113.61
,Harmonic 22 1.302 35.3
,Harmonic 23 (-1.849) 10.51
,Harmonic 24 (-3.118) 29.38
,Harmonic 25 (-1.976) 82.57
,Harmonic 26 0.373 40.73
,Harmonic 27 1.839 21.6
,Harmonic 28 2.97 10.48
,Harmonic 29 (-1.094) 31.83
,Harmonic 30 0.83 40.33
,Harmonic 31 2.494 24.35
,Harmonic 32 1.974 9.01
,Harmonic 33 (-1.592) 18.85
,Harmonic 34 (-0.232) 17.17
,Harmonic 35 1.346 11.24
,Harmonic 36 (-2.491) 19.7
,Harmonic 37 1.197 8.29
,Harmonic 38 2.661 15.7]
note13 :: Note
note13 = Note
(Pitch 277.183 49 "c#4")
14
(Range
(NoteRange
(NoteRangeAmplitude 8869.85 32 8.19)
(NoteRangeHarmonicFreq 1 277.18))
(NoteRange
(NoteRangeAmplitude 1385.91 5 6263.0)
(NoteRangeHarmonicFreq 36 9978.58)))
[Harmonic 1 1.969 4509.09
,Harmonic 2 (-0.872) 3526.63
,Harmonic 3 0.919 4387.78
,Harmonic 4 (-0.949) 2660.26
,Harmonic 5 (-2.375) 6263.0
,Harmonic 6 (-1.754) 4006.26
,Harmonic 7 (-3.037) 2661.3
,Harmonic 8 (-7.0e-3) 1148.94
,Harmonic 9 (-2.503) 370.52
,Harmonic 10 (-2.593) 907.38
,Harmonic 11 (-0.439) 819.06
,Harmonic 12 1.579 470.04
,Harmonic 13 2.735 793.17
,Harmonic 14 1.077 1403.06
,Harmonic 15 (-0.213) 238.99
,Harmonic 16 (-0.527) 67.72
,Harmonic 17 1.062 59.71
,Harmonic 18 3.087 172.41
,Harmonic 19 (-2.237) 125.86
,Harmonic 20 (-2.097) 103.46
,Harmonic 21 1.419 186.03
,Harmonic 22 1.73 153.13
,Harmonic 23 (-2.541) 112.95
,Harmonic 24 (-2.026) 41.49
,Harmonic 25 (-0.513) 23.87
,Harmonic 26 2.427 47.49
,Harmonic 27 (-1.954) 40.27
,Harmonic 28 (-0.529) 79.67
,Harmonic 29 (-0.581) 29.68
,Harmonic 30 0.735 25.66
,Harmonic 31 (-2.855) 22.26
,Harmonic 32 (-2.347) 8.19
,Harmonic 33 1.634 11.7
,Harmonic 34 (-2.988) 16.08
,Harmonic 35 (-2.574) 22.05
,Harmonic 36 (-1.521) 8.81]
note14 :: Note
note14 = Note
(Pitch 293.665 50 "d4")
15
(Range
(NoteRange
(NoteRangeAmplitude 9690.94 33 34.15)
(NoteRangeHarmonicFreq 1 293.66))
(NoteRange
(NoteRangeAmplitude 293.66 1 10821.0)
(NoteRangeHarmonicFreq 34 9984.61)))
[Harmonic 1 2.574 10821.0
,Harmonic 2 1.88 4804.88
,Harmonic 3 0.134 1267.58
,Harmonic 4 (-2.87) 4013.97
,Harmonic 5 (-0.864) 9345.71
,Harmonic 6 (-0.936) 2702.97
,Harmonic 7 (-1.411) 7831.49
,Harmonic 8 (-1.893) 1602.29
,Harmonic 9 (-1.436) 3950.3
,Harmonic 10 2.72 1084.73
,Harmonic 11 (-1.471) 3043.56
,Harmonic 12 1.422 1978.05
,Harmonic 13 0.739 1129.55
,Harmonic 14 1.89 364.76
,Harmonic 15 (-1.321) 325.05
,Harmonic 16 (-3.084) 349.39
,Harmonic 17 2.667 124.81
,Harmonic 18 (-0.634) 126.91
,Harmonic 19 (-0.151) 118.67
,Harmonic 20 1.883 238.95
,Harmonic 21 1.172 276.89
,Harmonic 22 (-0.465) 56.24
,Harmonic 23 (-1.336) 51.5
,Harmonic 24 (-0.7) 60.27
,Harmonic 25 3.131 67.57
,Harmonic 26 2.36 78.05
,Harmonic 27 (-1.035) 79.9
,Harmonic 28 0.461 35.66
,Harmonic 29 1.261 41.59
,Harmonic 30 (-2.182) 37.44
,Harmonic 31 1.816 39.83
,Harmonic 32 (-1.923) 66.6
,Harmonic 33 0.394 34.15
,Harmonic 34 (-2.028) 55.28]
note15 :: Note
note15 = Note
(Pitch 311.127 51 "d#4")
16
(Range
(NoteRange
(NoteRangeAmplitude 9022.68 29 5.99)
(NoteRangeHarmonicFreq 1 311.12))
(NoteRange
(NoteRangeAmplitude 2177.88 7 10586.0)
(NoteRangeHarmonicFreq 32 9956.06)))
[Harmonic 1 0.488 4236.58
,Harmonic 2 (-1.211) 2438.15
,Harmonic 3 1.942 1378.7
,Harmonic 4 1.702 3578.54
,Harmonic 5 0.17 1247.74
,Harmonic 6 2.03 3360.82
,Harmonic 7 1.178 10586.0
,Harmonic 8 0.348 346.51
,Harmonic 9 2.621 995.81
,Harmonic 10 1.951 1437.14
,Harmonic 11 (-2.177) 432.39
,Harmonic 12 (-0.718) 745.44
,Harmonic 13 (-2.717) 195.72
,Harmonic 14 (-2.471) 286.14
,Harmonic 15 2.946 173.15
,Harmonic 16 1.422 63.93
,Harmonic 17 1.877 203.54
,Harmonic 18 (-3.129) 51.93
,Harmonic 19 2.4 192.15
,Harmonic 20 2.553 77.73
,Harmonic 21 (-1.098) 58.5
,Harmonic 22 0.707 15.29
,Harmonic 23 (-0.221) 43.45
,Harmonic 24 (-1.916) 65.44
,Harmonic 25 (-2.328) 59.88
,Harmonic 26 (-2.906) 96.56
,Harmonic 27 2.957 51.0
,Harmonic 28 0.874 25.61
,Harmonic 29 0.527 5.99
,Harmonic 30 3.003 16.52
,Harmonic 31 (-2.626) 30.48
,Harmonic 32 (-1.453) 28.44]
note16 :: Note
note16 = Note
(Pitch 329.628 52 "e4")
17
(Range
(NoteRange
(NoteRangeAmplitude 8899.95 27 19.31)
(NoteRangeHarmonicFreq 1 329.62))
(NoteRange
(NoteRangeAmplitude 329.62 1 7162.0)
(NoteRangeHarmonicFreq 30 9888.84)))
[Harmonic 1 (-2.05) 7162.0
,Harmonic 2 (-0.209) 2500.43
,Harmonic 3 (-1.619) 1935.05
,Harmonic 4 (-2.366) 6058.87
,Harmonic 5 (-0.66) 3178.81
,Harmonic 6 1.627 2100.45
,Harmonic 7 2.314 2368.58
,Harmonic 8 (-1.668) 1808.14
,Harmonic 9 (-2.395) 854.49
,Harmonic 10 (-0.277) 348.2
,Harmonic 11 (-1.573) 1206.81
,Harmonic 12 (-1.127) 1271.52
,Harmonic 13 (-2.64) 423.32
,Harmonic 14 9.4e-2 425.97
,Harmonic 15 (-1.896) 27.31
,Harmonic 16 (-0.195) 221.32
,Harmonic 17 (-2.246) 515.39
,Harmonic 18 0.333 195.46
,Harmonic 19 2.627 128.13
,Harmonic 20 (-0.354) 130.72
,Harmonic 21 (-2.616) 113.99
,Harmonic 22 3.059 51.09
,Harmonic 23 (-2.336) 86.23
,Harmonic 24 1.601 141.64
,Harmonic 25 (-0.649) 51.95
,Harmonic 26 1.258 57.75
,Harmonic 27 (-2.891) 19.31
,Harmonic 28 (-2.647) 22.58
,Harmonic 29 1.842 148.45
,Harmonic 30 (-0.669) 39.78]
note17 :: Note
note17 = Note
(Pitch 349.228 53 "f4")
18
(Range
(NoteRange
(NoteRangeAmplitude 8730.7 25 10.47)
(NoteRangeHarmonicFreq 1 349.22))
(NoteRange
(NoteRangeAmplitude 349.22 1 9001.0)
(NoteRangeHarmonicFreq 28 9778.38)))
[Harmonic 1 (-0.76) 9001.0
,Harmonic 2 3.107 1108.5
,Harmonic 3 1.21 2633.15
,Harmonic 4 2.187 3968.97
,Harmonic 5 0.53 1287.12
,Harmonic 6 2.293 3185.73
,Harmonic 7 3.034 576.2
,Harmonic 8 0.954 1985.66
,Harmonic 9 (-1.948) 732.58
,Harmonic 10 (-2.871) 511.76
,Harmonic 11 (-1.803) 642.03
,Harmonic 12 (-1.061) 193.68
,Harmonic 13 2.58 124.51
,Harmonic 14 1.172 191.53
,Harmonic 15 (-0.65) 85.22
,Harmonic 16 (-2.275) 289.82
,Harmonic 17 (-2.944) 132.67
,Harmonic 18 1.906 106.65
,Harmonic 19 (-1.234) 102.74
,Harmonic 20 1.384 38.72
,Harmonic 21 (-2.974) 33.25
,Harmonic 22 2.513 41.59
,Harmonic 23 1.054 35.67
,Harmonic 24 (-2.215) 37.29
,Harmonic 25 0.827 10.47
,Harmonic 26 0.462 61.63
,Harmonic 27 0.139 43.86
,Harmonic 28 (-8.3e-2) 21.85]
note18 :: Note
note18 = Note
(Pitch 369.994 54 "f#4")
19
(Range
(NoteRange
(NoteRangeAmplitude 8879.85 24 7.43)
(NoteRangeHarmonicFreq 1 369.99))
(NoteRange
(NoteRangeAmplitude 1479.97 4 7675.0)
(NoteRangeHarmonicFreq 26 9619.84)))
[Harmonic 1 2.219 7591.78
,Harmonic 2 1.026 1324.87
,Harmonic 3 (-2.264) 1335.54
,Harmonic 4 (-1.062) 7675.0
,Harmonic 5 (-3.051) 1719.38
,Harmonic 6 (-1.706) 3738.3
,Harmonic 7 (-0.73) 1080.39
,Harmonic 8 (-1.65) 111.77
,Harmonic 9 2.936 316.49
,Harmonic 10 0.469 396.42
,Harmonic 11 3.037 531.54
,Harmonic 12 0.906 216.47
,Harmonic 13 (-2.819) 151.12
,Harmonic 14 (-2.974) 235.26
,Harmonic 15 0.429 115.38
,Harmonic 16 1.201 64.39
,Harmonic 17 (-2.932) 20.39
,Harmonic 18 (-0.133) 38.5
,Harmonic 19 (-1.239) 9.31
,Harmonic 20 2.181 58.37
,Harmonic 21 (-0.722) 30.39
,Harmonic 22 2.611 29.51
,Harmonic 23 1.606 28.26
,Harmonic 24 (-3.106) 7.43
,Harmonic 25 (-0.599) 15.39
,Harmonic 26 2.371 37.24]
note19 :: Note
note19 = Note
(Pitch 391.995 55 "g4")
20
(Range
(NoteRange
(NoteRangeAmplitude 7055.91 18 17.01)
(NoteRangeHarmonicFreq 1 391.99))
(NoteRange
(NoteRangeAmplitude 391.99 1 6129.0)
(NoteRangeHarmonicFreq 25 9799.87)))
[Harmonic 1 (-1.608) 6129.0
,Harmonic 2 0.496 1388.75
,Harmonic 3 2.047 3283.16
,Harmonic 4 0.55 5569.24
,Harmonic 5 (-2.572) 3979.83
,Harmonic 6 (-8.1e-2) 1567.27
,Harmonic 7 2.402 1409.07
,Harmonic 8 1.185 1191.46
,Harmonic 9 (-0.114) 1156.36
,Harmonic 10 2.378 1098.84
,Harmonic 11 2.772 368.14
,Harmonic 12 (-2.575) 181.44
,Harmonic 13 2.832 250.63
,Harmonic 14 1.217 203.72
,Harmonic 15 (-1.132) 25.79
,Harmonic 16 2.966 68.67
,Harmonic 17 (-1.314) 102.22
,Harmonic 18 2.523 17.01
,Harmonic 19 0.474 113.16
,Harmonic 20 2.9e-2 55.76
,Harmonic 21 (-2.031) 69.82
,Harmonic 22 (-2.29) 27.5
,Harmonic 23 7.0e-2 52.9
,Harmonic 24 1.35 62.34
,Harmonic 25 (-2.16) 28.26]
note20 :: Note
note20 = Note
(Pitch 415.305 56 "g#4")
21
(Range
(NoteRange
(NoteRangeAmplitude 7475.49 18 2.14)
(NoteRangeHarmonicFreq 1 415.3))
(NoteRange
(NoteRangeAmplitude 1245.91 3 6522.0)
(NoteRangeHarmonicFreq 23 9552.01)))
[Harmonic 1 (-0.97) 5184.39
,Harmonic 2 2.723 1538.56
,Harmonic 3 3.112 6522.0
,Harmonic 4 0.609 3871.29
,Harmonic 5 1.504 3033.58
,Harmonic 6 (-2.681) 1783.49
,Harmonic 7 (-2.638) 2625.95
,Harmonic 8 (-0.558) 232.59
,Harmonic 9 (-2.651) 1316.22
,Harmonic 10 1.743 309.75
,Harmonic 11 0.663 264.46
,Harmonic 12 (-2.361) 257.17
,Harmonic 13 (-0.202) 44.15
,Harmonic 14 2.825 184.83
,Harmonic 15 2.306 35.95
,Harmonic 16 2.125 57.46
,Harmonic 17 (-2.91) 32.95
,Harmonic 18 (-2.772) 2.14
,Harmonic 19 2.297 17.8
,Harmonic 20 (-1.166) 6.96
,Harmonic 21 0.995 14.45
,Harmonic 22 (-2.66) 10.58
,Harmonic 23 (-2.047) 10.57]
note21 :: Note
note21 = Note
(Pitch 440.0 57 "a4")
22
(Range
(NoteRange
(NoteRangeAmplitude 9240.0 21 18.52)
(NoteRangeHarmonicFreq 1 440.0))
(NoteRange
(NoteRangeAmplitude 440.0 1 5433.0)
(NoteRangeHarmonicFreq 22 9680.0)))
[Harmonic 1 (-2.408) 5433.0
,Harmonic 2 2.659 1020.55
,Harmonic 3 1.457 2541.88
,Harmonic 4 (-2.744) 998.74
,Harmonic 5 (-1.573) 4585.86
,Harmonic 6 (-0.558) 2102.96
,Harmonic 7 0.342 1178.77
,Harmonic 8 (-0.188) 1287.95
,Harmonic 9 (-0.435) 1599.37
,Harmonic 10 1.496 441.93
,Harmonic 11 (-2.485) 219.43
,Harmonic 12 (-0.507) 370.0
,Harmonic 13 0.35 70.1
,Harmonic 14 0.605 88.45
,Harmonic 15 (-1.377) 109.58
,Harmonic 16 0.131 40.15
,Harmonic 17 (-1.859) 60.03
,Harmonic 18 (-1.004) 113.08
,Harmonic 19 (-2.998) 69.64
,Harmonic 20 (-1.159) 111.67
,Harmonic 21 (-0.243) 18.52
,Harmonic 22 (-2.58) 44.34]
note22 :: Note
note22 = Note
(Pitch 466.164 58 "a#4")
23
(Range
(NoteRange
(NoteRangeAmplitude 9789.44 21 30.01)
(NoteRangeHarmonicFreq 1 466.16))
(NoteRange
(NoteRangeAmplitude 466.16 1 8241.0)
(NoteRangeHarmonicFreq 21 9789.44)))
[Harmonic 1 1.719 8241.0
,Harmonic 2 4.4e-2 1040.23
,Harmonic 3 2.599 1695.66
,Harmonic 4 (-0.406) 2248.4
,Harmonic 5 2.248 1040.75
,Harmonic 6 0.626 2052.03
,Harmonic 7 1.787 366.76
,Harmonic 8 1.83 1015.79
,Harmonic 9 (-1.685) 582.08
,Harmonic 10 (-1.558) 277.45
,Harmonic 11 1.337 66.38
,Harmonic 12 0.909 200.23
,Harmonic 13 (-2.988) 256.95
,Harmonic 14 (-1.499) 114.04
,Harmonic 15 1.422 36.25
,Harmonic 16 0.474 83.51
,Harmonic 17 2.861 39.34
,Harmonic 18 (-1.9) 51.06
,Harmonic 19 1.615 97.7
,Harmonic 20 0.971 46.11
,Harmonic 21 1.917 30.01]
note23 :: Note
note23 = Note
(Pitch 493.883 59 "b4")
24
(Range
(NoteRange
(NoteRangeAmplitude 8396.01 17 11.78)
(NoteRangeHarmonicFreq 1 493.88))
(NoteRange
(NoteRangeAmplitude 493.88 1 7498.0)
(NoteRangeHarmonicFreq 20 9877.66)))
[Harmonic 1 (-2.161) 7498.0
,Harmonic 2 (-0.726) 1638.17
,Harmonic 3 (-1.448) 6237.67
,Harmonic 4 3.116 3204.73
,Harmonic 5 (-1.043) 1186.58
,Harmonic 6 (-1.279) 1748.25
,Harmonic 7 2.023 420.44
,Harmonic 8 (-7.6e-2) 1370.7
,Harmonic 9 (-0.597) 505.84
,Harmonic 10 (-1.24) 548.75
,Harmonic 11 (-2.155) 186.13
,Harmonic 12 (-1.586) 173.18
,Harmonic 13 (-1.583) 305.74
,Harmonic 14 2.453 98.6
,Harmonic 15 (-0.737) 31.75
,Harmonic 16 (-0.749) 97.04
,Harmonic 17 3.04 11.78
,Harmonic 18 (-2.907) 24.69
,Harmonic 19 1.8 37.81
,Harmonic 20 (-1.514) 45.4]
note24 :: Note
note24 = Note
(Pitch 523.251 60 "c5")
25
(Range
(NoteRange
(NoteRangeAmplitude 7848.76 15 7.47)
(NoteRangeHarmonicFreq 1 523.25))
(NoteRange
(NoteRangeAmplitude 1569.75 3 6561.0)
(NoteRangeHarmonicFreq 19 9941.76)))
[Harmonic 1 2.216 2658.8
,Harmonic 2 0.751 3080.38
,Harmonic 3 1.14 6561.0
,Harmonic 4 1.241 4529.37
,Harmonic 5 (-0.353) 507.46
,Harmonic 6 2.847 1503.43
,Harmonic 7 (-2.105) 1053.57
,Harmonic 8 1.264 680.26
,Harmonic 9 2.151 241.65
,Harmonic 10 2.007 406.73
,Harmonic 11 0.683 636.65
,Harmonic 12 (-1.682) 677.39
,Harmonic 13 (-1.193) 138.13
,Harmonic 14 2.211 131.81
,Harmonic 15 2.591 7.47
,Harmonic 16 (-1.105) 24.53
,Harmonic 17 0.745 47.39
,Harmonic 18 (-1.861) 23.11
,Harmonic 19 (-1.434) 14.09]
note25 :: Note
note25 = Note
(Pitch 554.365 61 "c#5")
26
(Range
(NoteRange
(NoteRangeAmplitude 9424.2 17 13.77)
(NoteRangeHarmonicFreq 1 554.36))
(NoteRange
(NoteRangeAmplitude 1663.09 3 3873.0)
(NoteRangeHarmonicFreq 18 9978.57)))
[Harmonic 1 1.988 914.19
,Harmonic 2 (-2.412) 1805.84
,Harmonic 3 (-1.24) 3873.0
,Harmonic 4 (-2.407) 1980.98
,Harmonic 5 (-2.193) 2383.19
,Harmonic 6 1.517 616.16
,Harmonic 7 (-0.539) 1337.55
,Harmonic 8 (-3.103) 634.16
,Harmonic 9 0.452 605.15
,Harmonic 10 0.506 214.27
,Harmonic 11 2.23 233.94
,Harmonic 12 (-1.72) 90.11
,Harmonic 13 1.852 142.24
,Harmonic 14 (-0.481) 195.77
,Harmonic 15 (-0.584) 18.93
,Harmonic 16 2.335 105.44
,Harmonic 17 (-2.869) 13.77
,Harmonic 18 1.171 130.05]
note26 :: Note
note26 = Note
(Pitch 587.33 62 "d5")
27
(Range
(NoteRange
(NoteRangeAmplitude 8809.95 15 29.85)
(NoteRangeHarmonicFreq 1 587.33))
(NoteRange
(NoteRangeAmplitude 1174.66 2 3815.0)
(NoteRangeHarmonicFreq 17 9984.61)))
[Harmonic 1 (-2.753) 2881.62
,Harmonic 2 (-8.9e-2) 3815.0
,Harmonic 3 (-3.139) 3488.34
,Harmonic 4 (-1.163) 1879.4
,Harmonic 5 (-1.972) 2400.28
,Harmonic 6 (-2.642) 703.07
,Harmonic 7 1.083 320.77
,Harmonic 8 (-2.661) 898.26
,Harmonic 9 (-2.893) 891.15
,Harmonic 10 (-2.287) 609.16
,Harmonic 11 (-3.092) 306.91
,Harmonic 12 (-1.828) 117.91
,Harmonic 13 1.763 150.46
,Harmonic 14 (-1.889) 43.46
,Harmonic 15 0.138 29.85
,Harmonic 16 0.519 66.36
,Harmonic 17 2.682 52.65]
note27 :: Note
note27 = Note
(Pitch 622.254 63 "d#5")
28
(Range
(NoteRange
(NoteRangeAmplitude 8711.55 14 6.97)
(NoteRangeHarmonicFreq 1 622.25))
(NoteRange
(NoteRangeAmplitude 1244.5 2 5801.0)
(NoteRangeHarmonicFreq 16 9956.06)))
[Harmonic 1 2.448 3152.14
,Harmonic 2 2.042 5801.0
,Harmonic 3 (-0.332) 3357.98
,Harmonic 4 1.658 3124.3
,Harmonic 5 0.932 340.75
,Harmonic 6 (-7.0e-2) 3081.96
,Harmonic 7 2.041 1313.03
,Harmonic 8 (-0.924) 1179.4
,Harmonic 9 1.606 269.07
,Harmonic 10 (-1.976) 137.27
,Harmonic 11 (-1.07) 89.47
,Harmonic 12 0.711 190.19
,Harmonic 13 (-2.383) 221.3
,Harmonic 14 (-2.663) 6.97
,Harmonic 15 (-3.12) 47.94
,Harmonic 16 1.898 104.9]
note28 :: Note
note28 = Note
(Pitch 659.255 64 "e5")
29
(Range
(NoteRange
(NoteRangeAmplitude 9888.82 15 25.37)
(NoteRangeHarmonicFreq 1 659.25))
(NoteRange
(NoteRangeAmplitude 1318.51 2 5079.0)
(NoteRangeHarmonicFreq 15 9888.82)))
[Harmonic 1 (-0.738) 2878.03
,Harmonic 2 (-2.502) 5079.0
,Harmonic 3 1.368 3714.07
,Harmonic 4 (-1.653) 1502.53
,Harmonic 5 0.693 515.56
,Harmonic 6 (-0.254) 1731.13
,Harmonic 7 (-0.237) 657.64
,Harmonic 8 0.809 652.02
,Harmonic 9 (-2.779) 353.49
,Harmonic 10 0.903 183.65
,Harmonic 11 (-0.206) 82.73
,Harmonic 12 2.642 112.56
,Harmonic 13 1.082 76.27
,Harmonic 14 2.608 25.38
,Harmonic 15 (-2.327) 25.37]
note29 :: Note
note29 = Note
(Pitch 698.456 65 "f5")
30
(Range
(NoteRange
(NoteRangeAmplitude 9778.38 14 8.34)
(NoteRangeHarmonicFreq 1 698.45))
(NoteRange
(NoteRangeAmplitude 2095.36 3 3019.0)
(NoteRangeHarmonicFreq 14 9778.38)))
[Harmonic 1 (-1.611) 287.27
,Harmonic 2 (-1.955) 2094.7
,Harmonic 3 (-1.04) 3019.0
,Harmonic 4 (-1.914) 2477.51
,Harmonic 5 3.033 1189.66
,Harmonic 6 (-2.139) 833.07
,Harmonic 7 2.314 264.84
,Harmonic 8 2.002 126.98
,Harmonic 9 (-0.856) 59.03
,Harmonic 10 1.193 201.53
,Harmonic 11 0.374 66.62
,Harmonic 12 1.501 50.35
,Harmonic 13 0.402 17.76
,Harmonic 14 2.585 8.34]
note30 :: Note
note30 = Note
(Pitch 739.989 66 "f#5")
31
(Range
(NoteRange
(NoteRangeAmplitude 9619.85 13 90.07)
(NoteRangeHarmonicFreq 1 739.98))
(NoteRange
(NoteRangeAmplitude 1479.97 2 5275.0)
(NoteRangeHarmonicFreq 13 9619.85)))
[Harmonic 1 2.215 2914.6
,Harmonic 2 (-1.076) 5275.0
,Harmonic 3 (-2.089) 4251.75
,Harmonic 4 (-2.267) 1883.68
,Harmonic 5 0.434 3193.9
,Harmonic 6 (-1.781) 1236.65
,Harmonic 7 (-2.839) 843.44
,Harmonic 8 2.792 640.09
,Harmonic 9 0.853 266.03
,Harmonic 10 2.618 495.05
,Harmonic 11 1.839 98.93
,Harmonic 12 (-0.791) 96.66
,Harmonic 13 1.122 90.07]
note31 :: Note
note31 = Note
(Pitch 783.991 67 "g5")
32
(Range
(NoteRange
(NoteRangeAmplitude 8623.9 11 29.31)
(NoteRangeHarmonicFreq 1 783.99))
(NoteRange
(NoteRangeAmplitude 1567.98 2 9526.0)
(NoteRangeHarmonicFreq 12 9407.89)))
[Harmonic 1 2.919 162.38
,Harmonic 2 1.409 9526.0
,Harmonic 3 1.725 735.93
,Harmonic 4 (-2.464) 1232.79
,Harmonic 5 0.392 1473.24
,Harmonic 6 (-1.565) 326.76
,Harmonic 7 0.827 524.14
,Harmonic 8 2.442 433.83
,Harmonic 9 (-1.811) 417.2
,Harmonic 10 (-2.53) 118.08
,Harmonic 11 (-2.748) 29.31
,Harmonic 12 (-1.069) 36.13]
note32 :: Note
note32 = Note
(Pitch 830.609 68 "g#5")
33
(Range
(NoteRange
(NoteRangeAmplitude 8306.09 10 11.02)
(NoteRangeHarmonicFreq 1 830.6))
(NoteRange
(NoteRangeAmplitude 1661.21 2 3256.0)
(NoteRangeHarmonicFreq 12 9967.3)))
[Harmonic 1 (-1.602) 639.54
,Harmonic 2 (-1.523) 3256.0
,Harmonic 3 3.091 665.41
,Harmonic 4 2.212 439.47
,Harmonic 5 1.679 715.64
,Harmonic 6 (-1.872) 445.58
,Harmonic 7 1.49 273.09
,Harmonic 8 1.9e-2 120.89
,Harmonic 9 (-1.184) 84.44
,Harmonic 10 1.716 11.02
,Harmonic 11 (-0.486) 57.28
,Harmonic 12 1.729 59.97]
note33 :: Note
note33 = Note
(Pitch 880.0 69 "a5")
34
(Range
(NoteRange
(NoteRangeAmplitude 7920.0 9 20.37)
(NoteRangeHarmonicFreq 1 880.0))
(NoteRange
(NoteRangeAmplitude 2640.0 3 1686.0)
(NoteRangeHarmonicFreq 11 9680.0)))
[Harmonic 1 (-1.18) 661.8
,Harmonic 2 3.017 1230.51
,Harmonic 3 (-1.57) 1686.0
,Harmonic 4 (-1.239) 65.5
,Harmonic 5 2.702 602.05
,Harmonic 6 (-1.857) 478.9
,Harmonic 7 (-2.967) 326.2
,Harmonic 8 (-0.507) 177.24
,Harmonic 9 (-1.436) 20.37
,Harmonic 10 (-2.033) 24.82
,Harmonic 11 (-1.593) 21.62]
note34 :: Note
note34 = Note
(Pitch 932.328 70 "a#5")
35
(Range
(NoteRange
(NoteRangeAmplitude 8390.95 9 31.0)
(NoteRangeHarmonicFreq 1 932.32))
(NoteRange
(NoteRangeAmplitude 2796.98 3 3827.0)
(NoteRangeHarmonicFreq 10 9323.27)))
[Harmonic 1 2.729 1739.76
,Harmonic 2 0.618 3022.85
,Harmonic 3 0.959 3827.0
,Harmonic 4 1.165 1403.38
,Harmonic 5 2.288 213.53
,Harmonic 6 0.168 89.82
,Harmonic 7 (-3.5e-2) 94.02
,Harmonic 8 2.837 111.27
,Harmonic 9 (-2.376) 31.0
,Harmonic 10 (-2.092) 39.66]
note35 :: Note
note35 = Note
(Pitch 987.767 71 "b5")
36
(Range
(NoteRange
(NoteRangeAmplitude 9877.67 10 46.26)
(NoteRangeHarmonicFreq 1 987.76))
(NoteRange
(NoteRangeAmplitude 1975.53 2 2994.0)
(NoteRangeHarmonicFreq 10 9877.67)))
[Harmonic 1 (-0.956) 2257.56
,Harmonic 2 2.173 2994.0
,Harmonic 3 (-1.816) 615.05
,Harmonic 4 (-1.856) 1793.92
,Harmonic 5 (-1.694) 1012.59
,Harmonic 6 (-2.69) 1012.24
,Harmonic 7 2.548 107.07
,Harmonic 8 (-0.671) 145.76
,Harmonic 9 (-0.819) 132.18
,Harmonic 10 0.467 46.26]
note36 :: Note
note36 = Note
(Pitch 1046.5 72 "c6")
37
(Range
(NoteRange
(NoteRangeAmplitude 7325.5 7 67.6)
(NoteRangeHarmonicFreq 1 1046.5))
(NoteRange
(NoteRangeAmplitude 2093.0 2 4242.0)
(NoteRangeHarmonicFreq 9 9418.5)))
[Harmonic 1 (-0.873) 2617.16
,Harmonic 2 (-2.35) 4242.0
,Harmonic 3 (-1.181) 1356.33
,Harmonic 4 2.775 1125.42
,Harmonic 5 1.449 580.39
,Harmonic 6 2.022 431.31
,Harmonic 7 (-0.927) 67.6
,Harmonic 8 1.932 333.39
,Harmonic 9 2.219 259.1]
note37 :: Note
note37 = Note
(Pitch 1108.73 73 "c#6")
38
(Range
(NoteRange
(NoteRangeAmplitude 9978.57 9 2.7)
(NoteRangeHarmonicFreq 1 1108.73))
(NoteRange
(NoteRangeAmplitude 2217.46 2 2180.0)
(NoteRangeHarmonicFreq 9 9978.57)))
[Harmonic 1 1.417 1029.56
,Harmonic 2 (-1.859) 2180.0
,Harmonic 3 (-2.662) 482.16
,Harmonic 4 (-1.211) 295.94
,Harmonic 5 (-1.738) 108.27
,Harmonic 6 1.321 166.75
,Harmonic 7 2.461 91.77
,Harmonic 8 (-0.359) 98.52
,Harmonic 9 2.175 2.7]
note38 :: Note
note38 = Note
(Pitch 1174.66 74 "d6")
39
(Range
(NoteRange
(NoteRangeAmplitude 9397.28 8 13.99)
(NoteRangeHarmonicFreq 1 1174.66))
(NoteRange
(NoteRangeAmplitude 1174.66 1 2549.0)
(NoteRangeHarmonicFreq 8 9397.28)))
[Harmonic 1 (-1.896) 2549.0
,Harmonic 2 1.206 1060.86
,Harmonic 3 (-2.321) 404.24
,Harmonic 4 (-2.006) 180.37
,Harmonic 5 (-2.603) 404.86
,Harmonic 6 9.9e-2 85.92
,Harmonic 7 0.685 55.07
,Harmonic 8 (-1.956) 13.99] |
|
89f2c8c1f3ea15e61b70cd0de64cb9bd53f94ca458b48f162ba9a98dbb023556 | Earthen/clj-cb | fixtures.clj | (ns earthen.clj-cb.fixtures
(:require [clojure.test :refer :all]
[earthen.clj-cb.cluster :as c]))
(def cluster (atom nil))
(def bucket-name "earthen_test")
(def default-bucket-settings {:name bucket-name
:type :COUCHBASE
:quota 100
:port 0
:password ""
:replicas 0
:index-replicas false
:flush? true})
(defn bucket
([] (c/open-bucket @cluster bucket-name))
([name] (c/open-bucket @cluster name)))
(defn manager
[]
(c/manager @cluster {:username "Administrator" :password "Admin123"}))
( defn init - bucket
;; [f]
;; (c/remove-bucket! manager bucket-name)
;; (let [create-bucket (c/insert-bucket! manager default-bucket-settings)
;; get-bucket (fn [name] (->> (c/buckets manager) (some #(if (= (:name %) name) %))))
;; manager (c/manager cluster {:username "earthen" :password "earthen"})]
;; (f)))
(defn authenticate
[username password] (c/authenticate @cluster username password))
(defn re-authenticate
[username password]
(swap! cluster (fn [_] (c/create)))
(authenticate username password))
(defn init
[f]
(reset! cluster (c/create))
(c/remove-bucket! (manager) bucket-name)
(c/insert-bucket! (manager) default-bucket-settings)
(f)
(try
(c/disconnect @cluster)
(catch java.util.concurrent.RejectedExecutionException e (println (str "Caught Expected Exception " e)))))
| null | https://raw.githubusercontent.com/Earthen/clj-cb/aaf7db4bfd26a1d6506b980d6cae6399c3776751/test/earthen/clj_cb/fixtures.clj | clojure | [f]
(c/remove-bucket! manager bucket-name)
(let [create-bucket (c/insert-bucket! manager default-bucket-settings)
get-bucket (fn [name] (->> (c/buckets manager) (some #(if (= (:name %) name) %))))
manager (c/manager cluster {:username "earthen" :password "earthen"})]
(f))) | (ns earthen.clj-cb.fixtures
(:require [clojure.test :refer :all]
[earthen.clj-cb.cluster :as c]))
(def cluster (atom nil))
(def bucket-name "earthen_test")
(def default-bucket-settings {:name bucket-name
:type :COUCHBASE
:quota 100
:port 0
:password ""
:replicas 0
:index-replicas false
:flush? true})
(defn bucket
([] (c/open-bucket @cluster bucket-name))
([name] (c/open-bucket @cluster name)))
(defn manager
[]
(c/manager @cluster {:username "Administrator" :password "Admin123"}))
( defn init - bucket
(defn authenticate
[username password] (c/authenticate @cluster username password))
(defn re-authenticate
[username password]
(swap! cluster (fn [_] (c/create)))
(authenticate username password))
(defn init
[f]
(reset! cluster (c/create))
(c/remove-bucket! (manager) bucket-name)
(c/insert-bucket! (manager) default-bucket-settings)
(f)
(try
(c/disconnect @cluster)
(catch java.util.concurrent.RejectedExecutionException e (println (str "Caught Expected Exception " e)))))
|
22d527c83dd3df1914e8139cef8aecd1f2fd8ff6704ce4cddf77a5eac297545a | jrm-code-project/LISP-Machine | load.lisp | -*- Mode : LISP ; Package : USER ; : CL ; -*-
(LET* ((P (SEND FS:FDEFINE-FILE-PATHNAME :TRANSLATED-PATHNAME))
(H (SEND P :HOST))
(W (SEND P :NEW-PATHNAME
:NAME :WILD :TYPE :WILD :VERSION :WILD))
(D (IF (ATOM (SEND P :DIRECTORY)) (LIST (SEND P :DIRECTORY)) (SEND P :DIRECTORY)))
(LH "TS"))
(FORMAT T "~&;; Logical host ~S on physical host ~S rooted at ~S~%"
LH H D)
(FS:SET-LOGICAL-PATHNAME-HOST LH
:PHYSICAL-HOST H
:TRANSLATIONS `(("SOURCE;" ,W)
("*;" ,(SEND W :NEW-DIRECTORY (APPEND D '(:WILD))))
("*;*;" ,(SEND W :NEW-DIRECTORY (APPEND D '(:WILD :WILD)))))))
(si:set-system-source-file "TS" "TS:SOURCE;SYSDEF")
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/gjcx/ts/load.lisp | lisp | Package : USER ; : CL ; -*- |
(LET* ((P (SEND FS:FDEFINE-FILE-PATHNAME :TRANSLATED-PATHNAME))
(H (SEND P :HOST))
(W (SEND P :NEW-PATHNAME
:NAME :WILD :TYPE :WILD :VERSION :WILD))
(D (IF (ATOM (SEND P :DIRECTORY)) (LIST (SEND P :DIRECTORY)) (SEND P :DIRECTORY)))
(LH "TS"))
(FORMAT T "~&;; Logical host ~S on physical host ~S rooted at ~S~%"
LH H D)
(FS:SET-LOGICAL-PATHNAME-HOST LH
:PHYSICAL-HOST H
:TRANSLATIONS `(("SOURCE;" ,W)
("*;" ,(SEND W :NEW-DIRECTORY (APPEND D '(:WILD))))
("*;*;" ,(SEND W :NEW-DIRECTORY (APPEND D '(:WILD :WILD)))))))
(si:set-system-source-file "TS" "TS:SOURCE;SYSDEF")
|
07ff8b10697520f8701b63ea16632ce4104fbde42c6177b4480c7420c86d6131 | alanzplus/EOPL | a11.rkt | #lang racket
(require "mk.rkt")
(defrel (apply-Go G e t)
(fresh (a G^)
(== `(,a . ,G^) G)
(fresh (aa da)
(== `(,aa . ,da) a)
(conde
((== aa e) (== da t))
((=/= aa e) (apply-Go G^ e t))))))
(defrel (!- G e t)
(conde
((numbero e) (== 'Nat t))
((== t 'Bool)
(conde
((== #t e))
((== #f e))))
((fresh (ne1 ne2)
(== `(+ ,ne1 ,ne2) e)
(== 'Nat t)
(!- G ne1 'Nat)
(!- G ne2 'Nat)))
((fresh (teste anse elsee)
(== `(if ,teste ,anse ,elsee) e)
(!- G teste 'Bool)
(!- G anse t)
(!- G elsee t)))
((symbolo e) (apply-Go G e t))
((fresh (x b)
(== `(lambda (,x) ,b) e)
(symbolo x)
(fresh (tx tb)
(== `(,tx -> ,tb) t)
(!- `((,x . ,tx) . ,G) b tb))))
((fresh (e1 arg)
(== `(,e1 ,arg) e)
(fresh (targ)
(!- G e1 `(,targ -> ,t))
(!- G arg targ))))))
| null | https://raw.githubusercontent.com/alanzplus/EOPL/d7b06392d26d93df851d0ca66d9edc681a06693c/Indiana-CS311/a11-Type%20Inference/a11.rkt | racket | #lang racket
(require "mk.rkt")
(defrel (apply-Go G e t)
(fresh (a G^)
(== `(,a . ,G^) G)
(fresh (aa da)
(== `(,aa . ,da) a)
(conde
((== aa e) (== da t))
((=/= aa e) (apply-Go G^ e t))))))
(defrel (!- G e t)
(conde
((numbero e) (== 'Nat t))
((== t 'Bool)
(conde
((== #t e))
((== #f e))))
((fresh (ne1 ne2)
(== `(+ ,ne1 ,ne2) e)
(== 'Nat t)
(!- G ne1 'Nat)
(!- G ne2 'Nat)))
((fresh (teste anse elsee)
(== `(if ,teste ,anse ,elsee) e)
(!- G teste 'Bool)
(!- G anse t)
(!- G elsee t)))
((symbolo e) (apply-Go G e t))
((fresh (x b)
(== `(lambda (,x) ,b) e)
(symbolo x)
(fresh (tx tb)
(== `(,tx -> ,tb) t)
(!- `((,x . ,tx) . ,G) b tb))))
((fresh (e1 arg)
(== `(,e1 ,arg) e)
(fresh (targ)
(!- G e1 `(,targ -> ,t))
(!- G arg targ))))))
|
|
2592fa35b00931912f4574ed30e75b3ee4b42af5d9c4ac164e816f6902af1580 | typedclojure/typedclojure | apply.clj | Copyright ( c ) , contributors .
;; 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 typed.cljc.checker.check.apply
(:require [clojure.core.typed.util-vars :as vs]
[typed.cljc.checker.type-rep :as r]
[typed.cljc.checker.utils :as u]
[clojure.core.typed.errors :as err]
[typed.clj.checker.parse-unparse :as prs]
[clojure.string :as str]
[typed.cljc.checker.check.utils :as cu]
[typed.clj.checker.subtype :as sub]
[typed.cljc.checker.type-ctors :as c]
[typed.cljc.checker.cs-gen :as cgen]
[typed.cljc.checker.subst :as subst])
(:import (clojure.lang Seqable)))
; we should be able to remove check-apply completely, but we should also instantiate all poly function in test case
(defn maybe-check-apply
[check-fn -invoke-apply {[fexpr & args] :args :as expr} expected]
{:post [((some-fn nil? (comp r/TCResult? u/expr-type)) %)]}
(or (-invoke-apply expr expected)
(binding [vs/*current-expr* expr]
(let [cfexpr (check-fn fexpr)
ftype (r/ret-t (u/expr-type cfexpr))
[fixed-args tail] [(butlast args) (last args)]]
(cond
;; apply of a simple polymorphic function
(r/Poly? ftype)
(let [vars (c/Poly-fresh-symbols* ftype)
bbnds (c/Poly-bbnds* vars ftype)
body (c/Poly-body* vars ftype)
_ (assert (r/FnIntersection? body))
fixed-args (mapv check-fn fixed-args)
arg-tys (mapv (comp r/ret-t u/expr-type) fixed-args)
ctail (check-fn tail)
tail-ty (r/ret-t (u/expr-type ctail))
expr (assoc expr
:args (vec (cons cfexpr (conj fixed-args ctail))))]
(loop [[{:keys [dom rng rest drest prest] :as ftype0} :as fs] (:types body)]
(cond
(empty? fs) (err/tc-delayed-error (str "Bad arguments to polymorphic function in apply")
:return (assoc expr
u/expr-type (cu/error-ret expected)))
prest nil
;the actual work, when we have a * function and a list final argument
:else
(if-let [substitution (cgen/handle-failure
(and rest
(<= (count dom)
(count arg-tys))
(cgen/infer-vararg (zipmap vars bbnds)
{}
(cons tail-ty arg-tys)
(cons (c/Un r/-nil (c/RClass-of Seqable [rest])) dom)
rest
(r/Result-type* rng)
expected)))]
(assoc expr
u/expr-type (r/ret (subst/subst-all substitution (r/Result-type* rng))))
(recur (next fs)))))))))))
| null | https://raw.githubusercontent.com/typedclojure/typedclojure/45556897356f3c9cbc7b1b6b4df263086a9d5803/typed/clj.checker/src/typed/cljc/checker/check/apply.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.
we should be able to remove check-apply completely, but we should also instantiate all poly function in test case
apply of a simple polymorphic function
the actual work, when we have a * function and a list final argument | Copyright ( c ) , contributors .
(ns typed.cljc.checker.check.apply
(:require [clojure.core.typed.util-vars :as vs]
[typed.cljc.checker.type-rep :as r]
[typed.cljc.checker.utils :as u]
[clojure.core.typed.errors :as err]
[typed.clj.checker.parse-unparse :as prs]
[clojure.string :as str]
[typed.cljc.checker.check.utils :as cu]
[typed.clj.checker.subtype :as sub]
[typed.cljc.checker.type-ctors :as c]
[typed.cljc.checker.cs-gen :as cgen]
[typed.cljc.checker.subst :as subst])
(:import (clojure.lang Seqable)))
(defn maybe-check-apply
[check-fn -invoke-apply {[fexpr & args] :args :as expr} expected]
{:post [((some-fn nil? (comp r/TCResult? u/expr-type)) %)]}
(or (-invoke-apply expr expected)
(binding [vs/*current-expr* expr]
(let [cfexpr (check-fn fexpr)
ftype (r/ret-t (u/expr-type cfexpr))
[fixed-args tail] [(butlast args) (last args)]]
(cond
(r/Poly? ftype)
(let [vars (c/Poly-fresh-symbols* ftype)
bbnds (c/Poly-bbnds* vars ftype)
body (c/Poly-body* vars ftype)
_ (assert (r/FnIntersection? body))
fixed-args (mapv check-fn fixed-args)
arg-tys (mapv (comp r/ret-t u/expr-type) fixed-args)
ctail (check-fn tail)
tail-ty (r/ret-t (u/expr-type ctail))
expr (assoc expr
:args (vec (cons cfexpr (conj fixed-args ctail))))]
(loop [[{:keys [dom rng rest drest prest] :as ftype0} :as fs] (:types body)]
(cond
(empty? fs) (err/tc-delayed-error (str "Bad arguments to polymorphic function in apply")
:return (assoc expr
u/expr-type (cu/error-ret expected)))
prest nil
:else
(if-let [substitution (cgen/handle-failure
(and rest
(<= (count dom)
(count arg-tys))
(cgen/infer-vararg (zipmap vars bbnds)
{}
(cons tail-ty arg-tys)
(cons (c/Un r/-nil (c/RClass-of Seqable [rest])) dom)
rest
(r/Result-type* rng)
expected)))]
(assoc expr
u/expr-type (r/ret (subst/subst-all substitution (r/Result-type* rng))))
(recur (next fs)))))))))))
|
7304fd11416e95b1f8f3c8835a74bf9a0b00130c2b91e5c72e64465276a25209 | hjcapple/reading-sicp | binary_tree_set.scm | #lang racket
;; P105 - [ιεδ½δΈΊδΊεζ ]
(define (entry tree)
(car tree))
(define (left-branch tree)
(cadr tree))
(define (right-branch tree)
(caddr tree))
(define (make-tree entry left right)
(list entry left right))
(define (element-of-set? x set)
(cond ((null? set) false)
((= x (entry set)) true)
((< x (entry set))
(element-of-set? x (left-branch set)))
((> x (entry set))
(element-of-set? x (right-branch set)))))
(define (adjoin-set x set)
(cond ((null? set) (make-tree x null null))
((= x (entry set)) set)
((< x (entry set))
(make-tree (entry set)
(adjoin-set x (left-branch set))
(right-branch set)))
((> x (entry set))
(make-tree (entry set)
(left-branch set)
(adjoin-set x (right-branch set))))))
;;;;;;;;;;;;;;;;;;;;;
(define (list->tree lst)
(cond ((null? lst) null)
(else (adjoin-set (car lst) (list->tree (cdr lst))))))
(define a (list->tree '(2 4 6 8 10)))
(define b (list->tree '(3 4 5 6 7 8 9)))
(element-of-set? 3 a)
(element-of-set? 9 b)
(adjoin-set 7 a)
(adjoin-set 10 a)
(adjoin-set 11 a)
| null | https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_2/binary_tree_set.scm | scheme | P105 - [ιεδ½δΈΊδΊεζ ]
| #lang racket
(define (entry tree)
(car tree))
(define (left-branch tree)
(cadr tree))
(define (right-branch tree)
(caddr tree))
(define (make-tree entry left right)
(list entry left right))
(define (element-of-set? x set)
(cond ((null? set) false)
((= x (entry set)) true)
((< x (entry set))
(element-of-set? x (left-branch set)))
((> x (entry set))
(element-of-set? x (right-branch set)))))
(define (adjoin-set x set)
(cond ((null? set) (make-tree x null null))
((= x (entry set)) set)
((< x (entry set))
(make-tree (entry set)
(adjoin-set x (left-branch set))
(right-branch set)))
((> x (entry set))
(make-tree (entry set)
(left-branch set)
(adjoin-set x (right-branch set))))))
(define (list->tree lst)
(cond ((null? lst) null)
(else (adjoin-set (car lst) (list->tree (cdr lst))))))
(define a (list->tree '(2 4 6 8 10)))
(define b (list->tree '(3 4 5 6 7 8 9)))
(element-of-set? 3 a)
(element-of-set? 9 b)
(adjoin-set 7 a)
(adjoin-set 10 a)
(adjoin-set 11 a)
|
95b0b3e9edced1b9ff2741f51e26a3b9320e0a893eed5c0cc53a8cf4d5ce5529 | facebookarchive/hs-zstd | DictionaryCompression.hs | module Main (main) where
import Codec.Compression.Zstd.Efficient
import Control.Monad (forM_)
import System.Environment (getArgs, getProgName)
import System.Exit (exitFailure)
import System.FilePath (addExtension, splitExtension)
import System.IO (hPutStrLn, stderr)
import qualified Data.ByteString as B
main :: IO ()
main = do
args <- getArgs
case args of
"-c":dictName:files -> do
dict <- (createCDict 3 . mkDict) <$> B.readFile dictName
compress dict files
"-d":dictName:files -> do
dict <- (createDDict . mkDict) <$> B.readFile dictName
decompress dict files
"-t":dictSize:dictName:files ->
case reads dictSize of
[(size,['k'])] -> train (size * 1024) dictName files
[(size,['m'])] -> train (size * 1048576) dictName files
[(size,"")] -> train size dictName files
_ -> do
program <- getProgName
hPutStrLn stderr $ "usage: " ++ program ++ " -t SIZE DICT [FILES]"
exitFailure
_ -> do
program <- getProgName
hPutStrLn stderr $ "usage: " ++ program ++ " -[cdt] ARGS"
exitFailure
compress :: CDict -> [FilePath] -> IO ()
compress dict files = do
withCCtx $ \ctx ->
forM_ files $ \file -> do
content <- compressUsingCDict ctx dict =<< B.readFile file
B.writeFile (addExtension file "zst") content
decompress :: DDict -> [FilePath] -> IO ()
decompress dict files = do
withDCtx $ \ctx ->
forM_ files $ \file -> do
result <- decompressUsingDDict ctx dict =<< B.readFile file
let newFile = case splitExtension file of
(prefix,"zst") -> prefix
_ -> addExtension file "dzst"
case result of
Skip -> hPutStrLn stderr ("NOTE: skipping " ++ file)
Error desc -> hPutStrLn stderr ("ERROR (" ++ file ++ "): " ++ desc)
Decompress bs -> B.writeFile newFile bs
train :: Int -> FilePath -> [FilePath] -> IO ()
train size dictName files = do
md <- trainFromSamples size <$> mapM B.readFile files
case md of
Left err -> do
hPutStrLn stderr ("ERROR: " ++ err)
exitFailure
Right dict -> B.writeFile dictName (fromDict dict)
| null | https://raw.githubusercontent.com/facebookarchive/hs-zstd/ae7f174bb614a2fb71cfbb36e93a136ff9430fd7/examples/low-level/DictionaryCompression.hs | haskell | module Main (main) where
import Codec.Compression.Zstd.Efficient
import Control.Monad (forM_)
import System.Environment (getArgs, getProgName)
import System.Exit (exitFailure)
import System.FilePath (addExtension, splitExtension)
import System.IO (hPutStrLn, stderr)
import qualified Data.ByteString as B
main :: IO ()
main = do
args <- getArgs
case args of
"-c":dictName:files -> do
dict <- (createCDict 3 . mkDict) <$> B.readFile dictName
compress dict files
"-d":dictName:files -> do
dict <- (createDDict . mkDict) <$> B.readFile dictName
decompress dict files
"-t":dictSize:dictName:files ->
case reads dictSize of
[(size,['k'])] -> train (size * 1024) dictName files
[(size,['m'])] -> train (size * 1048576) dictName files
[(size,"")] -> train size dictName files
_ -> do
program <- getProgName
hPutStrLn stderr $ "usage: " ++ program ++ " -t SIZE DICT [FILES]"
exitFailure
_ -> do
program <- getProgName
hPutStrLn stderr $ "usage: " ++ program ++ " -[cdt] ARGS"
exitFailure
compress :: CDict -> [FilePath] -> IO ()
compress dict files = do
withCCtx $ \ctx ->
forM_ files $ \file -> do
content <- compressUsingCDict ctx dict =<< B.readFile file
B.writeFile (addExtension file "zst") content
decompress :: DDict -> [FilePath] -> IO ()
decompress dict files = do
withDCtx $ \ctx ->
forM_ files $ \file -> do
result <- decompressUsingDDict ctx dict =<< B.readFile file
let newFile = case splitExtension file of
(prefix,"zst") -> prefix
_ -> addExtension file "dzst"
case result of
Skip -> hPutStrLn stderr ("NOTE: skipping " ++ file)
Error desc -> hPutStrLn stderr ("ERROR (" ++ file ++ "): " ++ desc)
Decompress bs -> B.writeFile newFile bs
train :: Int -> FilePath -> [FilePath] -> IO ()
train size dictName files = do
md <- trainFromSamples size <$> mapM B.readFile files
case md of
Left err -> do
hPutStrLn stderr ("ERROR: " ++ err)
exitFailure
Right dict -> B.writeFile dictName (fromDict dict)
|
|
b9383281c666ca0a691ed0863fa9c1af03d50a48ea753feda941392d44b1d10d | maitria/avi | documents.clj | (ns avi.documents
(:refer-clojure :exclude [load])
(:require [clojure.spec :as s]
[avi.edit-context
[lines :as lines]]
[avi.world :as w])
(:import (java.io FileNotFoundException)))
(s/def ::name string?)
(s/def ::text string?)
(s/def ::in-transaction? boolean?)
(s/def ::undo-entry (s/keys :req [:avi.documents/lines :avi.lenses/point]))
(s/def ::undo-log (s/coll-of ::undo-entry :into list?))
(s/def ::redo-log (s/coll-of ::undo-entry :into list?))
(s/def ::document (s/keys :req [::name
::text
::in-transaction?
::undo-log
::redo-log]))
(s/def ::documents (s/map-of nat-int? ::document))
(s/def ::document-ref nat-int?)
(s/def ::editor (s/keys :req [::documents]))
(defn- try-load
[filename]
(try
(w/read-file w/*world* filename)
(catch FileNotFoundException e
"")))
(defn load
[filename]
(let [text (if filename
(try-load filename)
"")]
{::name filename
::text text
::undo-log ()
::redo-log ()
::in-transaction? false}))
| null | https://raw.githubusercontent.com/maitria/avi/c641e9e32af4300ea7273a41e86b4f47d0f2c092/src/avi/documents.clj | clojure | (ns avi.documents
(:refer-clojure :exclude [load])
(:require [clojure.spec :as s]
[avi.edit-context
[lines :as lines]]
[avi.world :as w])
(:import (java.io FileNotFoundException)))
(s/def ::name string?)
(s/def ::text string?)
(s/def ::in-transaction? boolean?)
(s/def ::undo-entry (s/keys :req [:avi.documents/lines :avi.lenses/point]))
(s/def ::undo-log (s/coll-of ::undo-entry :into list?))
(s/def ::redo-log (s/coll-of ::undo-entry :into list?))
(s/def ::document (s/keys :req [::name
::text
::in-transaction?
::undo-log
::redo-log]))
(s/def ::documents (s/map-of nat-int? ::document))
(s/def ::document-ref nat-int?)
(s/def ::editor (s/keys :req [::documents]))
(defn- try-load
[filename]
(try
(w/read-file w/*world* filename)
(catch FileNotFoundException e
"")))
(defn load
[filename]
(let [text (if filename
(try-load filename)
"")]
{::name filename
::text text
::undo-log ()
::redo-log ()
::in-transaction? false}))
|
|
16079f19e99f5e0b719491aae34faf7b28ecea31cf046785796c67024a88c374 | ekmett/ekmett.github.com | Ring.hs | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE FlexibleInstances , MultiParamTypeClasses , UndecidableInstances #
-----------------------------------------------------------------------------
-- |
-- Module : Data.Ring
Copyright : ( c ) 2009
-- License : BSD-style
-- Maintainer :
-- Stability : experimental
-- Portability : portable (instances use MPTCs)
--
--
Defines left- and right- seminearrings . Every ' MonadPlus ' wrapped around
a ' Monoid ' qualifies due to the distributivity of ( > > =) over ' ' .
--
-- See </~ccshan/wiki/blog/posts/WordNumbers1/>
--
-----------------------------------------------------------------------------
module Data.Ring
( module Data.Group
, Ringoid
, LeftSemiNearRing
, RightSemiNearRing
, SemiRing
, Ring
, DivisionRing
, Field
) where
import Data.Group
import Data.Monoid.Self
#ifdef X_OverloadedStrings
import Data.Monoid.FromString
#endif
#ifdef M_MTL
import Control.Monad.Reader
import qualified Control.Monad.RWS.Lazy as LRWS
import qualified Control.Monad.RWS.Strict as SRWS
import qualified Control.Monad.State.Lazy as LState
import qualified Control.Monad.State.Strict as SState
import qualified Control.Monad.Writer.Lazy as LWriter
import qualified Control.Monad.Writer.Strict as SWriter
#endif
#ifdef M_FINGERTREE
import Data.FingerTree
#endif
#ifdef M_CONTAINERS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
#endif
#ifdef M_PARSEC
import Text.Parsec.Prim
#endif
#ifdef X_OverloadedStrings
import Data.Monoid.FromString
#endif
| @0@ annihilates ` times `
class (Multiplicative m, Monoid m) => Ringoid m
instance Ringoid Integer
instance Ringoid Int
instance Ringoid m => Ringoid (Self m)
instance Ringoid m => Ringoid (Dual m)
instance Monoid m => Ringoid [m]
instance Monoid m => Ringoid (Maybe m)
| @a * ( b + c ) = ( a * b ) + ( a *
class Ringoid m => LeftSemiNearRing m
instance LeftSemiNearRing m => LeftSemiNearRing (Self m)
instance RightSemiNearRing m => LeftSemiNearRing (Dual m)
| @(a + b ) * c = ( a * c ) + ( b *
class Ringoid m => RightSemiNearRing m
instance RightSemiNearRing m => RightSemiNearRing (Self m)
instance LeftSemiNearRing m => RightSemiNearRing (Dual m)
instance Monoid m => RightSemiNearRing [m]
instance Monoid m => RightSemiNearRing (Maybe m)
| A ' SemiRing ' is an instance of both ' Multiplicative ' and ' Monoid ' where
-- 'times' distributes over 'plus'.
class (RightSemiNearRing a, LeftSemiNearRing a) => SemiRing a
instance SemiRing r => SemiRing (Self r)
instance SemiRing r => SemiRing (Dual r)
class (Group a, SemiRing a) => Ring a
instance Ring r => Ring (Self r)
instance Ring r => Ring (Dual r)
class (Ring a, MultiplicativeGroup a) => DivisionRing a
instance DivisionRing r => DivisionRing (Self r)
instance DivisionRing r => DivisionRing (Dual r)
class (Ring a, MultiplicativeGroup a) => Field a
instance Field f => Field (Dual f)
instance Field f => Field (Self f)
#ifdef M_REFLECTION
instance Ringoid m => Ringoid (ReducedBy m s)
instance LeftSemiNearRing m => LeftSemiNearRing (ReducedBy m s)
instance RightSemiNearRing m => RightSemiNearRing (ReducedBy m s)
instance SemiRing r => SemiRing (ReducedBy r s)
instance Ring r => Ring (ReducedBy r s)
instance DivisionRing r => DivisionRing (ReducedBy r s)
instance Field f => Field (ReducedBy f s)
#endif
#ifdef M_PARSEC
instance (Stream s m t, Monoid a) => Ringoid (ParsecT s u m a)
instance (Stream s m t, Monoid a) => RightSemiNearRing (ParsecT s u m a)
#endif
#ifdef M_MTL
instance (MonadPlus m, Monoid n) => Ringoid (SState.StateT s m n)
instance (MonadPlus m, Monoid n) => Ringoid (LState.StateT s m n)
instance (MonadPlus m, Monoid n) => Ringoid (ReaderT e m n)
instance (MonadPlus m, Monoid w, Monoid n) => Ringoid (SRWS.RWST r w s m n)
instance (MonadPlus m, Monoid w, Monoid n) => Ringoid (LRWS.RWST r w s m n)
instance (MonadPlus m, Monoid w, Monoid n) => Ringoid (SWriter.WriterT w m n)
instance (MonadPlus m, Monoid w, Monoid n) => Ringoid (LWriter.WriterT w m n)
instance (MonadPlus m, Monoid n) => RightSemiNearRing (SState.StateT s m n)
instance (MonadPlus m, Monoid n) => RightSemiNearRing (LState.StateT s m n)
instance (MonadPlus m, Monoid n) => RightSemiNearRing (ReaderT e m n)
instance (MonadPlus m, Monoid w, Monoid n) => RightSemiNearRing (SRWS.RWST r w s m n)
instance (MonadPlus m, Monoid w, Monoid n) => RightSemiNearRing (LRWS.RWST r w s m n)
instance (MonadPlus m, Monoid w, Monoid n) => RightSemiNearRing (SWriter.WriterT w m n)
instance (MonadPlus m, Monoid w, Monoid n) => RightSemiNearRing (LWriter.WriterT w m n)
#endif
#ifdef M_FINGERTREE
instance (Measured v m, Monoid m) => Ringoid (FingerTree v m)
instance (Measured v m, Monoid m) => RightSemiNearRing (FingerTree v m)
#endif
#ifdef M_CONTAINERS
instance Monoid m => Ringoid (Seq m)
instance Monoid m => RightSemiNearRing (Seq m)
#endif
#ifdef X_OverloadedStrings
instance Ringoid m => Ringoid (FromString m)
instance RightSemiNearRing m => RightSemiNearRing (FromString m)
instance LeftSemiNearRing m => LeftSemiNearRing (FromString m)
instance SemiRing r => SemiRing (FromString r)
instance Ring r => Ring (FromString r)
instance DivisionRing r => DivisionRing (FromString r)
instance Field f => Field (FromString f)
#endif
| null | https://raw.githubusercontent.com/ekmett/ekmett.github.com/8d3abab5b66db631e148e1d046d18909bece5893/haskell/monoids/_darcs/pristine/Data/Ring.hs | haskell | ---------------------------------------------------------------------------
|
Module : Data.Ring
License : BSD-style
Maintainer :
Stability : experimental
Portability : portable (instances use MPTCs)
See </~ccshan/wiki/blog/posts/WordNumbers1/>
---------------------------------------------------------------------------
'times' distributes over 'plus'. | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE FlexibleInstances , MultiParamTypeClasses , UndecidableInstances #
Copyright : ( c ) 2009
Defines left- and right- seminearrings . Every ' MonadPlus ' wrapped around
a ' Monoid ' qualifies due to the distributivity of ( > > =) over ' ' .
module Data.Ring
( module Data.Group
, Ringoid
, LeftSemiNearRing
, RightSemiNearRing
, SemiRing
, Ring
, DivisionRing
, Field
) where
import Data.Group
import Data.Monoid.Self
#ifdef X_OverloadedStrings
import Data.Monoid.FromString
#endif
#ifdef M_MTL
import Control.Monad.Reader
import qualified Control.Monad.RWS.Lazy as LRWS
import qualified Control.Monad.RWS.Strict as SRWS
import qualified Control.Monad.State.Lazy as LState
import qualified Control.Monad.State.Strict as SState
import qualified Control.Monad.Writer.Lazy as LWriter
import qualified Control.Monad.Writer.Strict as SWriter
#endif
#ifdef M_FINGERTREE
import Data.FingerTree
#endif
#ifdef M_CONTAINERS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
#endif
#ifdef M_PARSEC
import Text.Parsec.Prim
#endif
#ifdef X_OverloadedStrings
import Data.Monoid.FromString
#endif
| @0@ annihilates ` times `
class (Multiplicative m, Monoid m) => Ringoid m
instance Ringoid Integer
instance Ringoid Int
instance Ringoid m => Ringoid (Self m)
instance Ringoid m => Ringoid (Dual m)
instance Monoid m => Ringoid [m]
instance Monoid m => Ringoid (Maybe m)
| @a * ( b + c ) = ( a * b ) + ( a *
class Ringoid m => LeftSemiNearRing m
instance LeftSemiNearRing m => LeftSemiNearRing (Self m)
instance RightSemiNearRing m => LeftSemiNearRing (Dual m)
| @(a + b ) * c = ( a * c ) + ( b *
class Ringoid m => RightSemiNearRing m
instance RightSemiNearRing m => RightSemiNearRing (Self m)
instance LeftSemiNearRing m => RightSemiNearRing (Dual m)
instance Monoid m => RightSemiNearRing [m]
instance Monoid m => RightSemiNearRing (Maybe m)
| A ' SemiRing ' is an instance of both ' Multiplicative ' and ' Monoid ' where
class (RightSemiNearRing a, LeftSemiNearRing a) => SemiRing a
instance SemiRing r => SemiRing (Self r)
instance SemiRing r => SemiRing (Dual r)
class (Group a, SemiRing a) => Ring a
instance Ring r => Ring (Self r)
instance Ring r => Ring (Dual r)
class (Ring a, MultiplicativeGroup a) => DivisionRing a
instance DivisionRing r => DivisionRing (Self r)
instance DivisionRing r => DivisionRing (Dual r)
class (Ring a, MultiplicativeGroup a) => Field a
instance Field f => Field (Dual f)
instance Field f => Field (Self f)
#ifdef M_REFLECTION
instance Ringoid m => Ringoid (ReducedBy m s)
instance LeftSemiNearRing m => LeftSemiNearRing (ReducedBy m s)
instance RightSemiNearRing m => RightSemiNearRing (ReducedBy m s)
instance SemiRing r => SemiRing (ReducedBy r s)
instance Ring r => Ring (ReducedBy r s)
instance DivisionRing r => DivisionRing (ReducedBy r s)
instance Field f => Field (ReducedBy f s)
#endif
#ifdef M_PARSEC
instance (Stream s m t, Monoid a) => Ringoid (ParsecT s u m a)
instance (Stream s m t, Monoid a) => RightSemiNearRing (ParsecT s u m a)
#endif
#ifdef M_MTL
instance (MonadPlus m, Monoid n) => Ringoid (SState.StateT s m n)
instance (MonadPlus m, Monoid n) => Ringoid (LState.StateT s m n)
instance (MonadPlus m, Monoid n) => Ringoid (ReaderT e m n)
instance (MonadPlus m, Monoid w, Monoid n) => Ringoid (SRWS.RWST r w s m n)
instance (MonadPlus m, Monoid w, Monoid n) => Ringoid (LRWS.RWST r w s m n)
instance (MonadPlus m, Monoid w, Monoid n) => Ringoid (SWriter.WriterT w m n)
instance (MonadPlus m, Monoid w, Monoid n) => Ringoid (LWriter.WriterT w m n)
instance (MonadPlus m, Monoid n) => RightSemiNearRing (SState.StateT s m n)
instance (MonadPlus m, Monoid n) => RightSemiNearRing (LState.StateT s m n)
instance (MonadPlus m, Monoid n) => RightSemiNearRing (ReaderT e m n)
instance (MonadPlus m, Monoid w, Monoid n) => RightSemiNearRing (SRWS.RWST r w s m n)
instance (MonadPlus m, Monoid w, Monoid n) => RightSemiNearRing (LRWS.RWST r w s m n)
instance (MonadPlus m, Monoid w, Monoid n) => RightSemiNearRing (SWriter.WriterT w m n)
instance (MonadPlus m, Monoid w, Monoid n) => RightSemiNearRing (LWriter.WriterT w m n)
#endif
#ifdef M_FINGERTREE
instance (Measured v m, Monoid m) => Ringoid (FingerTree v m)
instance (Measured v m, Monoid m) => RightSemiNearRing (FingerTree v m)
#endif
#ifdef M_CONTAINERS
instance Monoid m => Ringoid (Seq m)
instance Monoid m => RightSemiNearRing (Seq m)
#endif
#ifdef X_OverloadedStrings
instance Ringoid m => Ringoid (FromString m)
instance RightSemiNearRing m => RightSemiNearRing (FromString m)
instance LeftSemiNearRing m => LeftSemiNearRing (FromString m)
instance SemiRing r => SemiRing (FromString r)
instance Ring r => Ring (FromString r)
instance DivisionRing r => DivisionRing (FromString r)
instance Field f => Field (FromString f)
#endif
|
3e97951b28c0b39fc2563554b43a5202884df55711d7c468c9e06eab278e48ea | AccelerateHS/accelerate-examples | Issue286.hs | --
--
module Test.Issues.Issue286 (test_issue286)
where
import Config
import Test.Framework
import Test.Framework.Providers.HUnit
import Prelude as P
import Data.Array.Accelerate as A hiding ( (>->), (==) )
import Data.Array.Accelerate.IO.Data.Vector.Storable as A
import Data.Array.Accelerate.Examples.Internal as A
import Pipes
import Data.Vector.Storable as S
test_issue286 :: Backend -> Config -> Test
test_issue286 backend _conf =
testGroup "286 (run with +RTS -M4M -RTS or check heap profile in EKG or similar)"
[
testCase "hs.hs" (void $ runEffect $ hs_producer sh >-> hs_consume_sv)
, testCase "hs.acc" (void $ runEffect $ hs_producer sh >-> acc_consume_sv sh backend)
, testCase "acc.hs" (void $ runEffect $ acc_producer sh >-> hs_consume_acc)
, testCase "acc.acc" (void $ runEffect $ acc_producer sh >-> acc_consume_acc backend)
]
where
sh :: DIM2
sh = Z :. 120 :. 659
hs_producer :: DIM2 -> Producer (S.Vector Word8) IO ()
hs_producer sh = producer' 0
where
producer' :: Int -> Producer (S.Vector Word8) IO ()
producer' i = do
yield $ S.replicate (arraySize sh) 1
if i == 5
then producer' 0
else producer' (i+1)
hs_consume_sv :: Consumer (S.Vector Word8) IO ()
hs_consume_sv = consumer' 0 0
where
consumer' :: Int -> Float -> Consumer (S.Vector Word8) IO ()
consumer' n acc = do
v <- await
let
i = S.sum $ S.map P.fromIntegral v
i' = i + acc
n' = n + 1
if i' `seq` n' `seq` (n == lIMIT)
then acc `seq` return ()
else consumer' n' i'
hs_consume_acc :: Consumer (Array DIM2 Word8) IO ()
hs_consume_acc = consumer' 0 0
where
consumer' :: Int -> Float -> Consumer (Array DIM2 Word8) IO ()
consumer' n acc = do
v <- await
let
a = toVectors v :: S.Vector Word8
i = S.sum $ S.map P.fromIntegral a
i' = i + acc
n' = n + 1
if i' `seq` n' `seq` (n == lIMIT)
then acc `seq` return ()
else consumer' n' i'
acc_producer :: DIM2 -> Producer (Array DIM2 Word8) IO ()
acc_producer sh = producer' 0
where
producer' :: Int -> Producer (Array DIM2 Word8) IO ()
producer' i =
do
yield $ A.fromFunction sh (\_ -> 1)
if i == 5
then producer' 0
else producer' (i+1)
acc_consume_sv :: DIM2 -> Backend -> Consumer (S.Vector Word8) IO ()
acc_consume_sv sh backend = consumer' 0 0
where
go = run1 backend (A.sum . A.flatten . A.map A.fromIntegral)
consumer' :: Int -> Float -> Consumer (S.Vector Word8) IO ()
consumer' n acc = do
v <- await
let
a = fromVectors sh v :: Array DIM2 Word8
i = the' $ go a
i' = i + acc
n' = n + 1
if i' `seq` n' `seq` (n == lIMIT)
then acc `seq` return ()
else consumer' n' i'
acc_consume_acc :: Backend -> Consumer (Array DIM2 Word8) IO ()
acc_consume_acc backend = consumer' 0 0
where
go = run1 backend (A.sum . A.flatten . A.map A.fromIntegral)
consumer' :: Int -> Float -> Consumer (Array DIM2 Word8) IO ()
consumer' n acc = do
a <- await
let
i = the' $ go a
i' = i + acc
n' = n + 1
if i' `seq` n' `seq` (n == lIMIT)
then acc `seq` return ()
else consumer' n' i'
lIMIT :: Int
lIMIT = 50000
the' :: Scalar a -> a
the' x = indexArray x Z
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate-examples/a973ee423b5eadda6ef2e2504d2383f625e49821/examples/icebox/nofib/Test/Issues/Issue286.hs | haskell |
module Test.Issues.Issue286 (test_issue286)
where
import Config
import Test.Framework
import Test.Framework.Providers.HUnit
import Prelude as P
import Data.Array.Accelerate as A hiding ( (>->), (==) )
import Data.Array.Accelerate.IO.Data.Vector.Storable as A
import Data.Array.Accelerate.Examples.Internal as A
import Pipes
import Data.Vector.Storable as S
test_issue286 :: Backend -> Config -> Test
test_issue286 backend _conf =
testGroup "286 (run with +RTS -M4M -RTS or check heap profile in EKG or similar)"
[
testCase "hs.hs" (void $ runEffect $ hs_producer sh >-> hs_consume_sv)
, testCase "hs.acc" (void $ runEffect $ hs_producer sh >-> acc_consume_sv sh backend)
, testCase "acc.hs" (void $ runEffect $ acc_producer sh >-> hs_consume_acc)
, testCase "acc.acc" (void $ runEffect $ acc_producer sh >-> acc_consume_acc backend)
]
where
sh :: DIM2
sh = Z :. 120 :. 659
hs_producer :: DIM2 -> Producer (S.Vector Word8) IO ()
hs_producer sh = producer' 0
where
producer' :: Int -> Producer (S.Vector Word8) IO ()
producer' i = do
yield $ S.replicate (arraySize sh) 1
if i == 5
then producer' 0
else producer' (i+1)
hs_consume_sv :: Consumer (S.Vector Word8) IO ()
hs_consume_sv = consumer' 0 0
where
consumer' :: Int -> Float -> Consumer (S.Vector Word8) IO ()
consumer' n acc = do
v <- await
let
i = S.sum $ S.map P.fromIntegral v
i' = i + acc
n' = n + 1
if i' `seq` n' `seq` (n == lIMIT)
then acc `seq` return ()
else consumer' n' i'
hs_consume_acc :: Consumer (Array DIM2 Word8) IO ()
hs_consume_acc = consumer' 0 0
where
consumer' :: Int -> Float -> Consumer (Array DIM2 Word8) IO ()
consumer' n acc = do
v <- await
let
a = toVectors v :: S.Vector Word8
i = S.sum $ S.map P.fromIntegral a
i' = i + acc
n' = n + 1
if i' `seq` n' `seq` (n == lIMIT)
then acc `seq` return ()
else consumer' n' i'
acc_producer :: DIM2 -> Producer (Array DIM2 Word8) IO ()
acc_producer sh = producer' 0
where
producer' :: Int -> Producer (Array DIM2 Word8) IO ()
producer' i =
do
yield $ A.fromFunction sh (\_ -> 1)
if i == 5
then producer' 0
else producer' (i+1)
acc_consume_sv :: DIM2 -> Backend -> Consumer (S.Vector Word8) IO ()
acc_consume_sv sh backend = consumer' 0 0
where
go = run1 backend (A.sum . A.flatten . A.map A.fromIntegral)
consumer' :: Int -> Float -> Consumer (S.Vector Word8) IO ()
consumer' n acc = do
v <- await
let
a = fromVectors sh v :: Array DIM2 Word8
i = the' $ go a
i' = i + acc
n' = n + 1
if i' `seq` n' `seq` (n == lIMIT)
then acc `seq` return ()
else consumer' n' i'
acc_consume_acc :: Backend -> Consumer (Array DIM2 Word8) IO ()
acc_consume_acc backend = consumer' 0 0
where
go = run1 backend (A.sum . A.flatten . A.map A.fromIntegral)
consumer' :: Int -> Float -> Consumer (Array DIM2 Word8) IO ()
consumer' n acc = do
a <- await
let
i = the' $ go a
i' = i + acc
n' = n + 1
if i' `seq` n' `seq` (n == lIMIT)
then acc `seq` return ()
else consumer' n' i'
lIMIT :: Int
lIMIT = 50000
the' :: Scalar a -> a
the' x = indexArray x Z
|
|
5d964889f865d4597a7efdea30c90a9d0a1ed496290ba838fedcf27f099192e6 | rabbitmq/khepri | timeout.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 Β© 2021 - 2023 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(timeout).
-include_lib("eunit/include/eunit.hrl").
-include("include/khepri.hrl").
-include("test/helpers.hrl").
can_specify_timeout_in_milliseconds_test_() ->
{setup,
fun() -> test_ra_server_helpers:setup(?FUNCTION_NAME) end,
fun(Priv) -> test_ra_server_helpers:cleanup(Priv) end,
[?_assertEqual(
ok,
khepri:put(?FUNCTION_NAME, [foo], foo_value, #{timeout => 60000})),
?_assertEqual(
{ok, foo_value},
khepri:get(?FUNCTION_NAME, [foo], #{timeout => 60000})),
?_assertEqual(
ok,
khepri:delete(?FUNCTION_NAME, [foo], #{timeout => 60000}))]}.
can_specify_infinity_timeout_test_() ->
{setup,
fun() -> test_ra_server_helpers:setup(?FUNCTION_NAME) end,
fun(Priv) -> test_ra_server_helpers:cleanup(Priv) end,
[?_assertEqual(
ok,
khepri:put(?FUNCTION_NAME, [foo], foo_value, #{timeout => infinity})),
?_assertEqual(
{ok, foo_value},
khepri:get(?FUNCTION_NAME, [foo], #{timeout => infinity})),
?_assertEqual(
ok,
khepri:delete(?FUNCTION_NAME, [foo], #{timeout => infinity}))]}.
| null | https://raw.githubusercontent.com/rabbitmq/khepri/3527362ad9f59cff36231eb4e7b34dc066aa0f50/test/timeout.erl | erlang | 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 Β© 2021 - 2023 VMware , Inc. or its affiliates . All rights reserved .
-module(timeout).
-include_lib("eunit/include/eunit.hrl").
-include("include/khepri.hrl").
-include("test/helpers.hrl").
can_specify_timeout_in_milliseconds_test_() ->
{setup,
fun() -> test_ra_server_helpers:setup(?FUNCTION_NAME) end,
fun(Priv) -> test_ra_server_helpers:cleanup(Priv) end,
[?_assertEqual(
ok,
khepri:put(?FUNCTION_NAME, [foo], foo_value, #{timeout => 60000})),
?_assertEqual(
{ok, foo_value},
khepri:get(?FUNCTION_NAME, [foo], #{timeout => 60000})),
?_assertEqual(
ok,
khepri:delete(?FUNCTION_NAME, [foo], #{timeout => 60000}))]}.
can_specify_infinity_timeout_test_() ->
{setup,
fun() -> test_ra_server_helpers:setup(?FUNCTION_NAME) end,
fun(Priv) -> test_ra_server_helpers:cleanup(Priv) end,
[?_assertEqual(
ok,
khepri:put(?FUNCTION_NAME, [foo], foo_value, #{timeout => infinity})),
?_assertEqual(
{ok, foo_value},
khepri:get(?FUNCTION_NAME, [foo], #{timeout => infinity})),
?_assertEqual(
ok,
khepri:delete(?FUNCTION_NAME, [foo], #{timeout => infinity}))]}.
|
|
fe8525f57942d2bd67016fda3a6045af80b21da3147e2461979bcad17d0ef9ee | wavewave/hoodle | HitTest.hs | -- deprecated. will be removed
module Graphics.Hoodle.Render.Type.HitTest
( AlterList (..), -- re-export
NotHitted (..), -- re-export
Hitted (..), -- re-export
TAlterHitted, -- re-export
TEitherAlterHitted (..), -- re-export
getA, -- re-export
getB, -- re-export
interleave, -- re-export
takeHitted, -- re-export
isAnyHitted, -- re-export
StrokeHitted,
RItemHitted,
takeFirstFromHitted,
takeLastFromHitted,
)
where
import Data.Hoodle.BBox (BBoxed)
import Data.Hoodle.Simple (Stroke)
import Graphics.Hoodle.Render.Type.Item (RItem)
import Hoodle.HitTest.Type
( AlterList (..),
Hitted (..),
NotHitted (..),
TAlterHitted,
TEitherAlterHitted (..),
getA,
getB,
interleave,
isAnyHitted,
takeHitted,
)
import Prelude hiding (fst, snd)
-- |
type StrokeHitted = AlterList (NotHitted (BBoxed Stroke)) (Hitted (BBoxed Stroke))
-- |
type RItemHitted = AlterList (NotHitted RItem) (Hitted RItem)
-- |
takeFirstFromHitted :: RItemHitted -> RItemHitted
takeFirstFromHitted Empty = Empty
takeFirstFromHitted (a :- Empty) = a :- Empty
takeFirstFromHitted (a :- b :- xs) =
let (b1, bs) = splitAt 1 (unHitted b)
rs = concat $ interleave unNotHitted unHitted xs
in a :- Hitted b1 :- NotHitted (bs ++ rs) :- Empty
-- |
takeLastFromHitted :: RItemHitted -> RItemHitted
takeLastFromHitted Empty = Empty
takeLastFromHitted (a :- Empty) = a :- Empty
takeLastFromHitted (a :- b :- Empty) =
let b' = unHitted b
in if (not . null) b'
then
let (bs, b1) = (,) <$> init <*> last $ b'
in NotHitted (unNotHitted a ++ bs) :- Hitted [b1] :- Empty
else NotHitted (unNotHitted a ++ b') :- Empty
takeLastFromHitted (a1 :- b :- a2 :- Empty) =
let b' = unHitted b
in if (not . null) b'
then
let (bs, b1) = (,) <$> init <*> last $ b'
in NotHitted (unNotHitted a1 ++ bs) :- Hitted [b1] :- a2 :- Empty
else NotHitted (unNotHitted a1 ++ b' ++ unNotHitted a2) :- Empty
takeLastFromHitted (a :- b :- xs) =
let xs' = takeLastFromHitted xs
in case xs' of
Empty ->
let b' = unHitted b
in if (not . null) b'
then
let (bs, b1) = (,) <$> init <*> last $ b'
in NotHitted (unNotHitted a ++ bs) :- Hitted [b1] :- Empty
else NotHitted (unNotHitted a ++ b') :- Empty
a' :- Empty ->
let b' = unHitted b
in if (not . null) b'
then
let (bs, b1) = (,) <$> init <*> last $ b'
in NotHitted (unNotHitted a ++ bs) :- Hitted [b1] :- a' :- Empty
else NotHitted (unNotHitted a ++ b' ++ unNotHitted a') :- Empty
a' :- b' :- xs'' -> NotHitted (unNotHitted a ++ unHitted b ++ unNotHitted a') :- b' :- xs''
| null | https://raw.githubusercontent.com/wavewave/hoodle/fa7481d14a53733b2f6ae9debc95357d904a943c/render/src/Graphics/Hoodle/Render/Type/HitTest.hs | haskell | deprecated. will be removed
re-export
re-export
re-export
re-export
re-export
re-export
re-export
re-export
re-export
re-export
|
|
|
| | module Graphics.Hoodle.Render.Type.HitTest
StrokeHitted,
RItemHitted,
takeFirstFromHitted,
takeLastFromHitted,
)
where
import Data.Hoodle.BBox (BBoxed)
import Data.Hoodle.Simple (Stroke)
import Graphics.Hoodle.Render.Type.Item (RItem)
import Hoodle.HitTest.Type
( AlterList (..),
Hitted (..),
NotHitted (..),
TAlterHitted,
TEitherAlterHitted (..),
getA,
getB,
interleave,
isAnyHitted,
takeHitted,
)
import Prelude hiding (fst, snd)
type StrokeHitted = AlterList (NotHitted (BBoxed Stroke)) (Hitted (BBoxed Stroke))
type RItemHitted = AlterList (NotHitted RItem) (Hitted RItem)
takeFirstFromHitted :: RItemHitted -> RItemHitted
takeFirstFromHitted Empty = Empty
takeFirstFromHitted (a :- Empty) = a :- Empty
takeFirstFromHitted (a :- b :- xs) =
let (b1, bs) = splitAt 1 (unHitted b)
rs = concat $ interleave unNotHitted unHitted xs
in a :- Hitted b1 :- NotHitted (bs ++ rs) :- Empty
takeLastFromHitted :: RItemHitted -> RItemHitted
takeLastFromHitted Empty = Empty
takeLastFromHitted (a :- Empty) = a :- Empty
takeLastFromHitted (a :- b :- Empty) =
let b' = unHitted b
in if (not . null) b'
then
let (bs, b1) = (,) <$> init <*> last $ b'
in NotHitted (unNotHitted a ++ bs) :- Hitted [b1] :- Empty
else NotHitted (unNotHitted a ++ b') :- Empty
takeLastFromHitted (a1 :- b :- a2 :- Empty) =
let b' = unHitted b
in if (not . null) b'
then
let (bs, b1) = (,) <$> init <*> last $ b'
in NotHitted (unNotHitted a1 ++ bs) :- Hitted [b1] :- a2 :- Empty
else NotHitted (unNotHitted a1 ++ b' ++ unNotHitted a2) :- Empty
takeLastFromHitted (a :- b :- xs) =
let xs' = takeLastFromHitted xs
in case xs' of
Empty ->
let b' = unHitted b
in if (not . null) b'
then
let (bs, b1) = (,) <$> init <*> last $ b'
in NotHitted (unNotHitted a ++ bs) :- Hitted [b1] :- Empty
else NotHitted (unNotHitted a ++ b') :- Empty
a' :- Empty ->
let b' = unHitted b
in if (not . null) b'
then
let (bs, b1) = (,) <$> init <*> last $ b'
in NotHitted (unNotHitted a ++ bs) :- Hitted [b1] :- a' :- Empty
else NotHitted (unNotHitted a ++ b' ++ unNotHitted a') :- Empty
a' :- b' :- xs'' -> NotHitted (unNotHitted a ++ unHitted b ++ unNotHitted a') :- b' :- xs''
|
94b3713d3e85479dcdbbaf1fed98fced16bdaa7c844860b0c7e734dbe1c5ca0d | wingo/fibers | concurrent-web-hello.scm | (use-modules (fibers web server))
(define (handler request body)
(values '((content-type . (text/plain)))
"Hello, World!"))
(run-server handler)
| null | https://raw.githubusercontent.com/wingo/fibers/44d17e64e581fb281bae1390f74c762ecf089b58/examples/concurrent-web-hello.scm | scheme | (use-modules (fibers web server))
(define (handler request body)
(values '((content-type . (text/plain)))
"Hello, World!"))
(run-server handler)
|
|
c903178207e4c0fa743e628534028451b8351404690a867e850536e13ae969b5 | kovasb/gamma-driver | arraybuffer.cljs | (ns gamma.webgl.model.arraybuffer
(:require [gamma.webgl.model.core :as m]))
(defn ->float32 [x]
(js/Float32Array.
(clj->js (flatten x))))
(defn arraybuffer-data [gl bo mode data]
(.bindBuffer gl (.-ARRAY_BUFFER gl) bo)
(.bufferData
gl
(.-ARRAY_BUFFER gl)
data
(.-STATIC_DRAW gl)))
(defrecord Arraybuffer [root parts compare bufferdata-fn]
m/IModel
(resolve [this val]
(@parts val))
(conform [this val]
(reduce-kv
(fn [_ k v]
(let [p @parts]
(case k
:data (when true ;(not (compare (:data p) v))
(arraybuffer-data (:gl root) (:object p) (:mode p) (bufferdata-fn v))
(swap! parts assoc :data v)))))
nil
val)))
(defn create-arraybuffer [root val]
(let [o (.createBuffer (:gl root))]
(->Arraybuffer root (atom (assoc val :object o)) = ->float32)))
| null | https://raw.githubusercontent.com/kovasb/gamma-driver/abe0e1dd01365404342f4e8e04263e48c4648b6e/src/gamma/webgl/model/arraybuffer.cljs | clojure | (not (compare (:data p) v)) | (ns gamma.webgl.model.arraybuffer
(:require [gamma.webgl.model.core :as m]))
(defn ->float32 [x]
(js/Float32Array.
(clj->js (flatten x))))
(defn arraybuffer-data [gl bo mode data]
(.bindBuffer gl (.-ARRAY_BUFFER gl) bo)
(.bufferData
gl
(.-ARRAY_BUFFER gl)
data
(.-STATIC_DRAW gl)))
(defrecord Arraybuffer [root parts compare bufferdata-fn]
m/IModel
(resolve [this val]
(@parts val))
(conform [this val]
(reduce-kv
(fn [_ k v]
(let [p @parts]
(case k
(arraybuffer-data (:gl root) (:object p) (:mode p) (bufferdata-fn v))
(swap! parts assoc :data v)))))
nil
val)))
(defn create-arraybuffer [root val]
(let [o (.createBuffer (:gl root))]
(->Arraybuffer root (atom (assoc val :object o)) = ->float32)))
|
7090aa41ca5a2a0629342b8c16c21606eb71ec8b6c594f4f956cb2f837c71a12 | omelkonian/AlgoRhythm | TMusic.hs | {-# LANGUAGE PostfixOperators #-}
# LANGUAGE ScopedTypeVariables #
module TMusic where
import Control.Arrow ((>>>))
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit ((@?=))
import Test.QuickCheck ((==>))
import GenSetup
import Music
musicTests :: Test
musicTests = testGroup "Music"
[ testGroup "Instances"
[ testCase "Functor" $
const (D#5) <$> line [C#4<|qn, D#2<|wn] @?= line [D#5<|qn, D#5<|wn]
, testCase "Foldable" $
let f a = [a]
in foldMap f (line [C#4<|qn, D#2<|wn]) @?= [C#4, D#2]
]
, testGroup "Transpose"
[ testCase "a pitch class" $
C ~> M3 @?= E
, testCase "a pitch" $
C#4 ~> M7 @?= B#4
, testCase "a note" $
C#4 <|hn ~> M3 @?= E#4<|hn
, testCase "a chord" $
let a = chord $ C#4=|maj <|| def
a' = chord $ C#5=|maj <|| def
in a ~> P8 @?= a'
, testCase "a sequence of chords" $
let a = chord $ C#4=|maj7 <|| 1%8
a' = chord $ Cs#4=|maj7 <|| 1%8
b = chord $ Ds#4=|aug <|| def
b' = chord $ E#4=|aug <|| def
in line [a, b, a] ~> Mi2 @?= line [a', b', a']
, testCase "a scale" $
let a = scale $ C#4+|minor <|| def
a' = scale $ B#4+|minor <|| def
in a ~> M7 @?= a'
, testCase "a sequence of scales" $
let a = line $ C#4+|blues <|| 1%8
a' = line $ Cs#4+|blues <|| 1%8
b = line $ Ds#4+|harmonicMinor <|| def
b' = line $ E#4+|harmonicMinor <|| def
in line [a, b, a] ~> Mi2 @?= line [a', b', a']
, testProperty "identityUp" $ \(p :: Pitch) (d :: Duration) ->
p<|d ~> P1 == p<|d
, testProperty "identityDown" $ \(p :: Pitch) (d :: Duration) ->
p<|d <~ P1 == p<|d
, testProperty "commutativeUp" $
\(p :: Pitch) (m :: Interval) (n :: Interval) (d :: Duration) ->
((~> m) >>> (~> n)) (p<|d) == ((~> n) >>> (~> m)) (p<|d)
, testProperty "commutativeDown" $
\(p :: Pitch) (m :: Interval) (n :: Interval) (d :: Duration) ->
((<~ m) >>> (<~ n)) (p<|d) == ((<~ n) >>> (<~ m)) (p<|d)
, testProperty "erasure" $
\(p :: Pitch) (m :: Interval) (d :: Duration) ->
fromEnum p + fromEnum m <= fromEnum (maxBound :: Pitch) ==>
((~> m) >>> (<~ m)) (p<|d) == (p<|d)
]
, testGroup "Invert"
[ testCase "absolute pitches" $
invert ([0, 10, -20] :: [AbsPitch]) @?= [0, -10, 20]
, testCase "a melody" $
let melody = line [C#4<|hn, E#2<|wn, C#3<|en]
melody' = line [C#4<|hn, Gs#5<|wn, C#5<|en]
in invert melody @?= melody'
, testCase "a chord" $
invert maj7 @?= [P1, Mi3, P5, Mi6]
, testProperty "a diminished chord" $ \n -> n > 0 ==>
invertN n dim7 == dim7
, testCase "a scale" $
mode vi ionian @?= minor
, testProperty "scale orbit" $ do
sc <- genScale
return $ or [invertN n sc == sc | n <- [5..9]]
, testProperty "chord orbit" $ do
ch <- genChord
return $ length ch < 5 ==> or [invertN n ch == ch | n <- [4, 5]]
]
, testGroup "Retro"
[ testCase "a melody" $
(line [C#4<|hn, (wn~~), Gs#4<|en] ><) @?=
line [Gs#4<|en, (wn~~), C#4<|hn]
, testCase "a chord" $
(chord (C#4=|maj <||wn) ><) @?= chord (C#4=|maj <||wn)
, testCase "a scale" $
(scale (C#4+|major <||sn) ><) @?=
line (reverse [C, D, E, F, G, A, B]<#4<||sn)
]
, testGroup "Repeat"
[ testCase "a single note" $
let note = C#4<|wn
in 4 ## note @?= note :+: note :+: note :+: note
, testCase "a piece of music" $
let piece = line $ chord <$> [c, c', c']
c = Cs#4=|maj7 <|| def
c' = db#3=|m7b5 <|| def
in 3 ## piece @?= piece :+: piece :+: piece
]
, testGroup "Scaling time"
[ testCase "to smaller single duration" $
2 *~ hn @?= qn
, testCase "to bigger single duration" $
1%2 *~ sn @?= en
, testCase "a melody" $
1%4 *~ C#4<|en :+: C#3<|sn @?= C#4<|hn :+: C#3<|qn
, testCase "a chord" $
4 *~ chord (C#4=|maj <||wn) @?= chord (C#4=|maj <||qn)
, testCase "a scale" $
1%4 *~ scale (eb#2+|bebopDorian <||qn) @?= scale (eb#2=|bebopDorian <||wn)
]
, testGroup "Other"
[ testCase "toList" $
musicToList (C#4<|hn :+: (wn~~) :+: C#5<|qn) @?=
[(Just $ C#4, hn), (Nothing, wn), (Just $ C#5, qn)]
, testCase "fromList" $
listToMusic [(Just $ C#4, hn), (Nothing, wn), (Just $ C#5, qn)] @?=
(C#4<|hn :+: (wn~~) :+: C#5<|qn)
, testCase "normalize" $
let m = (wn~~) :: Melody
in normalize ((m :+: m) :+: m) @?= m :+: m :+: m
]
]
| null | https://raw.githubusercontent.com/omelkonian/AlgoRhythm/fdc1ccbae0b3d8a7635b24d37716123aba2d6c11/AlgoRhythm/test/TMusic.hs | haskell | # LANGUAGE PostfixOperators # | # LANGUAGE ScopedTypeVariables #
module TMusic where
import Control.Arrow ((>>>))
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit ((@?=))
import Test.QuickCheck ((==>))
import GenSetup
import Music
musicTests :: Test
musicTests = testGroup "Music"
[ testGroup "Instances"
[ testCase "Functor" $
const (D#5) <$> line [C#4<|qn, D#2<|wn] @?= line [D#5<|qn, D#5<|wn]
, testCase "Foldable" $
let f a = [a]
in foldMap f (line [C#4<|qn, D#2<|wn]) @?= [C#4, D#2]
]
, testGroup "Transpose"
[ testCase "a pitch class" $
C ~> M3 @?= E
, testCase "a pitch" $
C#4 ~> M7 @?= B#4
, testCase "a note" $
C#4 <|hn ~> M3 @?= E#4<|hn
, testCase "a chord" $
let a = chord $ C#4=|maj <|| def
a' = chord $ C#5=|maj <|| def
in a ~> P8 @?= a'
, testCase "a sequence of chords" $
let a = chord $ C#4=|maj7 <|| 1%8
a' = chord $ Cs#4=|maj7 <|| 1%8
b = chord $ Ds#4=|aug <|| def
b' = chord $ E#4=|aug <|| def
in line [a, b, a] ~> Mi2 @?= line [a', b', a']
, testCase "a scale" $
let a = scale $ C#4+|minor <|| def
a' = scale $ B#4+|minor <|| def
in a ~> M7 @?= a'
, testCase "a sequence of scales" $
let a = line $ C#4+|blues <|| 1%8
a' = line $ Cs#4+|blues <|| 1%8
b = line $ Ds#4+|harmonicMinor <|| def
b' = line $ E#4+|harmonicMinor <|| def
in line [a, b, a] ~> Mi2 @?= line [a', b', a']
, testProperty "identityUp" $ \(p :: Pitch) (d :: Duration) ->
p<|d ~> P1 == p<|d
, testProperty "identityDown" $ \(p :: Pitch) (d :: Duration) ->
p<|d <~ P1 == p<|d
, testProperty "commutativeUp" $
\(p :: Pitch) (m :: Interval) (n :: Interval) (d :: Duration) ->
((~> m) >>> (~> n)) (p<|d) == ((~> n) >>> (~> m)) (p<|d)
, testProperty "commutativeDown" $
\(p :: Pitch) (m :: Interval) (n :: Interval) (d :: Duration) ->
((<~ m) >>> (<~ n)) (p<|d) == ((<~ n) >>> (<~ m)) (p<|d)
, testProperty "erasure" $
\(p :: Pitch) (m :: Interval) (d :: Duration) ->
fromEnum p + fromEnum m <= fromEnum (maxBound :: Pitch) ==>
((~> m) >>> (<~ m)) (p<|d) == (p<|d)
]
, testGroup "Invert"
[ testCase "absolute pitches" $
invert ([0, 10, -20] :: [AbsPitch]) @?= [0, -10, 20]
, testCase "a melody" $
let melody = line [C#4<|hn, E#2<|wn, C#3<|en]
melody' = line [C#4<|hn, Gs#5<|wn, C#5<|en]
in invert melody @?= melody'
, testCase "a chord" $
invert maj7 @?= [P1, Mi3, P5, Mi6]
, testProperty "a diminished chord" $ \n -> n > 0 ==>
invertN n dim7 == dim7
, testCase "a scale" $
mode vi ionian @?= minor
, testProperty "scale orbit" $ do
sc <- genScale
return $ or [invertN n sc == sc | n <- [5..9]]
, testProperty "chord orbit" $ do
ch <- genChord
return $ length ch < 5 ==> or [invertN n ch == ch | n <- [4, 5]]
]
, testGroup "Retro"
[ testCase "a melody" $
(line [C#4<|hn, (wn~~), Gs#4<|en] ><) @?=
line [Gs#4<|en, (wn~~), C#4<|hn]
, testCase "a chord" $
(chord (C#4=|maj <||wn) ><) @?= chord (C#4=|maj <||wn)
, testCase "a scale" $
(scale (C#4+|major <||sn) ><) @?=
line (reverse [C, D, E, F, G, A, B]<#4<||sn)
]
, testGroup "Repeat"
[ testCase "a single note" $
let note = C#4<|wn
in 4 ## note @?= note :+: note :+: note :+: note
, testCase "a piece of music" $
let piece = line $ chord <$> [c, c', c']
c = Cs#4=|maj7 <|| def
c' = db#3=|m7b5 <|| def
in 3 ## piece @?= piece :+: piece :+: piece
]
, testGroup "Scaling time"
[ testCase "to smaller single duration" $
2 *~ hn @?= qn
, testCase "to bigger single duration" $
1%2 *~ sn @?= en
, testCase "a melody" $
1%4 *~ C#4<|en :+: C#3<|sn @?= C#4<|hn :+: C#3<|qn
, testCase "a chord" $
4 *~ chord (C#4=|maj <||wn) @?= chord (C#4=|maj <||qn)
, testCase "a scale" $
1%4 *~ scale (eb#2+|bebopDorian <||qn) @?= scale (eb#2=|bebopDorian <||wn)
]
, testGroup "Other"
[ testCase "toList" $
musicToList (C#4<|hn :+: (wn~~) :+: C#5<|qn) @?=
[(Just $ C#4, hn), (Nothing, wn), (Just $ C#5, qn)]
, testCase "fromList" $
listToMusic [(Just $ C#4, hn), (Nothing, wn), (Just $ C#5, qn)] @?=
(C#4<|hn :+: (wn~~) :+: C#5<|qn)
, testCase "normalize" $
let m = (wn~~) :: Melody
in normalize ((m :+: m) :+: m) @?= m :+: m :+: m
]
]
|
aa3f93b323739cbf31577061a194a259bb60cf196307924312316eddb5c405e6 | redstarssystems/gantt | router.clj | (ns org.rssys.gantt.web.router
(:require
[reitit.ring]))
(def ^{:doc "Routes for health checks, like liveness / readiness probes."}
health-routes
["/health"
["/alive" {:handler (constantly {:status 200 :headers {"Content-Type" "text/plain"} :body "ok"})}]
["/ready" {:handler (constantly {:status 200 :headers {"Content-Type" "text/plain"} :body "ok"})}]])
(def routes
[""
health-routes])
(defn make-router
[]
(reitit.ring/router routes))
| null | https://raw.githubusercontent.com/redstarssystems/gantt/f419eed2bef7f2bfac8a4c06849ddc75ec0650fb/src/org/rssys/gantt/web/router.clj | clojure | (ns org.rssys.gantt.web.router
(:require
[reitit.ring]))
(def ^{:doc "Routes for health checks, like liveness / readiness probes."}
health-routes
["/health"
["/alive" {:handler (constantly {:status 200 :headers {"Content-Type" "text/plain"} :body "ok"})}]
["/ready" {:handler (constantly {:status 200 :headers {"Content-Type" "text/plain"} :body "ok"})}]])
(def routes
[""
health-routes])
(defn make-router
[]
(reitit.ring/router routes))
|
|
2d33c2c06aab42bd2bc254f57200590219197f5549e9be2ce7731e2056dc0193 | FranklinChen/hugs98-plus-Sep2006 | Path.hs | -----------------------------------------------------------------------------
-- |
-- Module : Graphics.Win32.GDI.Path
Copyright : ( c ) , 1997 - 2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
Maintainer : Vuokko < >
-- Stability : provisional
-- Portability : portable
--
A collection of FFI declarations for interfacing with Win32 .
--
-----------------------------------------------------------------------------
module Graphics.Win32.GDI.Path
( beginPath, closeFigure, endPath, fillPath, flattenPath
, pathToRegion, strokeAndFillPath, strokePath, widenPath
) where
import Graphics.Win32.GDI.Types
import System.Win32.Types
----------------------------------------------------------------
-- Paths
----------------------------------------------------------------
AbortPath : : HDC - > IO ( )
beginPath :: HDC -> IO ()
beginPath dc =
failIfFalse_ "BeginPath" $ c_BeginPath dc
foreign import stdcall unsafe "windows.h BeginPath"
c_BeginPath :: HDC -> IO Bool
closeFigure :: HDC -> IO ()
closeFigure dc =
failIfFalse_ "CloseFigure" $ c_CloseFigure dc
foreign import stdcall unsafe "windows.h CloseFigure"
c_CloseFigure :: HDC -> IO Bool
endPath :: HDC -> IO ()
endPath dc =
failIfFalse_ "EndPath" $ c_EndPath dc
foreign import stdcall unsafe "windows.h EndPath"
c_EndPath :: HDC -> IO Bool
fillPath :: HDC -> IO ()
fillPath dc =
failIfFalse_ "FillPath" $ c_FillPath dc
foreign import stdcall unsafe "windows.h FillPath"
c_FillPath :: HDC -> IO Bool
flattenPath :: HDC -> IO ()
flattenPath dc =
failIfFalse_ "FlattenPath" $ c_FlattenPath dc
foreign import stdcall unsafe "windows.h FlattenPath"
c_FlattenPath :: HDC -> IO Bool
pathToRegion :: HDC -> IO HRGN
pathToRegion dc = do
ptr <- failIfNull "PathToRegion" $ c_PathToRegion dc
newForeignHANDLE ptr
foreign import stdcall unsafe "windows.h PathToRegion"
c_PathToRegion :: HDC -> IO PRGN
strokeAndFillPath :: HDC -> IO ()
strokeAndFillPath dc =
failIfFalse_ "StrokeAndFillPath" $ c_StrokeAndFillPath dc
foreign import stdcall unsafe "windows.h StrokeAndFillPath"
c_StrokeAndFillPath :: HDC -> IO Bool
strokePath :: HDC -> IO ()
strokePath dc =
failIfFalse_ "StrokePath" $ c_StrokePath dc
foreign import stdcall unsafe "windows.h StrokePath"
c_StrokePath :: HDC -> IO Bool
widenPath :: HDC -> IO ()
widenPath dc =
failIfFalse_ "WidenPath" $ c_WidenPath dc
foreign import stdcall unsafe "windows.h WidenPath"
c_WidenPath :: HDC -> IO Bool
----------------------------------------------------------------
-- End
----------------------------------------------------------------
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/Win32/Graphics/Win32/GDI/Path.hs | haskell | ---------------------------------------------------------------------------
|
Module : Graphics.Win32.GDI.Path
License : BSD-style (see the file libraries/base/LICENSE)
Stability : provisional
Portability : portable
---------------------------------------------------------------------------
--------------------------------------------------------------
Paths
--------------------------------------------------------------
--------------------------------------------------------------
End
-------------------------------------------------------------- | Copyright : ( c ) , 1997 - 2003
Maintainer : Vuokko < >
A collection of FFI declarations for interfacing with Win32 .
module Graphics.Win32.GDI.Path
( beginPath, closeFigure, endPath, fillPath, flattenPath
, pathToRegion, strokeAndFillPath, strokePath, widenPath
) where
import Graphics.Win32.GDI.Types
import System.Win32.Types
AbortPath : : HDC - > IO ( )
beginPath :: HDC -> IO ()
beginPath dc =
failIfFalse_ "BeginPath" $ c_BeginPath dc
foreign import stdcall unsafe "windows.h BeginPath"
c_BeginPath :: HDC -> IO Bool
closeFigure :: HDC -> IO ()
closeFigure dc =
failIfFalse_ "CloseFigure" $ c_CloseFigure dc
foreign import stdcall unsafe "windows.h CloseFigure"
c_CloseFigure :: HDC -> IO Bool
endPath :: HDC -> IO ()
endPath dc =
failIfFalse_ "EndPath" $ c_EndPath dc
foreign import stdcall unsafe "windows.h EndPath"
c_EndPath :: HDC -> IO Bool
fillPath :: HDC -> IO ()
fillPath dc =
failIfFalse_ "FillPath" $ c_FillPath dc
foreign import stdcall unsafe "windows.h FillPath"
c_FillPath :: HDC -> IO Bool
flattenPath :: HDC -> IO ()
flattenPath dc =
failIfFalse_ "FlattenPath" $ c_FlattenPath dc
foreign import stdcall unsafe "windows.h FlattenPath"
c_FlattenPath :: HDC -> IO Bool
pathToRegion :: HDC -> IO HRGN
pathToRegion dc = do
ptr <- failIfNull "PathToRegion" $ c_PathToRegion dc
newForeignHANDLE ptr
foreign import stdcall unsafe "windows.h PathToRegion"
c_PathToRegion :: HDC -> IO PRGN
strokeAndFillPath :: HDC -> IO ()
strokeAndFillPath dc =
failIfFalse_ "StrokeAndFillPath" $ c_StrokeAndFillPath dc
foreign import stdcall unsafe "windows.h StrokeAndFillPath"
c_StrokeAndFillPath :: HDC -> IO Bool
strokePath :: HDC -> IO ()
strokePath dc =
failIfFalse_ "StrokePath" $ c_StrokePath dc
foreign import stdcall unsafe "windows.h StrokePath"
c_StrokePath :: HDC -> IO Bool
widenPath :: HDC -> IO ()
widenPath dc =
failIfFalse_ "WidenPath" $ c_WidenPath dc
foreign import stdcall unsafe "windows.h WidenPath"
c_WidenPath :: HDC -> IO Bool
|
d5d36375d6dc4dd5555900aef3b1401050dea672232c5880dccb11d6c8449282 | JustusAdam/language-haskell | T0146c.hs | SYNTAX TEST " source.haskell " " Highlighting in multiline data declarations "
data D
= MethodCall "getDecks" Cards
| null | https://raw.githubusercontent.com/JustusAdam/language-haskell/c9ee1b3ee166c44db9ce350920ba502fcc868245/test/tickets/T0146c.hs | haskell | SYNTAX TEST " source.haskell " " Highlighting in multiline data declarations "
data D
= MethodCall "getDecks" Cards
|
|
ac2302034906275ee843746e5c39490f2e51626011206acf34a6cb140ab8b1e3 | input-output-hk/project-icarus-importer | QuickCheck.hs | -- | Wrappers around Test.QuickCheck that use 'Buildable' instead of 'Show'
--
-- Intended as a drop-in replacement for "Test.QuickCheck" (but only for the
-- test drivers; the properties themselves should just use "Test.QuickCheck").
module Util.Buildable.QuickCheck (
-- * Wrappers
forAll
-- * Re-exports
, QC.Property
, QC.Gen
, QC.conjoin
, QC.choose
) where
import qualified Test.QuickCheck as QC
import Universum
import Util.Buildable
{-------------------------------------------------------------------------------
Wrappers
-------------------------------------------------------------------------------}
forAll :: (Buildable a, QC.Testable prop)
=> QC.Gen a -> (a -> prop) -> QC.Property
forAll gen f = QC.forAll (STB <$> gen) (f . unSTB)
| null | https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/wallet-new/test/unit/Util/Buildable/QuickCheck.hs | haskell | | Wrappers around Test.QuickCheck that use 'Buildable' instead of 'Show'
Intended as a drop-in replacement for "Test.QuickCheck" (but only for the
test drivers; the properties themselves should just use "Test.QuickCheck").
* Wrappers
* Re-exports
------------------------------------------------------------------------------
Wrappers
------------------------------------------------------------------------------ | module Util.Buildable.QuickCheck (
forAll
, QC.Property
, QC.Gen
, QC.conjoin
, QC.choose
) where
import qualified Test.QuickCheck as QC
import Universum
import Util.Buildable
forAll :: (Buildable a, QC.Testable prop)
=> QC.Gen a -> (a -> prop) -> QC.Property
forAll gen f = QC.forAll (STB <$> gen) (f . unSTB)
|
16dc0be1b49f11908dbc0ba9916694298baa8cdbbdd1c597675ae1fe1810f0ac | ocaml-gospel/gospel | dterm.ml | (**************************************************************************)
(* *)
GOSPEL -- A Specification Language for OCaml
(* *)
Copyright ( c ) 2018- The VOCaL Project
(* *)
This software is free software , distributed under the MIT license
(* (as described in file LICENSE enclosed). *)
(**************************************************************************)
module W = Warnings
open Ppxlib
open Utils
open Identifier
open Ttypes
open Symbols
open Tterm
open Tterm_helper
(* types *)
type dty = Tvar of dtvar | Tapp of tysymbol * dty list | Tty of ty
and dtvar = { dtv_id : int; mutable dtv_def : dty option }
let dty_fresh =
let i = ref 0 in
fun () ->
incr i;
Tvar { dtv_id = !i; dtv_def = None }
let dty_of_ty ty = Tty ty
let ty_of_dty =
let tyvars = Hashtbl.create 0 in
fun dty ->
let get_var id =
try Hashtbl.find tyvars id
with Not_found ->
let ty = fresh_ty_var ~loc:Location.none ("a" ^ string_of_int id) in
Hashtbl.add tyvars id ty;
ty
in
let rec to_ty dty =
match dty with
| Tvar { dtv_id; dtv_def = None } -> get_var dtv_id
| Tvar { dtv_def = Some dty; _ } -> to_ty dty
| Tapp (ts, dtyl) -> ty_app ts (List.map to_ty dtyl)
| Tty ty -> ty
in
to_ty dty
(* predefined types *)
let dty_integer = dty_of_ty ty_integer
let dty_int = dty_of_ty ty_int
let dty_bool = dty_of_ty ty_bool
let dty_float = dty_of_ty ty_float
let dty_char = dty_of_ty ty_char
let dty_string = dty_of_ty ty_string
(* lsymbol specialization *)
let specialize_ls ls =
let htv = Htv.create 3 in
let find_tv tv =
try Htv.find htv tv
with Not_found ->
let dtv = dty_fresh () in
Htv.add htv tv dtv;
dtv
in
let rec spec ty =
match ty.ty_node with
| Tyvar tv -> find_tv tv
| Tyapp (ts, tyl) -> Tapp (ts, List.map spec tyl)
in
(List.map spec ls.ls_args, Option.map spec ls.ls_value)
let specialize_cs ~loc cs =
if cs.ls_constr = false then
W.error ~loc (W.Not_a_constructor cs.ls_name.id_str);
let dtyl, dty = specialize_ls cs in
(dtyl, Option.get dty)
(* terms *)
module Mstr = Map.Make (String)
type dpattern = {
dp_node : dpattern_node;
dp_dty : dty;
dp_vars : dty Mstr.t;
dp_loc : Location.t;
}
and dpattern_node =
| DPwild
| DPvar of Preid.t
| DPapp of lsymbol * dpattern list
| DPor of dpattern * dpattern
| DPas of dpattern * Preid.t
| DPcast of dpattern * dty
| DPconst of Parsetree.constant
| DPinterval of char * char
type dbinder = Preid.t * dty
type dterm = { dt_node : dterm_node; dt_dty : dty option; dt_loc : Location.t }
and dterm_node =
| DTattr of dterm * string list
| DTvar of Preid.t
| DTconst of constant
| DTapp of lsymbol * dterm list
| DTif of dterm * dterm * dterm
| DTlet of Preid.t * dterm * dterm
| DTcase of dterm * (dpattern * dterm option * dterm) list
| DTquant of quant * dbinder list * dterm
| DTbinop of binop * dterm * dterm
| DTnot of dterm
| DTold of dterm
| DTtrue
| DTfalse
let dty_of_dterm dt = match dt.dt_dty with None -> dty_bool | Some dty -> dty
(* type unification *)
let rec head = function
| Tvar { dtv_def = None; _ } as t -> t
| Tvar { dtv_def = Some t; _ } -> head t
| dty -> dty
let rec occur dtvar dty =
match head dty with
| Tty _ -> false
| Tvar { dtv_id; _ } -> dtvar.dtv_id = dtv_id
| Tapp (_, dtys) -> List.exists (occur dtvar) dtys
let rec unify_dty_ty dty ty =
match (head dty, ty.ty_node) with
| Tvar tvar, _ -> tvar.dtv_def <- Some (Tty ty)
| Tty ty1, _ when ty_equal ty1 ty -> ()
| Tapp (ts1, dl), Tyapp (ts2, tl) when ts_equal ts1 ts2 -> (
try List.iter2 unify_dty_ty dl tl with Invalid_argument _ -> raise Exit)
| _ -> raise Exit
let rec unify dty1 dty2 =
match (head dty1, head dty2) with
| Tvar { dtv_id = id1; _ }, Tvar { dtv_id = id2; _ } when id1 = id2 -> ()
| Tvar tvar, dty | dty, Tvar tvar ->
if occur tvar dty then raise Exit else tvar.dtv_def <- Some dty
| Tapp (ts1, dtyl1), Tapp (ts2, dtyl2) when ts_equal ts1 ts2 -> (
try List.iter2 unify dtyl1 dtyl2 with Invalid_argument _ -> raise Exit)
| Tty ty, dty | dty, Tty ty -> unify_dty_ty dty ty
| _ -> raise Exit
(* the following functions should receive dterms for precise locations
to be given properly -- based on why3 *)
let app_unify ~loc ls unify l dtyl2 =
if List.length l <> List.length dtyl2 then
W.error ~loc
(W.Bad_arity (ls.ls_name.id_str, List.length ls.ls_args, List.length l));
List.iter2 unify l dtyl2
let app_unify_map ~loc ls unify l dtyl =
if List.length l <> List.length dtyl then
W.error ~loc
(W.Bad_arity (ls.ls_name.id_str, List.length ls.ls_args, List.length l));
List.map2 unify l dtyl
let dpattern_unify dp dty =
try unify dp.dp_dty dty
with Exit ->
let t1 = Fmt.str "%a" print_ty (ty_of_dty dp.dp_dty) in
let t2 = Fmt.str "%a" print_ty (ty_of_dty dty) in
W.error ~loc:dp.dp_loc (W.Pattern_bad_type (t1, t2))
let dty_unify ~loc dty1 dty2 =
let t1 = Fmt.str "%a" print_ty (ty_of_dty dty1) in
let t2 = Fmt.str "%a" print_ty (ty_of_dty dty2) in
try unify dty1 dty2 with Exit -> W.error ~loc (W.Bad_type (t1, t2))
let dterm_unify dt dty =
match dt.dt_dty with
| Some dt_dty -> dty_unify ~loc:dt.dt_loc dt_dty dty
| None -> (
try unify dty_bool dty
with Exit -> W.error ~loc:dt.dt_loc W.Term_expected)
let dfmla_unify dt =
match dt.dt_dty with
| None -> ()
| Some dt_dty -> (
try unify dt_dty dty_bool
with Exit -> W.error ~loc:dt.dt_loc W.Formula_expected)
let unify dt dty =
match dty with None -> dfmla_unify dt | Some dt_dty -> dterm_unify dt dt_dty
(* environment *)
type denv = dty Mstr.t
let denv_find ~loc s denv =
try Mstr.find s denv with Not_found -> W.error ~loc (W.Unbound_variable s)
let is_in_denv denv s = Mstr.mem s denv
(* let denv_empty = Mstr.empty *)
let denv_get_opt denv s = Mstr.find_opt s denv
let denv_add_var denv s dty = Mstr.add s dty denv
let denv_add_var_quant denv vl =
let add acc (pid, dty) =
if Mstr.mem pid.Preid.pid_str acc then
W.error ~loc:pid.pid_loc (W.Duplicated_variable pid.pid_str)
else Mstr.add pid.pid_str dty acc
in
let vl = List.fold_left add Mstr.empty vl in
let choose_snd _ _ x = Some x in
Mstr.union choose_snd denv vl
(** coercions *)
let apply_coercion l dt =
let apply dt ls =
let dtyl, dty = specialize_ls ls in
dterm_unify dt (List.hd dtyl);
{ dt_node = DTapp (ls, [ dt ]); dt_dty = dty; dt_loc = dt.dt_loc }
in
List.fold_left apply dt l
(* coercions using just head tysymbols without type arguments: *)
(* TODO: this can be improved *)
let rec ts_of_dty = function
| Tvar { dtv_def = Some dty; _ } -> ts_of_dty dty
| Tvar { dtv_def = None; _ } | Tty { ty_node = Tyvar _ } -> raise Exit
| Tty { ty_node = Tyapp (ts, _) } | Tapp (ts, _) -> ts
let ts_of_dty = function Some dt_dty -> ts_of_dty dt_dty | None -> ts_bool
NB : this function is not a morphism w.r.t .
the identity of type variables .
the identity of type variables. *)
let rec ty_of_dty_raw = function
| Tvar { dtv_def = Some (Tty ty); _ } -> ty
| Tvar { dtv_def = Some dty; _ } -> ty_of_dty_raw dty
| Tvar _ -> fresh_ty_var ~loc:Location.none "xi"
| Tapp (ts, dl) -> ty_app ts (List.map ty_of_dty_raw dl)
| Tty ty -> ty
let ty_of_dty_raw = function
| Some dt_dty -> ty_of_dty_raw dt_dty
| None -> ty_bool
let max_dty crcmap dtl =
let rec aux = function
| (dty1, ts1, ty1) :: l ->
(* find a type that cannot be coerced to another type *)
let check (_, ts2, ty2) =
try
if not (ts_equal ts1 ts2) then ignore (Coercion.find crcmap ty1 ty2);
true
with Not_found -> false
in
(* by transitivity, we never have to look back *)
if List.exists check l then aux l else dty1
| [] -> assert false
in
let l =
List.fold_left
(fun acc { dt_dty; _ } ->
try (dt_dty, ts_of_dty dt_dty, ty_of_dty_raw dt_dty) :: acc
with Exit -> acc)
[] dtl
in
if l = [] then (List.hd dtl).dt_dty else aux l
let max_dty crcmap dtl =
match max_dty crcmap dtl with
| Some (Tty ty)
when ty_equal ty ty_bool
&& List.exists (fun { dt_dty; _ } -> dt_dty = None) dtl ->
(* favor prop over bool *)
None
| dty -> dty
let dterm_expected crcmap dt dty =
try
let ts1, ts2 = (ts_of_dty dt.dt_dty, ts_of_dty dty) in
if ts_equal ts1 ts2 then dt
else
let ty1, ty2 = (ty_of_dty_raw dt.dt_dty, ty_of_dty_raw dty) in
let crc = Coercion.find crcmap ty1 ty2 in
apply_coercion crc dt
with Not_found | Exit -> dt
let dterm_expected_op crcmap dt dty =
let dt = dterm_expected crcmap dt dty in
unify dt dty;
dt
let dfmla_expected crcmap dt = dterm_expected_op crcmap dt None
let dterm_expected crcmap dt dty = dterm_expected_op crcmap dt (Some dty)
(** dterm to tterm *)
let pattern dp =
let vars = ref Mstr.empty in
let get_var pid ty =
try Mstr.find pid.Preid.pid_str !vars
with Not_found ->
let vs = create_vsymbol pid ty in
TODO the variable found is of type ty
vars := Mstr.add pid.pid_str vs !vars;
vs
in
let rec pattern_node dp =
let ty = ty_of_dty dp.dp_dty in
match dp.dp_node with
| DPwild -> p_wild ty
| DPvar pid -> p_var (get_var pid ty)
| DPconst c -> p_const c
| DPapp (ls, dpl) -> p_app ls (List.map pattern_node dpl) ty
| DPor (dp1, dp2) ->
let dp1 = pattern_node dp1 in
let dp2 = pattern_node dp2 in
p_or dp1 dp2
| DPas (dp, pid) -> p_as (pattern_node dp) (get_var pid ty)
| DPinterval (c1, c2) -> p_interval c1 c2
| DPcast _ -> assert false
in
let p = pattern_node dp in
(p, !vars)
let rec term env prop dt =
let loc = dt.dt_loc in
let t = term_node ~loc env prop dt.dt_dty dt.dt_node in
match t.t_ty with
| Some _ when prop -> (
try t_equ t (t_bool_true loc) loc
with TypeMismatch (ty1, ty2) ->
let t1 = Fmt.str "%a" print_ty ty1 in
let t2 = Fmt.str "%a" print_ty ty2 in
W.error ~loc (W.Bad_type (t1, t2)))
| None when not prop -> t_if t (t_bool_true loc) (t_bool_false loc) loc
| _ -> t
and term_node ~loc env prop dty dterm_node =
match dterm_node with
| DTvar pid ->
let vs = denv_find ~loc:pid.pid_loc pid.pid_str env in
TODO should I match vs.vs_ty with dty ?
t_var vs loc
| DTconst c -> t_const c (ty_of_dty (Option.get dty)) loc
| DTapp (ls, []) when ls_equal ls fs_bool_true ->
if prop then t_true loc else t_bool_true loc
| DTapp (ls, []) when ls_equal ls fs_bool_false ->
if prop then t_false loc else t_bool_false loc
| DTapp (ls, [ dt1; dt2 ]) when ls_equal ls ps_equ ->
if dt1.dt_dty = None || dt2.dt_dty = None then
f_iff (term env true dt1) (term env true dt2) loc
else t_equ (term env false dt1) (term env false dt2) loc
| DTapp (ls, [ dt1 ]) when ls.ls_field ->
t_field (term env false dt1) ls (Option.map ty_of_dty dty) loc
| DTapp (ls, dtl) ->
t_app ls (List.map (term env false) dtl) (Option.map ty_of_dty dty) loc
| DTif (dt1, dt2, dt3) ->
let prop = prop || dty = None in
t_if (term env true dt1) (term env prop dt2) (term env prop dt3) loc
| DTlet (pid, dt1, dt2) ->
let prop = prop || dty = None in
let t1 = term env false dt1 in
let vs = create_vsymbol pid (t_type t1) in
let env = Mstr.add pid.pid_str vs env in
let t2 = term env prop dt2 in
t_let vs t1 t2 loc
| DTbinop (b, dt1, dt2) ->
let t1, t2 = (term env true dt1, term env true dt2) in
t_binop b t1 t2 loc
| DTnot dt -> t_not (term env true dt) loc
| DTtrue -> if prop then t_true loc else t_bool_true loc
| DTfalse -> if prop then t_false loc else t_bool_false loc
| DTattr (dt, at) ->
let t = term env prop dt in
t_attr_set at t
| DTold dt -> t_old (term env prop dt) loc
| DTquant (q, bl, dt) ->
let add_var (env, vsl) (pid, dty) =
let vs = create_vsymbol pid (ty_of_dty dty) in
(Mstr.add pid.pid_str vs env, vs :: vsl)
in
let env, vsl = List.fold_left add_var (env, []) bl in
let t = term env prop dt in
t_quant q (List.rev vsl) t (Option.map ty_of_dty dty) loc
| DTcase (dt, ptl) ->
let t = term env false dt in
let branch (dp, guard, dt) =
let p, vars = pattern dp in
let join _ _ vs = Some vs in
let env = Mstr.union join env vars in
let dt = term env false dt in
let guard =
match guard with None -> None | Some g -> Some (term env true g)
in
(p, guard, dt)
in
let pl = List.map branch ptl in
let ty = ty_of_dty (Option.get dt.dt_dty) in
Patmat.checks ty pl ~loc;
t_case t pl loc
let fmla env dt = term env true dt
let term env dt = term env false dt
| null | https://raw.githubusercontent.com/ocaml-gospel/gospel/1662d614cbd171df757d2b3fed6cd9e76aead56d/src/dterm.ml | ocaml | ************************************************************************
(as described in file LICENSE enclosed).
************************************************************************
types
predefined types
lsymbol specialization
terms
type unification
the following functions should receive dterms for precise locations
to be given properly -- based on why3
environment
let denv_empty = Mstr.empty
* coercions
coercions using just head tysymbols without type arguments:
TODO: this can be improved
find a type that cannot be coerced to another type
by transitivity, we never have to look back
favor prop over bool
* dterm to tterm | GOSPEL -- A Specification Language for OCaml
Copyright ( c ) 2018- The VOCaL Project
This software is free software , distributed under the MIT license
module W = Warnings
open Ppxlib
open Utils
open Identifier
open Ttypes
open Symbols
open Tterm
open Tterm_helper
type dty = Tvar of dtvar | Tapp of tysymbol * dty list | Tty of ty
and dtvar = { dtv_id : int; mutable dtv_def : dty option }
let dty_fresh =
let i = ref 0 in
fun () ->
incr i;
Tvar { dtv_id = !i; dtv_def = None }
let dty_of_ty ty = Tty ty
let ty_of_dty =
let tyvars = Hashtbl.create 0 in
fun dty ->
let get_var id =
try Hashtbl.find tyvars id
with Not_found ->
let ty = fresh_ty_var ~loc:Location.none ("a" ^ string_of_int id) in
Hashtbl.add tyvars id ty;
ty
in
let rec to_ty dty =
match dty with
| Tvar { dtv_id; dtv_def = None } -> get_var dtv_id
| Tvar { dtv_def = Some dty; _ } -> to_ty dty
| Tapp (ts, dtyl) -> ty_app ts (List.map to_ty dtyl)
| Tty ty -> ty
in
to_ty dty
let dty_integer = dty_of_ty ty_integer
let dty_int = dty_of_ty ty_int
let dty_bool = dty_of_ty ty_bool
let dty_float = dty_of_ty ty_float
let dty_char = dty_of_ty ty_char
let dty_string = dty_of_ty ty_string
let specialize_ls ls =
let htv = Htv.create 3 in
let find_tv tv =
try Htv.find htv tv
with Not_found ->
let dtv = dty_fresh () in
Htv.add htv tv dtv;
dtv
in
let rec spec ty =
match ty.ty_node with
| Tyvar tv -> find_tv tv
| Tyapp (ts, tyl) -> Tapp (ts, List.map spec tyl)
in
(List.map spec ls.ls_args, Option.map spec ls.ls_value)
let specialize_cs ~loc cs =
if cs.ls_constr = false then
W.error ~loc (W.Not_a_constructor cs.ls_name.id_str);
let dtyl, dty = specialize_ls cs in
(dtyl, Option.get dty)
module Mstr = Map.Make (String)
type dpattern = {
dp_node : dpattern_node;
dp_dty : dty;
dp_vars : dty Mstr.t;
dp_loc : Location.t;
}
and dpattern_node =
| DPwild
| DPvar of Preid.t
| DPapp of lsymbol * dpattern list
| DPor of dpattern * dpattern
| DPas of dpattern * Preid.t
| DPcast of dpattern * dty
| DPconst of Parsetree.constant
| DPinterval of char * char
type dbinder = Preid.t * dty
type dterm = { dt_node : dterm_node; dt_dty : dty option; dt_loc : Location.t }
and dterm_node =
| DTattr of dterm * string list
| DTvar of Preid.t
| DTconst of constant
| DTapp of lsymbol * dterm list
| DTif of dterm * dterm * dterm
| DTlet of Preid.t * dterm * dterm
| DTcase of dterm * (dpattern * dterm option * dterm) list
| DTquant of quant * dbinder list * dterm
| DTbinop of binop * dterm * dterm
| DTnot of dterm
| DTold of dterm
| DTtrue
| DTfalse
let dty_of_dterm dt = match dt.dt_dty with None -> dty_bool | Some dty -> dty
let rec head = function
| Tvar { dtv_def = None; _ } as t -> t
| Tvar { dtv_def = Some t; _ } -> head t
| dty -> dty
let rec occur dtvar dty =
match head dty with
| Tty _ -> false
| Tvar { dtv_id; _ } -> dtvar.dtv_id = dtv_id
| Tapp (_, dtys) -> List.exists (occur dtvar) dtys
let rec unify_dty_ty dty ty =
match (head dty, ty.ty_node) with
| Tvar tvar, _ -> tvar.dtv_def <- Some (Tty ty)
| Tty ty1, _ when ty_equal ty1 ty -> ()
| Tapp (ts1, dl), Tyapp (ts2, tl) when ts_equal ts1 ts2 -> (
try List.iter2 unify_dty_ty dl tl with Invalid_argument _ -> raise Exit)
| _ -> raise Exit
let rec unify dty1 dty2 =
match (head dty1, head dty2) with
| Tvar { dtv_id = id1; _ }, Tvar { dtv_id = id2; _ } when id1 = id2 -> ()
| Tvar tvar, dty | dty, Tvar tvar ->
if occur tvar dty then raise Exit else tvar.dtv_def <- Some dty
| Tapp (ts1, dtyl1), Tapp (ts2, dtyl2) when ts_equal ts1 ts2 -> (
try List.iter2 unify dtyl1 dtyl2 with Invalid_argument _ -> raise Exit)
| Tty ty, dty | dty, Tty ty -> unify_dty_ty dty ty
| _ -> raise Exit
let app_unify ~loc ls unify l dtyl2 =
if List.length l <> List.length dtyl2 then
W.error ~loc
(W.Bad_arity (ls.ls_name.id_str, List.length ls.ls_args, List.length l));
List.iter2 unify l dtyl2
let app_unify_map ~loc ls unify l dtyl =
if List.length l <> List.length dtyl then
W.error ~loc
(W.Bad_arity (ls.ls_name.id_str, List.length ls.ls_args, List.length l));
List.map2 unify l dtyl
let dpattern_unify dp dty =
try unify dp.dp_dty dty
with Exit ->
let t1 = Fmt.str "%a" print_ty (ty_of_dty dp.dp_dty) in
let t2 = Fmt.str "%a" print_ty (ty_of_dty dty) in
W.error ~loc:dp.dp_loc (W.Pattern_bad_type (t1, t2))
let dty_unify ~loc dty1 dty2 =
let t1 = Fmt.str "%a" print_ty (ty_of_dty dty1) in
let t2 = Fmt.str "%a" print_ty (ty_of_dty dty2) in
try unify dty1 dty2 with Exit -> W.error ~loc (W.Bad_type (t1, t2))
let dterm_unify dt dty =
match dt.dt_dty with
| Some dt_dty -> dty_unify ~loc:dt.dt_loc dt_dty dty
| None -> (
try unify dty_bool dty
with Exit -> W.error ~loc:dt.dt_loc W.Term_expected)
let dfmla_unify dt =
match dt.dt_dty with
| None -> ()
| Some dt_dty -> (
try unify dt_dty dty_bool
with Exit -> W.error ~loc:dt.dt_loc W.Formula_expected)
let unify dt dty =
match dty with None -> dfmla_unify dt | Some dt_dty -> dterm_unify dt dt_dty
type denv = dty Mstr.t
let denv_find ~loc s denv =
try Mstr.find s denv with Not_found -> W.error ~loc (W.Unbound_variable s)
let is_in_denv denv s = Mstr.mem s denv
let denv_get_opt denv s = Mstr.find_opt s denv
let denv_add_var denv s dty = Mstr.add s dty denv
let denv_add_var_quant denv vl =
let add acc (pid, dty) =
if Mstr.mem pid.Preid.pid_str acc then
W.error ~loc:pid.pid_loc (W.Duplicated_variable pid.pid_str)
else Mstr.add pid.pid_str dty acc
in
let vl = List.fold_left add Mstr.empty vl in
let choose_snd _ _ x = Some x in
Mstr.union choose_snd denv vl
let apply_coercion l dt =
let apply dt ls =
let dtyl, dty = specialize_ls ls in
dterm_unify dt (List.hd dtyl);
{ dt_node = DTapp (ls, [ dt ]); dt_dty = dty; dt_loc = dt.dt_loc }
in
List.fold_left apply dt l
let rec ts_of_dty = function
| Tvar { dtv_def = Some dty; _ } -> ts_of_dty dty
| Tvar { dtv_def = None; _ } | Tty { ty_node = Tyvar _ } -> raise Exit
| Tty { ty_node = Tyapp (ts, _) } | Tapp (ts, _) -> ts
let ts_of_dty = function Some dt_dty -> ts_of_dty dt_dty | None -> ts_bool
NB : this function is not a morphism w.r.t .
the identity of type variables .
the identity of type variables. *)
let rec ty_of_dty_raw = function
| Tvar { dtv_def = Some (Tty ty); _ } -> ty
| Tvar { dtv_def = Some dty; _ } -> ty_of_dty_raw dty
| Tvar _ -> fresh_ty_var ~loc:Location.none "xi"
| Tapp (ts, dl) -> ty_app ts (List.map ty_of_dty_raw dl)
| Tty ty -> ty
let ty_of_dty_raw = function
| Some dt_dty -> ty_of_dty_raw dt_dty
| None -> ty_bool
let max_dty crcmap dtl =
let rec aux = function
| (dty1, ts1, ty1) :: l ->
let check (_, ts2, ty2) =
try
if not (ts_equal ts1 ts2) then ignore (Coercion.find crcmap ty1 ty2);
true
with Not_found -> false
in
if List.exists check l then aux l else dty1
| [] -> assert false
in
let l =
List.fold_left
(fun acc { dt_dty; _ } ->
try (dt_dty, ts_of_dty dt_dty, ty_of_dty_raw dt_dty) :: acc
with Exit -> acc)
[] dtl
in
if l = [] then (List.hd dtl).dt_dty else aux l
let max_dty crcmap dtl =
match max_dty crcmap dtl with
| Some (Tty ty)
when ty_equal ty ty_bool
&& List.exists (fun { dt_dty; _ } -> dt_dty = None) dtl ->
None
| dty -> dty
let dterm_expected crcmap dt dty =
try
let ts1, ts2 = (ts_of_dty dt.dt_dty, ts_of_dty dty) in
if ts_equal ts1 ts2 then dt
else
let ty1, ty2 = (ty_of_dty_raw dt.dt_dty, ty_of_dty_raw dty) in
let crc = Coercion.find crcmap ty1 ty2 in
apply_coercion crc dt
with Not_found | Exit -> dt
let dterm_expected_op crcmap dt dty =
let dt = dterm_expected crcmap dt dty in
unify dt dty;
dt
let dfmla_expected crcmap dt = dterm_expected_op crcmap dt None
let dterm_expected crcmap dt dty = dterm_expected_op crcmap dt (Some dty)
let pattern dp =
let vars = ref Mstr.empty in
let get_var pid ty =
try Mstr.find pid.Preid.pid_str !vars
with Not_found ->
let vs = create_vsymbol pid ty in
TODO the variable found is of type ty
vars := Mstr.add pid.pid_str vs !vars;
vs
in
let rec pattern_node dp =
let ty = ty_of_dty dp.dp_dty in
match dp.dp_node with
| DPwild -> p_wild ty
| DPvar pid -> p_var (get_var pid ty)
| DPconst c -> p_const c
| DPapp (ls, dpl) -> p_app ls (List.map pattern_node dpl) ty
| DPor (dp1, dp2) ->
let dp1 = pattern_node dp1 in
let dp2 = pattern_node dp2 in
p_or dp1 dp2
| DPas (dp, pid) -> p_as (pattern_node dp) (get_var pid ty)
| DPinterval (c1, c2) -> p_interval c1 c2
| DPcast _ -> assert false
in
let p = pattern_node dp in
(p, !vars)
let rec term env prop dt =
let loc = dt.dt_loc in
let t = term_node ~loc env prop dt.dt_dty dt.dt_node in
match t.t_ty with
| Some _ when prop -> (
try t_equ t (t_bool_true loc) loc
with TypeMismatch (ty1, ty2) ->
let t1 = Fmt.str "%a" print_ty ty1 in
let t2 = Fmt.str "%a" print_ty ty2 in
W.error ~loc (W.Bad_type (t1, t2)))
| None when not prop -> t_if t (t_bool_true loc) (t_bool_false loc) loc
| _ -> t
and term_node ~loc env prop dty dterm_node =
match dterm_node with
| DTvar pid ->
let vs = denv_find ~loc:pid.pid_loc pid.pid_str env in
TODO should I match vs.vs_ty with dty ?
t_var vs loc
| DTconst c -> t_const c (ty_of_dty (Option.get dty)) loc
| DTapp (ls, []) when ls_equal ls fs_bool_true ->
if prop then t_true loc else t_bool_true loc
| DTapp (ls, []) when ls_equal ls fs_bool_false ->
if prop then t_false loc else t_bool_false loc
| DTapp (ls, [ dt1; dt2 ]) when ls_equal ls ps_equ ->
if dt1.dt_dty = None || dt2.dt_dty = None then
f_iff (term env true dt1) (term env true dt2) loc
else t_equ (term env false dt1) (term env false dt2) loc
| DTapp (ls, [ dt1 ]) when ls.ls_field ->
t_field (term env false dt1) ls (Option.map ty_of_dty dty) loc
| DTapp (ls, dtl) ->
t_app ls (List.map (term env false) dtl) (Option.map ty_of_dty dty) loc
| DTif (dt1, dt2, dt3) ->
let prop = prop || dty = None in
t_if (term env true dt1) (term env prop dt2) (term env prop dt3) loc
| DTlet (pid, dt1, dt2) ->
let prop = prop || dty = None in
let t1 = term env false dt1 in
let vs = create_vsymbol pid (t_type t1) in
let env = Mstr.add pid.pid_str vs env in
let t2 = term env prop dt2 in
t_let vs t1 t2 loc
| DTbinop (b, dt1, dt2) ->
let t1, t2 = (term env true dt1, term env true dt2) in
t_binop b t1 t2 loc
| DTnot dt -> t_not (term env true dt) loc
| DTtrue -> if prop then t_true loc else t_bool_true loc
| DTfalse -> if prop then t_false loc else t_bool_false loc
| DTattr (dt, at) ->
let t = term env prop dt in
t_attr_set at t
| DTold dt -> t_old (term env prop dt) loc
| DTquant (q, bl, dt) ->
let add_var (env, vsl) (pid, dty) =
let vs = create_vsymbol pid (ty_of_dty dty) in
(Mstr.add pid.pid_str vs env, vs :: vsl)
in
let env, vsl = List.fold_left add_var (env, []) bl in
let t = term env prop dt in
t_quant q (List.rev vsl) t (Option.map ty_of_dty dty) loc
| DTcase (dt, ptl) ->
let t = term env false dt in
let branch (dp, guard, dt) =
let p, vars = pattern dp in
let join _ _ vs = Some vs in
let env = Mstr.union join env vars in
let dt = term env false dt in
let guard =
match guard with None -> None | Some g -> Some (term env true g)
in
(p, guard, dt)
in
let pl = List.map branch ptl in
let ty = ty_of_dty (Option.get dt.dt_dty) in
Patmat.checks ty pl ~loc;
t_case t pl loc
let fmla env dt = term env true dt
let term env dt = term env false dt
|
11b5f7184cf66b035a533a01a62638428f4e430e5096428b9d46b0d7733d6de1 | DSLsofMath/DSLsofMath | PropositionalLogic_code.hs | # LANGUAGE TypeOperators #
# LANGUAGE EmptyCase #
module DSLsofMath.PropositionalLogic where
data Prop = Implies Prop Prop | And Prop Prop | Or Prop Prop
| Not Prop | Name Name | Con Bool
deriving (Eq, Show)
type Name = String
p1, p2, p3, p4 :: Prop
p1 = And (Name "a") (Not (Name "a"))
p2 = Or (Name "a") (Not (Name "a"))
p3 = Implies (Name "a") (Name "b")
p4 = Implies (And a b) (And b a)
where a = Name "a"; b = Name "b"
type Env = Name -> Bool
eval :: Prop -> Env -> Bool
eval (Implies p q) env = eval p env ==> eval q env
eval (And p q) env = eval p env && eval q env
eval (Or p q) env = eval p env || eval q env
eval (Not p) env = not (eval p env)
eval (Name n) env = env n
eval (Con t) env = t
(==>) :: Bool -> Bool -> Bool
False ==> _ {-"\quad"-} = True
True ==> p = p
isTautology :: Prop -> Bool
isTautology p = and (map (eval p) (envs (freeNames p)))
envs :: [Name] -> [Env]
envs [] = [error "envs: never used"]
envs (n:ns) = [ \n' -> if n == n' then b else e n'
| b <- [False, True]
, e <- envs ns
]
freeNames :: Prop -> [Name]
freeNames = error "exercise"
checkProof :: Proof -> Prop -> Bool
checkProof TruthIntro (Con True) = True
checkProof (AndIntro t u) (And p q) = checkProof t p
&& checkProof u q
checkProof (OrIntroL t) (Or p q) = checkProof t p
checkProof (OrIntroR u) (Or p q) = checkProof u q
checkProof (NotIntro q t u) (Not p) = checkProof t (p `Implies` q)
&& checkProof u (p `Implies` Not q)
checkProof (AndElimL q t) p = checkProof t (p `And` q)
checkProof (AndElimR p t) q = checkProof t (p `And` q)
checkProof (OrElim p q t u v) r = checkProof t (p `Implies` r)
&& checkProof u (q `Implies` r)
&& checkProof v (Or p q)
checkProof (NotElim t) p = checkProof t (Not (Not p))
checkProof (FalseElim t) p = checkProof t (Con False)
checkProof (Assume p') p = p == p'
checkProof (ImplyIntro f) (p `Implies` q) = checkProof (f (Assume p)) q
checkProof (ImplyElim p t u) q = checkProof t (p `Implies` q)
&& checkProof u p
checkProof _ _ = False -- incorrect proof
data Proof = TruthIntro | FalseElim Proof
| AndIntro Proof Proof
| AndElimL Prop Proof | AndElimR Prop Proof
| OrIntroL Proof | OrIntroR Proof
| OrElim Prop Prop Proof Proof Proof
| NotIntro Prop Proof Proof | NotElim Proof
| Assume Prop
| ImplyIntro (Proof -> Proof) | ImplyElim Prop Proof Proof
conjunctionComm :: Prop
conjunctionComm = p4
conjunctionCommProof :: Proof
conjunctionCommProof = ImplyIntro step
where step :: Proof -> Proof
step evAB = AndIntro (AndElimR (Name "a") evAB )
(AndElimL (Name "b") evAB )
-- >>> checkProof conjunctionCommProof conjunctionComm
-- True
conjunctionCommProof2 :: Proof
conjunctionCommProof2 =
ImplyIntro (\evAB ->
AndIntro (AndElimL (Name "b") evAB)
(AndElimR (Name "a") evAB) )
-- >>> checkProof conjunctionCommProof2 conjunctionComm
-- False
conjunctionCommProof' :: Implies (And a b) (And b a)
conjunctionCommProof' = implyIntro step
where step :: And a b -> And b a
step evAB = andIntro (andElimR evAB)
(andElimL evAB)
truthIntro :: Truth
falseElim :: False -> p
andIntro :: p -> q -> And p q
andElimL :: And p q -> p
andElimR :: And p q -> q
orIntroL :: p -> Or p q
orIntroR :: q -> Or p q
orElim :: Or p q -> (p `Implies` r) -> (q `Implies` r) -> r
notIntro :: (p `Implies` q) `And` (p `Implies` Not q) -> Not p
notElim :: Not (Not p) -> p
implyIntro :: (p -> q) -> (p `Implies` q)
implyElim :: (p `Implies` q) -> (p -> q)
type Not p = p `Implies` False
notElim = error "not possible as such in intuitionistic logic"
type Implies p q = p -> q
implyElim f = f
implyIntro f = f
type And p q = (p,q)
andIntro t u = (t,u)
andElimL = fst
andElimR = snd
notIntro (evPimpQ, evPimpNotQ) evP =
{-""-} -- a proof of |False| wanted
let evQ = evPimpQ evP
evNotQ = evPimpNotQ evP
in evNotQ evQ
notIntro' :: (p -> q, p -> q -> False) -> p -> False
notIntro' (f, g) x = (g x) (f x)
type Or a b = Either a b
orIntroL = Left
orIntroR = Right
orElim pOrq f g = case pOrq of
Left p -> f p
Right q -> g q
type Truth = ()
truthIntro = ()
data False
falseElim x = case x of {}
excludedMiddle :: Not (Not (p `Or` Not p)) -- to prove this, we can ...
excludedMiddle k = -- ... assume |Not (Or p (Not p))| and prove falsity.
So , we can prove falsity if we can prove |Or p ( Not p)| .
We can prove in particular the right case ,
... by assuming that holds , and prove falsity .
Again , we can prove falsity if we can prove |Or p ( Not p)| .
This time , we can prove in particular the left case ,
evP))) -- because we assumed it earlier!
excludedMiddle' :: Not (Not (p `Or` Not p))
excludedMiddle' k = k (Right (\evP -> k (Left evP)))
test1' :: (a -> (b, c)) -> (a->b, a->c)
test1' a2bc = ( \a -> fst (a2bc a)
, \a -> snd (a2bc a) )
test2' :: (a->b, a->c) -> (a -> (b, c))
test2' fg = \a -> (fst fg a, snd fg a)
test1 :: Implies (Implies a (And b c)) (And (Implies a b) (Implies a c))
test1 = implyIntro (\a2bc ->
andIntro (implyIntro (\a -> andElimL (implyElim a2bc a)))
(implyIntro (\a -> andElimR (implyElim a2bc a))))
test2 :: Implies (And (Implies a b) (Implies a c)) (Implies a (And b c))
test2 = implyIntro (\fg ->
implyIntro (\a ->
andIntro (implyElim (andElimL fg) a)
(implyElim (andElimR fg) a)))
| null | https://raw.githubusercontent.com/DSLsofMath/DSLsofMath/18f6622b075771fefd6290ce20b1471d51435720/L/02/PropositionalLogic_code.hs | haskell | "\quad"
incorrect proof
>>> checkProof conjunctionCommProof conjunctionComm
True
>>> checkProof conjunctionCommProof2 conjunctionComm
False
""
a proof of |False| wanted
to prove this, we can ...
... assume |Not (Or p (Not p))| and prove falsity.
because we assumed it earlier! | # LANGUAGE TypeOperators #
# LANGUAGE EmptyCase #
module DSLsofMath.PropositionalLogic where
data Prop = Implies Prop Prop | And Prop Prop | Or Prop Prop
| Not Prop | Name Name | Con Bool
deriving (Eq, Show)
type Name = String
p1, p2, p3, p4 :: Prop
p1 = And (Name "a") (Not (Name "a"))
p2 = Or (Name "a") (Not (Name "a"))
p3 = Implies (Name "a") (Name "b")
p4 = Implies (And a b) (And b a)
where a = Name "a"; b = Name "b"
type Env = Name -> Bool
eval :: Prop -> Env -> Bool
eval (Implies p q) env = eval p env ==> eval q env
eval (And p q) env = eval p env && eval q env
eval (Or p q) env = eval p env || eval q env
eval (Not p) env = not (eval p env)
eval (Name n) env = env n
eval (Con t) env = t
(==>) :: Bool -> Bool -> Bool
True ==> p = p
isTautology :: Prop -> Bool
isTautology p = and (map (eval p) (envs (freeNames p)))
envs :: [Name] -> [Env]
envs [] = [error "envs: never used"]
envs (n:ns) = [ \n' -> if n == n' then b else e n'
| b <- [False, True]
, e <- envs ns
]
freeNames :: Prop -> [Name]
freeNames = error "exercise"
checkProof :: Proof -> Prop -> Bool
checkProof TruthIntro (Con True) = True
checkProof (AndIntro t u) (And p q) = checkProof t p
&& checkProof u q
checkProof (OrIntroL t) (Or p q) = checkProof t p
checkProof (OrIntroR u) (Or p q) = checkProof u q
checkProof (NotIntro q t u) (Not p) = checkProof t (p `Implies` q)
&& checkProof u (p `Implies` Not q)
checkProof (AndElimL q t) p = checkProof t (p `And` q)
checkProof (AndElimR p t) q = checkProof t (p `And` q)
checkProof (OrElim p q t u v) r = checkProof t (p `Implies` r)
&& checkProof u (q `Implies` r)
&& checkProof v (Or p q)
checkProof (NotElim t) p = checkProof t (Not (Not p))
checkProof (FalseElim t) p = checkProof t (Con False)
checkProof (Assume p') p = p == p'
checkProof (ImplyIntro f) (p `Implies` q) = checkProof (f (Assume p)) q
checkProof (ImplyElim p t u) q = checkProof t (p `Implies` q)
&& checkProof u p
data Proof = TruthIntro | FalseElim Proof
| AndIntro Proof Proof
| AndElimL Prop Proof | AndElimR Prop Proof
| OrIntroL Proof | OrIntroR Proof
| OrElim Prop Prop Proof Proof Proof
| NotIntro Prop Proof Proof | NotElim Proof
| Assume Prop
| ImplyIntro (Proof -> Proof) | ImplyElim Prop Proof Proof
conjunctionComm :: Prop
conjunctionComm = p4
conjunctionCommProof :: Proof
conjunctionCommProof = ImplyIntro step
where step :: Proof -> Proof
step evAB = AndIntro (AndElimR (Name "a") evAB )
(AndElimL (Name "b") evAB )
conjunctionCommProof2 :: Proof
conjunctionCommProof2 =
ImplyIntro (\evAB ->
AndIntro (AndElimL (Name "b") evAB)
(AndElimR (Name "a") evAB) )
conjunctionCommProof' :: Implies (And a b) (And b a)
conjunctionCommProof' = implyIntro step
where step :: And a b -> And b a
step evAB = andIntro (andElimR evAB)
(andElimL evAB)
truthIntro :: Truth
falseElim :: False -> p
andIntro :: p -> q -> And p q
andElimL :: And p q -> p
andElimR :: And p q -> q
orIntroL :: p -> Or p q
orIntroR :: q -> Or p q
orElim :: Or p q -> (p `Implies` r) -> (q `Implies` r) -> r
notIntro :: (p `Implies` q) `And` (p `Implies` Not q) -> Not p
notElim :: Not (Not p) -> p
implyIntro :: (p -> q) -> (p `Implies` q)
implyElim :: (p `Implies` q) -> (p -> q)
type Not p = p `Implies` False
notElim = error "not possible as such in intuitionistic logic"
type Implies p q = p -> q
implyElim f = f
implyIntro f = f
type And p q = (p,q)
andIntro t u = (t,u)
andElimL = fst
andElimR = snd
notIntro (evPimpQ, evPimpNotQ) evP =
let evQ = evPimpQ evP
evNotQ = evPimpNotQ evP
in evNotQ evQ
notIntro' :: (p -> q, p -> q -> False) -> p -> False
notIntro' (f, g) x = (g x) (f x)
type Or a b = Either a b
orIntroL = Left
orIntroR = Right
orElim pOrq f g = case pOrq of
Left p -> f p
Right q -> g q
type Truth = ()
truthIntro = ()
data False
falseElim x = case x of {}
So , we can prove falsity if we can prove |Or p ( Not p)| .
We can prove in particular the right case ,
... by assuming that holds , and prove falsity .
Again , we can prove falsity if we can prove |Or p ( Not p)| .
This time , we can prove in particular the left case ,
excludedMiddle' :: Not (Not (p `Or` Not p))
excludedMiddle' k = k (Right (\evP -> k (Left evP)))
test1' :: (a -> (b, c)) -> (a->b, a->c)
test1' a2bc = ( \a -> fst (a2bc a)
, \a -> snd (a2bc a) )
test2' :: (a->b, a->c) -> (a -> (b, c))
test2' fg = \a -> (fst fg a, snd fg a)
test1 :: Implies (Implies a (And b c)) (And (Implies a b) (Implies a c))
test1 = implyIntro (\a2bc ->
andIntro (implyIntro (\a -> andElimL (implyElim a2bc a)))
(implyIntro (\a -> andElimR (implyElim a2bc a))))
test2 :: Implies (And (Implies a b) (Implies a c)) (Implies a (And b c))
test2 = implyIntro (\fg ->
implyIntro (\a ->
andIntro (implyElim (andElimL fg) a)
(implyElim (andElimR fg) a)))
|
aa3ba5d57e529ee080e73edf5551aaed36b863b7bbcfc201ad8a5339248c1dcf | vernemq/vernemq | vmq_diversity_bcrypt.erl | Copyright 2018 Erlio GmbH Basel Switzerland ( )
%%
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(vmq_diversity_bcrypt).
-include_lib("luerl/include/luerl.hrl").
-export([install/1]).
install(St) ->
luerl_emul:alloc_table(table(), St).
table() ->
[
{<<"gen_salt">>, #erl_func{code = fun gen_salt/2}},
{<<"hashpw">>, #erl_func{code = fun hashpw/2}}
].
gen_salt(_, St) ->
{ok, Salt} = bcrypt:gen_salt(),
{[list_to_binary(Salt)], St}.
hashpw([Pass, Salt], St) when is_binary(Pass) and is_binary(Salt) ->
{ok, Hash} = bcrypt:hashpw(Pass, Salt),
{[list_to_binary(Hash)], St}.
| null | https://raw.githubusercontent.com/vernemq/vernemq/234d253250cb5371b97ebb588622076fdabc6a5f/apps/vmq_diversity/src/vmq_diversity_bcrypt.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. | Copyright 2018 Erlio GmbH Basel Switzerland ( )
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(vmq_diversity_bcrypt).
-include_lib("luerl/include/luerl.hrl").
-export([install/1]).
install(St) ->
luerl_emul:alloc_table(table(), St).
table() ->
[
{<<"gen_salt">>, #erl_func{code = fun gen_salt/2}},
{<<"hashpw">>, #erl_func{code = fun hashpw/2}}
].
gen_salt(_, St) ->
{ok, Salt} = bcrypt:gen_salt(),
{[list_to_binary(Salt)], St}.
hashpw([Pass, Salt], St) when is_binary(Pass) and is_binary(Salt) ->
{ok, Hash} = bcrypt:hashpw(Pass, Salt),
{[list_to_binary(Hash)], St}.
|
bd6af67cc2c1b485ee57b5e3f215b6817359f1602fa31081dad03f6f44ec3b63 | marcelosousa/llvmvf | Instruction.hs | # LANGUAGE UnicodeSyntax , DoAndIfThenElse #
-------------------------------------------------------------------------------
-- Module : Analysis.Type.Inference.Instruction
Copyright : ( c ) 2013
-- Type Constraints Instruction
-------------------------------------------------------------------------------
module Analysis.Type.Inference.Instruction where
import Language.LLVMIR hiding (Id)
import Language.LLVMIR.Util (typeOf)
import Analysis.Type.Inference.Base
import Analysis.Type.Memory.Util
import Analysis.Type.Memory.TyAnn as T
import Analysis.Type.Util
import Analysis.Type.Inference.Value
import Analysis.Type.Inference.Instruction.Memory
import Prelude.Unicode ((β§Ί))
import Data.List.Unicode ((β))
import Control.Monad.State
import qualified Data.Set as S
import Debug.Trace
instance TyConstr PHI where
-- Οβ β· β PHI β βState
Οβ (PHI pc n Ο v) = do
let ΟΞ± = (β)Ο -- lift type
nβ = (βΟ n) :=: (βΟ ΟΞ±) β Ξ΅ -- constraint the id to type ΟΞ±
(vi,vl) = unzip v -- get values
viβ = S.fromList $ map Ο vi -- compute elementary constraints
aβs = S.map ((βΟ n) :=:) viβ -- constraint the current name to viβ
lβ β ΟListR (nβ βͺ aβs) vi -- β§Ίvl)
(β£) $ liftΞ€β pc lβ
instance TyConstr Terminator where
-- Οβ β· β Terminator β βState
Οβ tmn = do
(fn,ΟΟ) β Ξ΄fn
bb β Ξ΄bb
let cΞ» c = βp (βΞ» ΟΟ c) T.AnyAddr
case tmn of
Ret pc VoidRet β do
let ΟΞ± = T.TyPri T.TyVoid
fnβ = βΟ fn :=: cΞ» (βΟ ΟΞ±)
bbβ = βΟ bb :=: βΟ ΟΞ±
(β£) $ liftΞ€β pc $ fnβ β (bbβ β Ξ΅)
Ret pc (ValueRet v) β do
Οβv β Οβr v
let Οv = Ο v
fnβ = βΟ fn :=: cΞ» Οv
bbβ = βΟ bb :=: Οv
(β£) $ liftΞ€β pc $ fnβ β (bbβ β Οβv)
Unreachable pc β do
let ΟΞ± = T.TyUndef
fnβ = βΟ fn :=: cΞ» (βΟ ΟΞ±)
bbβ = βΟ bb :=: βΟ ΟΞ±
(β£) $ liftΞ€β pc $ fnβ β (bbβ β Ξ΅)
Br pc c t f β do
Οβv β ΟListR Ξ΅ [c]--,t,f]
let (Οc,Οt,Οf) = (Ο c,Ο t,Ο f)
cβ = Οc :=: (βΟ $ T.TyPri $ T.TyInt 1)
tfβ = Οt :=: Οf
fnβ = βΟ fn :=: cΞ» Οt
bbβ = βΟ bb :=: Οt
(β£) $ liftΞ€β pc $ cβ β (tfβ β (fnβ β (bbβ β Οβv)))
UBr pc d β do
--Οβd β Οβ d
let Οd = Ο d
fnβ = βΟ fn :=: cΞ» Οd
bbβ = βΟ bb :=: Οd
(β£) $ liftΞ€β pc $ fnβ β (bbβ β Ξ΅) -- Οβd)
_ β error $ show tmn β§Ί " not supported"
instance TyConstr Instruction where
Οβ i = case i of
Standard Binary Operations
Integer Operations
Add pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
Sub pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
Mul pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
UDiv pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
SDiv pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
URem pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
SRem pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
Bitwise Binary Operations
Shl pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
LShr pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
AShr pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
And pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
Or pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
Xor pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
-- Float Operations
FAdd pc n Ο Ξ± Ξ² β Οβbin pc TFlt n Ο Ξ± Ξ²
FSub pc n Ο Ξ± Ξ² β Οβbin pc TFlt n Ο Ξ± Ξ²
FMul pc n Ο Ξ± Ξ² β Οβbin pc TFlt n Ο Ξ± Ξ²
FDiv pc n Ο Ξ± Ξ² β Οβbin pc TFlt n Ο Ξ± Ξ²
FRem pc n Ο Ξ± Ξ² β Οβbin pc TFlt n Ο Ξ± Ξ²
Cast Operations
Trunc pc n Ξ± Ο β Οβcast pc n (Ξ±,TInt) (Ο,TInt) -- (>:) -- Truncate integers
(: < :) -- Zero extend integers
SExt pc n Ξ± Ο β Οβcast pc n (Ξ±,TInt) (Ο,TInt) -- (:<:) -- Sign extend integers
FPTrunc pc n Ξ± Ο β Οβcast pc n (Ξ±,TFlt) (Ο,TFlt) -- (>:) -- Truncate floating point
FPExt pc n Ξ± Ο β Οβcast pc n (Ξ±,TFlt) (Ο,TFlt) -- (:β€:) -- Extend floating point
floating point β UInt
floating point β SInt
UInt β floating point
SIToFP pc n Ξ± Ο β ΟβnastyCast pc n (Ξ±,TInt) (Ο,TFlt) -- SInt β floating point
PtrToInt pc n Ξ± Ο β ΟβnastyCast pc n (Ξ±,TPtr) (Ο,TInt) -- Pointer β integer
IntToPtr pc n Ξ± Ο β ΟβnastyCast pc n (Ξ±,TInt) (Ο,TPtr) -- integer β Pointer
(: β€ :) -- 1stclass non agg β 1stclass non agg
Comparison Operations
ICmp pc n _ Ο Ξ± Ξ² β Οβcmp pc TInt n Ο Ξ± Ξ²
FCmp pc n _ Ο Ξ± Ξ² β Οβcmp pc TFlt n Ο Ξ± Ξ²
-- Memory Operations
Alloca pc n Ο _ β Οβalloca pc n Ο
Store pc Ο Ξ± Ξ² _ β Οβstore pc Ο Ξ± Ξ²
Load pc n Ξ± _ β Οβload pc n Ξ±
GetElementPtr pc n Ο Ξ± Ξ΄s β Οβgep pc n Ο Ξ± Ξ΄s
Atomic Operations
Cmpxchg pc n Ξ± Ξ² Ξ· _ β Οβaop pc n Ξ± [Ξ²,Ξ·]
AtomicRMW pc n Ξ± Ξ² _ _ β Οβaop pc n Ξ± [Ξ²]
-- Call
Call pc n Ο c Ο β Οβcall pc n Ο c Ο
InlineAsm pc n Ο Ξ² _ _ _ _ _ Ο β do
Οβ β ΟListR Ξ΅ Ο
let nΟ = βΟ $ (β)Ο
nβ = βΟ n :=: nΟ
(β£) $ liftΞ€β pc $ nβ β Οβ
if Ξ²
then error " error TypeInference InlineAsm : Could be lifted "
else do
Οβ β ΟListR Ξ΅ Ο
let nΟ = βΟ $ ( β)Ο
nβ = βΟ n : = : nΟ
( β£ ) $ liftΞ€β pc $ nβ β Οβ
then error "error TypeInference InlineAsm: Could be lifted"
else do
Οβ β ΟListR Ξ΅ Ο
let nΟ = βΟ $ (β)Ο
nβ = βΟ n :=: nΟ
(β£) $ liftΞ€β pc $ nβ β Οβ
-}
Vector Operations
Select pc n Ξ± Ξ² Ξ· β Οselect pc n Ξ± Ξ² Ξ·
ExtractValue pc n Ο Ξ± Ξ΄s β Οextract pc n Ο Ξ±
InsertValue pc n Ξ± Ξ² Ξ΄s β error "insert agg operations not supported"
-- Type Constraints for Cast Operations
( β β β β ) β βState
Οβcast pc n (Ξ±,ΟcΞ±) (Ο,ΟcΟ) = do
ΟβΞ± β Οβr Ξ±
let cΟΟ = βΟ $ (β)Ο
ΟΞ± = Ο Ξ±
cβΞ± = ΟΞ± : = : ΟcΞ±
cβΟ = cΟΟ : = :
Ξ±β = βq (βΟ n) :=: (βq ΟΞ±) -- ?: βΟ n
nβ = βΟ n :=: cΟΟ
(β£) $ liftΞ€β pc $ nβ β (Ξ±β β Ξ΅)-- ΟβΞ±)
-- (β£) $ liftΞ€β pc $ nβ β (Ξ±β β (cβΟ β (cβΞ± β ΟβΞ±)))
-- Type Constraints for Binary Operations
Οβbin β· Int β TClass β Id β Ξ€ β Value β Value β βState
Οβbin pc Οc n Ο Ξ± Ξ² = do
ΟβΞ± β Οβr Ξ±
ΟβΞ² β Οβr Ξ²
let cΟΟ = βΟ $ (β)Ο
(ΟΞ±,ΟΞ²) = (Ο Ξ±,Ο Ξ²)
Ξ±β = ΟΞ± :=: cΟΟ
Ξ²β = ΟΞ² :=: cΟΟ
Ξ±Ξ²β = ΟΞ± :=: ΟΞ²
-- cβ = cΟΟ :=: βc Οc
nβ = βΟ n :=: cΟΟ
(β£) $ liftΞ€β pc $ nβ β (Ξ±β β (Ξ²β β (Ξ±Ξ²β β (ΟβΞ± βͺ ΟβΞ²))))
--(β£) $ liftΞ€β pc $ nβ β (Ξ±β β (Ξ²β β (Ξ±Ξ²β β (cβ β (ΟβΞ± βͺ ΟβΞ²)))))
ΟβnastyCast β· Int β Id β (Value, TClass) β (Ξ€, TClass) β βState
ΟβnastyCast pc n (Ξ±,ΟcΞ±) (Ο,ΟcΟ) = do
ΟβΞ± β Οβr Ξ±
let cΟΟ = βΟ $ (β)Ο
ΟΞ± = Ο Ξ±
cβΞ± = ΟΞ± : = : ΟcΞ±
cβΟ = cΟΟ : = :
nβ = βΟ n :=: cΟΟ
(β£) $ liftΞ€β pc $ nβ β ΟβΞ±
-- (β£) $ liftΞ€β pc $ nβ β (cβΟ β (cβΞ± β ΟβΞ±))
-- Type Constraints for comparison operations
Οβcmp β· Int β TClass β Id β Ξ€ β Value β Value β βState
Οβcmp pc Οc n Ο Ξ± Ξ² = do
ΟβΞ± β Οβr Ξ±
ΟβΞ² β Οβr Ξ²
let cΟΟ = βΟ $ (β)Ο
(ΟΞ±,ΟΞ²) = (Ο Ξ±,Ο Ξ²)
Ξ±Ξ²β = ΟΞ± :=: ΟΞ²
--cβ = ΟΞ± :=: cΟΟ
--cβ = ΟΞ± :=: βc Οc
cΟn = βΟ $ T.TyPri $ T.TyInt 1
nβ = βΟ n :=: cΟn
--Οβ = cΟΟ :=: cΟn
(β£) $ liftΞ€β pc $ nβ β (Ξ±Ξ²β β (ΟβΞ± βͺ ΟβΞ²))
-- (β£) $ nβ β (Οβ β (Ξ±Ξ²β β (cβ β (ΟβΞ± βͺ ΟβΞ²))))
Οβcall β· Int β Id β Ξ€ β Id β Values β βState
Οβcall pc n Ο c Ο = do
ΟβΟ β ΟListR Ξ΅ Ο
let (Οn,Οc) = (βΟ n,βΟ c)
cΟΟ = βΟ $ (β)Ο -- OK
ΟΟ = map Ο Ο
ΟΟ = map ((β) . typeOf) Ο
nβ = Οn :=: cΟΟ -- OK
βΞ» ΟΟ cΟΟ
βΞ» ΟΟ cΟΟ
cβ = Οc :=: Ο
aβ = Οc :=: Οt
vfns β Ξ΄vfns
if c β vfns
then (β£) $ liftΞ€β pc $ nβ β ΟβΟ
else (β£) $ liftΞ€β pc $ nβ β (cβ β (aβ β ΟβΟ))
Οselect β· Int β Id β Value β Value β Value β βState
Οselect pc n Ξ± Ξ² Ξ· = do
let (ΟΞ±,ΟΞ²,ΟΞ·) = (Ο Ξ±,Ο Ξ²,Ο Ξ·)
Ξ±cΟ = βΟ $ T.TyPri $ T.TyInt 1
Ξ±β = ΟΞ± :=: Ξ±cΟ
nΟβ = βΟ n :=: (βΟ $ (β)(typeOf Ξ²))
nβ = βΟ n :=: ΟΞ²
Ξ²Ξ·β = βΟ n :=: ΟΞ·
-- Ξ²β = ΟΞ² :=: βc T1
(β£) $ liftΞ€β pc $ Ξ±β β (nβ β (Ξ²Ξ·β β (nΟβ β Ξ΅)))
--(β£) $ liftΞ€β pc $ Ξ±β β (nβ β (Ξ²Ξ·β β (Ξ²β β Ξ΅)))
Οextract β· Int β Id β Ξ€ β Value β βState
Οextract pc n Ο Ξ± = do
Ξ±β β Οβr Ξ±
let (Οn, ΟΞ±) = (βΟ n, Ο Ξ±)
nΟ = βΟ $ (β)Ο
nβ = Οn :=: nΟ
-- cβ = ΟΞ± :=: βc TAgg
(β£) $ liftΞ€β pc $ nβ β Ξ±β
--(β£) $ liftΞ€β pc $ nβ β (cβ β Ξ±β)
| null | https://raw.githubusercontent.com/marcelosousa/llvmvf/c314e43aa8bc8bb7fd9c83cebfbdcabee4ecfe1b/src/Analysis/Type/Inference/Instruction.hs | haskell | -----------------------------------------------------------------------------
Module : Analysis.Type.Inference.Instruction
Type Constraints Instruction
-----------------------------------------------------------------------------
Οβ β· β PHI β βState
lift type
constraint the id to type ΟΞ±
get values
compute elementary constraints
constraint the current name to viβ
β§Ίvl)
Οβ β· β Terminator β βState
,t,f]
Οβd β Οβ d
Οβd)
Float Operations
(>:) -- Truncate integers
Zero extend integers
(:<:) -- Sign extend integers
(>:) -- Truncate floating point
(:β€:) -- Extend floating point
SInt β floating point
Pointer β integer
integer β Pointer
1stclass non agg β 1stclass non agg
Memory Operations
Call
Type Constraints for Cast Operations
?: βΟ n
ΟβΞ±)
(β£) $ liftΞ€β pc $ nβ β (Ξ±β β (cβΟ β (cβΞ± β ΟβΞ±)))
Type Constraints for Binary Operations
cβ = cΟΟ :=: βc Οc
(β£) $ liftΞ€β pc $ nβ β (Ξ±β β (Ξ²β β (Ξ±Ξ²β β (cβ β (ΟβΞ± βͺ ΟβΞ²)))))
(β£) $ liftΞ€β pc $ nβ β (cβΟ β (cβΞ± β ΟβΞ±))
Type Constraints for comparison operations
cβ = ΟΞ± :=: cΟΟ
cβ = ΟΞ± :=: βc Οc
Οβ = cΟΟ :=: cΟn
(β£) $ nβ β (Οβ β (Ξ±Ξ²β β (cβ β (ΟβΞ± βͺ ΟβΞ²))))
OK
OK
Ξ²β = ΟΞ² :=: βc T1
(β£) $ liftΞ€β pc $ Ξ±β β (nβ β (Ξ²Ξ·β β (Ξ²β β Ξ΅)))
cβ = ΟΞ± :=: βc TAgg
(β£) $ liftΞ€β pc $ nβ β (cβ β Ξ±β) | # LANGUAGE UnicodeSyntax , DoAndIfThenElse #
Copyright : ( c ) 2013
module Analysis.Type.Inference.Instruction where
import Language.LLVMIR hiding (Id)
import Language.LLVMIR.Util (typeOf)
import Analysis.Type.Inference.Base
import Analysis.Type.Memory.Util
import Analysis.Type.Memory.TyAnn as T
import Analysis.Type.Util
import Analysis.Type.Inference.Value
import Analysis.Type.Inference.Instruction.Memory
import Prelude.Unicode ((β§Ί))
import Data.List.Unicode ((β))
import Control.Monad.State
import qualified Data.Set as S
import Debug.Trace
instance TyConstr PHI where
Οβ (PHI pc n Ο v) = do
(β£) $ liftΞ€β pc lβ
instance TyConstr Terminator where
Οβ tmn = do
(fn,ΟΟ) β Ξ΄fn
bb β Ξ΄bb
let cΞ» c = βp (βΞ» ΟΟ c) T.AnyAddr
case tmn of
Ret pc VoidRet β do
let ΟΞ± = T.TyPri T.TyVoid
fnβ = βΟ fn :=: cΞ» (βΟ ΟΞ±)
bbβ = βΟ bb :=: βΟ ΟΞ±
(β£) $ liftΞ€β pc $ fnβ β (bbβ β Ξ΅)
Ret pc (ValueRet v) β do
Οβv β Οβr v
let Οv = Ο v
fnβ = βΟ fn :=: cΞ» Οv
bbβ = βΟ bb :=: Οv
(β£) $ liftΞ€β pc $ fnβ β (bbβ β Οβv)
Unreachable pc β do
let ΟΞ± = T.TyUndef
fnβ = βΟ fn :=: cΞ» (βΟ ΟΞ±)
bbβ = βΟ bb :=: βΟ ΟΞ±
(β£) $ liftΞ€β pc $ fnβ β (bbβ β Ξ΅)
Br pc c t f β do
let (Οc,Οt,Οf) = (Ο c,Ο t,Ο f)
cβ = Οc :=: (βΟ $ T.TyPri $ T.TyInt 1)
tfβ = Οt :=: Οf
fnβ = βΟ fn :=: cΞ» Οt
bbβ = βΟ bb :=: Οt
(β£) $ liftΞ€β pc $ cβ β (tfβ β (fnβ β (bbβ β Οβv)))
UBr pc d β do
let Οd = Ο d
fnβ = βΟ fn :=: cΞ» Οd
bbβ = βΟ bb :=: Οd
_ β error $ show tmn β§Ί " not supported"
instance TyConstr Instruction where
Οβ i = case i of
Standard Binary Operations
Integer Operations
Add pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
Sub pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
Mul pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
UDiv pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
SDiv pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
URem pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
SRem pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
Bitwise Binary Operations
Shl pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
LShr pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
AShr pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
And pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
Or pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
Xor pc n Ο Ξ± Ξ² β Οβbin pc TInt n Ο Ξ± Ξ²
FAdd pc n Ο Ξ± Ξ² β Οβbin pc TFlt n Ο Ξ± Ξ²
FSub pc n Ο Ξ± Ξ² β Οβbin pc TFlt n Ο Ξ± Ξ²
FMul pc n Ο Ξ± Ξ² β Οβbin pc TFlt n Ο Ξ± Ξ²
FDiv pc n Ο Ξ± Ξ² β Οβbin pc TFlt n Ο Ξ± Ξ²
FRem pc n Ο Ξ± Ξ² β Οβbin pc TFlt n Ο Ξ± Ξ²
Cast Operations
floating point β UInt
floating point β SInt
UInt β floating point
Comparison Operations
ICmp pc n _ Ο Ξ± Ξ² β Οβcmp pc TInt n Ο Ξ± Ξ²
FCmp pc n _ Ο Ξ± Ξ² β Οβcmp pc TFlt n Ο Ξ± Ξ²
Alloca pc n Ο _ β Οβalloca pc n Ο
Store pc Ο Ξ± Ξ² _ β Οβstore pc Ο Ξ± Ξ²
Load pc n Ξ± _ β Οβload pc n Ξ±
GetElementPtr pc n Ο Ξ± Ξ΄s β Οβgep pc n Ο Ξ± Ξ΄s
Atomic Operations
Cmpxchg pc n Ξ± Ξ² Ξ· _ β Οβaop pc n Ξ± [Ξ²,Ξ·]
AtomicRMW pc n Ξ± Ξ² _ _ β Οβaop pc n Ξ± [Ξ²]
Call pc n Ο c Ο β Οβcall pc n Ο c Ο
InlineAsm pc n Ο Ξ² _ _ _ _ _ Ο β do
Οβ β ΟListR Ξ΅ Ο
let nΟ = βΟ $ (β)Ο
nβ = βΟ n :=: nΟ
(β£) $ liftΞ€β pc $ nβ β Οβ
if Ξ²
then error " error TypeInference InlineAsm : Could be lifted "
else do
Οβ β ΟListR Ξ΅ Ο
let nΟ = βΟ $ ( β)Ο
nβ = βΟ n : = : nΟ
( β£ ) $ liftΞ€β pc $ nβ β Οβ
then error "error TypeInference InlineAsm: Could be lifted"
else do
Οβ β ΟListR Ξ΅ Ο
let nΟ = βΟ $ (β)Ο
nβ = βΟ n :=: nΟ
(β£) $ liftΞ€β pc $ nβ β Οβ
-}
Vector Operations
Select pc n Ξ± Ξ² Ξ· β Οselect pc n Ξ± Ξ² Ξ·
ExtractValue pc n Ο Ξ± Ξ΄s β Οextract pc n Ο Ξ±
InsertValue pc n Ξ± Ξ² Ξ΄s β error "insert agg operations not supported"
( β β β β ) β βState
Οβcast pc n (Ξ±,ΟcΞ±) (Ο,ΟcΟ) = do
ΟβΞ± β Οβr Ξ±
let cΟΟ = βΟ $ (β)Ο
ΟΞ± = Ο Ξ±
cβΞ± = ΟΞ± : = : ΟcΞ±
cβΟ = cΟΟ : = :
nβ = βΟ n :=: cΟΟ
Οβbin β· Int β TClass β Id β Ξ€ β Value β Value β βState
Οβbin pc Οc n Ο Ξ± Ξ² = do
ΟβΞ± β Οβr Ξ±
ΟβΞ² β Οβr Ξ²
let cΟΟ = βΟ $ (β)Ο
(ΟΞ±,ΟΞ²) = (Ο Ξ±,Ο Ξ²)
Ξ±β = ΟΞ± :=: cΟΟ
Ξ²β = ΟΞ² :=: cΟΟ
Ξ±Ξ²β = ΟΞ± :=: ΟΞ²
nβ = βΟ n :=: cΟΟ
(β£) $ liftΞ€β pc $ nβ β (Ξ±β β (Ξ²β β (Ξ±Ξ²β β (ΟβΞ± βͺ ΟβΞ²))))
ΟβnastyCast β· Int β Id β (Value, TClass) β (Ξ€, TClass) β βState
ΟβnastyCast pc n (Ξ±,ΟcΞ±) (Ο,ΟcΟ) = do
ΟβΞ± β Οβr Ξ±
let cΟΟ = βΟ $ (β)Ο
ΟΞ± = Ο Ξ±
cβΞ± = ΟΞ± : = : ΟcΞ±
cβΟ = cΟΟ : = :
nβ = βΟ n :=: cΟΟ
(β£) $ liftΞ€β pc $ nβ β ΟβΞ±
Οβcmp β· Int β TClass β Id β Ξ€ β Value β Value β βState
Οβcmp pc Οc n Ο Ξ± Ξ² = do
ΟβΞ± β Οβr Ξ±
ΟβΞ² β Οβr Ξ²
let cΟΟ = βΟ $ (β)Ο
(ΟΞ±,ΟΞ²) = (Ο Ξ±,Ο Ξ²)
Ξ±Ξ²β = ΟΞ± :=: ΟΞ²
cΟn = βΟ $ T.TyPri $ T.TyInt 1
nβ = βΟ n :=: cΟn
(β£) $ liftΞ€β pc $ nβ β (Ξ±Ξ²β β (ΟβΞ± βͺ ΟβΞ²))
Οβcall β· Int β Id β Ξ€ β Id β Values β βState
Οβcall pc n Ο c Ο = do
ΟβΟ β ΟListR Ξ΅ Ο
let (Οn,Οc) = (βΟ n,βΟ c)
ΟΟ = map Ο Ο
ΟΟ = map ((β) . typeOf) Ο
βΞ» ΟΟ cΟΟ
βΞ» ΟΟ cΟΟ
cβ = Οc :=: Ο
aβ = Οc :=: Οt
vfns β Ξ΄vfns
if c β vfns
then (β£) $ liftΞ€β pc $ nβ β ΟβΟ
else (β£) $ liftΞ€β pc $ nβ β (cβ β (aβ β ΟβΟ))
Οselect β· Int β Id β Value β Value β Value β βState
Οselect pc n Ξ± Ξ² Ξ· = do
let (ΟΞ±,ΟΞ²,ΟΞ·) = (Ο Ξ±,Ο Ξ²,Ο Ξ·)
Ξ±cΟ = βΟ $ T.TyPri $ T.TyInt 1
Ξ±β = ΟΞ± :=: Ξ±cΟ
nΟβ = βΟ n :=: (βΟ $ (β)(typeOf Ξ²))
nβ = βΟ n :=: ΟΞ²
Ξ²Ξ·β = βΟ n :=: ΟΞ·
(β£) $ liftΞ€β pc $ Ξ±β β (nβ β (Ξ²Ξ·β β (nΟβ β Ξ΅)))
Οextract β· Int β Id β Ξ€ β Value β βState
Οextract pc n Ο Ξ± = do
Ξ±β β Οβr Ξ±
let (Οn, ΟΞ±) = (βΟ n, Ο Ξ±)
nΟ = βΟ $ (β)Ο
nβ = Οn :=: nΟ
(β£) $ liftΞ€β pc $ nβ β Ξ±β
|
77ef9c678e9eca74b0352de87ce45bbf1cea19924683afbf1c9fa81336c45757 | ocamllabs/ocaml-modular-implicits | t092-pushacc6.ml | open Lib;;
let x = false in
let y = true in
let z = true in
let a = true in
let b = true in
let c = true in
let d = true in
if x then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 CONST0
10 PUSHCONST1
11 PUSHCONST1
12 PUSHCONST1
13 PUSHCONST1
14 PUSHCONST1
15 PUSHCONST1
16 PUSHACC6
17 BRANCHIFNOT 24
19 GETGLOBAL Not_found
21 MAKEBLOCK1 0
23 RAISE
24 POP 7
26 ATOM0
27 SETGLOBAL T092 - pushacc6
29 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 CONST0
10 PUSHCONST1
11 PUSHCONST1
12 PUSHCONST1
13 PUSHCONST1
14 PUSHCONST1
15 PUSHCONST1
16 PUSHACC6
17 BRANCHIFNOT 24
19 GETGLOBAL Not_found
21 MAKEBLOCK1 0
23 RAISE
24 POP 7
26 ATOM0
27 SETGLOBAL T092-pushacc6
29 STOP
**)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/tool-ocaml/t092-pushacc6.ml | ocaml | open Lib;;
let x = false in
let y = true in
let z = true in
let a = true in
let b = true in
let c = true in
let d = true in
if x then raise Not_found
;;
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7
9 CONST0
10 PUSHCONST1
11 PUSHCONST1
12 PUSHCONST1
13 PUSHCONST1
14 PUSHCONST1
15 PUSHCONST1
16 PUSHACC6
17 BRANCHIFNOT 24
19 GETGLOBAL Not_found
21 MAKEBLOCK1 0
23 RAISE
24 POP 7
26 ATOM0
27 SETGLOBAL T092 - pushacc6
29 STOP
*
0 CONSTINT 42
2 PUSHACC0
3 MAKEBLOCK1 0
5 POP 1
7 SETGLOBAL Lib
9 CONST0
10 PUSHCONST1
11 PUSHCONST1
12 PUSHCONST1
13 PUSHCONST1
14 PUSHCONST1
15 PUSHCONST1
16 PUSHACC6
17 BRANCHIFNOT 24
19 GETGLOBAL Not_found
21 MAKEBLOCK1 0
23 RAISE
24 POP 7
26 ATOM0
27 SETGLOBAL T092-pushacc6
29 STOP
**)
|
|
11ec8ee16502521f38573e5f99bccea965b0942b0233630251baf2a0ff74e311 | ChaosCabbage/very-lazy-boy | Viewers.hs | module Viewers (
viewCPU
, viewStack
, viewMem
, viewMem16
) where
import qualified CPU.Instructions as Ops
import CPU.FrozenEnvironment (FrozenCPUEnvironment(..), readFrzMemory)
import CPU.Types (Address)
import BitTwiddling (joinBytes)
import Text.Printf (printf)
import Data.Word (Word8, Word16)
import Data.Bits (testBit)
-- A basic view showing the registers, flags and the next instruction:
--
-- A F B C D E H L SP
01B0 0013 00D8
--
-- IME : ENABLED
-- Flags ZNHC
-- 1011
--
PC = 0x0100 ( 0x00 )
--
viewCPU :: FrozenCPUEnvironment -> String
viewCPU cpu =
"A F B C D E H L SP \n" ++
(printf "%02X%02X %02X%02X %02X%02X %02X%02X %04X\n\n"
(frz_a cpu) (frz_f cpu) (frz_b cpu) (frz_c cpu) (frz_d cpu) (frz_e cpu) (frz_h cpu) (frz_l cpu) (frz_sp cpu)) ++
(" IME: " ++ (if frz_ime cpu then "ENABLED" else "DISABLED")) ++ "\n" ++
(viewFlags $ frz_f cpu) ++
"\n" ++
(peekInstruction cpu)
peekInstruction :: FrozenCPUEnvironment -> String
peekInstruction cpu =
let pointer = frz_pc cpu
opcode = readFrzMemory pointer cpu
arg1 = readFrzMemory (pointer+1) cpu
arg2 = readFrzMemory (pointer+2) cpu
op = Ops.opTable opcode
template = Ops.label op
label = case (Ops.instruction op) of
(Ops.Ary0 _) -> template
(Ops.Ary1 _) -> printf template arg1
(Ops.Ary2 _) -> printf template (arg1 `joinBytes` arg2)
(Ops.Unimplemented) -> printf "Unimplemented instruction: 0x%02X (%s)" opcode template
in
printf "PC = 0x%04X (%s)\n" pointer label
viewFlags :: Word8 -> String
viewFlags f =
"Flags ZNHC \n" ++
" " ++ (b 7) ++ (b 6) ++ (b 5) ++ (b 4) ++ "\n"
where
b n = if (testBit f n) then "1" else "0"
readMem16 :: Address -> FrozenCPUEnvironment -> Word16
readMem16 address cpu =
let
low = readFrzMemory address cpu
high = readFrzMemory (address + 1) cpu
in
joinBytes low high
viewMem16 :: Address -> FrozenCPUEnvironment -> String
viewMem16 address cpu =
printf "0x%04X" $ readMem16 address cpu
viewMem :: Address -> FrozenCPUEnvironment -> String
viewMem address cpu =
printf "0x%02X" $ readFrzMemory address cpu
-- Might be able to trace up the stack a bit,
-- but there's no way to tell where the base of the stack is.
viewStack :: FrozenCPUEnvironment -> String
viewStack cpu =
printf "[0x%04X] <- 0x%04X\n" value pointer
where
pointer = frz_sp cpu
value = readMem16 pointer cpu
| null | https://raw.githubusercontent.com/ChaosCabbage/very-lazy-boy/53ec41a3ff296e9d602b73fee33a512126c8a8b4/src/Viewers.hs | haskell | A basic view showing the registers, flags and the next instruction:
A F B C D E H L SP
IME : ENABLED
Flags ZNHC
1011
Might be able to trace up the stack a bit,
but there's no way to tell where the base of the stack is.
| module Viewers (
viewCPU
, viewStack
, viewMem
, viewMem16
) where
import qualified CPU.Instructions as Ops
import CPU.FrozenEnvironment (FrozenCPUEnvironment(..), readFrzMemory)
import CPU.Types (Address)
import BitTwiddling (joinBytes)
import Text.Printf (printf)
import Data.Word (Word8, Word16)
import Data.Bits (testBit)
01B0 0013 00D8
PC = 0x0100 ( 0x00 )
viewCPU :: FrozenCPUEnvironment -> String
viewCPU cpu =
"A F B C D E H L SP \n" ++
(printf "%02X%02X %02X%02X %02X%02X %02X%02X %04X\n\n"
(frz_a cpu) (frz_f cpu) (frz_b cpu) (frz_c cpu) (frz_d cpu) (frz_e cpu) (frz_h cpu) (frz_l cpu) (frz_sp cpu)) ++
(" IME: " ++ (if frz_ime cpu then "ENABLED" else "DISABLED")) ++ "\n" ++
(viewFlags $ frz_f cpu) ++
"\n" ++
(peekInstruction cpu)
peekInstruction :: FrozenCPUEnvironment -> String
peekInstruction cpu =
let pointer = frz_pc cpu
opcode = readFrzMemory pointer cpu
arg1 = readFrzMemory (pointer+1) cpu
arg2 = readFrzMemory (pointer+2) cpu
op = Ops.opTable opcode
template = Ops.label op
label = case (Ops.instruction op) of
(Ops.Ary0 _) -> template
(Ops.Ary1 _) -> printf template arg1
(Ops.Ary2 _) -> printf template (arg1 `joinBytes` arg2)
(Ops.Unimplemented) -> printf "Unimplemented instruction: 0x%02X (%s)" opcode template
in
printf "PC = 0x%04X (%s)\n" pointer label
viewFlags :: Word8 -> String
viewFlags f =
"Flags ZNHC \n" ++
" " ++ (b 7) ++ (b 6) ++ (b 5) ++ (b 4) ++ "\n"
where
b n = if (testBit f n) then "1" else "0"
readMem16 :: Address -> FrozenCPUEnvironment -> Word16
readMem16 address cpu =
let
low = readFrzMemory address cpu
high = readFrzMemory (address + 1) cpu
in
joinBytes low high
viewMem16 :: Address -> FrozenCPUEnvironment -> String
viewMem16 address cpu =
printf "0x%04X" $ readMem16 address cpu
viewMem :: Address -> FrozenCPUEnvironment -> String
viewMem address cpu =
printf "0x%02X" $ readFrzMemory address cpu
viewStack :: FrozenCPUEnvironment -> String
viewStack cpu =
printf "[0x%04X] <- 0x%04X\n" value pointer
where
pointer = frz_sp cpu
value = readMem16 pointer cpu
|
6ef810565849aa00a105900483b140fd155d9894e27174e200e15af88445b4ea | pierric/fei-nn | Optimizer.hs | {-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
# LANGUAGE OverloadedLists #
# LANGUAGE UndecidableInstances #
module MXNet.NN.Optimizer where
import Control.Lens (use, (.=))
import GHC.Exts (Constraint)
import GHC.TypeLits
import RIO
import qualified RIO.HashMap as M
import RIO.State
import MXNet.Base hiding (Symbol)
import qualified MXNet.Base.Operators.Tensor as T
import MXNet.NN.LrScheduler (LrScheduler (..))
import MXNet.NN.TaggedState (untag)
import MXNet.NN.Types (TaggedModuleState, mod_statistics,
stat_last_lr, stat_num_upd)
-- | Abstract Optimizer type class
class Optimizer (opt :: * -> *) where
data OptimizerTag opt :: *
-- | Specific required arguments
data opt : : *
-- | Specific optional arguments
-- type OptArgsList opt :: [KV *]
-- | make the optimizer
makeOptimizer :: (DType dtype, LrScheduler sch, OptimizerCst opt dtype args, MonadIO m)
=> OptimizerTag opt -> sch
-> ArgsHMap (OptimizerSym opt) '(NDArray, dtype) args
-> m (opt dtype)
-- | run the optimizer with the input & expected tensor
optimize :: (DType dtype, MonadState (TaggedModuleState dtype t) m, MonadIO m)
=> opt dtype -- optimizer
-> Text -- symbol name to optimize
-> NDArray dtype -- parameter
-> NDArray dtype -- gradient
-> m ()
type family OptimizerSym (opt :: * -> *) :: Symbol
type family OptimizerCst (opt :: * -> *) dt (args :: [*]) :: Constraint
-- | SGD optimizer
data SGD_Opt dtype where
SGD_Opt :: (LrScheduler sch, OptimizerCst SGD_Opt dtype args)
=> sch -> ArgsHMap (OptimizerSym SGD_Opt) '(NDArray, dtype) args
-> SGD_Opt dtype
type instance OptimizerSym SGD_Opt = "_sgd_update"
1.0.0 type instance OptimizerCst SGD_Opt dt args = ( OptimizerSym SGD_Opt ) args ' [ " wd " , " rescale_grad " , " clip_gradient " ]
type instance OptimizerCst SGD_Opt dt args =
HasArgs (OptimizerSym SGD_Opt) '(NDArray, dt) args '["wd", "rescale_grad", "clip_gradient", "lazy_update"]
instance Optimizer SGD_Opt where
data OptimizerTag SGD_Opt = SGD
makeOptimizer SGD sch args = return $ SGD_Opt sch args
optimize (SGD_Opt sch args) _ weight gradient = do
nup <- use $ untag . mod_statistics . stat_num_upd
let lr = getLR sch nup
untag . mod_statistics . stat_last_lr .= lr
liftIO $ void $ T._sgd_update (#weight := weight
.& #grad := gradient
.& #lr := lr .& args)
(Just [weight])
-- | SGD with momentum optimizer
data SGD_Mom_Opt dtype where
SGD_Mom_Opt :: (LrScheduler sch, OptimizerCst SGD_Mom_Opt dtype args)
=> sch -> ArgsHMap (OptimizerSym SGD_Mom_Opt) '(NDArray, dtype) args
-> IORef (M.HashMap Text (NDArray dtype))
-> SGD_Mom_Opt dtype
type instance OptimizerSym SGD_Mom_Opt = "_sgd_mom_update"
1.0.0 type instance SGD_Mom_Opt dt args = ( OptimizerSym SGD_Mom_Opt ) args ' [ " momentum " , " wd " , " rescale_grad " , " clip_gradient " ]
type instance OptimizerCst SGD_Mom_Opt dt args =
HasArgs (OptimizerSym SGD_Mom_Opt) '(NDArray, dt) args '["momentum", "wd", "rescale_grad", "clip_gradient", "lazy_update"]
instance Optimizer SGD_Mom_Opt where
data OptimizerTag SGD_Mom_Opt = SGD'Mom
makeOptimizer SGD'Mom sch args = do
empty <- newIORef M.empty
return $ SGD_Mom_Opt sch args empty
optimize (SGD_Mom_Opt sch args emaref) symbol weight gradient = do
nup <- use $ untag . mod_statistics . stat_num_upd
let lr = getLR sch nup
untag . mod_statistics . stat_last_lr .= lr
liftIO $ do
ema <- readIORef emaref
momentum <- case M.lookup symbol ema of
Nothing -> do
mom <- prim T._zeros_like (#data := weight .& Nil)
writeIORef emaref (M.insert symbol mom ema)
return mom
Just a -> return a
let norm x = prim T._norm ( # data : = x . & # ord : = 1 . & Nil )
-- [w0] <- toVector =<< norm weight
-- [m0] <- toVector =<< norm momentum
-- [g0] <- toVector =<< norm gradient
void $ T._sgd_mom_update (#weight := weight
.& #grad := gradient
.& #mom := momentum
.& #lr := lr .& args)
(Just [weight])
-- [w1] <- toVector =<< norm weight
-- [m1] <- toVector =<< norm momentum
-- traceShowM ("opt", symbol, w0, m0, g0, w1, m1)
-- | ADAM optmizer
data ADAM_Opt dtype where
ADAM_Opt :: (LrScheduler sch, OptimizerCst ADAM_Opt dtype args)
=> sch -> ArgsHMap (OptimizerSym ADAM_Opt) '(NDArray, dtype) args
-> IORef (M.HashMap Text (NDArray dtype, NDArray dtype))
-> ADAM_Opt dtype
type instance OptimizerSym ADAM_Opt = "_adam_update"
1.0.0 type instance OptimizerCst ADAM_Opt dt args = ( OptimizerSym ADAM_Opt ) args ' [ " beta1 " , " beta2 " , " epsilon " , " wd " , " rescale_grad " , " clip_gradient " ]
type instance OptimizerCst ADAM_Opt dt args =
HasArgs (OptimizerSym ADAM_Opt) '(NDArray, dt) args '["beta1", "beta2", "epsilon", "wd", "rescale_grad", "clip_gradient", "lazy_update"]
instance Optimizer ADAM_Opt where
data OptimizerTag ADAM_Opt = ADAM
makeOptimizer ADAM sch args = do
empty <- newIORef M.empty
return $ ADAM_Opt sch args empty
optimize (ADAM_Opt sch args emaref) symbol weight gradient = do
nup <- use $ untag . mod_statistics . stat_num_upd
let lr = getLR sch nup
untag . mod_statistics . stat_last_lr .= lr
liftIO $ do
ema <- readIORef emaref
(moving_avg, moving_var) <- case M.lookup symbol ema of
Nothing -> do
avg <- prim T._zeros_like (#data := weight .& Nil)
var <- prim T._ones_like (#data := weight .& Nil)
writeIORef emaref (M.insert symbol (avg, var) ema)
return (avg, var)
Just (a, v) -> return (a, v)
void $ T._adam_update (#weight := weight
.& #grad := gradient
.& #mean := moving_avg
.& #var := moving_var
.& #lr := lr .& args)
(Just [weight])
#if MXNET_VERSION >= 10600
data ADAMW_Opt dtype where
ADAMW_Opt :: (LrScheduler sch, OptimizerCst ADAMW_Opt dtype args)
=> sch -> ArgsHMap (OptimizerSym ADAMW_Opt) '(NDArray, dtype) args
-> IORef (M.HashMap Text (NDArray dtype, NDArray dtype))
-> ADAMW_Opt dtype
type instance OptimizerSym ADAMW_Opt = "__adamw_update"
type instance OptimizerCst ADAMW_Opt dt args =
HasArgs (OptimizerSym ADAMW_Opt) '(NDArray, dt) args
'["beta1", "beta2", "epsilon", "wd", "eta", "clip_gradient", "rescale_grad"]
instance Optimizer ADAMW_Opt where
data OptimizerTag ADAMW_Opt = ADAMW
makeOptimizer ADAMW sch args = do
empty <- newIORef M.empty
return $ ADAMW_Opt sch args empty
optimize (ADAMW_Opt sch args emaref) symbol weight gradient = do
nup <- use $ untag . mod_statistics . stat_num_upd
let lr = getLR sch nup
untag . mod_statistics . stat_last_lr .= lr
liftIO $ do
ema <- readIORef emaref
(moving_avg, moving_var) <- case M.lookup symbol ema of
Nothing -> do
avg <- prim T._zeros_like (#data := weight .& Nil)
var <- prim T._ones_like (#data := weight .& Nil)
writeIORef emaref (M.insert symbol (avg, var) ema)
return (avg, var)
Just (a, v) -> return (a, v)
void $ T.__adamw_update
(#weight := weight .&
#grad := gradient .&
#mean := moving_avg .&
#var := moving_var .&
#lr := lr .& args)
(Just [weight])
#endif
| null | https://raw.githubusercontent.com/pierric/fei-nn/0a78e31e98495a4ab5183ab1faabba5b0721280e/src/MXNet/NN/Optimizer.hs | haskell | # LANGUAGE CPP #
# LANGUAGE ConstraintKinds #
| Abstract Optimizer type class
| Specific required arguments
| Specific optional arguments
type OptArgsList opt :: [KV *]
| make the optimizer
| run the optimizer with the input & expected tensor
optimizer
symbol name to optimize
parameter
gradient
| SGD optimizer
| SGD with momentum optimizer
[w0] <- toVector =<< norm weight
[m0] <- toVector =<< norm momentum
[g0] <- toVector =<< norm gradient
[w1] <- toVector =<< norm weight
[m1] <- toVector =<< norm momentum
traceShowM ("opt", symbol, w0, m0, g0, w1, m1)
| ADAM optmizer | # LANGUAGE OverloadedLists #
# LANGUAGE UndecidableInstances #
module MXNet.NN.Optimizer where
import Control.Lens (use, (.=))
import GHC.Exts (Constraint)
import GHC.TypeLits
import RIO
import qualified RIO.HashMap as M
import RIO.State
import MXNet.Base hiding (Symbol)
import qualified MXNet.Base.Operators.Tensor as T
import MXNet.NN.LrScheduler (LrScheduler (..))
import MXNet.NN.TaggedState (untag)
import MXNet.NN.Types (TaggedModuleState, mod_statistics,
stat_last_lr, stat_num_upd)
class Optimizer (opt :: * -> *) where
data OptimizerTag opt :: *
data opt : : *
makeOptimizer :: (DType dtype, LrScheduler sch, OptimizerCst opt dtype args, MonadIO m)
=> OptimizerTag opt -> sch
-> ArgsHMap (OptimizerSym opt) '(NDArray, dtype) args
-> m (opt dtype)
optimize :: (DType dtype, MonadState (TaggedModuleState dtype t) m, MonadIO m)
-> m ()
type family OptimizerSym (opt :: * -> *) :: Symbol
type family OptimizerCst (opt :: * -> *) dt (args :: [*]) :: Constraint
data SGD_Opt dtype where
SGD_Opt :: (LrScheduler sch, OptimizerCst SGD_Opt dtype args)
=> sch -> ArgsHMap (OptimizerSym SGD_Opt) '(NDArray, dtype) args
-> SGD_Opt dtype
type instance OptimizerSym SGD_Opt = "_sgd_update"
1.0.0 type instance OptimizerCst SGD_Opt dt args = ( OptimizerSym SGD_Opt ) args ' [ " wd " , " rescale_grad " , " clip_gradient " ]
type instance OptimizerCst SGD_Opt dt args =
HasArgs (OptimizerSym SGD_Opt) '(NDArray, dt) args '["wd", "rescale_grad", "clip_gradient", "lazy_update"]
instance Optimizer SGD_Opt where
data OptimizerTag SGD_Opt = SGD
makeOptimizer SGD sch args = return $ SGD_Opt sch args
optimize (SGD_Opt sch args) _ weight gradient = do
nup <- use $ untag . mod_statistics . stat_num_upd
let lr = getLR sch nup
untag . mod_statistics . stat_last_lr .= lr
liftIO $ void $ T._sgd_update (#weight := weight
.& #grad := gradient
.& #lr := lr .& args)
(Just [weight])
data SGD_Mom_Opt dtype where
SGD_Mom_Opt :: (LrScheduler sch, OptimizerCst SGD_Mom_Opt dtype args)
=> sch -> ArgsHMap (OptimizerSym SGD_Mom_Opt) '(NDArray, dtype) args
-> IORef (M.HashMap Text (NDArray dtype))
-> SGD_Mom_Opt dtype
type instance OptimizerSym SGD_Mom_Opt = "_sgd_mom_update"
1.0.0 type instance SGD_Mom_Opt dt args = ( OptimizerSym SGD_Mom_Opt ) args ' [ " momentum " , " wd " , " rescale_grad " , " clip_gradient " ]
type instance OptimizerCst SGD_Mom_Opt dt args =
HasArgs (OptimizerSym SGD_Mom_Opt) '(NDArray, dt) args '["momentum", "wd", "rescale_grad", "clip_gradient", "lazy_update"]
instance Optimizer SGD_Mom_Opt where
data OptimizerTag SGD_Mom_Opt = SGD'Mom
makeOptimizer SGD'Mom sch args = do
empty <- newIORef M.empty
return $ SGD_Mom_Opt sch args empty
optimize (SGD_Mom_Opt sch args emaref) symbol weight gradient = do
nup <- use $ untag . mod_statistics . stat_num_upd
let lr = getLR sch nup
untag . mod_statistics . stat_last_lr .= lr
liftIO $ do
ema <- readIORef emaref
momentum <- case M.lookup symbol ema of
Nothing -> do
mom <- prim T._zeros_like (#data := weight .& Nil)
writeIORef emaref (M.insert symbol mom ema)
return mom
Just a -> return a
let norm x = prim T._norm ( # data : = x . & # ord : = 1 . & Nil )
void $ T._sgd_mom_update (#weight := weight
.& #grad := gradient
.& #mom := momentum
.& #lr := lr .& args)
(Just [weight])
data ADAM_Opt dtype where
ADAM_Opt :: (LrScheduler sch, OptimizerCst ADAM_Opt dtype args)
=> sch -> ArgsHMap (OptimizerSym ADAM_Opt) '(NDArray, dtype) args
-> IORef (M.HashMap Text (NDArray dtype, NDArray dtype))
-> ADAM_Opt dtype
type instance OptimizerSym ADAM_Opt = "_adam_update"
1.0.0 type instance OptimizerCst ADAM_Opt dt args = ( OptimizerSym ADAM_Opt ) args ' [ " beta1 " , " beta2 " , " epsilon " , " wd " , " rescale_grad " , " clip_gradient " ]
type instance OptimizerCst ADAM_Opt dt args =
HasArgs (OptimizerSym ADAM_Opt) '(NDArray, dt) args '["beta1", "beta2", "epsilon", "wd", "rescale_grad", "clip_gradient", "lazy_update"]
instance Optimizer ADAM_Opt where
data OptimizerTag ADAM_Opt = ADAM
makeOptimizer ADAM sch args = do
empty <- newIORef M.empty
return $ ADAM_Opt sch args empty
optimize (ADAM_Opt sch args emaref) symbol weight gradient = do
nup <- use $ untag . mod_statistics . stat_num_upd
let lr = getLR sch nup
untag . mod_statistics . stat_last_lr .= lr
liftIO $ do
ema <- readIORef emaref
(moving_avg, moving_var) <- case M.lookup symbol ema of
Nothing -> do
avg <- prim T._zeros_like (#data := weight .& Nil)
var <- prim T._ones_like (#data := weight .& Nil)
writeIORef emaref (M.insert symbol (avg, var) ema)
return (avg, var)
Just (a, v) -> return (a, v)
void $ T._adam_update (#weight := weight
.& #grad := gradient
.& #mean := moving_avg
.& #var := moving_var
.& #lr := lr .& args)
(Just [weight])
#if MXNET_VERSION >= 10600
data ADAMW_Opt dtype where
ADAMW_Opt :: (LrScheduler sch, OptimizerCst ADAMW_Opt dtype args)
=> sch -> ArgsHMap (OptimizerSym ADAMW_Opt) '(NDArray, dtype) args
-> IORef (M.HashMap Text (NDArray dtype, NDArray dtype))
-> ADAMW_Opt dtype
type instance OptimizerSym ADAMW_Opt = "__adamw_update"
type instance OptimizerCst ADAMW_Opt dt args =
HasArgs (OptimizerSym ADAMW_Opt) '(NDArray, dt) args
'["beta1", "beta2", "epsilon", "wd", "eta", "clip_gradient", "rescale_grad"]
instance Optimizer ADAMW_Opt where
data OptimizerTag ADAMW_Opt = ADAMW
makeOptimizer ADAMW sch args = do
empty <- newIORef M.empty
return $ ADAMW_Opt sch args empty
optimize (ADAMW_Opt sch args emaref) symbol weight gradient = do
nup <- use $ untag . mod_statistics . stat_num_upd
let lr = getLR sch nup
untag . mod_statistics . stat_last_lr .= lr
liftIO $ do
ema <- readIORef emaref
(moving_avg, moving_var) <- case M.lookup symbol ema of
Nothing -> do
avg <- prim T._zeros_like (#data := weight .& Nil)
var <- prim T._ones_like (#data := weight .& Nil)
writeIORef emaref (M.insert symbol (avg, var) ema)
return (avg, var)
Just (a, v) -> return (a, v)
void $ T.__adamw_update
(#weight := weight .&
#grad := gradient .&
#mean := moving_avg .&
#var := moving_var .&
#lr := lr .& args)
(Just [weight])
#endif
|
fb386c10621b64dc11626afba4c054f4c37257a7f7e8b3bc6ce2f34cdc1b78a4 | google/lisp-koans | clos.lisp | Copyright 2013 Google Inc.
;;;
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; -2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
CLOS is a shorthand for Common Lisp Object System .
(defclass racecar ()
;; A class definition lists all the slots of every instance.
(color speed))
(define-test defclass
;; Class instances are constructed via MAKE-INSTANCE.
(let ((car-1 (make-instance 'racecar))
(car-2 (make-instance 'racecar)))
Slot values can be set via SLOT - VALUE .
(setf (slot-value car-1 'color) :red)
(setf (slot-value car-1 'speed) 220)
(setf (slot-value car-2 'color) :blue)
(setf (slot-value car-2 'speed) 240)
(assert-equal ____ (slot-value car-1 'color))
(assert-equal ____ (slot-value car-2 'speed))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Common Lisp predefines the symbol SPEED in the COMMON - LISP package , which
means that we can not define a function named after it . The function SHADOW
;;; creates a new symbol with the same name in the current package and shadows
the predefined one within the current package .
(shadow 'speed)
(defclass spaceship ()
;; It is possible to define reader, writer, and accessor functions for slots.
((color :reader color :writer (setf color))
(speed :accessor speed)))
Specifying a reader function named COLOR is equivalent to
( DEFMETHOD COLOR ( ( OBJECT SPACECSHIP ) ) ... )
Specifying a writer function named ( SETF COLOR ) is equivalent to
( DEFMETHOD ( SETF COLOR ) ( NEW - VALUE ( OBJECT SPACECSHIP ) ) ... )
;;; Specifying an accessor function performs both of the above.
(define-test accessors
(let ((ship (make-instance 'spaceship)))
(setf (color ship) :orange
(speed ship) 1000)
(assert-equal ____ (color ship))
(assert-equal ____ (speed ship))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass bike ()
;; It is also possible to define initial arguments for slots.
((color :reader color :initarg :color)
(speed :reader speed :initarg :speed)))
(define-test initargs
(let ((bike (make-instance 'bike :color :blue :speed 30)))
(assert-equal ____ (color bike))
(assert-equal ____ (speed bike))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Lisp classes can inherit from one another .
(defclass person ()
((name :initarg :name :accessor person-name)))
(defclass lisp-programmer (person)
((favorite-lisp-implementation :initarg :favorite-lisp-implementation
:accessor favorite-lisp-implementation)))
(defclass c-programmer (person)
((favorite-c-compiler :initarg :favorite-c-compiler
:accessor favorite-c-compiler)))
(define-test inheritance
(let ((jack (make-instance 'person :name :jack))
(bob (make-instance 'lisp-programmer
:name :bob
:favorite-lisp-implementation :sbcl))
(adam (make-instance 'c-programmer
:name :adam
:favorite-c-compiler :clang)))
(assert-equal ____ (person-name jack))
(assert-equal ____ (person-name bob))
(assert-equal ____ (favorite-lisp-implementation bob))
(assert-equal ____ (person-name adam))
(assert-equal ____ (favorite-c-compiler adam))
(true-or-false? ____ (typep bob 'person))
(true-or-false? ____ (typep bob 'lisp-programmer))
(true-or-false? ____ (typep bob 'c-programmer))))
;;; This includes multiple inheritance.
(defclass clisp-programmer (lisp-programmer c-programmer) ())
(define-test multiple-inheritance
(let ((zenon (make-instance 'clisp-programmer
:name :zenon
:favorite-lisp-implementation :clisp
:favorite-c-compiler :gcc)))
(assert-equal ____ (person-name zenon))
(assert-equal ____ (favorite-lisp-implementation zenon))
(assert-equal ____ (favorite-c-compiler zenon))
(true-or-false? ____ (typep zenon 'person))
(true-or-false? ____ (typep zenon 'lisp-programmer))
(true-or-false? ____ (typep zenon 'c-programmer))
(true-or-false? ____ (typep zenon 'clisp-programmer))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Multiple inheritance makes it possible to work with mixin classes.
(defclass greeting-mixin ()
((greeted-people :accessor greeted-people :initform '())))
(defgeneric greet (greeter greetee))
(defmethod greet ((object greeting-mixin) name)
PUSHNEW is similar to PUSH , but it does not modify the place if the object
;; we want to push is already found on the list in the place.
(pushnew name (greeted-people object) :test #'equal)
(format nil "Hello, ~A." name))
(defclass chatbot ()
((version :reader version :initarg :version)))
(defclass greeting-chatbot (greeting-mixin chatbot) ())
(define-test greeting-chatbot ()
(let ((chatbot (make-instance 'greeting-chatbot :version "1.0.0")))
(true-or-false? ____ (typep chatbot 'greeting-mixin))
(true-or-false? ____ (typep chatbot 'chatbot))
(true-or-false? ____ (typep chatbot 'greeting-chatbot))
(assert-equal ____ (greet chatbot "Tom"))
(assert-equal ____ (greeted-people chatbot))
(assert-equal ____ (greet chatbot "Sue"))
(assert-equal ____ (greet chatbot "Mark"))
(assert-equal ____ (greet chatbot "Kate"))
(assert-equal ____ (greet chatbot "Mark"))
(assert-equal ____ (greeted-people chatbot))
(assert-equal ____ (version chatbot))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass american (person) ())
(defclass italian (person) ())
(defgeneric stereotypical-food (person)
The : METHOD option in is an alternative to DEFMETHOD .
(:method ((person italian)) :pasta)
(:method ((person american)) :burger))
When methods or slot definitions of superclasses overlap with each other ,
the order of superclasses is used to resolve the conflict .
(defclass stereotypical-person (american italian) ())
(defclass another-stereotypical-person (italian american) ())
(define-test stereotypes
(let ((james (make-instance 'american))
(antonio (make-instance 'italian))
(roy (make-instance 'stereotypical-person))
(mary (make-instance 'another-stereotypical-person)))
(assert-equal ____ (stereotypical-food james))
(assert-equal ____ (stereotypical-food antonio))
(assert-equal ____ (stereotypical-food roy))
(assert-equal ____ (stereotypical-food mary))))
| null | https://raw.githubusercontent.com/google/lisp-koans/df5e58dc88429ef0ff202d0b45c21ce572144ba8/koans/clos.lisp | lisp |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
A class definition lists all the slots of every instance.
Class instances are constructed via MAKE-INSTANCE.
creates a new symbol with the same name in the current package and shadows
It is possible to define reader, writer, and accessor functions for slots.
Specifying an accessor function performs both of the above.
It is also possible to define initial arguments for slots.
This includes multiple inheritance.
Multiple inheritance makes it possible to work with mixin classes.
we want to push is already found on the list in the place.
| Copyright 2013 Google Inc.
distributed under the License is distributed on an " AS IS " BASIS ,
CLOS is a shorthand for Common Lisp Object System .
(defclass racecar ()
(color speed))
(define-test defclass
(let ((car-1 (make-instance 'racecar))
(car-2 (make-instance 'racecar)))
Slot values can be set via SLOT - VALUE .
(setf (slot-value car-1 'color) :red)
(setf (slot-value car-1 'speed) 220)
(setf (slot-value car-2 'color) :blue)
(setf (slot-value car-2 'speed) 240)
(assert-equal ____ (slot-value car-1 'color))
(assert-equal ____ (slot-value car-2 'speed))))
Common Lisp predefines the symbol SPEED in the COMMON - LISP package , which
means that we can not define a function named after it . The function SHADOW
the predefined one within the current package .
(shadow 'speed)
(defclass spaceship ()
((color :reader color :writer (setf color))
(speed :accessor speed)))
Specifying a reader function named COLOR is equivalent to
( DEFMETHOD COLOR ( ( OBJECT SPACECSHIP ) ) ... )
Specifying a writer function named ( SETF COLOR ) is equivalent to
( DEFMETHOD ( SETF COLOR ) ( NEW - VALUE ( OBJECT SPACECSHIP ) ) ... )
(define-test accessors
(let ((ship (make-instance 'spaceship)))
(setf (color ship) :orange
(speed ship) 1000)
(assert-equal ____ (color ship))
(assert-equal ____ (speed ship))))
(defclass bike ()
((color :reader color :initarg :color)
(speed :reader speed :initarg :speed)))
(define-test initargs
(let ((bike (make-instance 'bike :color :blue :speed 30)))
(assert-equal ____ (color bike))
(assert-equal ____ (speed bike))))
Lisp classes can inherit from one another .
(defclass person ()
((name :initarg :name :accessor person-name)))
(defclass lisp-programmer (person)
((favorite-lisp-implementation :initarg :favorite-lisp-implementation
:accessor favorite-lisp-implementation)))
(defclass c-programmer (person)
((favorite-c-compiler :initarg :favorite-c-compiler
:accessor favorite-c-compiler)))
(define-test inheritance
(let ((jack (make-instance 'person :name :jack))
(bob (make-instance 'lisp-programmer
:name :bob
:favorite-lisp-implementation :sbcl))
(adam (make-instance 'c-programmer
:name :adam
:favorite-c-compiler :clang)))
(assert-equal ____ (person-name jack))
(assert-equal ____ (person-name bob))
(assert-equal ____ (favorite-lisp-implementation bob))
(assert-equal ____ (person-name adam))
(assert-equal ____ (favorite-c-compiler adam))
(true-or-false? ____ (typep bob 'person))
(true-or-false? ____ (typep bob 'lisp-programmer))
(true-or-false? ____ (typep bob 'c-programmer))))
(defclass clisp-programmer (lisp-programmer c-programmer) ())
(define-test multiple-inheritance
(let ((zenon (make-instance 'clisp-programmer
:name :zenon
:favorite-lisp-implementation :clisp
:favorite-c-compiler :gcc)))
(assert-equal ____ (person-name zenon))
(assert-equal ____ (favorite-lisp-implementation zenon))
(assert-equal ____ (favorite-c-compiler zenon))
(true-or-false? ____ (typep zenon 'person))
(true-or-false? ____ (typep zenon 'lisp-programmer))
(true-or-false? ____ (typep zenon 'c-programmer))
(true-or-false? ____ (typep zenon 'clisp-programmer))))
(defclass greeting-mixin ()
((greeted-people :accessor greeted-people :initform '())))
(defgeneric greet (greeter greetee))
(defmethod greet ((object greeting-mixin) name)
PUSHNEW is similar to PUSH , but it does not modify the place if the object
(pushnew name (greeted-people object) :test #'equal)
(format nil "Hello, ~A." name))
(defclass chatbot ()
((version :reader version :initarg :version)))
(defclass greeting-chatbot (greeting-mixin chatbot) ())
(define-test greeting-chatbot ()
(let ((chatbot (make-instance 'greeting-chatbot :version "1.0.0")))
(true-or-false? ____ (typep chatbot 'greeting-mixin))
(true-or-false? ____ (typep chatbot 'chatbot))
(true-or-false? ____ (typep chatbot 'greeting-chatbot))
(assert-equal ____ (greet chatbot "Tom"))
(assert-equal ____ (greeted-people chatbot))
(assert-equal ____ (greet chatbot "Sue"))
(assert-equal ____ (greet chatbot "Mark"))
(assert-equal ____ (greet chatbot "Kate"))
(assert-equal ____ (greet chatbot "Mark"))
(assert-equal ____ (greeted-people chatbot))
(assert-equal ____ (version chatbot))))
(defclass american (person) ())
(defclass italian (person) ())
(defgeneric stereotypical-food (person)
The : METHOD option in is an alternative to DEFMETHOD .
(:method ((person italian)) :pasta)
(:method ((person american)) :burger))
When methods or slot definitions of superclasses overlap with each other ,
the order of superclasses is used to resolve the conflict .
(defclass stereotypical-person (american italian) ())
(defclass another-stereotypical-person (italian american) ())
(define-test stereotypes
(let ((james (make-instance 'american))
(antonio (make-instance 'italian))
(roy (make-instance 'stereotypical-person))
(mary (make-instance 'another-stereotypical-person)))
(assert-equal ____ (stereotypical-food james))
(assert-equal ____ (stereotypical-food antonio))
(assert-equal ____ (stereotypical-food roy))
(assert-equal ____ (stereotypical-food mary))))
|
136b10215f0ad40128534a4894650a497984e08f8758c625379c5cd1daf31204 | SamB/coq | environ.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i $Id$ i*)
(*i*)
open Names
open Term
open Declarations
open Sign
(*i*)
(*s Unsafe environments. We define here a datatype for environments.
Since typing is not yet defined, it is not possible to check the
informations added in environments, and that is why we speak here
of ``unsafe'' environments. *)
Environments have the following components :
- a context for variables
- a context for variables vm values
- a context for section variables and goal assumptions
- a context for section variables and goal assumptions vm values
- a context for global constants and axioms
- a context for inductive definitions
- a set of universe constraints
- a flag telling if Set is , can be , or can not be set impredicative
- a context for de Bruijn variables
- a context for de Bruijn variables vm values
- a context for section variables and goal assumptions
- a context for section variables and goal assumptions vm values
- a context for global constants and axioms
- a context for inductive definitions
- a set of universe constraints
- a flag telling if Set is, can be, or cannot be set impredicative *)
type env
val pre_env : env -> Pre_env.env
val env_of_pre_env : Pre_env.env -> env
type named_context_val
val eq_named_context_val : named_context_val -> named_context_val -> bool
val empty_env : env
val universes : env -> Univ.universes
val rel_context : env -> rel_context
val named_context : env -> named_context
val named_context_val : env -> named_context_val
val engagement : env -> engagement option
(* is the local context empty *)
val empty_context : env -> bool
(************************************************************************)
(*s Context of de Bruijn variables ([rel_context]) *)
val nb_rel : env -> int
val push_rel : rel_declaration -> env -> env
val push_rel_context : rel_context -> env -> env
val push_rec_types : rec_declaration -> env -> env
(* Looks up in the context of local vars referred by indice ([rel_context]) *)
(* raises [Not_found] if the index points out of the context *)
val lookup_rel : int -> env -> rel_declaration
val evaluable_rel : int -> env -> bool
(*s Recurrence on [rel_context] *)
val fold_rel_context :
(env -> rel_declaration -> 'a -> 'a) -> env -> init:'a -> 'a
(************************************************************************)
(* Context of variables (section variables and goal assumptions) *)
val named_context_of_val : named_context_val -> named_context
val named_vals_of_val : named_context_val -> Pre_env.named_vals
val val_of_named_context : named_context -> named_context_val
val empty_named_context_val : named_context_val
(* [map_named_val f ctxt] apply [f] to the body and the type of
each declarations.
*** /!\ *** [f t] should be convertible with t *)
val map_named_val :
(constr -> constr) -> named_context_val -> named_context_val
val push_named : named_declaration -> env -> env
val push_named_context_val :
named_declaration -> named_context_val -> named_context_val
(* Looks up in the context of local vars referred by names ([named_context]) *)
(* raises [Not_found] if the identifier is not found *)
val lookup_named : variable -> env -> named_declaration
val lookup_named_val : variable -> named_context_val -> named_declaration
val evaluable_named : variable -> env -> bool
val named_type : variable -> env -> types
val named_body : variable -> env -> constr option
s Recurrence on [ named_context ] : older declarations processed first
val fold_named_context :
(env -> named_declaration -> 'a -> 'a) -> env -> init:'a -> 'a
Recurrence on [ named_context ] starting from younger
val fold_named_context_reverse :
('a -> named_declaration -> 'a) -> init:'a -> env -> 'a
(* This forgets named and rel contexts *)
val reset_context : env -> env
(* This forgets rel context and sets a new named context *)
val reset_with_named_context : named_context_val -> env -> env
(************************************************************************)
(*s Global constants *)
(*s Add entries to global environment *)
val add_constant : constant -> constant_body -> env -> env
(* Looks up in the context of global constant names *)
(* raises [Not_found] if the required path is not found *)
val lookup_constant : constant -> env -> constant_body
val evaluable_constant : constant -> env -> bool
s [ constant_value env c ] raises [ NotEvaluableConst Opaque ] if
[ c ] is opaque and [ ] if it has no
body and [ Not_found ] if it does not exist in [ env ]
[c] is opaque and [NotEvaluableConst NoBody] if it has no
body and [Not_found] if it does not exist in [env] *)
type const_evaluation_result = NoBody | Opaque
exception NotEvaluableConst of const_evaluation_result
val constant_value : env -> constant -> constr
val constant_type : env -> constant -> constant_type
val constant_opt_value : env -> constant -> constr option
(************************************************************************)
(*s Inductive types *)
val add_mind : mutual_inductive -> mutual_inductive_body -> env -> env
(* Looks up in the context of global inductive names *)
(* raises [Not_found] if the required path is not found *)
val lookup_mind : mutual_inductive -> env -> mutual_inductive_body
(* Find the ultimate inductive in the [mind_equiv] chain *)
val scrape_mind : env -> mutual_inductive -> mutual_inductive
(************************************************************************)
(*s Modules *)
val add_modtype : module_path -> module_type_body -> env -> env
(* [shallow_add_module] does not add module components *)
val shallow_add_module : module_path -> module_body -> env -> env
val lookup_module : module_path -> env -> module_body
val lookup_modtype : module_path -> env -> module_type_body
val register_alias : module_path -> module_path -> env -> env
val lookup_alias : module_path -> env -> module_path
val scrape_alias : module_path -> env -> module_path
(************************************************************************)
s Universe constraints
val set_universes : Univ.universes -> env -> env
val add_constraints : Univ.constraints -> env -> env
val set_engagement : engagement -> env -> env
(************************************************************************)
(* Sets of referred section variables *)
(* [global_vars_set env c] returns the list of [id]'s occurring as
[VAR id] in [c] *)
val global_vars_set : env -> constr -> Idset.t
(* the constr must be an atomic construction *)
val vars_of_global : env -> constr -> identifier list
val keep_hyps : env -> Idset.t -> section_context
(************************************************************************)
(*s Unsafe judgments. We introduce here the pre-type of judgments, which is
actually only a datatype to store a term with its type and the type of its
type. *)
type unsafe_judgment = {
uj_val : constr;
uj_type : types }
val make_judge : constr -> types -> unsafe_judgment
val j_val : unsafe_judgment -> constr
val j_type : unsafe_judgment -> types
type unsafe_type_judgment = {
utj_val : constr;
utj_type : sorts }
(*s Compilation of global declaration *)
val compile_constant_body :
env -> constr_substituted option -> bool -> bool -> Cemitcodes.body_code
(* opaque *) (* boxed *)
exception Hyp_not_found
(* [apply_to_hyp sign id f] split [sign] into [tail::(id,_,_)::head] and
return [tail::(f head (id,_,_) (rev tail))::head].
the value associated to id should not change *)
val apply_to_hyp : named_context_val -> variable ->
(named_context -> named_declaration -> named_context -> named_declaration) ->
named_context_val
(* [apply_to_hyp_and_dependent_on sign id f g] split [sign] into
[tail::(id,_,_)::head] and
return [(g tail)::(f (id,_,_))::head]. *)
val apply_to_hyp_and_dependent_on : named_context_val -> variable ->
(named_declaration -> named_context_val -> named_declaration) ->
(named_declaration -> named_context_val -> named_declaration) ->
named_context_val
val insert_after_hyp : named_context_val -> variable ->
named_declaration ->
(named_context -> unit) -> named_context_val
val remove_hyps : identifier list -> (named_declaration -> named_declaration) -> (Pre_env.lazy_val -> Pre_env.lazy_val) -> named_context_val -> named_context_val * identifier list
(* spiwack: functions manipulating the retroknowledge *)
open Retroknowledge
val retroknowledge : (retroknowledge->'a) -> env -> 'a
val registered : env -> field -> bool
val unregister : env -> field -> env
val register : env -> field -> Retroknowledge.entry -> env
(******************************************************************)
spiwack : a few declarations for the " Print Assumption " command
type context_object =
| Variable of identifier (* A section variable or a Let definition *)
| Axiom of constant (* An axiom or a constant. *)
(* AssumptionSet.t is a set of [assumption] *)
module OrderedContextObject : Set.OrderedType with type t = context_object
module ContextObjectMap : Map.S with type key = context_object
(* collects all the assumptions on which a term relies (together with
their type *)
val assumptions : constr -> env -> Term.types ContextObjectMap.t
| null | https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/kernel/environ.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i $Id$ i
i
i
s Unsafe environments. We define here a datatype for environments.
Since typing is not yet defined, it is not possible to check the
informations added in environments, and that is why we speak here
of ``unsafe'' environments.
is the local context empty
**********************************************************************
s Context of de Bruijn variables ([rel_context])
Looks up in the context of local vars referred by indice ([rel_context])
raises [Not_found] if the index points out of the context
s Recurrence on [rel_context]
**********************************************************************
Context of variables (section variables and goal assumptions)
[map_named_val f ctxt] apply [f] to the body and the type of
each declarations.
*** /!\ *** [f t] should be convertible with t
Looks up in the context of local vars referred by names ([named_context])
raises [Not_found] if the identifier is not found
This forgets named and rel contexts
This forgets rel context and sets a new named context
**********************************************************************
s Global constants
s Add entries to global environment
Looks up in the context of global constant names
raises [Not_found] if the required path is not found
**********************************************************************
s Inductive types
Looks up in the context of global inductive names
raises [Not_found] if the required path is not found
Find the ultimate inductive in the [mind_equiv] chain
**********************************************************************
s Modules
[shallow_add_module] does not add module components
**********************************************************************
**********************************************************************
Sets of referred section variables
[global_vars_set env c] returns the list of [id]'s occurring as
[VAR id] in [c]
the constr must be an atomic construction
**********************************************************************
s Unsafe judgments. We introduce here the pre-type of judgments, which is
actually only a datatype to store a term with its type and the type of its
type.
s Compilation of global declaration
opaque
boxed
[apply_to_hyp sign id f] split [sign] into [tail::(id,_,_)::head] and
return [tail::(f head (id,_,_) (rev tail))::head].
the value associated to id should not change
[apply_to_hyp_and_dependent_on sign id f g] split [sign] into
[tail::(id,_,_)::head] and
return [(g tail)::(f (id,_,_))::head].
spiwack: functions manipulating the retroknowledge
****************************************************************
A section variable or a Let definition
An axiom or a constant.
AssumptionSet.t is a set of [assumption]
collects all the assumptions on which a term relies (together with
their type | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Term
open Declarations
open Sign
Environments have the following components :
- a context for variables
- a context for variables vm values
- a context for section variables and goal assumptions
- a context for section variables and goal assumptions vm values
- a context for global constants and axioms
- a context for inductive definitions
- a set of universe constraints
- a flag telling if Set is , can be , or can not be set impredicative
- a context for de Bruijn variables
- a context for de Bruijn variables vm values
- a context for section variables and goal assumptions
- a context for section variables and goal assumptions vm values
- a context for global constants and axioms
- a context for inductive definitions
- a set of universe constraints
- a flag telling if Set is, can be, or cannot be set impredicative *)
type env
val pre_env : env -> Pre_env.env
val env_of_pre_env : Pre_env.env -> env
type named_context_val
val eq_named_context_val : named_context_val -> named_context_val -> bool
val empty_env : env
val universes : env -> Univ.universes
val rel_context : env -> rel_context
val named_context : env -> named_context
val named_context_val : env -> named_context_val
val engagement : env -> engagement option
val empty_context : env -> bool
val nb_rel : env -> int
val push_rel : rel_declaration -> env -> env
val push_rel_context : rel_context -> env -> env
val push_rec_types : rec_declaration -> env -> env
val lookup_rel : int -> env -> rel_declaration
val evaluable_rel : int -> env -> bool
val fold_rel_context :
(env -> rel_declaration -> 'a -> 'a) -> env -> init:'a -> 'a
val named_context_of_val : named_context_val -> named_context
val named_vals_of_val : named_context_val -> Pre_env.named_vals
val val_of_named_context : named_context -> named_context_val
val empty_named_context_val : named_context_val
val map_named_val :
(constr -> constr) -> named_context_val -> named_context_val
val push_named : named_declaration -> env -> env
val push_named_context_val :
named_declaration -> named_context_val -> named_context_val
val lookup_named : variable -> env -> named_declaration
val lookup_named_val : variable -> named_context_val -> named_declaration
val evaluable_named : variable -> env -> bool
val named_type : variable -> env -> types
val named_body : variable -> env -> constr option
s Recurrence on [ named_context ] : older declarations processed first
val fold_named_context :
(env -> named_declaration -> 'a -> 'a) -> env -> init:'a -> 'a
Recurrence on [ named_context ] starting from younger
val fold_named_context_reverse :
('a -> named_declaration -> 'a) -> init:'a -> env -> 'a
val reset_context : env -> env
val reset_with_named_context : named_context_val -> env -> env
val add_constant : constant -> constant_body -> env -> env
val lookup_constant : constant -> env -> constant_body
val evaluable_constant : constant -> env -> bool
s [ constant_value env c ] raises [ NotEvaluableConst Opaque ] if
[ c ] is opaque and [ ] if it has no
body and [ Not_found ] if it does not exist in [ env ]
[c] is opaque and [NotEvaluableConst NoBody] if it has no
body and [Not_found] if it does not exist in [env] *)
type const_evaluation_result = NoBody | Opaque
exception NotEvaluableConst of const_evaluation_result
val constant_value : env -> constant -> constr
val constant_type : env -> constant -> constant_type
val constant_opt_value : env -> constant -> constr option
val add_mind : mutual_inductive -> mutual_inductive_body -> env -> env
val lookup_mind : mutual_inductive -> env -> mutual_inductive_body
val scrape_mind : env -> mutual_inductive -> mutual_inductive
val add_modtype : module_path -> module_type_body -> env -> env
val shallow_add_module : module_path -> module_body -> env -> env
val lookup_module : module_path -> env -> module_body
val lookup_modtype : module_path -> env -> module_type_body
val register_alias : module_path -> module_path -> env -> env
val lookup_alias : module_path -> env -> module_path
val scrape_alias : module_path -> env -> module_path
s Universe constraints
val set_universes : Univ.universes -> env -> env
val add_constraints : Univ.constraints -> env -> env
val set_engagement : engagement -> env -> env
val global_vars_set : env -> constr -> Idset.t
val vars_of_global : env -> constr -> identifier list
val keep_hyps : env -> Idset.t -> section_context
type unsafe_judgment = {
uj_val : constr;
uj_type : types }
val make_judge : constr -> types -> unsafe_judgment
val j_val : unsafe_judgment -> constr
val j_type : unsafe_judgment -> types
type unsafe_type_judgment = {
utj_val : constr;
utj_type : sorts }
val compile_constant_body :
env -> constr_substituted option -> bool -> bool -> Cemitcodes.body_code
exception Hyp_not_found
val apply_to_hyp : named_context_val -> variable ->
(named_context -> named_declaration -> named_context -> named_declaration) ->
named_context_val
val apply_to_hyp_and_dependent_on : named_context_val -> variable ->
(named_declaration -> named_context_val -> named_declaration) ->
(named_declaration -> named_context_val -> named_declaration) ->
named_context_val
val insert_after_hyp : named_context_val -> variable ->
named_declaration ->
(named_context -> unit) -> named_context_val
val remove_hyps : identifier list -> (named_declaration -> named_declaration) -> (Pre_env.lazy_val -> Pre_env.lazy_val) -> named_context_val -> named_context_val * identifier list
open Retroknowledge
val retroknowledge : (retroknowledge->'a) -> env -> 'a
val registered : env -> field -> bool
val unregister : env -> field -> env
val register : env -> field -> Retroknowledge.entry -> env
spiwack : a few declarations for the " Print Assumption " command
type context_object =
module OrderedContextObject : Set.OrderedType with type t = context_object
module ContextObjectMap : Map.S with type key = context_object
val assumptions : constr -> env -> Term.types ContextObjectMap.t
|
7c2a6e508f6d578e85ff9944bcd464cdaac6f568596f7965897602ce8007a2d2 | Eduap-com/WordMat | cgrind.lisp | (in-package :maxima)
(macsyma-module cgrind)
This is heavily lifted from grind.lisp and fortra.lisp , and should have the
;; same features as the fortran command. In order to work it needs to be compiled and
then loaded , as in ( for the case of cmucl ):
: lisp ( compile - file " cgrind.lisp " ) , copy cgrind.sse2f to ~/.maxima
;; load(cgrind)
;; Then one can run cgrind(expression) or cgrind(matrix).
( 2011 )
If NIL , no load message gets printed .
This function is called from toplevel . First the arguments is
;; checked to be a single expression. Then if the argument is a
;; symbol, and the symbol is bound to a matrix, the matrix is printed
;; using an array assignment notation.
(defmspec $cgrind (l)
(setq l (fexprcheck l))
(let ((value (strmeval l)))
(cond ((msetqp l) (setq value `((mequal) ,(cadr l) ,(meval l)))))
(cond ((and (symbolp l) ($matrixp value))
($cgrindmx l value))
((and (not (atom value)) (eq (caar value) 'mequal)
(symbolp (cadr value)) ($matrixp (caddr value)))
($cgrindmx (cadr value) (caddr value)))
(t (c-print value)))))
(defun c-print (x &optional (stream *standard-output*))
;; Restructure the expression for displaying.
;; Mainly sanitizes exponentials, notably exp(2/3) becomes
;; exp(2.0/3.0)
(setq x (scanforc x))
Protects the modifications to from creeping out .
(unwind-protect
(progn
(defprop mexpt msz-cmexpt grind)
;; This means basic printing for atoms, grind does fancy things.
(setq *fortran-print* t)
;; Prints using the usual grind mechanisms
(mgrind x stream)(write-char #\; stream)(write-char #\Newline stream))
Restore usual property etc . before exiting this frame .
(defprop mexpt msz-mexpt grind)
(setq *fortran-print* nil))
'$done)
;; The only modification to grind, converts a^b to pow(a,b), but taking
;; care of appropriate bracketing. The argument l to the left of (MEXPT)
;; has to be composed backwards. Finally a^-b has special treatment.
(defun msz-cmexpt (x l r)
(setq l (msize (cadr x) (revappend '(#\p #\o #\w #\() l) (list #\,) 'mparen 'mparen)
r (if (mmminusp (setq x (nformat (caddr x))))
(msize (cadr x) (list #\-) (cons #\) r) 'mexpt rop)
(msize x nil (cons #\) r ) 'mparen 'mparen)))
(list (+ (car l) (car r)) l r))
;; Takes a name and a matrix and prints a sequence of C assignment
;; statements of the form
NAME[I][J ] = < corresponding matrix element >
;; This requires some formatting work unnecessary for the fortran case.
(defmfun $cgrindmx (name mat &optional (stream *standard-output*) &aux ($loadprint nil))
(cond ((not (symbolp name))
(merror (intl:gettext "cgrindmx: first argument must be a symbol; found: ~M") name))
((not ($matrixp mat))
(merror (intl:gettext "cgrindmx: second argument must be a matrix; found: ~M") mat)))
(do ((mat (cdr mat) (cdr mat)) (i 1 (1+ i)))
((null mat))
(do ((m (cdar mat) (cdr m)) (j 1 (1+ j)))
((null m))
(format stream "~a[~a][~a] = " (string-left-trim "$" name) (1- i) (1- j) )
(c-print (car m) stream)))
'$done)
This C scanning function is similar to fortscan . Prepare an expression
;; for printing by converting x^(1/2) to sqrt(x), etc. Since C has no
support for complex numbers , contrary to Fortran , ban them .
(defun scanforc (e)
(cond ((atom e) (cond ((eq e '$%i) ;; ban complex numbers
(merror (intl:gettext "Take real and imaginary parts")))
(t e)))
;; %e^a -> exp(a)
((and (eq (caar e) 'mexpt) (eq (cadr e) '$%e))
(list '(%exp simp) (scanforc (caddr e))))
a^1/2 - > sqrt(a ) 1//2 is defined as ( ( rat simp ) 1 2 )
((and (eq (caar e) 'mexpt) (alike1 (caddr e) 1//2))
(list '(%sqrt simp) (scanforc (cadr e))))
;; a^-1/2 -> 1/sqrt(a)
((and (eq (caar e) 'mexpt) (alike1 (caddr e) -1//2))
(list '(mquotient simp) 1 (list '(%sqrt simp) (scanforc (cadr e)))))
;; (1/3)*b -> b/3.0 and (-1/3)*b -> -b/3.0
((and (eq (caar e) 'mtimes) (ratnump (cadr e))
(member (cadadr e) '(1 -1) :test #'equal))
(cond ((equal (cadadr e) 1) (scanforc-mtimes e))
(t (list '(mminus simp) (scanforc-mtimes e)))))
1/3 - > 1.0/3.0
((eq (caar e) 'rat)
(list '(mquotient simp) (float (cadr e)) (float (caddr e))))
;; rat(a/b) -> a/b via ratdisrep
((eq (caar e) 'mrat) (scanforc (ratdisrep e)))
;; ban complex numbers
((and (member (caar e) '(mtimes mplus) :test #'eq)
(let ((a (simplify ($bothcoef e '$%i))))
(and (numberp (cadr a))
(numberp (caddr a))
(not (zerop1 (cadr a)))
(merror (intl:gettext "Take real and imaginary parts"))))))
;; in general do nothing, recurse
(t (cons (car e) (mapcar 'scanforc (cdr e))))))
;; This is used above 1/3*b*c -> b*c/3.0
(defun scanforc-mtimes (e)
(list '(mquotient simp)
(cond ((null (cdddr e)) (scanforc (caddr e)))
(t (cons (car e) (mapcar 'scanforc (cddr e)))))
(float (caddr (cadr e)))))
| null | https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/contrib/cgrind.lisp | lisp | same features as the fortran command. In order to work it needs to be compiled and
load(cgrind)
Then one can run cgrind(expression) or cgrind(matrix).
checked to be a single expression. Then if the argument is a
symbol, and the symbol is bound to a matrix, the matrix is printed
using an array assignment notation.
Restructure the expression for displaying.
Mainly sanitizes exponentials, notably exp(2/3) becomes
exp(2.0/3.0)
This means basic printing for atoms, grind does fancy things.
Prints using the usual grind mechanisms
stream)(write-char #\Newline stream))
The only modification to grind, converts a^b to pow(a,b), but taking
care of appropriate bracketing. The argument l to the left of (MEXPT)
has to be composed backwards. Finally a^-b has special treatment.
Takes a name and a matrix and prints a sequence of C assignment
statements of the form
This requires some formatting work unnecessary for the fortran case.
for printing by converting x^(1/2) to sqrt(x), etc. Since C has no
ban complex numbers
%e^a -> exp(a)
a^-1/2 -> 1/sqrt(a)
(1/3)*b -> b/3.0 and (-1/3)*b -> -b/3.0
rat(a/b) -> a/b via ratdisrep
ban complex numbers
in general do nothing, recurse
This is used above 1/3*b*c -> b*c/3.0 | (in-package :maxima)
(macsyma-module cgrind)
This is heavily lifted from grind.lisp and fortra.lisp , and should have the
then loaded , as in ( for the case of cmucl ):
: lisp ( compile - file " cgrind.lisp " ) , copy cgrind.sse2f to ~/.maxima
( 2011 )
If NIL , no load message gets printed .
This function is called from toplevel . First the arguments is
(defmspec $cgrind (l)
(setq l (fexprcheck l))
(let ((value (strmeval l)))
(cond ((msetqp l) (setq value `((mequal) ,(cadr l) ,(meval l)))))
(cond ((and (symbolp l) ($matrixp value))
($cgrindmx l value))
((and (not (atom value)) (eq (caar value) 'mequal)
(symbolp (cadr value)) ($matrixp (caddr value)))
($cgrindmx (cadr value) (caddr value)))
(t (c-print value)))))
(defun c-print (x &optional (stream *standard-output*))
(setq x (scanforc x))
Protects the modifications to from creeping out .
(unwind-protect
(progn
(defprop mexpt msz-cmexpt grind)
(setq *fortran-print* t)
Restore usual property etc . before exiting this frame .
(defprop mexpt msz-mexpt grind)
(setq *fortran-print* nil))
'$done)
(defun msz-cmexpt (x l r)
(setq l (msize (cadr x) (revappend '(#\p #\o #\w #\() l) (list #\,) 'mparen 'mparen)
r (if (mmminusp (setq x (nformat (caddr x))))
(msize (cadr x) (list #\-) (cons #\) r) 'mexpt rop)
(msize x nil (cons #\) r ) 'mparen 'mparen)))
(list (+ (car l) (car r)) l r))
NAME[I][J ] = < corresponding matrix element >
(defmfun $cgrindmx (name mat &optional (stream *standard-output*) &aux ($loadprint nil))
(cond ((not (symbolp name))
(merror (intl:gettext "cgrindmx: first argument must be a symbol; found: ~M") name))
((not ($matrixp mat))
(merror (intl:gettext "cgrindmx: second argument must be a matrix; found: ~M") mat)))
(do ((mat (cdr mat) (cdr mat)) (i 1 (1+ i)))
((null mat))
(do ((m (cdar mat) (cdr m)) (j 1 (1+ j)))
((null m))
(format stream "~a[~a][~a] = " (string-left-trim "$" name) (1- i) (1- j) )
(c-print (car m) stream)))
'$done)
This C scanning function is similar to fortscan . Prepare an expression
support for complex numbers , contrary to Fortran , ban them .
(defun scanforc (e)
(merror (intl:gettext "Take real and imaginary parts")))
(t e)))
((and (eq (caar e) 'mexpt) (eq (cadr e) '$%e))
(list '(%exp simp) (scanforc (caddr e))))
a^1/2 - > sqrt(a ) 1//2 is defined as ( ( rat simp ) 1 2 )
((and (eq (caar e) 'mexpt) (alike1 (caddr e) 1//2))
(list '(%sqrt simp) (scanforc (cadr e))))
((and (eq (caar e) 'mexpt) (alike1 (caddr e) -1//2))
(list '(mquotient simp) 1 (list '(%sqrt simp) (scanforc (cadr e)))))
((and (eq (caar e) 'mtimes) (ratnump (cadr e))
(member (cadadr e) '(1 -1) :test #'equal))
(cond ((equal (cadadr e) 1) (scanforc-mtimes e))
(t (list '(mminus simp) (scanforc-mtimes e)))))
1/3 - > 1.0/3.0
((eq (caar e) 'rat)
(list '(mquotient simp) (float (cadr e)) (float (caddr e))))
((eq (caar e) 'mrat) (scanforc (ratdisrep e)))
((and (member (caar e) '(mtimes mplus) :test #'eq)
(let ((a (simplify ($bothcoef e '$%i))))
(and (numberp (cadr a))
(numberp (caddr a))
(not (zerop1 (cadr a)))
(merror (intl:gettext "Take real and imaginary parts"))))))
(t (cons (car e) (mapcar 'scanforc (cdr e))))))
(defun scanforc-mtimes (e)
(list '(mquotient simp)
(cond ((null (cdddr e)) (scanforc (caddr e)))
(t (cons (car e) (mapcar 'scanforc (cddr e)))))
(float (caddr (cadr e)))))
|
6d1dbf6fc4d7bbda22f39cc0b5ad32cc7c2c38bb9c45f3e68af8d09407772fff | timjb/halma | Types.hs | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
# LANGUAGE StandaloneDeriving #
module Game.Halma.TelegramBot.Model.Types
( Player (..)
, PartyResult (..)
, ExtendedPartyResult (..)
, GameResult (..)
, HalmaState (..)
, Party (..)
, Match (..)
, MatchState (..)
, ChatId
, PlayersSoFar (..)
, LocaleId (..)
, HalmaChat (..)
) where
import Game.Halma.Board
import Game.Halma.Configuration
import Game.Halma.Rules
import Game.TurnCounter
import Data.Aeson ((.=), (.:))
import Data.Int (Int64)
import Control.Applicative ((<|>))
import qualified Data.Aeson as A
import qualified Data.Text as T
import qualified Data.Vector as V
import qualified Web.Telegram.API.Bot as TG
data Player
= AIPlayer
| TelegramPlayer TG.User
deriving (Show)
instance Eq Player where
AIPlayer == AIPlayer = True
TelegramPlayer p1 == TelegramPlayer p2 =
TG.user_id p1 == TG.user_id p2
_ == _ = False
instance A.ToJSON Player where
toJSON = \case
AIPlayer -> "AIPlayer"
TelegramPlayer user -> A.toJSON user
instance A.FromJSON Player where
parseJSON = \case
A.String "AIPlayer" -> pure AIPlayer
other -> TelegramPlayer <$> A.parseJSON other
data PartyResult
= PartyResult
{ prParty :: Party
, prNumberOfTurns :: Int
} deriving (Eq, Show)
instance A.ToJSON PartyResult where
toJSON pr =
A.object
[ "party" .= prParty pr
, "number_of_turns" .= prNumberOfTurns pr
]
instance A.FromJSON PartyResult where
parseJSON =
A.withObject "PartyResult" $ \o -> do
prParty <- o .: "party"
prNumberOfTurns <- o .: "number_of_turns"
pure PartyResult {..}
data ExtendedPartyResult
= ExtendedPartyResult
{ eprPartyResult :: PartyResult
^ zero - based position
, eprPlaceShared :: Bool -- ^ has another player finished in the same round?
, eprLag :: Int -- ^ number of moves after winner
, eprNumberOfPlayers :: Int
} deriving (Eq, Show)
newtype GameResult
= GameResult
{ grNumberOfMoves :: [PartyResult]
} deriving (Eq, Show)
instance A.ToJSON GameResult where
toJSON gameResult =
A.object
[ "number_of_moves" .= grNumberOfMoves gameResult
]
instance A.FromJSON GameResult where
parseJSON =
A.withObject "GameResult" $ \o ->
GameResult <$> o .: "number_of_moves"
data Party
= Party
{ partyHomeCorner :: HalmaDirection
, partyPlayer :: Player
} deriving (Show, Eq)
instance A.ToJSON Party where
toJSON party =
A.object
[ "home_corner" .= partyHomeCorner party
, "player" .= partyPlayer party
]
instance A.FromJSON Party where
parseJSON =
A.withObject "Party" $ \o -> do
homeCorner <- o .: "home_corner"
player <- o .: "player"
pure Party { partyHomeCorner = homeCorner, partyPlayer = player }
data HalmaState
= HalmaState
{ hsBoard :: HalmaBoard
, hsTurnCounter :: TurnCounter Party
, hsLastMove :: Maybe Move
, hsFinished :: [PartyResult]
} deriving (Eq, Show)
instance A.ToJSON HalmaState where
toJSON game =
A.object
[ "board" .= hsBoard game
, "parties" .= tcPlayers (hsTurnCounter game)
, "total_moves" .= tcCounter (hsTurnCounter game)
, "last_move" .= hsLastMove game
, "finished" .= hsFinished game
]
instance A.FromJSON HalmaState where
parseJSON =
A.withObject "HalmaState" $ \o -> do
hsBoard <- o .: "board"
tcPlayers <- o .: "parties"
tcCounter <- o .: "total_moves"
hsLastMove <- o .: "last_move"
hsFinished <- o .: "finished"
let hsTurnCounter = TurnCounter {..}
pure HalmaState {..}
data Match
= Match
{ matchConfig :: Configuration Player
, matchRules :: RuleOptions
, matchHistory :: [GameResult]
, matchCurrentGame :: Maybe HalmaState
} deriving (Eq, Show)
instance A.ToJSON Match where
toJSON match =
A.object
[ "config" .= matchConfig match
, "rules" .= matchRules match
, "history" .= matchHistory match
, "current_game" .= matchCurrentGame match
]
instance A.FromJSON Match where
parseJSON =
A.withObject "Match size" $ \o -> do
config <- o .: "config"
rules <- o .: "rules"
history <- o .: "history"
currentGame <- o .: "current_game"
pure
Match
{ matchConfig = config
, matchRules = rules
, matchHistory = history
, matchCurrentGame = currentGame
}
data PlayersSoFar a
= NoPlayers
| OnePlayer a
| EnoughPlayers (Configuration a)
deriving (Eq, Show)
instance A.ToJSON a => A.ToJSON (PlayersSoFar a) where
toJSON =
\case
NoPlayers -> A.Array mempty
OnePlayer p -> A.toJSON [p]
EnoughPlayers config -> A.toJSON config
instance A.FromJSON a => A.FromJSON (PlayersSoFar a) where
parseJSON val =
parseEnoughPlayers val <|> parseTooFewPlayers val
where
parseEnoughPlayers v =
EnoughPlayers <$> A.parseJSON v
parseTooFewPlayers =
A.withArray "PlayersSoFar" $ \v ->
case V.length v of
0 -> pure NoPlayers
1 -> OnePlayer <$> A.parseJSON (V.head v)
_ -> fail "expected an array of length 1 or 2"
data MatchState
= NoMatch
| GatheringPlayers (PlayersSoFar Player)
| MatchRunning Match
deriving (Eq, Show)
instance A.ToJSON MatchState where
toJSON =
\case
NoMatch ->
A.object [ "state" .= ("no_match" :: T.Text) ]
GatheringPlayers playersSoFar ->
A.object
[ "state" .= ("gathering_players" :: T.Text)
, "players_so_far" .= playersSoFar
]
MatchRunning match ->
A.object
[ "state" .= ("match_running" :: T.Text)
, "match" .= match
]
instance A.FromJSON MatchState where
parseJSON =
A.withObject "MatchState" $ \o -> do
state <- o .: "state"
case state :: T.Text of
"no_match" ->
pure NoMatch
"gathering_players" ->
GatheringPlayers <$> (o .: "players_so_far")
"match_running" ->
MatchRunning <$> (o .: "match")
_other ->
fail $ "unexpected state: " ++ T.unpack state
data LocaleId
= En
| De
deriving (Show, Eq, Bounded, Enum)
showLocaleId :: LocaleId -> T.Text
showLocaleId localeId =
case localeId of
En -> "en"
De -> "de"
parseLocaleId :: T.Text -> Maybe LocaleId
parseLocaleId text =
case T.toLower text of
"de" -> Just De
"en" -> Just En
_ -> Nothing
instance A.ToJSON LocaleId where
toJSON = A.String . showLocaleId
instance A.FromJSON LocaleId where
parseJSON =
A.withText "LocaleId" $ \t ->
case parseLocaleId t of
Nothing -> fail "unrecognized locale id"
Just localeId -> pure localeId
type ChatId = Int64
data HalmaChat
= HalmaChat
{ hcId :: ChatId
, hcLastUpdateId :: Int
, hcLastUpdateDate :: Int -- ^ in Unix time
, hcLocale :: LocaleId
, hcMatchState :: MatchState
} deriving (Eq, Show)
instance A.ToJSON HalmaChat where
toJSON HalmaChat {..} =
A.object
[ "id" .= hcId
, "last_update_id" .= hcLastUpdateId
, "last_update_date" .= hcLastUpdateDate
, "locale" .= hcLocale
, "match_state" .= hcMatchState
]
instance A.FromJSON HalmaChat where
parseJSON =
A.withObject "HalmaChat" $ \o -> do
hcId <- o .: "id"
hcLastUpdateId <- o .: "last_update_id" <|> pure 0
hcLastUpdateDate <- o .: "last_update_date" <|> pure 0
hcLocale <- o .: "locale"
hcMatchState <- o .: "match_state"
pure HalmaChat {..}
| null | https://raw.githubusercontent.com/timjb/halma/0267d636dbed0de03d2d6527ca35458637a0021c/halma-telegram-bot/src/Game/Halma/TelegramBot/Model/Types.hs | haskell | # LANGUAGE OverloadedStrings #
^ has another player finished in the same round?
^ number of moves after winner
^ in Unix time | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# LANGUAGE StandaloneDeriving #
module Game.Halma.TelegramBot.Model.Types
( Player (..)
, PartyResult (..)
, ExtendedPartyResult (..)
, GameResult (..)
, HalmaState (..)
, Party (..)
, Match (..)
, MatchState (..)
, ChatId
, PlayersSoFar (..)
, LocaleId (..)
, HalmaChat (..)
) where
import Game.Halma.Board
import Game.Halma.Configuration
import Game.Halma.Rules
import Game.TurnCounter
import Data.Aeson ((.=), (.:))
import Data.Int (Int64)
import Control.Applicative ((<|>))
import qualified Data.Aeson as A
import qualified Data.Text as T
import qualified Data.Vector as V
import qualified Web.Telegram.API.Bot as TG
data Player
= AIPlayer
| TelegramPlayer TG.User
deriving (Show)
instance Eq Player where
AIPlayer == AIPlayer = True
TelegramPlayer p1 == TelegramPlayer p2 =
TG.user_id p1 == TG.user_id p2
_ == _ = False
instance A.ToJSON Player where
toJSON = \case
AIPlayer -> "AIPlayer"
TelegramPlayer user -> A.toJSON user
instance A.FromJSON Player where
parseJSON = \case
A.String "AIPlayer" -> pure AIPlayer
other -> TelegramPlayer <$> A.parseJSON other
data PartyResult
= PartyResult
{ prParty :: Party
, prNumberOfTurns :: Int
} deriving (Eq, Show)
instance A.ToJSON PartyResult where
toJSON pr =
A.object
[ "party" .= prParty pr
, "number_of_turns" .= prNumberOfTurns pr
]
instance A.FromJSON PartyResult where
parseJSON =
A.withObject "PartyResult" $ \o -> do
prParty <- o .: "party"
prNumberOfTurns <- o .: "number_of_turns"
pure PartyResult {..}
data ExtendedPartyResult
= ExtendedPartyResult
{ eprPartyResult :: PartyResult
^ zero - based position
, eprNumberOfPlayers :: Int
} deriving (Eq, Show)
newtype GameResult
= GameResult
{ grNumberOfMoves :: [PartyResult]
} deriving (Eq, Show)
instance A.ToJSON GameResult where
toJSON gameResult =
A.object
[ "number_of_moves" .= grNumberOfMoves gameResult
]
instance A.FromJSON GameResult where
parseJSON =
A.withObject "GameResult" $ \o ->
GameResult <$> o .: "number_of_moves"
data Party
= Party
{ partyHomeCorner :: HalmaDirection
, partyPlayer :: Player
} deriving (Show, Eq)
instance A.ToJSON Party where
toJSON party =
A.object
[ "home_corner" .= partyHomeCorner party
, "player" .= partyPlayer party
]
instance A.FromJSON Party where
parseJSON =
A.withObject "Party" $ \o -> do
homeCorner <- o .: "home_corner"
player <- o .: "player"
pure Party { partyHomeCorner = homeCorner, partyPlayer = player }
data HalmaState
= HalmaState
{ hsBoard :: HalmaBoard
, hsTurnCounter :: TurnCounter Party
, hsLastMove :: Maybe Move
, hsFinished :: [PartyResult]
} deriving (Eq, Show)
instance A.ToJSON HalmaState where
toJSON game =
A.object
[ "board" .= hsBoard game
, "parties" .= tcPlayers (hsTurnCounter game)
, "total_moves" .= tcCounter (hsTurnCounter game)
, "last_move" .= hsLastMove game
, "finished" .= hsFinished game
]
instance A.FromJSON HalmaState where
parseJSON =
A.withObject "HalmaState" $ \o -> do
hsBoard <- o .: "board"
tcPlayers <- o .: "parties"
tcCounter <- o .: "total_moves"
hsLastMove <- o .: "last_move"
hsFinished <- o .: "finished"
let hsTurnCounter = TurnCounter {..}
pure HalmaState {..}
data Match
= Match
{ matchConfig :: Configuration Player
, matchRules :: RuleOptions
, matchHistory :: [GameResult]
, matchCurrentGame :: Maybe HalmaState
} deriving (Eq, Show)
instance A.ToJSON Match where
toJSON match =
A.object
[ "config" .= matchConfig match
, "rules" .= matchRules match
, "history" .= matchHistory match
, "current_game" .= matchCurrentGame match
]
instance A.FromJSON Match where
parseJSON =
A.withObject "Match size" $ \o -> do
config <- o .: "config"
rules <- o .: "rules"
history <- o .: "history"
currentGame <- o .: "current_game"
pure
Match
{ matchConfig = config
, matchRules = rules
, matchHistory = history
, matchCurrentGame = currentGame
}
data PlayersSoFar a
= NoPlayers
| OnePlayer a
| EnoughPlayers (Configuration a)
deriving (Eq, Show)
instance A.ToJSON a => A.ToJSON (PlayersSoFar a) where
toJSON =
\case
NoPlayers -> A.Array mempty
OnePlayer p -> A.toJSON [p]
EnoughPlayers config -> A.toJSON config
instance A.FromJSON a => A.FromJSON (PlayersSoFar a) where
parseJSON val =
parseEnoughPlayers val <|> parseTooFewPlayers val
where
parseEnoughPlayers v =
EnoughPlayers <$> A.parseJSON v
parseTooFewPlayers =
A.withArray "PlayersSoFar" $ \v ->
case V.length v of
0 -> pure NoPlayers
1 -> OnePlayer <$> A.parseJSON (V.head v)
_ -> fail "expected an array of length 1 or 2"
data MatchState
= NoMatch
| GatheringPlayers (PlayersSoFar Player)
| MatchRunning Match
deriving (Eq, Show)
instance A.ToJSON MatchState where
toJSON =
\case
NoMatch ->
A.object [ "state" .= ("no_match" :: T.Text) ]
GatheringPlayers playersSoFar ->
A.object
[ "state" .= ("gathering_players" :: T.Text)
, "players_so_far" .= playersSoFar
]
MatchRunning match ->
A.object
[ "state" .= ("match_running" :: T.Text)
, "match" .= match
]
instance A.FromJSON MatchState where
parseJSON =
A.withObject "MatchState" $ \o -> do
state <- o .: "state"
case state :: T.Text of
"no_match" ->
pure NoMatch
"gathering_players" ->
GatheringPlayers <$> (o .: "players_so_far")
"match_running" ->
MatchRunning <$> (o .: "match")
_other ->
fail $ "unexpected state: " ++ T.unpack state
data LocaleId
= En
| De
deriving (Show, Eq, Bounded, Enum)
showLocaleId :: LocaleId -> T.Text
showLocaleId localeId =
case localeId of
En -> "en"
De -> "de"
parseLocaleId :: T.Text -> Maybe LocaleId
parseLocaleId text =
case T.toLower text of
"de" -> Just De
"en" -> Just En
_ -> Nothing
instance A.ToJSON LocaleId where
toJSON = A.String . showLocaleId
instance A.FromJSON LocaleId where
parseJSON =
A.withText "LocaleId" $ \t ->
case parseLocaleId t of
Nothing -> fail "unrecognized locale id"
Just localeId -> pure localeId
type ChatId = Int64
data HalmaChat
= HalmaChat
{ hcId :: ChatId
, hcLastUpdateId :: Int
, hcLocale :: LocaleId
, hcMatchState :: MatchState
} deriving (Eq, Show)
instance A.ToJSON HalmaChat where
toJSON HalmaChat {..} =
A.object
[ "id" .= hcId
, "last_update_id" .= hcLastUpdateId
, "last_update_date" .= hcLastUpdateDate
, "locale" .= hcLocale
, "match_state" .= hcMatchState
]
instance A.FromJSON HalmaChat where
parseJSON =
A.withObject "HalmaChat" $ \o -> do
hcId <- o .: "id"
hcLastUpdateId <- o .: "last_update_id" <|> pure 0
hcLastUpdateDate <- o .: "last_update_date" <|> pure 0
hcLocale <- o .: "locale"
hcMatchState <- o .: "match_state"
pure HalmaChat {..}
|
b7b37889d8c4b508afc91be75fc9e27286d622111f84b2c0535f4eefc667c088 | polytypic/rea-ml | SeqLazy.ml | open Rea
module Seq : sig
include module type of Stdlib.Seq
include module type of StdRea.Seq
end = struct
include Stdlib.Seq
include StdRea.Seq
end
let () =
let n_calls = ref 0 in
assert (
(let+ x = iota 1000000000000000 in
incr n_calls;
x + 1)
|> run Seq.monad_plus |> Seq.of_rea
|> Traverse.to_exists Seq.map_er (( = ) 3));
assert (3 = !n_calls)
let () =
let n_calls = ref 0 in
assert (
(let* x = iota 1000000000000000 in
incr n_calls;
pure (x + 1))
|> run Seq.monad_plus |> Seq.of_rea
|> Traverse.to_exists Seq.map_er (( = ) 3));
assert (3 = !n_calls)
| null | https://raw.githubusercontent.com/polytypic/rea-ml/9849c3cf602702bc0cf0a955866b7932eb62a4bf/src/test/Rea/SeqLazy.ml | ocaml | open Rea
module Seq : sig
include module type of Stdlib.Seq
include module type of StdRea.Seq
end = struct
include Stdlib.Seq
include StdRea.Seq
end
let () =
let n_calls = ref 0 in
assert (
(let+ x = iota 1000000000000000 in
incr n_calls;
x + 1)
|> run Seq.monad_plus |> Seq.of_rea
|> Traverse.to_exists Seq.map_er (( = ) 3));
assert (3 = !n_calls)
let () =
let n_calls = ref 0 in
assert (
(let* x = iota 1000000000000000 in
incr n_calls;
pure (x + 1))
|> run Seq.monad_plus |> Seq.of_rea
|> Traverse.to_exists Seq.map_er (( = ) 3));
assert (3 = !n_calls)
|
|
1e1e80f6740026adc45ece1116328766bd50c6f650ab0c71602e0885176b73df | biocaml/biocaml | histogram.mli | * Histograms with polymorphic bin types .
A histogram is a list of bins , each with a count . [ i ] is
defined by a lower limit [ lo(i ) ] and an upper limit [ hi(i ) ] . It is
inclusive of the lower limit and exclusive of the upper limit . For
all [ i ] , [ hi(i ) = lo(i+1 ) ] . By convention the first bin is
numbered 0 . The count of a bin is a floating point number ,
allowing fractional values if necessary .
A histogram is a list of bins, each with a count. Bin [i] is
defined by a lower limit [lo(i)] and an upper limit [hi(i)]. It is
inclusive of the lower limit and exclusive of the upper limit. For
all [i], [hi(i) = lo(i+1)]. By convention the first bin is
numbered 0. The count of a bin is a floating point number,
allowing fractional values if necessary.
*)
type 'a t
* The type of a histogram whose limits are of type [ ' a ] .
val make : ('a -> 'a -> int) -> 'a list -> 'a t option
* [ make cmp bins ] returns a new histogram from the given [ bins ] ,
all initialized to a count of 0.0 . The [ bins ] must be provided as a
list of the boundaries dividing them . The list [ \[v0 ; v1 ; ... ; vn\ ] ]
of length [ n+1 ] represents the [ n ] bins [ \[v0 , v1 ) ] , [ \[v1 , v2 ) ] ,
... , [ \[vn-1 , vn ) ] , where [ cmp ] is used as the comparison
function . Returns [ None ] if [ bins ] are not monotonically
increasing , or if length of [ bins ] is less than 2 .
all initialized to a count of 0.0. The [bins] must be provided as a
list of the boundaries dividing them. The list [\[v0; v1; ...; vn\]]
of length [n+1] represents the [n] bins [\[v0, v1)], [\[v1, v2)],
..., [\[vn-1, vn)], where [cmp] is used as the comparison
function. Returns [None] if [bins] are not monotonically
increasing, or if length of [bins] is less than 2. *)
val to_list : 'a t -> (('a * 'a) * float) list
* Return a list of all / count pairs . Answer will be in
ascending order by the limits .
ascending order by the bin limits. *)
val copy : 'a t -> 'a t
(** Copy histogram. *)
val bin : 'a t -> int -> ('a * 'a) option
(** [bin hist i] returns the [i]th bin of [hist]. *)
val bin_exn : 'a t -> int -> 'a * 'a
(** [bin hist i] returns the [i]th bin of [hist]. Raise
[Invalid_argument] if an invalid bin number is requested. *)
val count : 'a t -> int -> float option
(** [count hist i] returns the count the [i]th bin. *)
val count_exn : 'a t -> int -> float
(** [count hist i] returns the count the [i]th bin. Raise
[Invalid_argument] if an invalid bin number is requested. *)
val num_bins : 'a t -> int
(** Number of bins. *)
val minimum : 'a t -> 'a
(** Lower limit of the minimum bin. *)
val maximum : 'a t -> 'a
(** Upper limit of the maximum bin. *)
val increment : ?delt:float -> 'a t -> 'a -> 'a t
* [ increment delt hist x ] increments the count of the bin containing
[ x ] by [ delt ] ( default is 1.0 ) . The histogram is unaltered if [ x ] not
in any bin . This is not considered an error because it is often
necessary to calculate a histogram for a subset of a larger data
set .
[x] by [delt] (default is 1.0). The histogram is unaltered if [x] not
in any bin. This is not considered an error because it is often
necessary to calculate a histogram for a subset of a larger data
set. *)
val reset : 'a t -> 'a t
* Return histogram with same bins but all counts reset to 0.0 .
val find_bin_index : 'a t -> 'a -> int option
(** [find_bin_index hist x] returns the index of the bin in [hist]
containing [x]. Return None if [x] is outside the histogram's
range. *)
val in_range : 'a t -> 'a -> bool
(** [in_range hist x] is true if [x] greater than or equal to [minimum
hist] and strictly less than [maximum hist]. *)
* { 6 Histograms With Float Bins }
val make_uniform : float -> float -> int -> (float t, string) Result.t
* [ make_uniform min max n ] returns a histogram with [ n ] bins
uniformly dividing up the range from [ min ] to [ max ] . will be
inclusive of the lower limit and exclusive of the upper limit ,
i.e. value of [ min ] will fall into lowest bin and value of [ max ] will
fall outside the range of the histogram . Raise [ Failure ] if [ min ] not
strictly less than [ max ] or if [ n ] not greater than 0 .
uniformly dividing up the range from [min] to [max]. Bins will be
inclusive of the lower limit and exclusive of the upper limit,
i.e. value of [min] will fall into lowest bin and value of [max] will
fall outside the range of the histogram. Raise [Failure] if [min] not
strictly less than [max] or if [n] not greater than 0. *)
| null | https://raw.githubusercontent.com/biocaml/biocaml/ac619539fed348747d686b8f628e80c1bb8bfc59/lib/unix/histogram.mli | ocaml | * Copy histogram.
* [bin hist i] returns the [i]th bin of [hist].
* [bin hist i] returns the [i]th bin of [hist]. Raise
[Invalid_argument] if an invalid bin number is requested.
* [count hist i] returns the count the [i]th bin.
* [count hist i] returns the count the [i]th bin. Raise
[Invalid_argument] if an invalid bin number is requested.
* Number of bins.
* Lower limit of the minimum bin.
* Upper limit of the maximum bin.
* [find_bin_index hist x] returns the index of the bin in [hist]
containing [x]. Return None if [x] is outside the histogram's
range.
* [in_range hist x] is true if [x] greater than or equal to [minimum
hist] and strictly less than [maximum hist]. | * Histograms with polymorphic bin types .
A histogram is a list of bins , each with a count . [ i ] is
defined by a lower limit [ lo(i ) ] and an upper limit [ hi(i ) ] . It is
inclusive of the lower limit and exclusive of the upper limit . For
all [ i ] , [ hi(i ) = lo(i+1 ) ] . By convention the first bin is
numbered 0 . The count of a bin is a floating point number ,
allowing fractional values if necessary .
A histogram is a list of bins, each with a count. Bin [i] is
defined by a lower limit [lo(i)] and an upper limit [hi(i)]. It is
inclusive of the lower limit and exclusive of the upper limit. For
all [i], [hi(i) = lo(i+1)]. By convention the first bin is
numbered 0. The count of a bin is a floating point number,
allowing fractional values if necessary.
*)
type 'a t
* The type of a histogram whose limits are of type [ ' a ] .
val make : ('a -> 'a -> int) -> 'a list -> 'a t option
* [ make cmp bins ] returns a new histogram from the given [ bins ] ,
all initialized to a count of 0.0 . The [ bins ] must be provided as a
list of the boundaries dividing them . The list [ \[v0 ; v1 ; ... ; vn\ ] ]
of length [ n+1 ] represents the [ n ] bins [ \[v0 , v1 ) ] , [ \[v1 , v2 ) ] ,
... , [ \[vn-1 , vn ) ] , where [ cmp ] is used as the comparison
function . Returns [ None ] if [ bins ] are not monotonically
increasing , or if length of [ bins ] is less than 2 .
all initialized to a count of 0.0. The [bins] must be provided as a
list of the boundaries dividing them. The list [\[v0; v1; ...; vn\]]
of length [n+1] represents the [n] bins [\[v0, v1)], [\[v1, v2)],
..., [\[vn-1, vn)], where [cmp] is used as the comparison
function. Returns [None] if [bins] are not monotonically
increasing, or if length of [bins] is less than 2. *)
val to_list : 'a t -> (('a * 'a) * float) list
* Return a list of all / count pairs . Answer will be in
ascending order by the limits .
ascending order by the bin limits. *)
val copy : 'a t -> 'a t
val bin : 'a t -> int -> ('a * 'a) option
val bin_exn : 'a t -> int -> 'a * 'a
val count : 'a t -> int -> float option
val count_exn : 'a t -> int -> float
val num_bins : 'a t -> int
val minimum : 'a t -> 'a
val maximum : 'a t -> 'a
val increment : ?delt:float -> 'a t -> 'a -> 'a t
* [ increment delt hist x ] increments the count of the bin containing
[ x ] by [ delt ] ( default is 1.0 ) . The histogram is unaltered if [ x ] not
in any bin . This is not considered an error because it is often
necessary to calculate a histogram for a subset of a larger data
set .
[x] by [delt] (default is 1.0). The histogram is unaltered if [x] not
in any bin. This is not considered an error because it is often
necessary to calculate a histogram for a subset of a larger data
set. *)
val reset : 'a t -> 'a t
* Return histogram with same bins but all counts reset to 0.0 .
val find_bin_index : 'a t -> 'a -> int option
val in_range : 'a t -> 'a -> bool
* { 6 Histograms With Float Bins }
val make_uniform : float -> float -> int -> (float t, string) Result.t
* [ make_uniform min max n ] returns a histogram with [ n ] bins
uniformly dividing up the range from [ min ] to [ max ] . will be
inclusive of the lower limit and exclusive of the upper limit ,
i.e. value of [ min ] will fall into lowest bin and value of [ max ] will
fall outside the range of the histogram . Raise [ Failure ] if [ min ] not
strictly less than [ max ] or if [ n ] not greater than 0 .
uniformly dividing up the range from [min] to [max]. Bins will be
inclusive of the lower limit and exclusive of the upper limit,
i.e. value of [min] will fall into lowest bin and value of [max] will
fall outside the range of the histogram. Raise [Failure] if [min] not
strictly less than [max] or if [n] not greater than 0. *)
|
12b8387a31564ab6268037be952df19f60c575350245a612c933c3984013f754 | TrustInSoft/tis-interpreter | hptmap.mli | (**************************************************************************)
(* *)
This file was originally part of Menhir
(* *)
and , INRIA Rocquencourt
(* *)
Copyright 2005 Institut National de Recherche en Informatique et
(* en Automatique. All rights reserved. This file is distributed *)
under the terms of the Q Public License version 1.0 , with the
(* change described in the file licenses/Q_MODIFIED_LICENSE. *)
(* *)
File modified by CEA ( Commissariat Γ l'Γ©nergie atomique et aux
(* Γ©nergies alternatives). *)
(* *)
(**************************************************************************)
* Efficient maps from hash - consed trees to values , implemented as
trees .
Patricia trees. *)
* This implementation of big - endian trees follows 's paper at the 1998 ML Workshop in Baltimore . Maps are
implemented on top of trees . A tree is big - endian if it
expects the key 's most significant bits to be tested first .
Okasaki's paper at the 1998 ML Workshop in Baltimore. Maps are
implemented on top of Patricia trees. A tree is big-endian if it
expects the key's most significant bits to be tested first. *)
(**/**) (* Undocumented. Needed for advanced users only *)
type prefix
val sentinel_prefix : prefix
(**/**)
type tag
(** Type of the keys of the map. *)
module type Id_Datatype = sig
include Datatype.S
val id: t -> int (** Identity of a key. Must verify [id k >= 0] and
[equal k1 k2 ==> id k1 = id k2] *)
end
(** Values stored in the map *)
module type V = sig
include Datatype.S
val pretty_debug: t Pretty_utils.formatter
end
(** This functor exports the {i shape} of the maps indexed by keys [Key].
Those shapes can be used by various functions to efficiently build
new maps whose shape are already known. *)
module Shape (Key : Id_Datatype): sig
type 'value t
end
module Make
(Key : Id_Datatype)
(V : V)
(Compositional_bool : sig
(** A boolean information is maintained for each tree, by composing the
boolean on the subtrees and the value information present on each leaf.
See {!Comp_unused} for a default implementation. *)
val e: bool (** Value for the empty tree *)
val f : Key.t -> V.t -> bool (** Value for a leaf *)
val compose : bool -> bool -> bool
* Composition of the values of two subtrees
val default:bool
end)
(Initial_Values : sig
val v : (Key.t*V.t) list list
* List of the maps that must be shared between all instances of Frama - C
( the maps being described by the list of their elements ) .
Must include all maps that are exported at Caml link - time when the
functor is applied . This usually includes at least the empty map , hence
[ v ] nearly always contains [ [ ] ] .
(the maps being described by the list of their elements).
Must include all maps that are exported at Caml link-time when the
functor is applied. This usually includes at least the empty map, hence
[v] nearly always contains [[]]. *)
end)
(Datatype_deps: sig
val l : State.t list
* Dependencies of the hash - consing table . The table will be cleared
whenever one of those dependencies is cleared .
whenever one of those dependencies is cleared. *)
end)
: Hptmap_sig.S with type key = Key.t
and type v = V.t
and type 'a shape = 'a Shape(Key).t
and type prefix = prefix
(** Default implementation for the [Compositional_bool] argument of the functor
{!Make}. To be used when no interesting compositional bit can be computed. *)
module Comp_unused : sig
val e : bool
val f : 'a -> 'b -> bool
val compose : bool -> bool -> bool
val default : bool
end
(*
Local Variables:
compile-command: "make -C .."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/libraries/utils/hptmap.mli | ocaml | ************************************************************************
en Automatique. All rights reserved. This file is distributed
change described in the file licenses/Q_MODIFIED_LICENSE.
Γ©nergies alternatives).
************************************************************************
*/*
Undocumented. Needed for advanced users only
*/*
* Type of the keys of the map.
* Identity of a key. Must verify [id k >= 0] and
[equal k1 k2 ==> id k1 = id k2]
* Values stored in the map
* This functor exports the {i shape} of the maps indexed by keys [Key].
Those shapes can be used by various functions to efficiently build
new maps whose shape are already known.
* A boolean information is maintained for each tree, by composing the
boolean on the subtrees and the value information present on each leaf.
See {!Comp_unused} for a default implementation.
* Value for the empty tree
* Value for a leaf
* Default implementation for the [Compositional_bool] argument of the functor
{!Make}. To be used when no interesting compositional bit can be computed.
Local Variables:
compile-command: "make -C .."
End:
| This file was originally part of Menhir
and , INRIA Rocquencourt
Copyright 2005 Institut National de Recherche en Informatique et
under the terms of the Q Public License version 1.0 , with the
File modified by CEA ( Commissariat Γ l'Γ©nergie atomique et aux
* Efficient maps from hash - consed trees to values , implemented as
trees .
Patricia trees. *)
* This implementation of big - endian trees follows 's paper at the 1998 ML Workshop in Baltimore . Maps are
implemented on top of trees . A tree is big - endian if it
expects the key 's most significant bits to be tested first .
Okasaki's paper at the 1998 ML Workshop in Baltimore. Maps are
implemented on top of Patricia trees. A tree is big-endian if it
expects the key's most significant bits to be tested first. *)
type prefix
val sentinel_prefix : prefix
type tag
module type Id_Datatype = sig
include Datatype.S
end
module type V = sig
include Datatype.S
val pretty_debug: t Pretty_utils.formatter
end
module Shape (Key : Id_Datatype): sig
type 'value t
end
module Make
(Key : Id_Datatype)
(V : V)
(Compositional_bool : sig
val compose : bool -> bool -> bool
* Composition of the values of two subtrees
val default:bool
end)
(Initial_Values : sig
val v : (Key.t*V.t) list list
* List of the maps that must be shared between all instances of Frama - C
( the maps being described by the list of their elements ) .
Must include all maps that are exported at Caml link - time when the
functor is applied . This usually includes at least the empty map , hence
[ v ] nearly always contains [ [ ] ] .
(the maps being described by the list of their elements).
Must include all maps that are exported at Caml link-time when the
functor is applied. This usually includes at least the empty map, hence
[v] nearly always contains [[]]. *)
end)
(Datatype_deps: sig
val l : State.t list
* Dependencies of the hash - consing table . The table will be cleared
whenever one of those dependencies is cleared .
whenever one of those dependencies is cleared. *)
end)
: Hptmap_sig.S with type key = Key.t
and type v = V.t
and type 'a shape = 'a Shape(Key).t
and type prefix = prefix
module Comp_unused : sig
val e : bool
val f : 'a -> 'b -> bool
val compose : bool -> bool -> bool
val default : bool
end
|
1e3de9c6b248219e69dfd42255bee32532566e6f04062499d3b96bb298386c5c | travelping/ergw | ergw_charging.erl | Copyright 2018 , Travelping GmbH < >
%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version
2 of the License , or ( at your option ) any later version .
-module(ergw_charging).
-export([validate_profile/2, validate_rule/2, validate_rulebase/2,
add_profile/2, add_rule/2, add_rulebase/2,
reporting_triggers/0,
is_charging_event/2,
is_enabled/1,
rulebase/0]).
-include("ergw_core_config.hrl").
%%%===================================================================
%%% Options Validation
%%%===================================================================
-define(DefaultProfile, [{online, []}, {offline, []}]).
-define(DefaultRulebase, []).
-define(DefaultRuleDef, []).
-define(DefaultOnlineChargingOpts, []).
-define(DefaultOfflineChargingOpts, [{enable, true}, {triggers, []}]).
-define(DefaultOfflineChargingTriggers,
[{'cgi-sai-change', 'container'},
{'ecgi-change', 'container'},
{'max-cond-change', 'cdr'},
{'ms-time-zone-change', 'cdr'},
{'qos-change', 'container'},
{'rai-change', 'container'},
{'rat-change', 'cdr'},
{'sgsn-sgw-change', 'cdr'},
{'sgsn-sgw-plmn-id-change', 'cdr'},
{'tai-change', 'container'},
{'tariff-switch-change', 'container'},
{'user-location-info-change', 'container'}]).
validate_profile(_Name, Opts)
when ?is_opts(Opts) ->
ergw_core_config:validate_options(fun validate_charging_options/2, Opts, ?DefaultProfile);
validate_profile(Name, Opts) ->
erlang:error(badarg, [Name, Opts]).
%% validate_rule_def('Service-Identifier', [Value] = V)
%% when is_integer(Value) ->
%% V;
validate_rule_def('Rating-Group', [Value] = V)
when is_integer(Value), Value >= 0 ->
V;
validate_rule_def('Online-Rating-Group', [Value] = V)
when is_integer(Value), Value >= 0 ->
V;
validate_rule_def('Offline-Rating-Group', [Value] = V)
when is_integer(Value), Value >= 0 ->
V;
validate_rule_def('Flow-Information', Value)
when length(Value) /= 0 ->
Value;
validate_rule_def('Default - Bearer - Indication ' , [ Value ] = V ) - >
%% V;
validate_rule_def('TDF-Application-Identifier', [Value] = V)
when is_binary(Value) ->
V;
%% validate_rule_def('Flow-Status', [Value] = V) ->
%% V;
validate_rule_def('QoS - Information ' , [ Value ] = V ) - >
%% V;
%% validate_rule_def('PS-to-CS-Session-Continuity', [Value] = V) ->
%% V;
%% validate_rule_def('Reporting-Level', [Value] = V) ->
%% V;
validate_rule_def('Online', [Value] = V)
when Value =:= 0; Value =:= 1 ->
V;
validate_rule_def('Offline', [Value] = V)
when Value =:= 0; Value =:= 1 ->
V;
validate_rule_def('Max - PLR - DL ' , [ Value ] = V ) - >
%% V;
validate_rule_def('Max - PLR - UL ' , [ Value ] = V ) - >
%% V;
validate_rule_def('Metering-Method', [Value] = V)
when Value =:= 0; Value =:= 1; Value =:= 2; Value =:= 3 ->
V;
validate_rule_def('Precedence', [Value] = V)
when is_integer(Value), Value >= 0 ->
V;
%% validate_rule_def('AF-Charging-Identifier', [Value] = V) ->
%% V;
%% validate_rule_def('Flows', [Value] = V) ->
%% V;
%% validate_rule_def('Monitoring-Key', [Value] = V) ->
%% V;
validate_rule_def('Redirect-Information', Value = V)
when is_list(Value), length(Value) /= 0, length(Value) =< 2 ->
V;
validate_rule_def('Mute - Notification ' , [ Value ] = V ) - >
%% V;
%% validate_rule_def('AF-Signalling-Protocol', [Value] = V) ->
%% V;
%% validate_rule_def('Sponsor-Identity', [Value] = V) ->
%% V;
%% validate_rule_def('Application-Service-Provider-Identity', [Value] = V) ->
%% V;
%% validate_rule_def('Required-Access-Info', [Value] = V) ->
%% V;
%% validate_rule_def('Sharing-Key-DL', [Value] = V) ->
%% V;
%% validate_rule_def('Sharing-Key-UL', [Value] = V) ->
%% V;
%% validate_rule_def('Traffic-Steering-Policy-Identifier-DL', [Value] = V) ->
%% V;
%% validate_rule_def('Traffic-Steering-Policy-Identifier-UL', [Value] = V) ->
%% V;
%% validate_rule_def('Content-Version', [Value] = V) ->
%% V;
validate_rule_def(AVP, Value) ->
only known AVP are supported for now
erlang:error(badarg, [AVP, Value]).
validate_rule(Key, Opts)
when is_binary(Key), ?is_non_empty_opts(Opts) ->
3GPP TS 29.212 Charging - Rule - Definition AVP in Erlang terms
ergw_core_config:validate_options(fun validate_rule_def/2, Opts, []);
validate_rule(Key, Opts) ->
erlang:error(badarg, [Key, Opts]).
validate_rulebase(Key, RuleBaseDef)
when is_binary(Key), is_list(RuleBaseDef) ->
S = lists:usort([X || X <- RuleBaseDef, is_binary(X)]),
if length(S) /= length(RuleBaseDef) ->
erlang:error(badarg, [Key, RuleBaseDef]);
true ->
ok
end,
RuleBaseDef;
validate_rulebase(Key, RuleBase) ->
erlang:error(badarg, [Key, RuleBase]).
validate_online_charging_options(Key, Opts) ->
erlang:error(badarg, [{online, charging}, {Key, Opts}]).
validate_offline_charging_triggers(Key, Opt)
when (Opt == 'cdr' orelse Opt == 'off') andalso
(Key == 'max-cond-change' orelse
Key == 'ms-time-zone-change' orelse
Key == 'rat-change' orelse
Key == 'sgsn-sgw-change' orelse
Key == 'sgsn-sgw-plmn-id-change') ->
Opt;
validate_offline_charging_triggers(Key, Opt)
when (Opt == 'container' orelse Opt == 'off') andalso
(Key == 'cgi-sai-change' orelse
Key == 'ecgi-change' orelse
Key == 'qos-change' orelse
Key == 'rai-change' orelse
Key == 'rat-change' orelse
Key == 'sgsn-sgw-change' orelse
Key == 'sgsn-sgw-plmn-id-change' orelse
Key == 'tai-change' orelse
Key == 'tariff-switch-change' orelse
Key == 'user-location-info-change') ->
Opt;
validate_offline_charging_triggers(Key, Opts) ->
erlang:error(badarg, [{offline, charging, triggers}, {Key, Opts}]).
validate_offline_charging_options(enable, Opt) when is_boolean(Opt) ->
Opt;
validate_offline_charging_options(triggers, Opts) ->
ergw_core_config:validate_options(fun validate_offline_charging_triggers/2,
Opts, ?DefaultOfflineChargingTriggers);
validate_offline_charging_options(Key, Opts) ->
erlang:error(badarg, [{offline, charging}, {Key, Opts}]).
validate_charging_options(online, Opts) ->
ergw_core_config:validate_options(fun validate_online_charging_options/2,
Opts, ?DefaultOnlineChargingOpts);
validate_charging_options(offline, Opts) ->
ergw_core_config:validate_options(fun validate_offline_charging_options/2,
Opts, ?DefaultOfflineChargingOpts);
validate_charging_options(Key, Opts) ->
erlang:error(badarg, [charging, {Key, Opts}]).
%%%===================================================================
%%% API
%%%===================================================================
add_profile(Name, Opts0) ->
Opts = validate_profile(Name, Opts0),
{ok, Profiles} = ergw_core_config:get([charging_profile], #{}),
ergw_core_config:put(charging_profile, maps:put(Name, Opts, Profiles)).
add_rule(Name, Opts0) ->
Opts = validate_rule(Name, Opts0),
{ok, Rules} = ergw_core_config:get([charging_rule], #{}),
ergw_core_config:put(charging_rule, maps:put(Name, Opts, Rules)).
add_rulebase(Name, Opts0) ->
Opts = validate_rulebase(Name, Opts0),
{ok, RBs} = ergw_core_config:get([charging_rulebase], #{}),
ergw_core_config:put(charging_rulebase, maps:put(Name, Opts, RBs)).
TODO : use APN , VPLMN , HPLMN and Charging Characteristics
%% to select config
get_profile() ->
case ergw_core_config:get([charging_profile, default], []) of
{ok, Opts0} when is_map(Opts0) ->
Opts0;
undefined ->
Opts = validate_profile(default, []),
ergw_core_config:put(charging_profile, #{default => Opts}),
Opts
end.
reporting_triggers() ->
Triggers =
maps:get(triggers,
maps:get(offline, get_profile(), #{}), #{}),
maps:map(
fun(_Key, Cond) -> Cond /= 'off' end, Triggers).
is_charging_event(offline, Evs) ->
Filter =
maps:get(triggers,
maps:get(offline, get_profile(), #{}), #{}),
is_offline_charging_event(Evs, Filter);
is_charging_event(online, _) ->
true.
is_enabled(Type = offline) ->
maps:get(enable, maps:get(Type, get_profile(), #{}), true).
rulebase() ->
{ok, Rules} = ergw_core_config:get([charging_rule], #{}),
{ok, RuleBase} = ergw_core_config:get([charging_rulebase], #{}),
#{rules => Rules, rulebase => RuleBase}.
%%%===================================================================
%%% Helper functions
%%%===================================================================
use the numeric ordering from 3GPP TS 32.299 ,
%% sect. 7.2.37 Change-Condition AVP
ev_highest_prio(Evs) ->
PrioM =
#{
'qos-change' => 2,
'sgsn-sgw-change' => 5,
'sgsn-sgw-plmn-id-change' => 6,
'user-location-info-change' => 7,
'rat-change' => 8,
'ms-time-zone-change' => 9,
'tariff-switch-change' => 10,
'max-cond-change' => 13,
'cgi-sai-change' => 14,
'rai-change' => 15,
'ecgi-change' => 16,
'tai-change' => 17
},
{_, H} = lists:min([{maps:get(Ev, PrioM, 255), Ev} || Ev <- Evs]),
H.
assign_ev(Key, Ev, M) ->
maps:update_with(Key, fun(L) -> [Ev|L] end, [Ev], M).
is_offline_charging_event(Evs, Filter)
when is_map(Filter) ->
Em = lists:foldl(
fun(Ev, M) -> assign_ev(maps:get(Ev, Filter, off), Ev, M) end,
#{}, Evs),
case Em of
#{cdr := CdrEvs} when CdrEvs /= [] ->
{cdr_closure, ev_highest_prio(CdrEvs)};
#{container := CCEvs} when CCEvs /= [] ->
{container_closure, ev_highest_prio(CCEvs)};
_ ->
false
end.
| null | https://raw.githubusercontent.com/travelping/ergw/1b6cc3ee89eea4cf9df1d7de612744f0a850dfd9/apps/ergw_core/src/ergw_charging.erl | erlang | This program is free software; you can redistribute it and/or
===================================================================
Options Validation
===================================================================
validate_rule_def('Service-Identifier', [Value] = V)
when is_integer(Value) ->
V;
V;
validate_rule_def('Flow-Status', [Value] = V) ->
V;
V;
validate_rule_def('PS-to-CS-Session-Continuity', [Value] = V) ->
V;
validate_rule_def('Reporting-Level', [Value] = V) ->
V;
V;
V;
validate_rule_def('AF-Charging-Identifier', [Value] = V) ->
V;
validate_rule_def('Flows', [Value] = V) ->
V;
validate_rule_def('Monitoring-Key', [Value] = V) ->
V;
V;
validate_rule_def('AF-Signalling-Protocol', [Value] = V) ->
V;
validate_rule_def('Sponsor-Identity', [Value] = V) ->
V;
validate_rule_def('Application-Service-Provider-Identity', [Value] = V) ->
V;
validate_rule_def('Required-Access-Info', [Value] = V) ->
V;
validate_rule_def('Sharing-Key-DL', [Value] = V) ->
V;
validate_rule_def('Sharing-Key-UL', [Value] = V) ->
V;
validate_rule_def('Traffic-Steering-Policy-Identifier-DL', [Value] = V) ->
V;
validate_rule_def('Traffic-Steering-Policy-Identifier-UL', [Value] = V) ->
V;
validate_rule_def('Content-Version', [Value] = V) ->
V;
===================================================================
API
===================================================================
to select config
===================================================================
Helper functions
===================================================================
sect. 7.2.37 Change-Condition AVP | Copyright 2018 , Travelping GmbH < >
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version
2 of the License , or ( at your option ) any later version .
-module(ergw_charging).
-export([validate_profile/2, validate_rule/2, validate_rulebase/2,
add_profile/2, add_rule/2, add_rulebase/2,
reporting_triggers/0,
is_charging_event/2,
is_enabled/1,
rulebase/0]).
-include("ergw_core_config.hrl").
-define(DefaultProfile, [{online, []}, {offline, []}]).
-define(DefaultRulebase, []).
-define(DefaultRuleDef, []).
-define(DefaultOnlineChargingOpts, []).
-define(DefaultOfflineChargingOpts, [{enable, true}, {triggers, []}]).
-define(DefaultOfflineChargingTriggers,
[{'cgi-sai-change', 'container'},
{'ecgi-change', 'container'},
{'max-cond-change', 'cdr'},
{'ms-time-zone-change', 'cdr'},
{'qos-change', 'container'},
{'rai-change', 'container'},
{'rat-change', 'cdr'},
{'sgsn-sgw-change', 'cdr'},
{'sgsn-sgw-plmn-id-change', 'cdr'},
{'tai-change', 'container'},
{'tariff-switch-change', 'container'},
{'user-location-info-change', 'container'}]).
validate_profile(_Name, Opts)
when ?is_opts(Opts) ->
ergw_core_config:validate_options(fun validate_charging_options/2, Opts, ?DefaultProfile);
validate_profile(Name, Opts) ->
erlang:error(badarg, [Name, Opts]).
validate_rule_def('Rating-Group', [Value] = V)
when is_integer(Value), Value >= 0 ->
V;
validate_rule_def('Online-Rating-Group', [Value] = V)
when is_integer(Value), Value >= 0 ->
V;
validate_rule_def('Offline-Rating-Group', [Value] = V)
when is_integer(Value), Value >= 0 ->
V;
validate_rule_def('Flow-Information', Value)
when length(Value) /= 0 ->
Value;
validate_rule_def('Default - Bearer - Indication ' , [ Value ] = V ) - >
validate_rule_def('TDF-Application-Identifier', [Value] = V)
when is_binary(Value) ->
V;
validate_rule_def('QoS - Information ' , [ Value ] = V ) - >
validate_rule_def('Online', [Value] = V)
when Value =:= 0; Value =:= 1 ->
V;
validate_rule_def('Offline', [Value] = V)
when Value =:= 0; Value =:= 1 ->
V;
validate_rule_def('Max - PLR - DL ' , [ Value ] = V ) - >
validate_rule_def('Max - PLR - UL ' , [ Value ] = V ) - >
validate_rule_def('Metering-Method', [Value] = V)
when Value =:= 0; Value =:= 1; Value =:= 2; Value =:= 3 ->
V;
validate_rule_def('Precedence', [Value] = V)
when is_integer(Value), Value >= 0 ->
V;
validate_rule_def('Redirect-Information', Value = V)
when is_list(Value), length(Value) /= 0, length(Value) =< 2 ->
V;
validate_rule_def('Mute - Notification ' , [ Value ] = V ) - >
validate_rule_def(AVP, Value) ->
only known AVP are supported for now
erlang:error(badarg, [AVP, Value]).
validate_rule(Key, Opts)
when is_binary(Key), ?is_non_empty_opts(Opts) ->
3GPP TS 29.212 Charging - Rule - Definition AVP in Erlang terms
ergw_core_config:validate_options(fun validate_rule_def/2, Opts, []);
validate_rule(Key, Opts) ->
erlang:error(badarg, [Key, Opts]).
validate_rulebase(Key, RuleBaseDef)
when is_binary(Key), is_list(RuleBaseDef) ->
S = lists:usort([X || X <- RuleBaseDef, is_binary(X)]),
if length(S) /= length(RuleBaseDef) ->
erlang:error(badarg, [Key, RuleBaseDef]);
true ->
ok
end,
RuleBaseDef;
validate_rulebase(Key, RuleBase) ->
erlang:error(badarg, [Key, RuleBase]).
validate_online_charging_options(Key, Opts) ->
erlang:error(badarg, [{online, charging}, {Key, Opts}]).
validate_offline_charging_triggers(Key, Opt)
when (Opt == 'cdr' orelse Opt == 'off') andalso
(Key == 'max-cond-change' orelse
Key == 'ms-time-zone-change' orelse
Key == 'rat-change' orelse
Key == 'sgsn-sgw-change' orelse
Key == 'sgsn-sgw-plmn-id-change') ->
Opt;
validate_offline_charging_triggers(Key, Opt)
when (Opt == 'container' orelse Opt == 'off') andalso
(Key == 'cgi-sai-change' orelse
Key == 'ecgi-change' orelse
Key == 'qos-change' orelse
Key == 'rai-change' orelse
Key == 'rat-change' orelse
Key == 'sgsn-sgw-change' orelse
Key == 'sgsn-sgw-plmn-id-change' orelse
Key == 'tai-change' orelse
Key == 'tariff-switch-change' orelse
Key == 'user-location-info-change') ->
Opt;
validate_offline_charging_triggers(Key, Opts) ->
erlang:error(badarg, [{offline, charging, triggers}, {Key, Opts}]).
validate_offline_charging_options(enable, Opt) when is_boolean(Opt) ->
Opt;
validate_offline_charging_options(triggers, Opts) ->
ergw_core_config:validate_options(fun validate_offline_charging_triggers/2,
Opts, ?DefaultOfflineChargingTriggers);
validate_offline_charging_options(Key, Opts) ->
erlang:error(badarg, [{offline, charging}, {Key, Opts}]).
validate_charging_options(online, Opts) ->
ergw_core_config:validate_options(fun validate_online_charging_options/2,
Opts, ?DefaultOnlineChargingOpts);
validate_charging_options(offline, Opts) ->
ergw_core_config:validate_options(fun validate_offline_charging_options/2,
Opts, ?DefaultOfflineChargingOpts);
validate_charging_options(Key, Opts) ->
erlang:error(badarg, [charging, {Key, Opts}]).
add_profile(Name, Opts0) ->
Opts = validate_profile(Name, Opts0),
{ok, Profiles} = ergw_core_config:get([charging_profile], #{}),
ergw_core_config:put(charging_profile, maps:put(Name, Opts, Profiles)).
add_rule(Name, Opts0) ->
Opts = validate_rule(Name, Opts0),
{ok, Rules} = ergw_core_config:get([charging_rule], #{}),
ergw_core_config:put(charging_rule, maps:put(Name, Opts, Rules)).
add_rulebase(Name, Opts0) ->
Opts = validate_rulebase(Name, Opts0),
{ok, RBs} = ergw_core_config:get([charging_rulebase], #{}),
ergw_core_config:put(charging_rulebase, maps:put(Name, Opts, RBs)).
TODO : use APN , VPLMN , HPLMN and Charging Characteristics
get_profile() ->
case ergw_core_config:get([charging_profile, default], []) of
{ok, Opts0} when is_map(Opts0) ->
Opts0;
undefined ->
Opts = validate_profile(default, []),
ergw_core_config:put(charging_profile, #{default => Opts}),
Opts
end.
reporting_triggers() ->
Triggers =
maps:get(triggers,
maps:get(offline, get_profile(), #{}), #{}),
maps:map(
fun(_Key, Cond) -> Cond /= 'off' end, Triggers).
is_charging_event(offline, Evs) ->
Filter =
maps:get(triggers,
maps:get(offline, get_profile(), #{}), #{}),
is_offline_charging_event(Evs, Filter);
is_charging_event(online, _) ->
true.
is_enabled(Type = offline) ->
maps:get(enable, maps:get(Type, get_profile(), #{}), true).
rulebase() ->
{ok, Rules} = ergw_core_config:get([charging_rule], #{}),
{ok, RuleBase} = ergw_core_config:get([charging_rulebase], #{}),
#{rules => Rules, rulebase => RuleBase}.
use the numeric ordering from 3GPP TS 32.299 ,
ev_highest_prio(Evs) ->
PrioM =
#{
'qos-change' => 2,
'sgsn-sgw-change' => 5,
'sgsn-sgw-plmn-id-change' => 6,
'user-location-info-change' => 7,
'rat-change' => 8,
'ms-time-zone-change' => 9,
'tariff-switch-change' => 10,
'max-cond-change' => 13,
'cgi-sai-change' => 14,
'rai-change' => 15,
'ecgi-change' => 16,
'tai-change' => 17
},
{_, H} = lists:min([{maps:get(Ev, PrioM, 255), Ev} || Ev <- Evs]),
H.
assign_ev(Key, Ev, M) ->
maps:update_with(Key, fun(L) -> [Ev|L] end, [Ev], M).
is_offline_charging_event(Evs, Filter)
when is_map(Filter) ->
Em = lists:foldl(
fun(Ev, M) -> assign_ev(maps:get(Ev, Filter, off), Ev, M) end,
#{}, Evs),
case Em of
#{cdr := CdrEvs} when CdrEvs /= [] ->
{cdr_closure, ev_highest_prio(CdrEvs)};
#{container := CCEvs} when CCEvs /= [] ->
{container_closure, ev_highest_prio(CCEvs)};
_ ->
false
end.
|
8188236d250064ee04868857268a56cc978117747cd5d7f74b71aa28d551b9de | erlang-ls/erlang_ls | elvis_diagnostics.erl | -module(elvis_diagnostics).
-export([foo/2]).
%% Trigger some elvis warnings
-spec foo(any(),any()) -> any().
foo(_X,_Y) -> 3 .
| null | https://raw.githubusercontent.com/erlang-ls/erlang_ls/36bf0815e35db5d25a76e80f98f306f25fff7d8c/apps/els_lsp/priv/code_navigation/src/elvis_diagnostics.erl | erlang | Trigger some elvis warnings | -module(elvis_diagnostics).
-export([foo/2]).
-spec foo(any(),any()) -> any().
foo(_X,_Y) -> 3 .
|
dd4b9f803c7b2f97e18e223762144c595169de7593618a73967937d0c152c479 | tweag/asterius | CmmSwitchTestGen.hs | # LANGUAGE TupleSections #
-- Generates CmmSwitchTest.hs
import qualified Data.Set as S
import Data.Int
import Data.Word
import Data.List
import System.Environment
output :: Integer -> Integer
output n = n`div`2 + 42
def :: Integer
def = 1337
data Bits = X32 | X64
deriving Eq
type Spec = (String, Bool, [Integer], Bits)
primtyp True = "Int#"
primtyp False = "Word#"
con True = "I#"
con False = "W#"
hash True = "#"
hash False = "##"
primLit s v = show v ++ hash s
genSwitch :: Spec -> String
genSwitch (name, signed, values, _) = unlines $
[ "{-# NOINLINE " ++ name ++ " #-}" ] ++
[ name ++ " :: " ++ primtyp signed ++ " -> " ++ primtyp signed ] ++
[ name ++ " " ++ primLit signed v ++ " = " ++ primLit signed (output v)
| v <- values] ++
[ name ++ " _ = " ++ primLit signed def ]
genCheck :: Spec -> String
genCheck (name, signed, values, bits) = unlines $
[ checkName name ++ " :: IO ()"
, checkName name ++ " = forM_\n [ " ++ pairs ++ "] $ \\(" ++ con signed ++ " i,o) -> do"
, " let r = " ++ con signed ++ " (" ++ name ++ " i)"
, " unless (r == o) $ putStrLn $ \"ERR: " ++ name ++ " (\" ++ show (" ++ con signed ++ " i)++ \") is \" ++ show r ++ \" and not \" ++ show o ++\".\""
]
where
f x | x `S.member` range = output x
| otherwise = def
range = S.fromList values
minS = if bits == X32 then minS32 else minS64
maxS = if bits == X32 then maxS32 else maxS64
maxU = if bits == X32 then maxU32 else maxU64
checkValues = S.toList $ S.fromList $
[ v' | v <- values, v' <- [v-1,v,v+1],
if signed then v' >= minS && v' <= maxS else v' >= minU && v' <= maxU ]
pairs = intercalate "\n , " ["(" ++ show v ++ "," ++ show (f v) ++ ")" | v <- checkValues ]
checkName :: String -> String
checkName f = f ++ "_check"
genMain :: [Spec] -> String
genMain specs = unlines $ "main = do" : [ " " ++ checkName n | (n,_,_,_) <- specs ]
genMod :: [Spec] -> String
genMod specs = unlines $
"-- This file is generated from CmmSwitchTestGen! @generated" :
"{-# LANGUAGE MagicHash, NegativeLiterals #-}" :
"import Control.Monad (unless, forM_)" :
"import GHC.Exts" :
map genSwitch specs ++
map genCheck specs ++
[ genMain specs ]
main = do
args <- getArgs
bits <- parse args
putStrLn $
genMod $ zipWith (\n (s,v) -> (n,s,v,bits)) names $ signedChecks bits ++ unsignedChecks bits
parse :: [String] -> IO Bits -- Use IO to avoid lazy parsing
parse ["-32"] = return X32
parse ["-64"] = return X64
parse _ = error "Please, supply -32 or -64 option"
signedChecks :: Bits -> [(Bool, [Integer])]
signedChecks bits = map (True,)
[ [1..10]
, [0..10]
, [1..3]
, [1..4]
, [1..5]
, [-1..10]
, [-10..10]
, [-20.. -10]++[0..10]
, [-20.. -10]++[1..10]
, [minS,0,maxS]
, [maxS-10 .. maxS]
, [minS..minS+10]++[maxS-10 .. maxS]
]
where
minS = if bits == X32 then minS32 else minS64
maxS = if bits == X32 then maxS32 else maxS64
minU, maxU32, maxU64, minS32, minS64, maxS32, maxS64 :: Integer
minU = 0
maxU32 = fromIntegral (maxBound :: Word32)
maxU64 = fromIntegral (maxBound :: Word64)
minS32 = fromIntegral (minBound :: Int32)
minS64 = fromIntegral (minBound :: Int64)
maxS32 = fromIntegral (maxBound :: Int32)
maxS64 = fromIntegral (maxBound :: Int64)
unsignedChecks :: Bits -> [(Bool, [Integer])]
unsignedChecks bits = map (False,)
[ [0..10]
, [1..10]
, [0]
, [0..1]
, [0..2]
, [0..3]
, [0..4]
, [1]
, [1..2]
, [1..3]
, [1..4]
, [1..5]
, [minU,maxU]
, [maxU-10 .. maxU]
, [minU..minU+10]++[maxU-10 .. maxU]
]
where
maxU = if bits == X32 then maxU32 else maxU64
names :: [String]
names = [ c1:c2:[] | c1 <- ['a'..'z'], c2 <- ['a'..'z']]
| null | https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/codeGen/CmmSwitchTestGen.hs | haskell | Generates CmmSwitchTest.hs
Use IO to avoid lazy parsing | # LANGUAGE TupleSections #
import qualified Data.Set as S
import Data.Int
import Data.Word
import Data.List
import System.Environment
output :: Integer -> Integer
output n = n`div`2 + 42
def :: Integer
def = 1337
data Bits = X32 | X64
deriving Eq
type Spec = (String, Bool, [Integer], Bits)
primtyp True = "Int#"
primtyp False = "Word#"
con True = "I#"
con False = "W#"
hash True = "#"
hash False = "##"
primLit s v = show v ++ hash s
genSwitch :: Spec -> String
genSwitch (name, signed, values, _) = unlines $
[ "{-# NOINLINE " ++ name ++ " #-}" ] ++
[ name ++ " :: " ++ primtyp signed ++ " -> " ++ primtyp signed ] ++
[ name ++ " " ++ primLit signed v ++ " = " ++ primLit signed (output v)
| v <- values] ++
[ name ++ " _ = " ++ primLit signed def ]
genCheck :: Spec -> String
genCheck (name, signed, values, bits) = unlines $
[ checkName name ++ " :: IO ()"
, checkName name ++ " = forM_\n [ " ++ pairs ++ "] $ \\(" ++ con signed ++ " i,o) -> do"
, " let r = " ++ con signed ++ " (" ++ name ++ " i)"
, " unless (r == o) $ putStrLn $ \"ERR: " ++ name ++ " (\" ++ show (" ++ con signed ++ " i)++ \") is \" ++ show r ++ \" and not \" ++ show o ++\".\""
]
where
f x | x `S.member` range = output x
| otherwise = def
range = S.fromList values
minS = if bits == X32 then minS32 else minS64
maxS = if bits == X32 then maxS32 else maxS64
maxU = if bits == X32 then maxU32 else maxU64
checkValues = S.toList $ S.fromList $
[ v' | v <- values, v' <- [v-1,v,v+1],
if signed then v' >= minS && v' <= maxS else v' >= minU && v' <= maxU ]
pairs = intercalate "\n , " ["(" ++ show v ++ "," ++ show (f v) ++ ")" | v <- checkValues ]
checkName :: String -> String
checkName f = f ++ "_check"
genMain :: [Spec] -> String
genMain specs = unlines $ "main = do" : [ " " ++ checkName n | (n,_,_,_) <- specs ]
genMod :: [Spec] -> String
genMod specs = unlines $
"-- This file is generated from CmmSwitchTestGen! @generated" :
"{-# LANGUAGE MagicHash, NegativeLiterals #-}" :
"import Control.Monad (unless, forM_)" :
"import GHC.Exts" :
map genSwitch specs ++
map genCheck specs ++
[ genMain specs ]
main = do
args <- getArgs
bits <- parse args
putStrLn $
genMod $ zipWith (\n (s,v) -> (n,s,v,bits)) names $ signedChecks bits ++ unsignedChecks bits
parse ["-32"] = return X32
parse ["-64"] = return X64
parse _ = error "Please, supply -32 or -64 option"
signedChecks :: Bits -> [(Bool, [Integer])]
signedChecks bits = map (True,)
[ [1..10]
, [0..10]
, [1..3]
, [1..4]
, [1..5]
, [-1..10]
, [-10..10]
, [-20.. -10]++[0..10]
, [-20.. -10]++[1..10]
, [minS,0,maxS]
, [maxS-10 .. maxS]
, [minS..minS+10]++[maxS-10 .. maxS]
]
where
minS = if bits == X32 then minS32 else minS64
maxS = if bits == X32 then maxS32 else maxS64
minU, maxU32, maxU64, minS32, minS64, maxS32, maxS64 :: Integer
minU = 0
maxU32 = fromIntegral (maxBound :: Word32)
maxU64 = fromIntegral (maxBound :: Word64)
minS32 = fromIntegral (minBound :: Int32)
minS64 = fromIntegral (minBound :: Int64)
maxS32 = fromIntegral (maxBound :: Int32)
maxS64 = fromIntegral (maxBound :: Int64)
unsignedChecks :: Bits -> [(Bool, [Integer])]
unsignedChecks bits = map (False,)
[ [0..10]
, [1..10]
, [0]
, [0..1]
, [0..2]
, [0..3]
, [0..4]
, [1]
, [1..2]
, [1..3]
, [1..4]
, [1..5]
, [minU,maxU]
, [maxU-10 .. maxU]
, [minU..minU+10]++[maxU-10 .. maxU]
]
where
maxU = if bits == X32 then maxU32 else maxU64
names :: [String]
names = [ c1:c2:[] | c1 <- ['a'..'z'], c2 <- ['a'..'z']]
|
a941104d143da397d7b2673d8e3462e19d920f4458cb5500a227345906d9e2a5 | teamwalnut/graphql-ppx | custom_decoder.ml | open Test_shared
module IntOfString = struct
let parse = int_of_string
let serialize = string_of_int
type t = int
end
module StringOfInt = struct
let parse = string_of_int
let serialize = int_of_string
type t = string
end
module My_query =
[%graphql
{|
{
variousScalars {
string @ppxDecoder(module: "IntOfString")
int @ppxDecoder(module: "StringOfInt")
}
}
|}]
type t = My_query.t
let equal_payload (a : t) (b : t) =
a.variousScalars.string = b.variousScalars.string
&& a.variousScalars.int = b.variousScalars.int
let payload_to_json p = p |> My_query.serialize |> My_query.toJson
let test_payload (a : t) (b : t) =
test_json_ (payload_to_json a) (payload_to_json b)
let runs_the_decoder () =
test_payload
(Json.Read.from_string {|{"variousScalars": {"string": "123", "int": 456}}|}
|> My_query.unsafe_fromJson |> My_query.parse)
{ variousScalars = { string = 123; int = "456" } }
let tests = [ ("Runs the decoder", runs_the_decoder) ]
| null | https://raw.githubusercontent.com/teamwalnut/graphql-ppx/8276452ebe8d89a748b6b267afc94161650ab620/tests_native/custom_decoder.ml | ocaml | open Test_shared
module IntOfString = struct
let parse = int_of_string
let serialize = string_of_int
type t = int
end
module StringOfInt = struct
let parse = string_of_int
let serialize = int_of_string
type t = string
end
module My_query =
[%graphql
{|
{
variousScalars {
string @ppxDecoder(module: "IntOfString")
int @ppxDecoder(module: "StringOfInt")
}
}
|}]
type t = My_query.t
let equal_payload (a : t) (b : t) =
a.variousScalars.string = b.variousScalars.string
&& a.variousScalars.int = b.variousScalars.int
let payload_to_json p = p |> My_query.serialize |> My_query.toJson
let test_payload (a : t) (b : t) =
test_json_ (payload_to_json a) (payload_to_json b)
let runs_the_decoder () =
test_payload
(Json.Read.from_string {|{"variousScalars": {"string": "123", "int": 456}}|}
|> My_query.unsafe_fromJson |> My_query.parse)
{ variousScalars = { string = 123; int = "456" } }
let tests = [ ("Runs the decoder", runs_the_decoder) ]
|
|
dbe3700d219537d9ced2f4aa7697183d1d52134b169e3bd1548ffd26e0fef86e | penpot/penpot | viewport.cljs | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
;;
;; Copyright (c) KALEIDOS INC
(ns app.main.ui.workspace.viewport
(:require
[app.common.colors :as clr]
[app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.geom.shapes :as gsh]
[app.common.pages.helpers :as cph]
[app.common.types.shape.layout :as ctl]
[app.main.data.workspace.modifiers :as dwm]
[app.main.refs :as refs]
[app.main.ui.context :as ctx]
[app.main.ui.hooks :as ui-hooks]
[app.main.ui.measurements :as msr]
[app.main.ui.shapes.embed :as embed]
[app.main.ui.shapes.export :as use]
[app.main.ui.workspace.shapes :as shapes]
[app.main.ui.workspace.shapes.text.editor :as editor]
[app.main.ui.workspace.shapes.text.text-edition-outline :refer [text-edition-outline]]
[app.main.ui.workspace.shapes.text.viewport-texts-html :as stvh]
[app.main.ui.workspace.viewport.actions :as actions]
[app.main.ui.workspace.viewport.comments :as comments]
[app.main.ui.workspace.viewport.debug :as wvd]
[app.main.ui.workspace.viewport.drawarea :as drawarea]
[app.main.ui.workspace.viewport.frame-grid :as frame-grid]
[app.main.ui.workspace.viewport.gradients :as gradients]
[app.main.ui.workspace.viewport.grid-layout-editor :as grid-layout]
[app.main.ui.workspace.viewport.guides :as guides]
[app.main.ui.workspace.viewport.hooks :as hooks]
[app.main.ui.workspace.viewport.interactions :as interactions]
[app.main.ui.workspace.viewport.outline :as outline]
[app.main.ui.workspace.viewport.pixel-overlay :as pixel-overlay]
[app.main.ui.workspace.viewport.presence :as presence]
[app.main.ui.workspace.viewport.rules :as rules]
[app.main.ui.workspace.viewport.scroll-bars :as scroll-bars]
[app.main.ui.workspace.viewport.selection :as selection]
[app.main.ui.workspace.viewport.snap-distances :as snap-distances]
[app.main.ui.workspace.viewport.snap-points :as snap-points]
[app.main.ui.workspace.viewport.utils :as utils]
[app.main.ui.workspace.viewport.viewport-ref :refer [create-viewport-ref]]
[app.main.ui.workspace.viewport.widgets :as widgets]
[beicon.core :as rx]
[debug :refer [debug?]]
[rumext.v2 :as mf]))
;; --- Viewport
(defn apply-modifiers-to-selected
[selected objects text-modifiers modifiers]
(reduce
(fn [objects id]
(update
objects id
(fn [shape]
(cond-> shape
(and (cph/text-shape? shape) (contains? text-modifiers id))
(dwm/apply-text-modifier (get text-modifiers id))
(contains? modifiers id)
(gsh/transform-shape (dm/get-in modifiers [id :modifiers]))))))
objects
selected))
(mf/defc viewport
[{:keys [wlocal wglobal selected layout file] :as props}]
(let [;; When adding data from workspace-local revisit `app.main.ui.workspace` to check
;; that the new parameter is sent
{:keys [edit-path
panning
selrect
transform
highlighted
vbox
vport
zoom
edition]} wlocal
{:keys [options-mode
tooltip
show-distances?
picking-color?]} wglobal
;; CONTEXT
page-id (mf/use-ctx ctx/current-page-id)
;; DEREFS
drawing (mf/deref refs/workspace-drawing)
options (mf/deref refs/workspace-page-options)
focus (mf/deref refs/workspace-focus-selected)
objects-ref (mf/use-memo #(refs/workspace-page-objects-by-id page-id))
objects (mf/deref objects-ref)
base-objects (-> objects (ui-hooks/with-focus-objects focus))
modifiers (mf/deref refs/workspace-modifiers)
text-modifiers (mf/deref refs/workspace-text-modifier)
objects-modified (mf/with-memo
[base-objects text-modifiers modifiers]
(apply-modifiers-to-selected selected base-objects text-modifiers modifiers))
selected-shapes (->> selected (keep (d/getf objects-modified)))
background (get options :background clr/canvas)
;; STATE
alt? (mf/use-state false)
shift? (mf/use-state false)
mod? (mf/use-state false)
space? (mf/use-state false)
z? (mf/use-state false)
cursor (mf/use-state (utils/get-cursor :pointer-inner))
hover-ids (mf/use-state nil)
hover (mf/use-state nil)
hover-disabled? (mf/use-state false)
hover-top-frame-id (mf/use-state nil)
frame-hover (mf/use-state nil)
active-frames (mf/use-state #{})
;; REFS
[viewport-ref
on-viewport-ref] (create-viewport-ref)
VARS
disable-paste (mf/use-var false)
in-viewport? (mf/use-var false)
;; STREAMS
move-stream (mf/use-memo #(rx/subject))
frame-parent (mf/use-memo
(mf/deps @hover-ids base-objects)
(fn []
(let [parent (get base-objects (last @hover-ids))]
(when (= :frame (:type parent))
parent))))
zoom (d/check-num zoom 1)
drawing-tool (:tool drawing)
drawing-obj (:object drawing)
selected-frames (into #{} (map :frame-id) selected-shapes)
Only when we have all the selected shapes in one frame
selected-frame (when (= (count selected-frames) 1) (get base-objects (first selected-frames)))
editing-shape (when edition (get base-objects edition))
create-comment? (= :comments drawing-tool)
drawing-path? (or (and edition (= :draw (get-in edit-path [edition :edit-mode])))
(and (some? drawing-obj) (= :path (:type drawing-obj))))
node-editing? (and edition (not= :text (get-in base-objects [edition :type])))
text-editing? (and edition (= :text (get-in base-objects [edition :type])))
grid-editing? (and edition (ctl/grid-layout? base-objects edition))
workspace-read-only? (mf/use-ctx ctx/workspace-read-only?)
mode-inspect? (= options-mode :inspect)
on-click (actions/on-click hover selected edition drawing-path? drawing-tool space? selrect z?)
on-context-menu (actions/on-context-menu hover hover-ids workspace-read-only?)
on-double-click (actions/on-double-click hover hover-ids drawing-path? base-objects edition drawing-tool z? workspace-read-only?)
on-drag-enter (actions/on-drag-enter)
on-drag-over (actions/on-drag-over)
on-drop (actions/on-drop file)
on-mouse-down (actions/on-mouse-down @hover selected edition drawing-tool text-editing? node-editing? grid-editing?
drawing-path? create-comment? space? panning z? workspace-read-only?)
on-mouse-up (actions/on-mouse-up disable-paste)
on-pointer-down (actions/on-pointer-down)
on-pointer-enter (actions/on-pointer-enter in-viewport?)
on-pointer-leave (actions/on-pointer-leave in-viewport?)
on-pointer-move (actions/on-pointer-move move-stream)
on-pointer-up (actions/on-pointer-up)
on-move-selected (actions/on-move-selected hover hover-ids selected space? z? workspace-read-only?)
on-menu-selected (actions/on-menu-selected hover hover-ids selected workspace-read-only?)
on-frame-enter (actions/on-frame-enter frame-hover)
on-frame-leave (actions/on-frame-leave frame-hover)
on-frame-select (actions/on-frame-select selected workspace-read-only?)
disable-events? (contains? layout :comments)
show-comments? (= drawing-tool :comments)
show-cursor-tooltip? tooltip
show-draw-area? drawing-obj
show-gradient-handlers? (= (count selected) 1)
show-grids? (contains? layout :display-grid)
show-frame-outline? (= transform :move)
show-outlines? (and (nil? transform)
(not edition)
(not drawing-obj)
(not (#{:comments :path :curve} drawing-tool)))
show-pixel-grid? (and (contains? layout :show-pixel-grid)
(>= zoom 8))
show-text-editor? (and editing-shape (= :text (:type editing-shape)))
show-grid-editor? (and editing-shape (ctl/grid-layout? editing-shape))
show-presence? page-id
show-prototypes? (= options-mode :prototype)
show-selection-handlers? (and (seq selected) (not show-text-editor?))
show-snap-distance? (and (contains? layout :dynamic-alignment)
(= transform :move)
(seq selected))
show-snap-points? (and (or (contains? layout :dynamic-alignment)
(contains? layout :snap-grid))
(or drawing-obj transform))
show-selrect? (and selrect (empty? drawing) (not text-editing?))
show-measures? (and (not transform)
(not node-editing?)
(or show-distances? mode-inspect?))
show-artboard-names? (contains? layout :display-artboard-names)
show-rules? (and (contains? layout :rules) (not (contains? layout :hide-ui)))
disabled-guides? (or drawing-tool transform)
show-padding? (and (= (count selected-shapes) 1)
(= (:type (first selected-shapes)) :frame)
(= (:layout (first selected-shapes)) :flex))]
(hooks/setup-dom-events viewport-ref zoom disable-paste in-viewport? workspace-read-only?)
(hooks/setup-viewport-size vport viewport-ref)
(hooks/setup-cursor cursor alt? mod? space? panning drawing-tool drawing-path? node-editing? z? workspace-read-only?)
(hooks/setup-keyboard alt? mod? space? z? shift?)
(hooks/setup-hover-shapes page-id move-stream base-objects transform selected mod? hover hover-ids hover-top-frame-id @hover-disabled? focus zoom show-measures?)
(hooks/setup-viewport-modifiers modifiers base-objects)
(hooks/setup-shortcuts node-editing? drawing-path? text-editing?)
(hooks/setup-active-frames base-objects hover-ids selected active-frames zoom transform vbox)
[:div.viewport
[:div.viewport-overlays
;; The behaviour inside a foreign object is a bit different that in plain HTML so we wrap
;; inside a foreign object "dummy" so this awkward behaviour is take into account
[:svg {:style {:top 0 :left 0 :position "fixed" :width "100%" :height "100%" :opacity (when-not (debug? :html-text) 0)}}
[:foreignObject {:x 0 :y 0 :width "100%" :height "100%"}
[:div {:style {:pointer-events (when-not (debug? :html-text) "none")
;; some opacity because to debug auto-width events will fill the screen
:opacity 0.6}}
[:& stvh/viewport-texts
{:key (dm/str "texts-" page-id)
:page-id page-id
:objects objects
:modifiers modifiers
:edition edition}]]]]
(when show-comments?
[:& comments/comments-layer {:vbox vbox
:vport vport
:zoom zoom
:drawing drawing
:page-id page-id
:file-id (:id file)}])
(when picking-color?
[:& pixel-overlay/pixel-overlay {:vport vport
:vbox vbox
:options options
:layout layout
:viewport-ref viewport-ref}])
[:& widgets/viewport-actions]]
[:svg.render-shapes
{:id "render"
:xmlns ""
:xmlnsXlink ""
:xmlns:penpot ""
:preserveAspectRatio "xMidYMid meet"
:key (str "render" page-id)
:width (:width vport 0)
:height (:height vport 0)
:view-box (utils/format-viewbox vbox)
:style {:background-color background
:pointer-events "none"}
:fill "none"}
(when (debug? :show-export-metadata)
[:& use/export-page {:options options}])
;; We need a "real" background shape so layer transforms work properly in firefox
[:rect {:width (:width vbox 0)
:height (:height vbox 0)
:x (:x vbox 0)
:y (:y vbox 0)
:fill background}]
[:& (mf/provider use/include-metadata-ctx) {:value (debug? :show-export-metadata)}
[:& (mf/provider embed/context) {:value true}
;; Render root shape
[:& shapes/root-shape {:key page-id
:objects base-objects
:active-frames @active-frames}]]]]
[:svg.viewport-controls
{:xmlns ""
:xmlnsXlink ""
:preserveAspectRatio "xMidYMid meet"
:key (str "viewport" page-id)
:view-box (utils/format-viewbox vbox)
:ref on-viewport-ref
:class (when drawing-tool "drawing")
:style {:cursor @cursor}
:fill "none"
:on-click on-click
:on-context-menu on-context-menu
:on-double-click on-double-click
:on-drag-enter on-drag-enter
:on-drag-over on-drag-over
:on-drop on-drop
:on-mouse-down on-mouse-down
:on-mouse-up on-mouse-up
:on-pointer-down on-pointer-down
:on-pointer-enter on-pointer-enter
:on-pointer-leave on-pointer-leave
:on-pointer-move on-pointer-move
:on-pointer-up on-pointer-up}
[:g {:style {:pointer-events (if disable-events? "none" "auto")}}
(when show-text-editor?
[:& editor/text-editor-svg {:shape editing-shape
:modifiers modifiers}])
(when show-frame-outline?
(let [outlined-frame-id
(->> @hover-ids
(filter #(cph/frame-shape? (get base-objects %)))
(remove selected)
(first))
outlined-frame (get objects outlined-frame-id)]
[:*
[:& outline/shape-outlines
{:objects base-objects
:hover #{outlined-frame-id}
:zoom zoom
:modifiers modifiers}]
(when (ctl/any-layout? outlined-frame)
[:g.ghost-outline
[:& outline/shape-outlines
{:objects base-objects
:selected selected
:zoom zoom}]])]))
(when show-outlines?
[:& outline/shape-outlines
{:objects base-objects
:selected selected
:hover #{(:id @hover) @frame-hover}
:highlighted highlighted
:edition edition
:zoom zoom
:modifiers modifiers}])
(when show-selection-handlers?
[:& selection/selection-area
{:shapes selected-shapes
:zoom zoom
:edition edition
:disable-handlers (or drawing-tool edition @space? @mod?)
:on-move-selected on-move-selected
:on-context-menu on-menu-selected}])
(when show-text-editor?
[:& text-edition-outline
{:shape (get base-objects edition)
:zoom zoom
:modifiers modifiers}])
(when show-measures?
[:& msr/measurement
{:bounds vbox
:selected-shapes selected-shapes
:frame selected-frame
:hover-shape @hover
:zoom zoom}])
(when show-padding?
[:& msr/padding
{:frame (first selected-shapes)
:hover @frame-hover
:zoom zoom
:alt? @alt?
:shift? @shift?}])
[:& widgets/frame-titles
{:objects base-objects
:selected selected
:zoom zoom
:show-artboard-names? show-artboard-names?
:on-frame-enter on-frame-enter
:on-frame-leave on-frame-leave
:on-frame-select on-frame-select
:focus focus}]
(when show-prototypes?
[:& widgets/frame-flows
{:flows (:flows options)
:objects objects-modified
:selected selected
:zoom zoom
:on-frame-enter on-frame-enter
:on-frame-leave on-frame-leave
:on-frame-select on-frame-select}])
(when show-draw-area?
[:& drawarea/draw-area
{:shape drawing-obj
:zoom zoom
:tool drawing-tool}])
(when show-grids?
[:& frame-grid/frame-grid
{:zoom zoom
:selected selected
:transform transform
:focus focus}])
(when show-pixel-grid?
[:& widgets/pixel-grid
{:vbox vbox
:zoom zoom}])
(when show-snap-points?
[:& snap-points/snap-points
{:layout layout
:transform transform
:drawing drawing-obj
:zoom zoom
:page-id page-id
:selected selected
:objects objects-modified
:focus focus}])
(when show-snap-distance?
[:& snap-distances/snap-distances
{:layout layout
:zoom zoom
:transform transform
:selected selected
:selected-shapes selected-shapes
:page-id page-id}])
(when show-cursor-tooltip?
[:& widgets/cursor-tooltip
{:zoom zoom
:tooltip tooltip}])
(when show-selrect?
[:& widgets/selection-rect {:data selrect
:zoom zoom}])
(when show-presence?
[:& presence/active-cursors
{:page-id page-id}])
[:& scroll-bars/viewport-scrollbars
{:objects base-objects
:zoom zoom
:vbox vbox}]
(when show-rules?
[:& rules/rules
{:zoom zoom
:vbox vbox
:selected-shapes selected-shapes}])
(when show-rules?
[:& guides/viewport-guides
{:zoom zoom
:vbox vbox
:hover-frame frame-parent
:disabled-guides? disabled-guides?
:modifiers modifiers}])
DEBUG LAYOUT DROP - ZONES
(when (debug? :layout-drop-zones)
[:& wvd/debug-drop-zones {:selected-shapes selected-shapes
:objects base-objects
:hover-top-frame-id @hover-top-frame-id
:zoom zoom}])
(when (debug? :layout-content-bounds)
[:& wvd/debug-content-bounds {:selected-shapes selected-shapes
:objects base-objects
:hover-top-frame-id @hover-top-frame-id
:zoom zoom}])
(when (debug? :layout-lines)
[:& wvd/debug-layout-lines {:selected-shapes selected-shapes
:objects base-objects
:hover-top-frame-id @hover-top-frame-id
:zoom zoom}])
(when (debug? :parent-bounds)
[:& wvd/debug-parent-bounds {:selected-shapes selected-shapes
:objects base-objects
:hover-top-frame-id @hover-top-frame-id
:zoom zoom}])
(when (debug? :grid-layout)
[:& wvd/debug-grid-layout {:selected-shapes selected-shapes
:objects base-objects
:hover-top-frame-id @hover-top-frame-id
:zoom zoom}])
(when show-selection-handlers?
[:g.selection-handlers {:clipPath "url(#clip-handlers)"}
[:defs
(let [rule-area-size (/ rules/rule-area-size zoom)]
;; This clip is so the handlers are not over the rules
[:clipPath {:id "clip-handlers"}
[:rect {:x (+ (:x vbox) rule-area-size)
:y (+ (:y vbox) rule-area-size)
:width (- (:width vbox) (* rule-area-size 2))
:height (- (:height vbox) (* rule-area-size 2))}]])]
[:& selection/selection-handlers
{:selected selected
:shapes selected-shapes
:zoom zoom
:edition edition
:disable-handlers (or drawing-tool edition @space?)}]
(when show-prototypes?
[:& interactions/interactions
{:selected selected
:page-id page-id
:zoom zoom
:objects objects-modified
:current-transform transform
:hover-disabled? hover-disabled?}])])
(when show-gradient-handlers?
[:& gradients/gradient-handlers
{:id (first selected)
:zoom zoom}])
(when show-grid-editor?
[:& grid-layout/editor
{:zoom zoom
:objects base-objects
:shape (get base-objects edition)}])
]]]))
| null | https://raw.githubusercontent.com/penpot/penpot/0e585cd585af68829e86868cda494139a02b32f1/frontend/src/app/main/ui/workspace/viewport.cljs | clojure |
Copyright (c) KALEIDOS INC
--- Viewport
When adding data from workspace-local revisit `app.main.ui.workspace` to check
that the new parameter is sent
CONTEXT
DEREFS
STATE
REFS
STREAMS
The behaviour inside a foreign object is a bit different that in plain HTML so we wrap
inside a foreign object "dummy" so this awkward behaviour is take into account
some opacity because to debug auto-width events will fill the screen
We need a "real" background shape so layer transforms work properly in firefox
Render root shape
This clip is so the handlers are not over the rules | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
(ns app.main.ui.workspace.viewport
(:require
[app.common.colors :as clr]
[app.common.data :as d]
[app.common.data.macros :as dm]
[app.common.geom.shapes :as gsh]
[app.common.pages.helpers :as cph]
[app.common.types.shape.layout :as ctl]
[app.main.data.workspace.modifiers :as dwm]
[app.main.refs :as refs]
[app.main.ui.context :as ctx]
[app.main.ui.hooks :as ui-hooks]
[app.main.ui.measurements :as msr]
[app.main.ui.shapes.embed :as embed]
[app.main.ui.shapes.export :as use]
[app.main.ui.workspace.shapes :as shapes]
[app.main.ui.workspace.shapes.text.editor :as editor]
[app.main.ui.workspace.shapes.text.text-edition-outline :refer [text-edition-outline]]
[app.main.ui.workspace.shapes.text.viewport-texts-html :as stvh]
[app.main.ui.workspace.viewport.actions :as actions]
[app.main.ui.workspace.viewport.comments :as comments]
[app.main.ui.workspace.viewport.debug :as wvd]
[app.main.ui.workspace.viewport.drawarea :as drawarea]
[app.main.ui.workspace.viewport.frame-grid :as frame-grid]
[app.main.ui.workspace.viewport.gradients :as gradients]
[app.main.ui.workspace.viewport.grid-layout-editor :as grid-layout]
[app.main.ui.workspace.viewport.guides :as guides]
[app.main.ui.workspace.viewport.hooks :as hooks]
[app.main.ui.workspace.viewport.interactions :as interactions]
[app.main.ui.workspace.viewport.outline :as outline]
[app.main.ui.workspace.viewport.pixel-overlay :as pixel-overlay]
[app.main.ui.workspace.viewport.presence :as presence]
[app.main.ui.workspace.viewport.rules :as rules]
[app.main.ui.workspace.viewport.scroll-bars :as scroll-bars]
[app.main.ui.workspace.viewport.selection :as selection]
[app.main.ui.workspace.viewport.snap-distances :as snap-distances]
[app.main.ui.workspace.viewport.snap-points :as snap-points]
[app.main.ui.workspace.viewport.utils :as utils]
[app.main.ui.workspace.viewport.viewport-ref :refer [create-viewport-ref]]
[app.main.ui.workspace.viewport.widgets :as widgets]
[beicon.core :as rx]
[debug :refer [debug?]]
[rumext.v2 :as mf]))
(defn apply-modifiers-to-selected
[selected objects text-modifiers modifiers]
(reduce
(fn [objects id]
(update
objects id
(fn [shape]
(cond-> shape
(and (cph/text-shape? shape) (contains? text-modifiers id))
(dwm/apply-text-modifier (get text-modifiers id))
(contains? modifiers id)
(gsh/transform-shape (dm/get-in modifiers [id :modifiers]))))))
objects
selected))
(mf/defc viewport
[{:keys [wlocal wglobal selected layout file] :as props}]
{:keys [edit-path
panning
selrect
transform
highlighted
vbox
vport
zoom
edition]} wlocal
{:keys [options-mode
tooltip
show-distances?
picking-color?]} wglobal
page-id (mf/use-ctx ctx/current-page-id)
drawing (mf/deref refs/workspace-drawing)
options (mf/deref refs/workspace-page-options)
focus (mf/deref refs/workspace-focus-selected)
objects-ref (mf/use-memo #(refs/workspace-page-objects-by-id page-id))
objects (mf/deref objects-ref)
base-objects (-> objects (ui-hooks/with-focus-objects focus))
modifiers (mf/deref refs/workspace-modifiers)
text-modifiers (mf/deref refs/workspace-text-modifier)
objects-modified (mf/with-memo
[base-objects text-modifiers modifiers]
(apply-modifiers-to-selected selected base-objects text-modifiers modifiers))
selected-shapes (->> selected (keep (d/getf objects-modified)))
background (get options :background clr/canvas)
alt? (mf/use-state false)
shift? (mf/use-state false)
mod? (mf/use-state false)
space? (mf/use-state false)
z? (mf/use-state false)
cursor (mf/use-state (utils/get-cursor :pointer-inner))
hover-ids (mf/use-state nil)
hover (mf/use-state nil)
hover-disabled? (mf/use-state false)
hover-top-frame-id (mf/use-state nil)
frame-hover (mf/use-state nil)
active-frames (mf/use-state #{})
[viewport-ref
on-viewport-ref] (create-viewport-ref)
VARS
disable-paste (mf/use-var false)
in-viewport? (mf/use-var false)
move-stream (mf/use-memo #(rx/subject))
frame-parent (mf/use-memo
(mf/deps @hover-ids base-objects)
(fn []
(let [parent (get base-objects (last @hover-ids))]
(when (= :frame (:type parent))
parent))))
zoom (d/check-num zoom 1)
drawing-tool (:tool drawing)
drawing-obj (:object drawing)
selected-frames (into #{} (map :frame-id) selected-shapes)
Only when we have all the selected shapes in one frame
selected-frame (when (= (count selected-frames) 1) (get base-objects (first selected-frames)))
editing-shape (when edition (get base-objects edition))
create-comment? (= :comments drawing-tool)
drawing-path? (or (and edition (= :draw (get-in edit-path [edition :edit-mode])))
(and (some? drawing-obj) (= :path (:type drawing-obj))))
node-editing? (and edition (not= :text (get-in base-objects [edition :type])))
text-editing? (and edition (= :text (get-in base-objects [edition :type])))
grid-editing? (and edition (ctl/grid-layout? base-objects edition))
workspace-read-only? (mf/use-ctx ctx/workspace-read-only?)
mode-inspect? (= options-mode :inspect)
on-click (actions/on-click hover selected edition drawing-path? drawing-tool space? selrect z?)
on-context-menu (actions/on-context-menu hover hover-ids workspace-read-only?)
on-double-click (actions/on-double-click hover hover-ids drawing-path? base-objects edition drawing-tool z? workspace-read-only?)
on-drag-enter (actions/on-drag-enter)
on-drag-over (actions/on-drag-over)
on-drop (actions/on-drop file)
on-mouse-down (actions/on-mouse-down @hover selected edition drawing-tool text-editing? node-editing? grid-editing?
drawing-path? create-comment? space? panning z? workspace-read-only?)
on-mouse-up (actions/on-mouse-up disable-paste)
on-pointer-down (actions/on-pointer-down)
on-pointer-enter (actions/on-pointer-enter in-viewport?)
on-pointer-leave (actions/on-pointer-leave in-viewport?)
on-pointer-move (actions/on-pointer-move move-stream)
on-pointer-up (actions/on-pointer-up)
on-move-selected (actions/on-move-selected hover hover-ids selected space? z? workspace-read-only?)
on-menu-selected (actions/on-menu-selected hover hover-ids selected workspace-read-only?)
on-frame-enter (actions/on-frame-enter frame-hover)
on-frame-leave (actions/on-frame-leave frame-hover)
on-frame-select (actions/on-frame-select selected workspace-read-only?)
disable-events? (contains? layout :comments)
show-comments? (= drawing-tool :comments)
show-cursor-tooltip? tooltip
show-draw-area? drawing-obj
show-gradient-handlers? (= (count selected) 1)
show-grids? (contains? layout :display-grid)
show-frame-outline? (= transform :move)
show-outlines? (and (nil? transform)
(not edition)
(not drawing-obj)
(not (#{:comments :path :curve} drawing-tool)))
show-pixel-grid? (and (contains? layout :show-pixel-grid)
(>= zoom 8))
show-text-editor? (and editing-shape (= :text (:type editing-shape)))
show-grid-editor? (and editing-shape (ctl/grid-layout? editing-shape))
show-presence? page-id
show-prototypes? (= options-mode :prototype)
show-selection-handlers? (and (seq selected) (not show-text-editor?))
show-snap-distance? (and (contains? layout :dynamic-alignment)
(= transform :move)
(seq selected))
show-snap-points? (and (or (contains? layout :dynamic-alignment)
(contains? layout :snap-grid))
(or drawing-obj transform))
show-selrect? (and selrect (empty? drawing) (not text-editing?))
show-measures? (and (not transform)
(not node-editing?)
(or show-distances? mode-inspect?))
show-artboard-names? (contains? layout :display-artboard-names)
show-rules? (and (contains? layout :rules) (not (contains? layout :hide-ui)))
disabled-guides? (or drawing-tool transform)
show-padding? (and (= (count selected-shapes) 1)
(= (:type (first selected-shapes)) :frame)
(= (:layout (first selected-shapes)) :flex))]
(hooks/setup-dom-events viewport-ref zoom disable-paste in-viewport? workspace-read-only?)
(hooks/setup-viewport-size vport viewport-ref)
(hooks/setup-cursor cursor alt? mod? space? panning drawing-tool drawing-path? node-editing? z? workspace-read-only?)
(hooks/setup-keyboard alt? mod? space? z? shift?)
(hooks/setup-hover-shapes page-id move-stream base-objects transform selected mod? hover hover-ids hover-top-frame-id @hover-disabled? focus zoom show-measures?)
(hooks/setup-viewport-modifiers modifiers base-objects)
(hooks/setup-shortcuts node-editing? drawing-path? text-editing?)
(hooks/setup-active-frames base-objects hover-ids selected active-frames zoom transform vbox)
[:div.viewport
[:div.viewport-overlays
[:svg {:style {:top 0 :left 0 :position "fixed" :width "100%" :height "100%" :opacity (when-not (debug? :html-text) 0)}}
[:foreignObject {:x 0 :y 0 :width "100%" :height "100%"}
[:div {:style {:pointer-events (when-not (debug? :html-text) "none")
:opacity 0.6}}
[:& stvh/viewport-texts
{:key (dm/str "texts-" page-id)
:page-id page-id
:objects objects
:modifiers modifiers
:edition edition}]]]]
(when show-comments?
[:& comments/comments-layer {:vbox vbox
:vport vport
:zoom zoom
:drawing drawing
:page-id page-id
:file-id (:id file)}])
(when picking-color?
[:& pixel-overlay/pixel-overlay {:vport vport
:vbox vbox
:options options
:layout layout
:viewport-ref viewport-ref}])
[:& widgets/viewport-actions]]
[:svg.render-shapes
{:id "render"
:xmlns ""
:xmlnsXlink ""
:xmlns:penpot ""
:preserveAspectRatio "xMidYMid meet"
:key (str "render" page-id)
:width (:width vport 0)
:height (:height vport 0)
:view-box (utils/format-viewbox vbox)
:style {:background-color background
:pointer-events "none"}
:fill "none"}
(when (debug? :show-export-metadata)
[:& use/export-page {:options options}])
[:rect {:width (:width vbox 0)
:height (:height vbox 0)
:x (:x vbox 0)
:y (:y vbox 0)
:fill background}]
[:& (mf/provider use/include-metadata-ctx) {:value (debug? :show-export-metadata)}
[:& (mf/provider embed/context) {:value true}
[:& shapes/root-shape {:key page-id
:objects base-objects
:active-frames @active-frames}]]]]
[:svg.viewport-controls
{:xmlns ""
:xmlnsXlink ""
:preserveAspectRatio "xMidYMid meet"
:key (str "viewport" page-id)
:view-box (utils/format-viewbox vbox)
:ref on-viewport-ref
:class (when drawing-tool "drawing")
:style {:cursor @cursor}
:fill "none"
:on-click on-click
:on-context-menu on-context-menu
:on-double-click on-double-click
:on-drag-enter on-drag-enter
:on-drag-over on-drag-over
:on-drop on-drop
:on-mouse-down on-mouse-down
:on-mouse-up on-mouse-up
:on-pointer-down on-pointer-down
:on-pointer-enter on-pointer-enter
:on-pointer-leave on-pointer-leave
:on-pointer-move on-pointer-move
:on-pointer-up on-pointer-up}
[:g {:style {:pointer-events (if disable-events? "none" "auto")}}
(when show-text-editor?
[:& editor/text-editor-svg {:shape editing-shape
:modifiers modifiers}])
(when show-frame-outline?
(let [outlined-frame-id
(->> @hover-ids
(filter #(cph/frame-shape? (get base-objects %)))
(remove selected)
(first))
outlined-frame (get objects outlined-frame-id)]
[:*
[:& outline/shape-outlines
{:objects base-objects
:hover #{outlined-frame-id}
:zoom zoom
:modifiers modifiers}]
(when (ctl/any-layout? outlined-frame)
[:g.ghost-outline
[:& outline/shape-outlines
{:objects base-objects
:selected selected
:zoom zoom}]])]))
(when show-outlines?
[:& outline/shape-outlines
{:objects base-objects
:selected selected
:hover #{(:id @hover) @frame-hover}
:highlighted highlighted
:edition edition
:zoom zoom
:modifiers modifiers}])
(when show-selection-handlers?
[:& selection/selection-area
{:shapes selected-shapes
:zoom zoom
:edition edition
:disable-handlers (or drawing-tool edition @space? @mod?)
:on-move-selected on-move-selected
:on-context-menu on-menu-selected}])
(when show-text-editor?
[:& text-edition-outline
{:shape (get base-objects edition)
:zoom zoom
:modifiers modifiers}])
(when show-measures?
[:& msr/measurement
{:bounds vbox
:selected-shapes selected-shapes
:frame selected-frame
:hover-shape @hover
:zoom zoom}])
(when show-padding?
[:& msr/padding
{:frame (first selected-shapes)
:hover @frame-hover
:zoom zoom
:alt? @alt?
:shift? @shift?}])
[:& widgets/frame-titles
{:objects base-objects
:selected selected
:zoom zoom
:show-artboard-names? show-artboard-names?
:on-frame-enter on-frame-enter
:on-frame-leave on-frame-leave
:on-frame-select on-frame-select
:focus focus}]
(when show-prototypes?
[:& widgets/frame-flows
{:flows (:flows options)
:objects objects-modified
:selected selected
:zoom zoom
:on-frame-enter on-frame-enter
:on-frame-leave on-frame-leave
:on-frame-select on-frame-select}])
(when show-draw-area?
[:& drawarea/draw-area
{:shape drawing-obj
:zoom zoom
:tool drawing-tool}])
(when show-grids?
[:& frame-grid/frame-grid
{:zoom zoom
:selected selected
:transform transform
:focus focus}])
(when show-pixel-grid?
[:& widgets/pixel-grid
{:vbox vbox
:zoom zoom}])
(when show-snap-points?
[:& snap-points/snap-points
{:layout layout
:transform transform
:drawing drawing-obj
:zoom zoom
:page-id page-id
:selected selected
:objects objects-modified
:focus focus}])
(when show-snap-distance?
[:& snap-distances/snap-distances
{:layout layout
:zoom zoom
:transform transform
:selected selected
:selected-shapes selected-shapes
:page-id page-id}])
(when show-cursor-tooltip?
[:& widgets/cursor-tooltip
{:zoom zoom
:tooltip tooltip}])
(when show-selrect?
[:& widgets/selection-rect {:data selrect
:zoom zoom}])
(when show-presence?
[:& presence/active-cursors
{:page-id page-id}])
[:& scroll-bars/viewport-scrollbars
{:objects base-objects
:zoom zoom
:vbox vbox}]
(when show-rules?
[:& rules/rules
{:zoom zoom
:vbox vbox
:selected-shapes selected-shapes}])
(when show-rules?
[:& guides/viewport-guides
{:zoom zoom
:vbox vbox
:hover-frame frame-parent
:disabled-guides? disabled-guides?
:modifiers modifiers}])
DEBUG LAYOUT DROP - ZONES
(when (debug? :layout-drop-zones)
[:& wvd/debug-drop-zones {:selected-shapes selected-shapes
:objects base-objects
:hover-top-frame-id @hover-top-frame-id
:zoom zoom}])
(when (debug? :layout-content-bounds)
[:& wvd/debug-content-bounds {:selected-shapes selected-shapes
:objects base-objects
:hover-top-frame-id @hover-top-frame-id
:zoom zoom}])
(when (debug? :layout-lines)
[:& wvd/debug-layout-lines {:selected-shapes selected-shapes
:objects base-objects
:hover-top-frame-id @hover-top-frame-id
:zoom zoom}])
(when (debug? :parent-bounds)
[:& wvd/debug-parent-bounds {:selected-shapes selected-shapes
:objects base-objects
:hover-top-frame-id @hover-top-frame-id
:zoom zoom}])
(when (debug? :grid-layout)
[:& wvd/debug-grid-layout {:selected-shapes selected-shapes
:objects base-objects
:hover-top-frame-id @hover-top-frame-id
:zoom zoom}])
(when show-selection-handlers?
[:g.selection-handlers {:clipPath "url(#clip-handlers)"}
[:defs
(let [rule-area-size (/ rules/rule-area-size zoom)]
[:clipPath {:id "clip-handlers"}
[:rect {:x (+ (:x vbox) rule-area-size)
:y (+ (:y vbox) rule-area-size)
:width (- (:width vbox) (* rule-area-size 2))
:height (- (:height vbox) (* rule-area-size 2))}]])]
[:& selection/selection-handlers
{:selected selected
:shapes selected-shapes
:zoom zoom
:edition edition
:disable-handlers (or drawing-tool edition @space?)}]
(when show-prototypes?
[:& interactions/interactions
{:selected selected
:page-id page-id
:zoom zoom
:objects objects-modified
:current-transform transform
:hover-disabled? hover-disabled?}])])
(when show-gradient-handlers?
[:& gradients/gradient-handlers
{:id (first selected)
:zoom zoom}])
(when show-grid-editor?
[:& grid-layout/editor
{:zoom zoom
:objects base-objects
:shape (get base-objects edition)}])
]]]))
|
fcb7cf8f0827b2a1402a5487387403e61e00121e0dbfef051acfddc877b6c2f6 | softlab-ntua/bencherl | db_generator.erl | 2010 - 2011 Zuse Institute Berlin
% @end
%
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.
%%%-------------------------------------------------------------------
%%% File merkle_tree_builder.erl
@author < >
@doc construction .
%%% @end
Created : 15/11/2011 by < >
%%%-------------------------------------------------------------------
%% @version $Id: $
-module(db_generator).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-include("scalaris.hrl").
-export([get_db/3, get_db/4]).
-type distribution() :: uniform.% |
%{binomial, P::float()}.
-type result() :: ?RT:key() |
{?RT:key(), ?DB:value()}.
-type option() :: {output, list_key_val | list_key}.
-ifdef(with_export_type_support).
-export_type([distribution/0]).
-endif.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@doc This will generate a list of [ ItemCount ] keys with requested distribution
% in the given interval.
-spec get_db(intervals:interval(), non_neg_integer(), distribution()) -> [result()].
get_db(I, Count, Distribution) ->
get_db(I, Count, Distribution, []).
-spec get_db(intervals:interval(), non_neg_integer(), distribution(), [option()]) -> [result()].
get_db(Interval, ItemCount, Distribution, Options) ->
OutputType = proplists:get_value(output, Options, list_key),
case Distribution of
uniform -> uniform_key_list([{Interval, ItemCount}], [], OutputType);
_ -> []
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec uniform_key_list([{Interval, ToAdd}], Acc::Result, OutputType) -> Result when
is_subtype(Interval, intervals:interval()),
is_subtype(ToAdd, non_neg_integer()),
is_subtype(OutputType, list_key_val | list_key),
is_subtype(Result, [result()]).
uniform_key_list([], Acc, _) -> Acc;
uniform_key_list([{I, Add} | R], Acc, AccType) ->
case Add > 100 of
true ->
[I1, I2] = intervals:split(I, 2),
uniform_key_list([{I1, Add div 2}, {I2, (Add div 2) + (Add rem 2)} | R], Acc, AccType);
false ->
{_, IL, IR, _} = intervals:get_bounds(I),
ToAdd = util:for_to_ex(1, Add,
fun(Index) ->
Key = ?RT:get_split_key(IL, IR, {Index, Add}),
case AccType of
list_key -> Key;
list_key_val -> {Key, gen_value()}
end
end),
uniform_key_list(R, lists:append(ToAdd, Acc), AccType)
end.
gen_value() ->
tester_value_creator:create_value(integer, 0, tester_parse_state:new_parse_state()).
| null | https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/scalaris/test/db_generator.erl | erlang | @end
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.
-------------------------------------------------------------------
File merkle_tree_builder.erl
@end
-------------------------------------------------------------------
@version $Id: $
|
{binomial, P::float()}.
in the given interval.
| 2010 - 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 < >
@doc construction .
Created : 15/11/2011 by < >
-module(db_generator).
-include("scalaris.hrl").
-export([get_db/3, get_db/4]).
-type result() :: ?RT:key() |
{?RT:key(), ?DB:value()}.
-type option() :: {output, list_key_val | list_key}.
-ifdef(with_export_type_support).
-export_type([distribution/0]).
-endif.
@doc This will generate a list of [ ItemCount ] keys with requested distribution
-spec get_db(intervals:interval(), non_neg_integer(), distribution()) -> [result()].
get_db(I, Count, Distribution) ->
get_db(I, Count, Distribution, []).
-spec get_db(intervals:interval(), non_neg_integer(), distribution(), [option()]) -> [result()].
get_db(Interval, ItemCount, Distribution, Options) ->
OutputType = proplists:get_value(output, Options, list_key),
case Distribution of
uniform -> uniform_key_list([{Interval, ItemCount}], [], OutputType);
_ -> []
end.
-spec uniform_key_list([{Interval, ToAdd}], Acc::Result, OutputType) -> Result when
is_subtype(Interval, intervals:interval()),
is_subtype(ToAdd, non_neg_integer()),
is_subtype(OutputType, list_key_val | list_key),
is_subtype(Result, [result()]).
uniform_key_list([], Acc, _) -> Acc;
uniform_key_list([{I, Add} | R], Acc, AccType) ->
case Add > 100 of
true ->
[I1, I2] = intervals:split(I, 2),
uniform_key_list([{I1, Add div 2}, {I2, (Add div 2) + (Add rem 2)} | R], Acc, AccType);
false ->
{_, IL, IR, _} = intervals:get_bounds(I),
ToAdd = util:for_to_ex(1, Add,
fun(Index) ->
Key = ?RT:get_split_key(IL, IR, {Index, Add}),
case AccType of
list_key -> Key;
list_key_val -> {Key, gen_value()}
end
end),
uniform_key_list(R, lists:append(ToAdd, Acc), AccType)
end.
gen_value() ->
tester_value_creator:create_value(integer, 0, tester_parse_state:new_parse_state()).
|
0be22a443fb5820f67faf4b4fc537dac7db80d9b7ef1ee58ea5ddcbe937949f2 | nikodemus/SBCL | ir1opt.lisp | ;;;; This file implements the IR1 optimization phase of the compiler.
;;;; IR1 optimization is a grab-bag of optimizations that don't make
;;;; major changes to the block-level control flow and don't use flow
;;;; analysis. These optimizations can mostly be classified as
;;;; "meta-evaluation", but there is a sizable top-down component as
;;;; well.
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB!C")
;;;; interface for obtaining results of constant folding
Return true for an LVAR whose sole use is a reference to a
;;; constant leaf.
(defun constant-lvar-p (thing)
(declare (type (or lvar null) thing))
(and (lvar-p thing)
(or (let ((use (principal-lvar-use thing)))
(and (ref-p use) (constant-p (ref-leaf use))))
check for EQL types ( but not singleton numeric types )
(let ((type (lvar-type thing)))
(values (type-singleton-p type))))))
Return the constant value for an LVAR whose only use is a constant
;;; node.
(declaim (ftype (function (lvar) t) lvar-value))
(defun lvar-value (lvar)
(let ((use (principal-lvar-use lvar))
(type (lvar-type lvar))
leaf)
(if (and (ref-p use)
(constant-p (setf leaf (ref-leaf use))))
(constant-value leaf)
(multiple-value-bind (constantp value) (type-singleton-p type)
(unless constantp
(error "~S used on non-constant LVAR ~S" 'lvar-value lvar))
value))))
;;;; interface for obtaining results of type inference
Our best guess for the type of this lvar 's value . Note that this
;;; may be VALUES or FUNCTION type, which cannot be passed as an
argument to the normal type operations . See LVAR - TYPE .
;;;
The result value is cached in the - TYPE slot . If the
;;; slot is true, just return that value, otherwise recompute and
;;; stash the value there.
(eval-when (:compile-toplevel :execute)
(#+sb-xc-host cl:defmacro
#-sb-xc-host sb!xc:defmacro
lvar-type-using (lvar accessor)
`(let ((uses (lvar-uses ,lvar)))
(cond ((null uses) *empty-type*)
((listp uses)
(do ((res (,accessor (first uses))
(values-type-union (,accessor (first current))
res))
(current (rest uses) (rest current)))
((or (null current) (eq res *wild-type*))
res)))
(t
(,accessor uses))))))
#!-sb-fluid (declaim (inline lvar-derived-type))
(defun lvar-derived-type (lvar)
(declare (type lvar lvar))
(or (lvar-%derived-type lvar)
(setf (lvar-%derived-type lvar)
(%lvar-derived-type lvar))))
(defun %lvar-derived-type (lvar)
(lvar-type-using lvar node-derived-type))
Return the derived type for LVAR 's first value . This is guaranteed
;;; not to be a VALUES or FUNCTION type.
(declaim (ftype (sfunction (lvar) ctype) lvar-type))
(defun lvar-type (lvar)
(single-value-type (lvar-derived-type lvar)))
LVAR - CONSERVATIVE - TYPE
;;;
;;; Certain types refer to the contents of an object, which can
;;; change without type derivation noticing: CONS types and ARRAY
;;; types suffer from this:
;;;
;;; (let ((x (the (cons fixnum fixnum) (cons a b))))
( setf ( car x ) c )
( + ( car x ) ) ) )
;;;
Python does n't realize that the SETF CAR can change the type of X -- so we
can not use LVAR - TYPE which gets the derived results . Worse , still , instead
of ( SETF CAR ) we might have a call to a user - defined function FOO which
;;; does the same -- so there is no way to use the derived information in
;;; general.
;;;
;;; So, the conservative option is to use the derived type if the leaf has
;;; only a single ref -- in which case there cannot be a prior call that
;;; mutates it. Otherwise we use the declared type or punt to the most general
;;; type we know to be correct for sure.
(defun lvar-conservative-type (lvar)
(let ((derived-type (lvar-type lvar))
(t-type *universal-type*))
Recompute using NODE - CONSERVATIVE - TYPE instead of derived type if
;; necessary -- picking off some easy cases up front.
(cond ((or (eq derived-type t-type)
Ca n't use CSUBTYPEP !
(type= derived-type (specifier-type 'list))
(type= derived-type (specifier-type 'null)))
derived-type)
((and (cons-type-p derived-type)
(eq t-type (cons-type-car-type derived-type))
(eq t-type (cons-type-cdr-type derived-type)))
derived-type)
((and (array-type-p derived-type)
(or (not (array-type-complexp derived-type))
(let ((dimensions (array-type-dimensions derived-type)))
(or (eq '* dimensions)
(every (lambda (dim) (eq '* dim)) dimensions)))))
derived-type)
((type-needs-conservation-p derived-type)
(single-value-type (lvar-type-using lvar node-conservative-type)))
(t
derived-type))))
(defun node-conservative-type (node)
(let* ((derived-values-type (node-derived-type node))
(derived-type (single-value-type derived-values-type)))
(if (ref-p node)
(let ((leaf (ref-leaf node)))
(if (and (basic-var-p leaf)
(cdr (leaf-refs leaf)))
(coerce-to-values
(if (eq :declared (leaf-where-from leaf))
(leaf-type leaf)
(conservative-type derived-type)))
derived-values-type))
derived-values-type)))
(defun conservative-type (type)
(cond ((or (eq type *universal-type*)
(eq type (specifier-type 'list))
(eq type (specifier-type 'null)))
type)
((cons-type-p type)
(specifier-type 'cons))
((array-type-p type)
(if (array-type-complexp type)
(make-array-type
;; ADJUST-ARRAY may change dimensions, but rank stays same.
:dimensions
(let ((old (array-type-dimensions type)))
(if (eq '* old)
old
(mapcar (constantly '*) old)))
Complexity can not change .
:complexp (array-type-complexp type)
;; Element type cannot change.
:element-type (array-type-element-type type)
:specialized-element-type (array-type-specialized-element-type type))
;; Simple arrays cannot change at all.
type))
((union-type-p type)
Conservative union type is an union of conservative types .
(let ((res *empty-type*))
(dolist (part (union-type-types type) res)
(setf res (type-union res (conservative-type part))))))
(t
;; Catch-all.
;;
;; If the type contains some CONS types, the conservative type contains all
;; of them.
(when (types-equal-or-intersect type (specifier-type 'cons))
(setf type (type-union type (specifier-type 'cons))))
;; Similarly for non-simple arrays -- it should be possible to preserve
;; more information here, but really...
(let ((non-simple-arrays (specifier-type '(and array (not simple-array)))))
(when (types-equal-or-intersect type non-simple-arrays)
(setf type (type-union type non-simple-arrays))))
type)))
(defun type-needs-conservation-p (type)
(cond ((eq type *universal-type*)
;; Excluding T is necessary, because we do want type derivation to
;; be able to narrow it down in case someone (most like a macro-expansion...)
;; actually declares something as having type T.
nil)
((or (cons-type-p type) (and (array-type-p type) (array-type-complexp type)))
;; Covered by the next case as well, but this is a quick test.
t)
((types-equal-or-intersect type (specifier-type '(or cons (and array (not simple-array)))))
t)))
If LVAR is an argument of a function , return a type which the
function checks LVAR for .
#!-sb-fluid (declaim (inline lvar-externally-checkable-type))
(defun lvar-externally-checkable-type (lvar)
(or (lvar-%externally-checkable-type lvar)
(%lvar-%externally-checkable-type lvar)))
(defun %lvar-%externally-checkable-type (lvar)
(declare (type lvar lvar))
(let ((dest (lvar-dest lvar)))
(if (not (and dest (combination-p dest)))
;; TODO: MV-COMBINATION
(setf (lvar-%externally-checkable-type lvar) *wild-type*)
(let* ((fun (combination-fun dest))
(args (combination-args dest))
(fun-type (lvar-type fun)))
(setf (lvar-%externally-checkable-type fun) *wild-type*)
(if (or (not (call-full-like-p dest))
(not (fun-type-p fun-type))
;; FUN-TYPE might be (AND FUNCTION (SATISFIES ...)).
(fun-type-wild-args fun-type))
(dolist (arg args)
(when arg
(setf (lvar-%externally-checkable-type arg)
*wild-type*)))
(map-combination-args-and-types
(lambda (arg type)
(setf (lvar-%externally-checkable-type arg)
(acond ((lvar-%externally-checkable-type arg)
(values-type-intersection
it (coerce-to-values type)))
(t (coerce-to-values type)))))
dest)))))
(or (lvar-%externally-checkable-type lvar) *wild-type*))
#!-sb-fluid(declaim (inline flush-lvar-externally-checkable-type))
(defun flush-lvar-externally-checkable-type (lvar)
(declare (type lvar lvar))
(setf (lvar-%externally-checkable-type lvar) nil))
;;;; interface routines used by optimizers
(declaim (inline reoptimize-component))
(defun reoptimize-component (component kind)
(declare (type component component)
(type (member nil :maybe t) kind))
(aver kind)
(unless (eq (component-reoptimize component) t)
(setf (component-reoptimize component) kind)))
;;; This function is called by optimizers to indicate that something
interesting has happened to the value of LVAR . Optimizers must
;;; make sure that they don't call for reoptimization when nothing has
;;; happened, since optimization will fail to terminate.
;;;
We clear any cached type for the lvar and set the reoptimize flags
;;; on everything in sight.
(defun reoptimize-lvar (lvar)
(declare (type (or lvar null) lvar))
(when lvar
(setf (lvar-%derived-type lvar) nil)
(let ((dest (lvar-dest lvar)))
(when dest
(setf (lvar-reoptimize lvar) t)
(setf (node-reoptimize dest) t)
(binding* (;; Since this may be called during IR1 conversion,
;; PREV may be missing.
(prev (node-prev dest) :exit-if-null)
(block (ctran-block prev))
(component (block-component block)))
(when (typep dest 'cif)
(setf (block-test-modified block) t))
(setf (block-reoptimize block) t)
(reoptimize-component component :maybe))))
(do-uses (node lvar)
(setf (block-type-check (node-block node)) t)))
(values))
(defun reoptimize-lvar-uses (lvar)
(declare (type lvar lvar))
(do-uses (use lvar)
(setf (node-reoptimize use) t)
(setf (block-reoptimize (node-block use)) t)
(reoptimize-component (node-component use) :maybe)))
;;; Annotate NODE to indicate that its result has been proven to be
TYPEP to RTYPE . After IR1 conversion has happened , this is the
;;; only correct way to supply information discovered about a node's
;;; type. If you screw with the NODE-DERIVED-TYPE directly, then
;;; information may be lost and reoptimization may not happen.
;;;
What we do is intersect RTYPE with NODE 's DERIVED - TYPE . If the
;;; intersection is different from the old type, then we do a
REOPTIMIZE - LVAR on the NODE - LVAR .
(defun derive-node-type (node rtype)
(declare (type valued-node node) (type ctype rtype))
(let ((node-type (node-derived-type node)))
(unless (eq node-type rtype)
(let ((int (values-type-intersection node-type rtype))
(lvar (node-lvar node)))
(when (type/= node-type int)
(when (and *check-consistency*
(eq int *empty-type*)
(not (eq rtype *empty-type*)))
(let ((*compiler-error-context* node))
(compiler-warn
"New inferred type ~S conflicts with old type:~
~% ~S~%*** possible internal error? Please report this."
(type-specifier rtype) (type-specifier node-type))))
(setf (node-derived-type node) int)
If the new type consists of only one object , replace the
;; node with a constant reference.
(when (and (ref-p node)
(lambda-var-p (ref-leaf node)))
(let ((type (single-value-type int)))
(when (and (member-type-p type)
(eql 1 (member-type-size type)))
(change-ref-leaf node (find-constant
(first (member-type-members type)))))))
(reoptimize-lvar lvar)))))
(values))
;;; This is similar to DERIVE-NODE-TYPE, but asserts that it is an
error for LVAR 's value not to be TYPEP to TYPE . We implement it
splitting off DEST a new CAST node ; old LVAR will deliver values
to CAST . If we improve the assertion , we set TYPE - CHECK and
TYPE - ASSERTED to guarantee that the new assertion will be checked .
(defun assert-lvar-type (lvar type policy)
(declare (type lvar lvar) (type ctype type))
(unless (values-subtypep (lvar-derived-type lvar) type)
(let ((internal-lvar (make-lvar))
(dest (lvar-dest lvar)))
(substitute-lvar internal-lvar lvar)
(let ((cast (insert-cast-before dest lvar type policy)))
(use-lvar cast internal-lvar)
t))))
;;;; IR1-OPTIMIZE
Do one forward pass over COMPONENT , deleting unreachable blocks
;;; and doing IR1 optimizations. We can ignore all blocks that don't
;;; have the REOPTIMIZE flag set. If COMPONENT-REOPTIMIZE is true when
;;; we are done, then another iteration would be beneficial.
(defun ir1-optimize (component fastp)
(declare (type component component))
(setf (component-reoptimize component) nil)
(loop with block = (block-next (component-head component))
with tail = (component-tail component)
for last-block = block
until (eq block tail)
do (cond
;; We delete blocks when there is either no predecessor or the
;; block is in a lambda that has been deleted. These blocks
would eventually be deleted by DFO recomputation , but doing
;; it here immediately makes the effect available to IR1
;; optimization.
((or (block-delete-p block)
(null (block-pred block)))
(delete-block-lazily block)
(setq block (clean-component component block)))
((eq (functional-kind (block-home-lambda block)) :deleted)
;; Preserve the BLOCK-SUCC invariant that almost every block has
one successor ( and a block with DELETE - P set is an acceptable
;; exception).
(mark-for-deletion block)
(setq block (clean-component component block)))
(t
(loop
(let ((succ (block-succ block)))
(unless (singleton-p succ)
(return)))
(let ((last (block-last block)))
(typecase last
(cif
(flush-dest (if-test last))
(when (unlink-node last)
(return)))
(exit
(when (maybe-delete-exit last)
(return)))))
(unless (join-successor-if-possible block)
(return)))
(when (and (not fastp) (block-reoptimize block) (block-component block))
(aver (not (block-delete-p block)))
(ir1-optimize-block block))
(cond ((and (block-delete-p block) (block-component block))
(setq block (clean-component component block)))
((and (block-flush-p block) (block-component block))
(flush-dead-code block)))))
do (when (eq block last-block)
(setq block (block-next block))))
(values))
;;; Loop over the nodes in BLOCK, acting on (and clearing) REOPTIMIZE
;;; flags.
;;;
;;; Note that although they are cleared here, REOPTIMIZE flags might
;;; still be set upon return from this function, meaning that further
;;; optimization is wanted (as a consequence of optimizations we did).
(defun ir1-optimize-block (block)
(declare (type cblock block))
;; We clear the node and block REOPTIMIZE flags before doing the
;; optimization, not after. This ensures that the node or block will
;; be reoptimized if necessary.
(setf (block-reoptimize block) nil)
(do-nodes (node nil block :restart-p t)
(when (node-reoptimize node)
;; As above, we clear the node REOPTIMIZE flag before optimizing.
(setf (node-reoptimize node) nil)
(typecase node
(ref)
(combination
;; With a COMBINATION, we call PROPAGATE-FUN-CHANGE whenever
;; the function changes, and call IR1-OPTIMIZE-COMBINATION if
;; any argument changes.
(ir1-optimize-combination node))
(cif
(ir1-optimize-if node))
(creturn
: We leave the NODE - OPTIMIZE flag set going into
;; IR1-OPTIMIZE-RETURN, since IR1-OPTIMIZE-RETURN wants to
clear the flag itself . -- WHN 2002 - 02 - 02 , quoting original
CMU CL comments
(setf (node-reoptimize node) t)
(ir1-optimize-return node))
(mv-combination
(ir1-optimize-mv-combination node))
(exit
With an EXIT , we derive the node 's type from the VALUE 's
;; type.
(let ((value (exit-value node)))
(when value
(derive-node-type node (lvar-derived-type value)))))
(cset
PROPAGATE - FROM - SETS can do a better job if NODE - REOPTIMIZE
;; is accurate till the node actually has been reoptimized.
(setf (node-reoptimize node) t)
(ir1-optimize-set node))
(cast
(ir1-optimize-cast node)))))
(values))
;;; Try to join with a successor block. If we succeed, we return true,
;;; otherwise false.
(defun join-successor-if-possible (block)
(declare (type cblock block))
(let ((next (first (block-succ block))))
NEXT is not an END - OF - COMPONENT marker
(cond ( ;; We cannot combine with a successor block if:
(or
the successor has more than one predecessor ;
(rest (block-pred next))
;; the successor is the current block (infinite loop);
(eq next block)
;; the next block has a different cleanup, and thus
;; we may want to insert cleanup code between the
two blocks at some point ;
(not (eq (block-end-cleanup block)
(block-start-cleanup next)))
;; the next block has a different home lambda, and
;; thus the control transfer is a non-local exit.
(not (eq (block-home-lambda block)
(block-home-lambda next)))
Stack analysis phase wants ENTRY to start a block ...
(entry-p (block-start-node next))
(let ((last (block-last block)))
(and (valued-node-p last)
(awhen (node-lvar last)
(or
... and a DX - allocator to end a block .
(lvar-dynamic-extent it)
FIXME : This is a partial workaround for bug 303 .
(consp (lvar-uses it)))))))
nil)
(t
(join-blocks block next)
t)))))
Join together two blocks . The code in BLOCK2 is moved into BLOCK1
and BLOCK2 is deleted from the DFO . We combine the optimize flags
for the two blocks so that any indicated optimization gets done .
(defun join-blocks (block1 block2)
(declare (type cblock block1 block2))
(let* ((last1 (block-last block1))
(last2 (block-last block2))
(succ (block-succ block2))
(start2 (block-start block2)))
(do ((ctran start2 (node-next (ctran-next ctran))))
((not ctran))
(setf (ctran-block ctran) block1))
(unlink-blocks block1 block2)
(dolist (block succ)
(unlink-blocks block2 block)
(link-blocks block1 block))
(setf (ctran-kind start2) :inside-block)
(setf (node-next last1) start2)
(setf (ctran-use start2) last1)
(setf (block-last block1) last2))
(setf (block-flags block1)
(attributes-union (block-flags block1)
(block-flags block2)
(block-attributes type-asserted test-modified)))
(let ((next (block-next block2))
(prev (block-prev block2)))
(setf (block-next prev) next)
(setf (block-prev next) prev))
(values))
;;; Delete any nodes in BLOCK whose value is unused and which have no
;;; side effects. We can delete sets of lexical variables when the set
;;; variable has no references.
(defun flush-dead-code (block)
(declare (type cblock block))
(setf (block-flush-p block) nil)
(do-nodes-backwards (node lvar block :restart-p t)
(unless lvar
(typecase node
(ref
(delete-ref node)
(unlink-node node))
(combination
(when (flushable-combination-p node)
(flush-combination node)))
(mv-combination
(when (eq (basic-combination-kind node) :local)
(let ((fun (combination-lambda node)))
(when (dolist (var (lambda-vars fun) t)
(when (or (leaf-refs var)
(lambda-var-sets var))
(return nil)))
(flush-dest (first (basic-combination-args node)))
(delete-let fun)))))
(exit
(let ((value (exit-value node)))
(when value
(flush-dest value)
(setf (exit-value node) nil))))
(cset
(let ((var (set-var node)))
(when (and (lambda-var-p var)
(null (leaf-refs var)))
(flush-dest (set-value node))
(setf (basic-var-sets var)
(delq node (basic-var-sets var)))
(unlink-node node))))
(cast
(unless (cast-type-check node)
(flush-dest (cast-value node))
(unlink-node node))))))
(values))
;;;; local call return type propagation
;;; This function is called on RETURN nodes that have their REOPTIMIZE
;;; flag set. It iterates over the uses of the RESULT, looking for
;;; interesting stuff to update the TAIL-SET. If a use isn't a local
;;; call, then we union its type together with the types of other such
;;; uses. We assign to the RETURN-RESULT-TYPE the intersection of this
;;; type with the RESULT's asserted type. We can make this
;;; intersection now (potentially before type checking) because this
;;; assertion on the result will eventually be checked (if
;;; appropriate.)
;;;
;;; We call MAYBE-CONVERT-TAIL-LOCAL-CALL on each local non-MV
;;; combination, which may change the successor of the call to be the
;;; called function, and if so, checks if the call can become an
;;; assignment. If we convert to an assignment, we abort, since the
;;; RETURN has been deleted.
(defun find-result-type (node)
(declare (type creturn node))
(let ((result (return-result node)))
(collect ((use-union *empty-type* values-type-union))
(do-uses (use result)
(let ((use-home (node-home-lambda use)))
(cond ((or (eq (functional-kind use-home) :deleted)
(block-delete-p (node-block use))))
((and (basic-combination-p use)
(eq (basic-combination-kind use) :local))
(aver (eq (lambda-tail-set use-home)
(lambda-tail-set (combination-lambda use))))
(when (combination-p use)
(when (nth-value 1 (maybe-convert-tail-local-call use))
(return-from find-result-type t))))
(t
(use-union (node-derived-type use))))))
(let ((int
;; (values-type-intersection
( continuation - asserted - type result ) ; FIXME -- APD , 2002 - 01 - 26
(use-union)
;; )
))
(setf (return-result-type node) int))))
nil)
;;; Do stuff to realize that something has changed about the value
;;; delivered to a return node. Since we consider the return values of
;;; all functions in the tail set to be equivalent, this amounts to
;;; bringing the entire tail set up to date. We iterate over the
;;; returns for all the functions in the tail set, reanalyzing them
all ( not treating NODE specially . )
;;;
;;; When we are done, we check whether the new type is different from
;;; the old TAIL-SET-TYPE. If so, we set the type and also reoptimize
;;; all the lvars for references to functions in the tail set. This
;;; will cause IR1-OPTIMIZE-COMBINATION to derive the new type as the
;;; results of the calls.
(defun ir1-optimize-return (node)
(declare (type creturn node))
(tagbody
:restart
(let* ((tails (lambda-tail-set (return-lambda node)))
(funs (tail-set-funs tails)))
(collect ((res *empty-type* values-type-union))
(dolist (fun funs)
(let ((return (lambda-return fun)))
(when return
(when (node-reoptimize return)
(setf (node-reoptimize return) nil)
(when (find-result-type return)
(go :restart)))
(res (return-result-type return)))))
(when (type/= (res) (tail-set-type tails))
(setf (tail-set-type tails) (res))
(dolist (fun (tail-set-funs tails))
(dolist (ref (leaf-refs fun))
(reoptimize-lvar (node-lvar ref))))))))
(values))
;;;; IF optimization
;;; Utility: return T if both argument cblocks are equivalent. For now,
detect only blocks that read the same leaf into the same lvar , and
;;; continue to the same block.
(defun cblocks-equivalent-p (x y)
(declare (type cblock x y))
(and (ref-p (block-start-node x))
(eq (block-last x) (block-start-node x))
(ref-p (block-start-node y))
(eq (block-last y) (block-start-node y))
(equal (block-succ x) (block-succ y))
(eql (ref-lvar (block-start-node x)) (ref-lvar (block-start-node y)))
(eql (ref-leaf (block-start-node x)) (ref-leaf (block-start-node y)))))
;;; Check whether the predicate is known to be true or false,
;;; deleting the IF node in favor of the appropriate branch when this
;;; is the case.
;;; Similarly, when both branches are equivalent, branch directly to either
;;; of them.
;;; Also, if the test has multiple uses, replicate the node when possible.
(defun ir1-optimize-if (node)
(declare (type cif node))
(let ((test (if-test node))
(block (node-block node)))
(let* ((type (lvar-type test))
(consequent (if-consequent node))
(alternative (if-alternative node))
(victim
(cond ((constant-lvar-p test)
(if (lvar-value test) alternative consequent))
((not (types-equal-or-intersect type (specifier-type 'null)))
alternative)
((type= type (specifier-type 'null))
consequent)
((cblocks-equivalent-p alternative consequent)
alternative))))
(when victim
(flush-dest test)
(when (rest (block-succ block))
(unlink-blocks block victim))
(setf (component-reanalyze (node-component node)) t)
(unlink-node node)
(return-from ir1-optimize-if (values))))
(when (and (eq (block-start-node block) node)
(listp (lvar-uses test)))
(do-uses (use test)
(when (immediately-used-p test use)
(convert-if-if use node)
(when (not (listp (lvar-uses test))) (return))))))
(values))
;;; Create a new copy of an IF node that tests the value of the node
USE . The test must have > 1 use , and must be immediately used by
USE . NODE must be the only node in its block ( implying that
;;; block-start = if-test).
;;;
;;; This optimization has an effect semantically similar to the
;;; source-to-source transformation:
;;; (IF (IF A B C) D E) ==>
;;; (IF A (IF B D E) (IF C D E))
;;;
;;; We clobber the NODE-SOURCE-PATH of both the original and the new
;;; node so that dead code deletion notes will definitely not consider
either node to be part of the original source . One node might
;;; become unreachable, resulting in a spurious note.
(defun convert-if-if (use node)
(declare (type node use) (type cif node))
(with-ir1-environment-from-node node
(let* ((block (node-block node))
(test (if-test node))
(cblock (if-consequent node))
(ablock (if-alternative node))
(use-block (node-block use))
(new-ctran (make-ctran))
(new-lvar (make-lvar))
(new-node (make-if :test new-lvar
:consequent cblock
:alternative ablock))
(new-block (ctran-starts-block new-ctran)))
(link-node-to-previous-ctran new-node new-ctran)
(setf (lvar-dest new-lvar) new-node)
(setf (block-last new-block) new-node)
(unlink-blocks use-block block)
(%delete-lvar-use use)
(add-lvar-use use new-lvar)
(link-blocks use-block new-block)
(link-blocks new-block cblock)
(link-blocks new-block ablock)
(push "<IF Duplication>" (node-source-path node))
(push "<IF Duplication>" (node-source-path new-node))
(reoptimize-lvar test)
(reoptimize-lvar new-lvar)
(setf (component-reanalyze *current-component*) t)))
(values))
;;;; exit IR1 optimization
;;; This function attempts to delete an exit node, returning true if
;;; it deletes the block as a consequence:
;;; -- If the exit is degenerate (has no ENTRY), then we don't do
;;; anything, since there is nothing to be done.
;;; -- If the exit node and its ENTRY have the same home lambda then
;;; we know the exit is local, and can delete the exit. We change
uses of the Exit - Value to be uses of the original lvar ,
;;; then unlink the node. If the exit is to a TR context, then we
;;; must do MERGE-TAIL-SETS on any local calls which delivered
;;; their value to this exit.
;;; -- If there is no value (as in a GO), then we skip the value
;;; semantics.
;;;
;;; This function is also called by environment analysis, since it
;;; wants all exits to be optimized even if normal optimization was
;;; omitted.
(defun maybe-delete-exit (node)
(declare (type exit node))
(let ((value (exit-value node))
(entry (exit-entry node)))
(when (and entry
(eq (node-home-lambda node) (node-home-lambda entry)))
(setf (entry-exits entry) (delq node (entry-exits entry)))
(if value
(delete-filter node (node-lvar node) value)
(unlink-node node)))))
;;;; combination IR1 optimization
;;; Report as we try each transform?
#!+sb-show
(defvar *show-transforms-p* nil)
(defun check-important-result (node info)
(when (and (null (node-lvar node))
(ir1-attributep (fun-info-attributes info) important-result))
(let ((*compiler-error-context* node))
(compiler-style-warn
"The return value of ~A should not be discarded."
(lvar-fun-name (basic-combination-fun node))))))
;;; Do IR1 optimizations on a COMBINATION node.
(declaim (ftype (function (combination) (values)) ir1-optimize-combination))
(defun ir1-optimize-combination (node)
(when (lvar-reoptimize (basic-combination-fun node))
(propagate-fun-change node)
(maybe-terminate-block node nil))
(let ((args (basic-combination-args node))
(kind (basic-combination-kind node))
(info (basic-combination-fun-info node)))
(ecase kind
(:local
(let ((fun (combination-lambda node)))
(if (eq (functional-kind fun) :let)
(propagate-let-args node fun)
(propagate-local-call-args node fun))))
(:error
(dolist (arg args)
(when arg
(setf (lvar-reoptimize arg) nil))))
(:full
(dolist (arg args)
(when arg
(setf (lvar-reoptimize arg) nil)))
(cond (info
(check-important-result node info)
(let ((fun (fun-info-destroyed-constant-args info)))
(when fun
(let ((destroyed-constant-args (funcall fun args)))
(when destroyed-constant-args
(let ((*compiler-error-context* node))
(warn 'constant-modified
:fun-name (lvar-fun-name
(basic-combination-fun node)))
(setf (basic-combination-kind node) :error)
(return-from ir1-optimize-combination))))))
(let ((fun (fun-info-derive-type info)))
(when fun
(let ((res (funcall fun node)))
(when res
(derive-node-type node (coerce-to-values res))
(maybe-terminate-block node nil))))))
(t
;; Check against the DEFINED-TYPE unless TYPE is already good.
(let* ((fun (basic-combination-fun node))
(uses (lvar-uses fun))
(leaf (when (ref-p uses) (ref-leaf uses))))
(multiple-value-bind (type defined-type)
(if (global-var-p leaf)
(values (leaf-type leaf) (leaf-defined-type leaf))
(values nil nil))
(when (and (not (fun-type-p type)) (fun-type-p defined-type))
(validate-call-type node type leaf)))))))
(:known
(aver info)
(dolist (arg args)
(when arg
(setf (lvar-reoptimize arg) nil)))
(check-important-result node info)
(let ((fun (fun-info-destroyed-constant-args info)))
(when (and fun
;; If somebody is really sure that they want to modify
;; constants, let them.
(policy node (> check-constant-modification 0)))
(let ((destroyed-constant-args (funcall fun args)))
(when destroyed-constant-args
(let ((*compiler-error-context* node))
(warn 'constant-modified
:fun-name (lvar-fun-name
(basic-combination-fun node)))
(setf (basic-combination-kind node) :error)
(return-from ir1-optimize-combination))))))
(let ((attr (fun-info-attributes info)))
(when (and (ir1-attributep attr foldable)
: The next test could be made more sensitive ,
;; only suppressing constant-folding of functions with
;; CALL attributes when they're actually passed
;; function arguments. -- WHN 19990918
(not (ir1-attributep attr call))
(every #'constant-lvar-p args)
(node-lvar node))
(constant-fold-call node)
(return-from ir1-optimize-combination)))
(let ((fun (fun-info-derive-type info)))
(when fun
(let ((res (funcall fun node)))
(when res
(derive-node-type node (coerce-to-values res))
(maybe-terminate-block node nil)))))
(let ((fun (fun-info-optimizer info)))
(unless (and fun (funcall fun node))
First give the VM a peek at the call
(multiple-value-bind (style transform)
(combination-implementation-style node)
(ecase style
(:direct
;; The VM knows how to handle this.
)
(:transform
;; The VM mostly knows how to handle this. We need
;; to massage the call slightly, though.
(transform-call node transform (combination-fun-source-name node)))
(:default
;; Let transforms have a crack at it.
(dolist (x (fun-info-transforms info))
#!+sb-show
(when *show-transforms-p*
(let* ((lvar (basic-combination-fun node))
(fname (lvar-fun-name lvar t)))
(/show "trying transform" x (transform-function x) "for" fname)))
(unless (ir1-transform node x)
#!+sb-show
(when *show-transforms-p*
(/show "quitting because IR1-TRANSFORM result was NIL"))
(return)))))))))))
(values))
(defun xep-tail-combination-p (node)
(and (combination-p node)
(let* ((lvar (combination-lvar node))
(dest (when (lvar-p lvar) (lvar-dest lvar)))
(lambda (when (return-p dest) (return-lambda dest))))
(and (lambda-p lambda)
(eq :external (lambda-kind lambda))))))
If NODE does n't return ( i.e. return type is NIL ) , then terminate
;;; the block there, and link it to the component tail.
;;;
;;; Except when called during IR1 convertion, we delete the
;;; continuation if it has no other uses. (If it does have other uses,
;;; we reoptimize.)
;;;
;;; Termination on the basis of a continuation type is
;;; inhibited when:
;;; -- The continuation is deleted (hence the assertion is spurious), or
;;; -- We are in IR1 conversion (where THE assertions are subject to
;;; weakening.) FIXME: Now THE assertions are not weakened, but new
uses can ( ? ) be added later . -- APD , 2003 - 07 - 17
;;;
Why do we need to consider LVAR type ? -- APD , 2003 - 07 - 30
(defun maybe-terminate-block (node ir1-converting-not-optimizing-p)
(declare (type (or basic-combination cast ref) node))
(let* ((block (node-block node))
(lvar (node-lvar node))
(ctran (node-next node))
(tail (component-tail (block-component block)))
(succ (first (block-succ block))))
(declare (ignore lvar))
(unless (or (and (eq node (block-last block)) (eq succ tail))
(block-delete-p block))
;; Even if the combination will never return, don't terminate if this
;; is the tail call of a XEP: doing that would inhibit TCO.
(when (and (eq (node-derived-type node) *empty-type*)
(not (xep-tail-combination-p node)))
(cond (ir1-converting-not-optimizing-p
(cond
((block-last block)
(aver (eq (block-last block) node)))
(t
(setf (block-last block) node)
(setf (ctran-use ctran) nil)
(setf (ctran-kind ctran) :unused)
(setf (ctran-block ctran) nil)
(setf (node-next node) nil)
(link-blocks block (ctran-starts-block ctran)))))
(t
(node-ends-block node)))
(let ((succ (first (block-succ block))))
(unlink-blocks block succ)
(setf (component-reanalyze (block-component block)) t)
(aver (not (block-succ block)))
(link-blocks block tail)
(cond (ir1-converting-not-optimizing-p
(%delete-lvar-use node))
(t (delete-lvar-use node)
(when (null (block-pred succ))
(mark-for-deletion succ)))))
t))))
;;; This is called both by IR1 conversion and IR1 optimization when
;;; they have verified the type signature for the call, and are
;;; wondering if something should be done to special-case the call. If
;;; CALL is a call to a global function, then see whether it defined
;;; or known:
;;; -- If a DEFINED-FUN should be inline expanded, then convert
;;; the expansion and change the call to call it. Expansion is
;;; enabled if :INLINE or if SPACE=0. If the FUNCTIONAL slot is
;;; true, we never expand, since this function has already been
;;; converted. Local call analysis will duplicate the definition
;;; if necessary. We claim that the parent form is LABELS for
;;; context declarations, since we don't want it to be considered
;;; a real global function.
;;; -- If it is a known function, mark it as such by setting the KIND.
;;;
;;; We return the leaf referenced (NIL if not a leaf) and the
;;; FUN-INFO assigned.
(defun recognize-known-call (call ir1-converting-not-optimizing-p)
(declare (type combination call))
(let* ((ref (lvar-uses (basic-combination-fun call)))
(leaf (when (ref-p ref) (ref-leaf ref)))
(inlinep (if (defined-fun-p leaf)
(defined-fun-inlinep leaf)
:no-chance)))
(cond
((eq inlinep :notinline)
(let ((info (info :function :info (leaf-source-name leaf))))
(when info
(setf (basic-combination-fun-info call) info))
(values nil nil)))
((not (and (global-var-p leaf)
(eq (global-var-kind leaf) :global-function)))
(values leaf nil))
((and (ecase inlinep
(:inline t)
(:no-chance nil)
((nil :maybe-inline) (policy call (zerop space))))
(defined-fun-p leaf)
(defined-fun-inline-expansion leaf)
(inline-expansion-ok call))
;; Inline: if the function has already been converted at another call
site in this component , we point this REF to the functional . If not ,
;; we convert the expansion.
;;
;; For :INLINE case local call analysis will copy the expansion later,
but for : MAYBE - INLINE and NIL cases we only get one copy of the
;; expansion per component.
;;
FIXME : We also convert in : INLINE & FUNCTIONAL - KIND case below . What
;; is it for?
(flet ((frob ()
(let* ((name (leaf-source-name leaf))
(res (ir1-convert-inline-expansion
name
(defined-fun-inline-expansion leaf)
leaf
inlinep
(info :function :info name))))
;; Allow backward references to this function from following
;; forms. (Reused only if policy matches.)
(push res (defined-fun-functionals leaf))
(change-ref-leaf ref res))))
(let ((fun (defined-fun-functional leaf)))
(if (or (not fun)
(and (eq inlinep :inline) (functional-kind fun)))
;; Convert.
(if ir1-converting-not-optimizing-p
(frob)
(with-ir1-environment-from-node call
(frob)
(locall-analyze-component *current-component*)))
;; If we've already converted, change ref to the converted
;; functional.
(change-ref-leaf ref fun))))
(values (ref-leaf ref) nil))
(t
(let ((info (info :function :info (leaf-source-name leaf))))
(if info
(values leaf
(progn
(setf (basic-combination-kind call) :known)
(setf (basic-combination-fun-info call) info)))
(values leaf nil)))))))
;;; Check whether CALL satisfies TYPE. If so, apply the type to the
;;; call, and do MAYBE-TERMINATE-BLOCK and return the values of
;;; RECOGNIZE-KNOWN-CALL. If an error, set the combination kind and
return NIL , NIL . If the type is just FUNCTION , then skip the
;;; syntax check, arg/result type processing, but still call
;;; RECOGNIZE-KNOWN-CALL, since the call might be to a known lambda,
;;; and that checking is done by local call analysis.
(defun validate-call-type (call type fun &optional ir1-converting-not-optimizing-p)
(declare (type combination call) (type ctype type))
(let* ((where (when fun (leaf-where-from fun)))
(same-file-p (eq :defined-here where)))
(cond ((not (fun-type-p type))
(aver (multiple-value-bind (val win)
(csubtypep type (specifier-type 'function))
(or val (not win))))
;; Using the defined-type too early is a bit of a waste: during
conversion we can not use the untrusted ASSERT - CALL - TYPE , etc .
(when (and fun (not ir1-converting-not-optimizing-p))
(let ((defined-type (leaf-defined-type fun)))
(when (and (fun-type-p defined-type)
(neq fun (combination-type-validated-for-leaf call)))
;; Don't validate multiple times against the same leaf --
;; it doesn't add any information, but may generate the same warning
;; multiple times.
(setf (combination-type-validated-for-leaf call) fun)
(when (and (valid-fun-use call defined-type
:argument-test #'always-subtypep
:result-test nil
:lossage-fun (if same-file-p
#'compiler-warn
#'compiler-style-warn)
:unwinnage-fun #'compiler-notify)
same-file-p)
(assert-call-type call defined-type nil)
(maybe-terminate-block call ir1-converting-not-optimizing-p)))))
(recognize-known-call call ir1-converting-not-optimizing-p))
((valid-fun-use call type
:argument-test #'always-subtypep
:result-test nil
:lossage-fun #'compiler-warn
:unwinnage-fun #'compiler-notify)
(assert-call-type call type)
(maybe-terminate-block call ir1-converting-not-optimizing-p)
(recognize-known-call call ir1-converting-not-optimizing-p))
(t
(setf (combination-kind call) :error)
(values nil nil)))))
;;; This is called by IR1-OPTIMIZE when the function for a call has
;;; changed. If the call is local, we try to LET-convert it, and
;;; derive the result type. If it is a :FULL call, we validate it
;;; against the type, which recognizes known calls, does inline
;;; expansion, etc. If a call to a predicate in a non-conditional
;;; position or to a function with a source transform, then we
;;; reconvert the form to give IR1 another chance.
(defun propagate-fun-change (call)
(declare (type combination call))
(let ((*compiler-error-context* call)
(fun-lvar (basic-combination-fun call)))
(setf (lvar-reoptimize fun-lvar) nil)
(case (combination-kind call)
(:local
(let ((fun (combination-lambda call)))
(maybe-let-convert fun)
(unless (member (functional-kind fun) '(:let :assignment :deleted))
(derive-node-type call (tail-set-type (lambda-tail-set fun))))))
(:full
(multiple-value-bind (leaf info)
(let* ((uses (lvar-uses fun-lvar))
(leaf (when (ref-p uses) (ref-leaf uses))))
(validate-call-type call (lvar-type fun-lvar) leaf))
(cond ((functional-p leaf)
(convert-call-if-possible
(lvar-uses (basic-combination-fun call))
call))
((not leaf))
((and (global-var-p leaf)
(eq (global-var-kind leaf) :global-function)
(leaf-has-source-name-p leaf)
(or (info :function :source-transform (leaf-source-name leaf))
(and info
(ir1-attributep (fun-info-attributes info)
predicate)
(let ((lvar (node-lvar call)))
(and lvar (not (if-p (lvar-dest lvar))))))))
(let ((name (leaf-source-name leaf))
(dummies (make-gensym-list
(length (combination-args call)))))
(transform-call call
`(lambda ,dummies
(,@(if (symbolp name)
`(,name)
`(funcall #',name))
,@dummies))
(leaf-source-name leaf)))))))))
(values))
;;;; known function optimization
Add a failed optimization note to FAILED - OPTIMZATIONS for NODE ,
FUN and ARGS . If there is already a note for NODE and TRANSFORM ,
;;; replace it, otherwise add a new one.
(defun record-optimization-failure (node transform args)
(declare (type combination node) (type transform transform)
(type (or fun-type list) args))
(let* ((table (component-failed-optimizations *component-being-compiled*))
(found (assoc transform (gethash node table))))
(if found
(setf (cdr found) args)
(push (cons transform args) (gethash node table))))
(values))
Attempt to transform NODE using TRANSFORM - FUNCTION , subject to the
;;; call type constraint TRANSFORM-TYPE. If we are inhibited from
doing the transform for some reason and is true , then we
;;; make a note of the message in FAILED-OPTIMIZATIONS for IR1
;;; finalize to pick up. We return true if the transform failed, and
;;; thus further transformation should be attempted. We return false
;;; if either the transform succeeded or was aborted.
(defun ir1-transform (node transform)
(declare (type combination node) (type transform transform))
(let* ((type (transform-type transform))
(fun (transform-function transform))
(constrained (fun-type-p type))
(table (component-failed-optimizations *component-being-compiled*))
(flame (if (transform-important transform)
(policy node (>= speed inhibit-warnings))
(policy node (> speed inhibit-warnings))))
(*compiler-error-context* node))
(cond ((or (not constrained)
(valid-fun-use node type))
(multiple-value-bind (severity args)
(catch 'give-up-ir1-transform
(transform-call node
(funcall fun node)
(combination-fun-source-name node))
(values :none nil))
(ecase severity
(:none
(remhash node table)
nil)
(:aborted
(setf (combination-kind node) :error)
(when args
(apply #'warn args))
(remhash node table)
nil)
(:failure
(if args
(when flame
(record-optimization-failure node transform args))
(setf (gethash node table)
(remove transform (gethash node table) :key #'car)))
t)
(:delayed
(remhash node table)
nil))))
((and flame
(valid-fun-use node
type
:argument-test #'types-equal-or-intersect
:result-test #'values-types-equal-or-intersect))
(record-optimization-failure node transform type)
t)
(t
t))))
;;; When we don't like an IR1 transform, we throw the severity/reason
;;; and args.
;;;
;;; GIVE-UP-IR1-TRANSFORM is used to throw out of an IR1 transform,
;;; aborting this attempt to transform the call, but admitting the
;;; possibility that this or some other transform will later succeed.
;;; If arguments are supplied, they are format arguments for an
;;; efficiency note.
;;;
;;; ABORT-IR1-TRANSFORM is used to throw out of an IR1 transform and
;;; force a normal call to the function at run time. No further
;;; optimizations will be attempted.
;;;
;;; DELAY-IR1-TRANSFORM is used to throw out of an IR1 transform, and
;;; delay the transform on the node until later. REASONS specifies
;;; when the transform will be later retried. The :OPTIMIZE reason
;;; causes the transform to be delayed until after the current IR1
optimization pass . The : CONSTRAINT reason causes the transform to
;;; be delayed until after constraint propagation.
;;;
FIXME : Now ( 0.6.11.44 ) that there are 4 variants of this ( GIVE - UP ,
ABORT , DELAY/:OPTIMIZE , ) and we 're starting to
do CASE operations on the various REASON values , it might be a
good idea to go OO , representing the reasons by objects , using
CLOS methods on the objects instead of CASE , and ( possibly ) using
SIGNAL instead of THROW .
(declaim (ftype (function (&rest t) nil) give-up-ir1-transform))
(defun give-up-ir1-transform (&rest args)
(throw 'give-up-ir1-transform (values :failure args)))
(defun abort-ir1-transform (&rest args)
(throw 'give-up-ir1-transform (values :aborted args)))
(defun delay-ir1-transform (node &rest reasons)
(let ((assoc (assoc node *delayed-ir1-transforms*)))
(cond ((not assoc)
(setf *delayed-ir1-transforms*
(acons node reasons *delayed-ir1-transforms*))
(throw 'give-up-ir1-transform :delayed))
((cdr assoc)
(dolist (reason reasons)
(pushnew reason (cdr assoc)))
(throw 'give-up-ir1-transform :delayed)))))
;;; Clear any delayed transform with no reasons - these should have
;;; been tried in the last pass. Then remove the reason from the
;;; delayed transform reasons, and if any become empty then set
;;; reoptimize flags for the node. Return true if any transforms are
;;; to be retried.
(defun retry-delayed-ir1-transforms (reason)
(setf *delayed-ir1-transforms*
(remove-if-not #'cdr *delayed-ir1-transforms*))
(let ((reoptimize nil))
(dolist (assoc *delayed-ir1-transforms*)
(let ((reasons (remove reason (cdr assoc))))
(setf (cdr assoc) reasons)
(unless reasons
(let ((node (car assoc)))
(unless (node-deleted node)
(setf reoptimize t)
(setf (node-reoptimize node) t)
(let ((block (node-block node)))
(setf (block-reoptimize block) t)
(reoptimize-component (block-component block) :maybe)))))))
reoptimize))
Take the lambda - expression RES , IR1 convert it in the proper
;;; environment, and then install it as the function for the call
NODE . We do local call analysis so that the new function is
;;; integrated into the control flow.
;;;
;;; We require the original function source name in order to generate
;;; a meaningful debug name for the lambda we set up. (It'd be
;;; possible to do this starting from debug names as well as source
names , but as of sbcl-0.7.1.5 , there was no need for this
;;; generality, since source names are always known to our callers.)
(defun transform-call (call res source-name)
(declare (type combination call) (list res))
(aver (and (legal-fun-name-p source-name)
(not (eql source-name '.anonymous.))))
(node-ends-block call)
;; The internal variables of a transform are not going to be
;; interesting to the debugger, so there's no sense in
suppressing the substitution of variables with only one use
;; (the extra variables can slow down constraint propagation).
;;
;; This needs to be done before the WITH-IR1-ENVIRONMENT-FROM-NODE,
;; so that it will bind *LEXENV* to the right environment.
(setf (combination-lexenv call)
(make-lexenv :default (combination-lexenv call)
:policy (process-optimize-decl
'(optimize
(preserve-single-use-debug-variables 0))
(lexenv-policy
(combination-lexenv call)))))
(with-ir1-environment-from-node call
(with-component-last-block (*current-component*
(block-next (node-block call)))
(let ((new-fun (ir1-convert-inline-lambda
res
:debug-name (debug-name 'lambda-inlined source-name)
:system-lambda t))
(ref (lvar-use (combination-fun call))))
(change-ref-leaf ref new-fun)
(setf (combination-kind call) :full)
(locall-analyze-component *current-component*))))
(values))
;;; Replace a call to a foldable function of constant arguments with
;;; the result of evaluating the form. If there is an error during the
;;; evaluation, we give a warning and leave the call alone, making the
;;; call a :ERROR call.
;;;
If there is more than one value , then we transform the call into a
;;; VALUES form.
(defun constant-fold-call (call)
(let ((args (mapcar #'lvar-value (combination-args call)))
(fun-name (combination-fun-source-name call)))
(multiple-value-bind (values win)
(careful-call fun-name
args
call
Note : CMU CL had COMPILER - WARN here , and that
;; seems more natural, but it's probably not.
;;
It 's especially not while bug 173 exists :
;; Expressions like
;; (COND (END
;; (UNLESS (OR UNSAFE? (<= END SIZE)))
;; ...))
;; can cause constant-folding TYPE-ERRORs (in
;; #'<=) when END can be proved to be NIL, even
;; though the code is perfectly legal and safe
;; because a NIL value of END means that the
;; #'<= will never be executed.
;;
Moreover , even without bug 173 ,
;; quite-possibly-valid code like
;; (COND ((NONINLINED-PREDICATE END)
;; (UNLESS (<= END SIZE))
;; ...))
;; (where NONINLINED-PREDICATE is something the
;; compiler can't do at compile time, but which
;; turns out to make the #'<= expression
;; unreachable when END=NIL) could cause errors
;; when the compiler tries to constant-fold (<=
;; END SIZE).
;;
So , with or without bug 173 , it 'd be
;; unnecessarily evil to do a full
COMPILER - WARNING ( and thus return FAILURE - P = T
from COMPILE - FILE ) for legal code , so we we
use a wimpier COMPILE - STYLE - WARNING instead .
#-sb-xc-host #'compiler-style-warn
;; On the other hand, for code we control, we
;; should be able to work around any bug
173 - related problems , and in particular we
;; want to be alerted to calls to our own
;; functions which aren't being folded away; a
COMPILER - WARNING is butch enough to stop the
SBCL build itself in its tracks .
#+sb-xc-host #'compiler-warn
"constant folding")
(cond ((not win)
(setf (combination-kind call) :error))
((and (proper-list-of-length-p values 1))
(with-ir1-environment-from-node call
(let* ((lvar (node-lvar call))
(prev (node-prev call))
(intermediate-ctran (make-ctran)))
(%delete-lvar-use call)
(setf (ctran-next prev) nil)
(setf (node-prev call) nil)
(reference-constant prev intermediate-ctran lvar
(first values))
(link-node-to-previous-ctran call intermediate-ctran)
(reoptimize-lvar lvar)
(flush-combination call))))
(t (let ((dummies (make-gensym-list (length args))))
(transform-call
call
`(lambda ,dummies
(declare (ignore ,@dummies))
(values ,@(mapcar (lambda (x) `',x) values)))
fun-name))))))
(values))
;;;; local call optimization
Propagate TYPE to LEAF and its REFS , marking things changed .
;;;
;;; If the leaf type is a function type, then just leave it alone, since TYPE
;;; is never going to be more specific than that (and TYPE-INTERSECTION would
;;; choke.)
;;;
;;; Also, if the type is one requiring special care don't touch it if the leaf
has multiple references -- otherwise LVAR - CONSERVATIVE - TYPE is screwed .
(defun propagate-to-refs (leaf type)
(declare (type leaf leaf) (type ctype type))
(let ((var-type (leaf-type leaf))
(refs (leaf-refs leaf)))
(unless (or (fun-type-p var-type)
(and (cdr refs)
(eq :declared (leaf-where-from leaf))
(type-needs-conservation-p var-type)))
(let ((int (type-approx-intersection2 var-type type)))
(when (type/= int var-type)
(setf (leaf-type leaf) int)
(let ((s-int (make-single-value-type int)))
(dolist (ref refs)
(derive-node-type ref s-int)
: LET var substitution
(let* ((lvar (node-lvar ref)))
(when (and lvar (combination-p (lvar-dest lvar)))
(reoptimize-lvar lvar)))))))
(values))))
Iteration variable : exactly one SETQ of the form :
;;;
;;; (let ((var initial))
;;; ...
;;; (setq var (+ var step))
;;; ...)
(defun maybe-infer-iteration-var-type (var initial-type)
(binding* ((sets (lambda-var-sets var) :exit-if-null)
(set (first sets))
(() (null (rest sets)) :exit-if-null)
(set-use (principal-lvar-use (set-value set)))
(() (and (combination-p set-use)
(eq (combination-kind set-use) :known)
(fun-info-p (combination-fun-info set-use))
(not (node-to-be-deleted-p set-use))
(or (eq (combination-fun-source-name set-use) '+)
(eq (combination-fun-source-name set-use) '-)))
:exit-if-null)
(minusp (eq (combination-fun-source-name set-use) '-))
(+-args (basic-combination-args set-use))
(() (and (proper-list-of-length-p +-args 2 2)
(let ((first (principal-lvar-use
(first +-args))))
(and (ref-p first)
(eq (ref-leaf first) var))))
:exit-if-null)
(step-type (lvar-type (second +-args)))
(set-type (lvar-type (set-value set))))
(when (and (numeric-type-p initial-type)
(numeric-type-p step-type)
(or (numeric-type-equal initial-type step-type)
Detect cases like ( LOOP FOR 1.0 to 5.0 ... ) , where
;; the initial and the step are of different types,
;; and the step is less contagious.
(numeric-type-equal initial-type
(numeric-contagion initial-type
step-type))))
(labels ((leftmost (x y cmp cmp=)
(cond ((eq x nil) nil)
((eq y nil) nil)
((listp x)
(let ((x1 (first x)))
(cond ((listp y)
(let ((y1 (first y)))
(if (funcall cmp x1 y1) x y)))
(t
(if (funcall cmp x1 y) x y)))))
((listp y)
(let ((y1 (first y)))
(if (funcall cmp= x y1) x y)))
(t (if (funcall cmp x y) x y))))
(max* (x y) (leftmost x y #'> #'>=))
(min* (x y) (leftmost x y #'< #'<=)))
(multiple-value-bind (low high)
(let ((step-type-non-negative (csubtypep step-type (specifier-type
'(real 0 *))))
(step-type-non-positive (csubtypep step-type (specifier-type
'(real * 0)))))
(cond ((or (and step-type-non-negative (not minusp))
(and step-type-non-positive minusp))
(values (numeric-type-low initial-type)
(when (and (numeric-type-p set-type)
(numeric-type-equal set-type initial-type))
(max* (numeric-type-high initial-type)
(numeric-type-high set-type)))))
((or (and step-type-non-positive (not minusp))
(and step-type-non-negative minusp))
(values (when (and (numeric-type-p set-type)
(numeric-type-equal set-type initial-type))
(min* (numeric-type-low initial-type)
(numeric-type-low set-type)))
(numeric-type-high initial-type)))
(t
(values nil nil))))
(modified-numeric-type initial-type
:low low
:high high
:enumerable nil))))))
(deftransform + ((x y) * * :result result)
"check for iteration variable reoptimization"
(let ((dest (principal-lvar-end result))
(use (principal-lvar-use x)))
(when (and (ref-p use)
(set-p dest)
(eq (ref-leaf use)
(set-var dest)))
(reoptimize-lvar (set-value dest))))
(give-up-ir1-transform))
;;; Figure out the type of a LET variable that has sets. We compute
;;; the union of the INITIAL-TYPE and the types of all the set
;;; values and to a PROPAGATE-TO-REFS with this type.
(defun propagate-from-sets (var initial-type)
(let ((changes (not (csubtypep (lambda-var-last-initial-type var) initial-type)))
(types nil))
(dolist (set (lambda-var-sets var))
(let ((type (lvar-type (set-value set))))
(push type types)
(when (node-reoptimize set)
(let ((old-type (node-derived-type set)))
(unless (values-subtypep old-type type)
(derive-node-type set (make-single-value-type type))
(setf changes t)))
(setf (node-reoptimize set) nil))))
(when changes
(setf (lambda-var-last-initial-type var) initial-type)
(let ((res-type (or (maybe-infer-iteration-var-type var initial-type)
(apply #'type-union initial-type types))))
(propagate-to-refs var res-type))))
(values))
;;; If a LET variable, find the initial value's type and do
PROPAGATE - FROM - SETS . We also derive the VALUE 's type as the node 's
;;; type.
(defun ir1-optimize-set (node)
(declare (type cset node))
(let ((var (set-var node)))
(when (and (lambda-var-p var) (leaf-refs var))
(let ((home (lambda-var-home var)))
(when (eq (functional-kind home) :let)
(let* ((initial-value (let-var-initial-value var))
(initial-type (lvar-type initial-value)))
(setf (lvar-reoptimize initial-value) nil)
(propagate-from-sets var initial-type))))))
(derive-node-type node (make-single-value-type
(lvar-type (set-value node))))
(setf (node-reoptimize node) nil)
(values))
Return true if the value of REF will always be the same ( and is
;;; thus legal to substitute.)
(defun constant-reference-p (ref)
(declare (type ref ref))
(let ((leaf (ref-leaf ref)))
(typecase leaf
((or constant functional) t)
(lambda-var
(null (lambda-var-sets leaf)))
(defined-fun
(not (eq (defined-fun-inlinep leaf) :notinline)))
(global-var
(case (global-var-kind leaf)
(:global-function
(let ((name (leaf-source-name leaf)))
(or #-sb-xc-host
(eq (symbol-package (fun-name-block-name name))
*cl-package*)
(info :function :info name)))))))))
;;; If we have a non-set LET var with a single use, then (if possible)
replace the variable reference 's LVAR with the arg lvar .
;;;
We change the REF to be a reference to NIL with unused value , and
;;; let it be flushed as dead code. A side effect of this substitution
;;; is to delete the variable.
(defun substitute-single-use-lvar (arg var)
(declare (type lvar arg) (type lambda-var var))
(binding* ((ref (first (leaf-refs var)))
(lvar (node-lvar ref) :exit-if-null)
(dest (lvar-dest lvar))
(dest-lvar (when (valued-node-p dest) (node-lvar dest))))
(when (and
Think about ( LET ( ( A ... ) ) ( IF ... A ... ) ): two
LVAR - USEs should not be met on one path . Another problem
;; is with dynamic-extent.
(eq (lvar-uses lvar) ref)
(not (block-delete-p (node-block ref)))
;; If the destinatation is dynamic extent, don't substitute unless
;; the source is as well.
(or (not dest-lvar)
(not (lvar-dynamic-extent dest-lvar))
(lvar-dynamic-extent lvar))
(typecase dest
;; we should not change lifetime of unknown values lvars
(cast
(and (type-single-value-p (lvar-derived-type arg))
(multiple-value-bind (pdest pprev)
(principal-lvar-end lvar)
(declare (ignore pdest))
(lvar-single-value-p pprev))))
(mv-combination
(or (eq (basic-combination-fun dest) lvar)
(and (eq (basic-combination-kind dest) :local)
(type-single-value-p (lvar-derived-type arg)))))
((or creturn exit)
While CRETURN and EXIT nodes may be known - values ,
;; they have their own complications, such as
substitution into CRETURN may create new tail calls .
nil)
(t
(aver (lvar-single-value-p lvar))
t))
(eq (node-home-lambda ref)
(lambda-home (lambda-var-home var))))
(let ((ref-type (single-value-type (node-derived-type ref))))
(cond ((csubtypep (single-value-type (lvar-type arg)) ref-type)
(substitute-lvar-uses lvar arg
Really it is ( EQ ( LVAR - USES LVAR ) REF ):
t)
(delete-lvar-use ref))
(t
(let* ((value (make-lvar))
(cast (insert-cast-before ref value ref-type
: it should be ( TYPE - CHECK 0 )
*policy*)))
(setf (cast-type-to-check cast) *wild-type*)
(substitute-lvar-uses value arg
FIXME
t)
(%delete-lvar-use ref)
(add-lvar-use cast lvar)))))
(setf (node-derived-type ref) *wild-type*)
(change-ref-leaf ref (find-constant nil))
(delete-ref ref)
(unlink-node ref)
(reoptimize-lvar lvar)
t)))
;;; Delete a LET, removing the call and bind nodes, and warning about
;;; any unreferenced variables. Note that FLUSH-DEAD-CODE will come
along right away and delete the REF and then the lambda , since we
;;; flush the FUN lvar.
(defun delete-let (clambda)
(declare (type clambda clambda))
(aver (functional-letlike-p clambda))
(note-unreferenced-vars clambda)
(let ((call (let-combination clambda)))
(flush-dest (basic-combination-fun call))
(unlink-node call)
(unlink-node (lambda-bind clambda))
(setf (lambda-bind clambda) nil))
(setf (functional-kind clambda) :zombie)
(let ((home (lambda-home clambda)))
(setf (lambda-lets home) (delete clambda (lambda-lets home))))
(values))
This function is called when one of the arguments to a LET
;;; changes. We look at each changed argument. If the corresponding
;;; variable is set, then we call PROPAGATE-FROM-SETS. Otherwise, we
;;; consider substituting for the variable, and also propagate
derived - type information for the arg to all the VAR 's refs .
;;;
;;; Substitution is inhibited when the arg leaf's derived type isn't a
;;; subtype of the argument's leaf type. This prevents type checking
;;; from being defeated, and also ensures that the best representation
;;; for the variable can be used.
;;;
;;; Substitution of individual references is inhibited if the
;;; reference is in a different component from the home. This can only
;;; happen with closures over top level lambda vars. In such cases,
;;; the references may have already been compiled, and thus can't be
;;; retroactively modified.
;;;
;;; If all of the variables are deleted (have no references) when we
are done , then we delete the LET .
;;;
Note that we are responsible for clearing the LVAR - REOPTIMIZE
;;; flags.
(defun propagate-let-args (call fun)
(declare (type combination call) (type clambda fun))
(loop for arg in (combination-args call)
and var in (lambda-vars fun) do
(when (and arg (lvar-reoptimize arg))
(setf (lvar-reoptimize arg) nil)
(cond
((lambda-var-sets var)
(propagate-from-sets var (lvar-type arg)))
((let ((use (lvar-uses arg)))
(when (ref-p use)
(let ((leaf (ref-leaf use)))
(when (and (constant-reference-p use)
(csubtypep (leaf-type leaf)
;; (NODE-DERIVED-TYPE USE) would
be better -- APD , 2003 - 05 - 15
(leaf-type var)))
(propagate-to-refs var (lvar-type arg))
(let ((use-component (node-component use)))
(prog1 (substitute-leaf-if
(lambda (ref)
(cond ((eq (node-component ref) use-component)
t)
(t
(aver (lambda-toplevelish-p (lambda-home fun)))
nil)))
leaf var)))
t)))))
((and (null (rest (leaf-refs var)))
(not (preserve-single-use-debug-var-p call var))
(substitute-single-use-lvar arg var)))
(t
(propagate-to-refs var (lvar-type arg))))))
(when (every #'not (combination-args call))
(delete-let fun))
(values))
This function is called when one of the args to a non - LET local
;;; call changes. For each changed argument corresponding to an unset
;;; variable, we compute the union of the types across all calls and
;;; propagate this type information to the var's refs.
;;;
;;; If the function has an entry-fun, then we don't do anything: since
;;; it has a XEP we would not discover anything.
;;;
;;; If the function is an optional-entry-point, we will just make sure
;;; &REST lists are known to be lists. Doing the regular rigamarole
;;; can erronously propagate too strict types into refs: see
BUG-655203 - REGRESSION in tests / compiler.pure.lisp .
;;;
We can clear the LVAR - REOPTIMIZE flags for arguments in all calls
;;; corresponding to changed arguments in CALL, since the only use in
;;; IR1 optimization of the REOPTIMIZE flag for local call args is
;;; right here.
(defun propagate-local-call-args (call fun)
(declare (type combination call) (type clambda fun))
(unless (functional-entry-fun fun)
(if (lambda-optional-dispatch fun)
;; We can still make sure &REST is known to be a list.
(loop for var in (lambda-vars fun)
do (let ((info (lambda-var-arg-info var)))
(when (and info (eq :rest (arg-info-kind info)))
(propagate-from-sets var (specifier-type 'list)))))
;; The normal case.
(let* ((vars (lambda-vars fun))
(union (mapcar (lambda (arg var)
(when (and arg
(lvar-reoptimize arg)
(null (basic-var-sets var)))
(lvar-type arg)))
(basic-combination-args call)
vars))
(this-ref (lvar-use (basic-combination-fun call))))
(dolist (arg (basic-combination-args call))
(when arg
(setf (lvar-reoptimize arg) nil)))
(dolist (ref (leaf-refs fun))
(let ((dest (node-dest ref)))
(unless (or (eq ref this-ref) (not dest))
(setq union
(mapcar (lambda (this-arg old)
(when old
(setf (lvar-reoptimize this-arg) nil)
(type-union (lvar-type this-arg) old)))
(basic-combination-args dest)
union)))))
(loop for var in vars
and type in union
when type do (propagate-to-refs var type)))))
(values))
;;;; multiple values optimization
;;; Do stuff to notice a change to a MV combination node. There are
two main branches here :
;;; -- If the call is local, then it is already a MV let, or should
;;; become one. Note that although all :LOCAL MV calls must eventually
be converted to : MV - LETs , there can be a window when the call
;;; is local, but has not been LET converted yet. This is because
;;; the entry-point lambdas may have stray references (in other
;;; entry points) that have not been deleted yet.
;;; -- The call is full. This case is somewhat similar to the non-MV
;;; combination optimization: we propagate return type information and
;;; notice non-returning calls. We also have an optimization
which tries to convert MV - CALLs into MV - binds .
(defun ir1-optimize-mv-combination (node)
(ecase (basic-combination-kind node)
(:local
(let ((fun-lvar (basic-combination-fun node)))
(when (lvar-reoptimize fun-lvar)
(setf (lvar-reoptimize fun-lvar) nil)
(maybe-let-convert (combination-lambda node))))
(setf (lvar-reoptimize (first (basic-combination-args node))) nil)
(when (eq (functional-kind (combination-lambda node)) :mv-let)
(unless (convert-mv-bind-to-let node)
(ir1-optimize-mv-bind node))))
(:full
(let* ((fun (basic-combination-fun node))
(fun-changed (lvar-reoptimize fun))
(args (basic-combination-args node)))
(when fun-changed
(setf (lvar-reoptimize fun) nil)
(let ((type (lvar-type fun)))
(when (fun-type-p type)
(derive-node-type node (fun-type-returns type))))
(maybe-terminate-block node nil)
(let ((use (lvar-uses fun)))
(when (and (ref-p use) (functional-p (ref-leaf use)))
(convert-call-if-possible use node)
(when (eq (basic-combination-kind node) :local)
(maybe-let-convert (ref-leaf use))))))
(unless (or (eq (basic-combination-kind node) :local)
(eq (lvar-fun-name fun) '%throw))
(ir1-optimize-mv-call node))
(dolist (arg args)
(setf (lvar-reoptimize arg) nil))))
(:error))
(values))
Propagate derived type info from the values lvar to the vars .
(defun ir1-optimize-mv-bind (node)
(declare (type mv-combination node))
(let* ((arg (first (basic-combination-args node)))
(vars (lambda-vars (combination-lambda node)))
(n-vars (length vars))
(types (values-type-in (lvar-derived-type arg)
n-vars)))
(loop for var in vars
and type in types
do (if (basic-var-sets var)
(propagate-from-sets var type)
(propagate-to-refs var type)))
(setf (lvar-reoptimize arg) nil))
(values))
If possible , convert a general MV call to an MV - BIND . We can do
;;; this if:
-- The call has only one argument , and
;;; -- The function has a known fixed number of arguments, or
;;; -- The argument yields a known fixed number of values.
;;;
;;; What we do is change the function in the MV-CALL to be a lambda
that " looks like an MV bind " , which allows
;;; IR1-OPTIMIZE-MV-COMBINATION to notice that this call can be
;;; converted (the next time around.) This new lambda just calls the
actual function with the MV - BIND variables as arguments . Note that
this new MV bind is not let - converted immediately , as there are
;;; going to be stray references from the entry-point functions until
;;; they get deleted.
;;;
;;; In order to avoid loss of argument count checking, we only do the
;;; transformation according to a known number of expected argument if
;;; safety is unimportant. We can always convert if we know the number
;;; of actual values, since the normal call that we build will still
;;; do any appropriate argument count checking.
;;;
;;; We only attempt the transformation if the called function is a
;;; constant reference. This allows us to just splice the leaf into
;;; the new function, instead of trying to somehow bind the function
;;; expression. The leaf must be constant because we are evaluating it
;;; again in a different place. This also has the effect of squelching
;;; multiple warnings when there is an argument count error.
(defun ir1-optimize-mv-call (node)
(let ((fun (basic-combination-fun node))
(*compiler-error-context* node)
(ref (lvar-uses (basic-combination-fun node)))
(args (basic-combination-args node)))
(unless (and (ref-p ref) (constant-reference-p ref)
(singleton-p args))
(return-from ir1-optimize-mv-call))
(multiple-value-bind (min max)
(fun-type-nargs (lvar-type fun))
(let ((total-nvals
(multiple-value-bind (types nvals)
(values-types (lvar-derived-type (first args)))
(declare (ignore types))
(if (eq nvals :unknown) nil nvals))))
(when total-nvals
(when (and min (< total-nvals min))
(compiler-warn
"MULTIPLE-VALUE-CALL with ~R values when the function expects ~
at least ~R."
total-nvals min)
(setf (basic-combination-kind node) :error)
(return-from ir1-optimize-mv-call))
(when (and max (> total-nvals max))
(compiler-warn
"MULTIPLE-VALUE-CALL with ~R values when the function expects ~
at most ~R."
total-nvals max)
(setf (basic-combination-kind node) :error)
(return-from ir1-optimize-mv-call)))
(let ((count (cond (total-nvals)
((and (policy node (zerop verify-arg-count))
(eql min max))
min)
(t nil))))
(when count
(with-ir1-environment-from-node node
(let* ((dums (make-gensym-list count))
(ignore (gensym))
(leaf (ref-leaf ref))
(fun (ir1-convert-lambda
`(lambda (&optional ,@dums &rest ,ignore)
(declare (ignore ,ignore))
(%funcall ,leaf ,@dums))
:source-name (leaf-%source-name leaf)
:debug-name (leaf-%debug-name leaf))))
(change-ref-leaf ref fun)
(aver (eq (basic-combination-kind node) :full))
(locall-analyze-component *current-component*)
(aver (eq (basic-combination-kind node) :local)))))))))
(values))
;;; If we see:
;;; (multiple-value-bind
;;; (x y)
( values )
;;; ...)
;;; Convert to:
;;; (let ((x xx)
;;; (y yy))
;;; ...)
;;;
;;; What we actually do is convert the VALUES combination into a
normal LET combination calling the original : MV - LET lambda . If
;;; there are extra args to VALUES, discard the corresponding
lvars . If there are insufficient args , insert references to NIL .
(defun convert-mv-bind-to-let (call)
(declare (type mv-combination call))
(let* ((arg (first (basic-combination-args call)))
(use (lvar-uses arg)))
(when (and (combination-p use)
(eq (lvar-fun-name (combination-fun use))
'values))
(let* ((fun (combination-lambda call))
(vars (lambda-vars fun))
(vals (combination-args use))
(nvars (length vars))
(nvals (length vals)))
(cond ((> nvals nvars)
(mapc #'flush-dest (subseq vals nvars))
(setq vals (subseq vals 0 nvars)))
((< nvals nvars)
(with-ir1-environment-from-node use
(let ((node-prev (node-prev use)))
(setf (node-prev use) nil)
(setf (ctran-next node-prev) nil)
(collect ((res vals))
(loop for count below (- nvars nvals)
for prev = node-prev then ctran
for ctran = (make-ctran)
and lvar = (make-lvar use)
do (reference-constant prev ctran lvar nil)
(res lvar)
finally (link-node-to-previous-ctran
use ctran))
(setq vals (res)))))))
(setf (combination-args use) vals)
(flush-dest (combination-fun use))
(let ((fun-lvar (basic-combination-fun call)))
(setf (lvar-dest fun-lvar) use)
(setf (combination-fun use) fun-lvar)
(flush-lvar-externally-checkable-type fun-lvar))
(setf (combination-kind use) :local)
(setf (functional-kind fun) :let)
(flush-dest (first (basic-combination-args call)))
(unlink-node call)
(when vals
(reoptimize-lvar (first vals)))
;; Propagate derived types from the VALUES call to its args:
;; transforms can leave the VALUES call with a better type
;; than its args have, so make sure not to throw that away.
(let ((types (values-type-types (node-derived-type use))))
(dolist (val vals)
(when types
(let ((type (pop types)))
(assert-lvar-type val type '((type-check . 0)))))))
Propagate declared types of MV - BIND variables .
(propagate-to-args use fun)
(reoptimize-call use))
t)))
;;; If we see:
;;; (values-list (list x y z))
;;;
;;; Convert to:
;;; (values x y z)
;;;
;;; In implementation, this is somewhat similar to
CONVERT - MV - BIND - TO - LET . We grab the args of LIST and make them
args of the VALUES - LIST call , flushing the old argument
;;; (allowing the LIST to be flushed.)
;;;
;;; FIXME: Thus we lose possible type assertions on (LIST ...).
(defoptimizer (values-list optimizer) ((list) node)
(let ((use (lvar-uses list)))
(when (and (combination-p use)
(eq (lvar-fun-name (combination-fun use))
'list))
FIXME : VALUES might not satisfy an assertion on NODE - LVAR .
(change-ref-leaf (lvar-uses (combination-fun node))
(find-free-fun 'values "in a strange place"))
(setf (combination-kind node) :full)
(let ((args (combination-args use)))
(dolist (arg args)
(setf (lvar-dest arg) node)
(flush-lvar-externally-checkable-type arg))
(setf (combination-args use) nil)
(flush-dest list)
(setf (combination-args node) args))
t)))
;;; If VALUES appears in a non-MV context, then effectively convert it
to a PROG1 . This allows the computation of the additional values
;;; to become dead code.
(deftransform values ((&rest vals) * * :node node)
(unless (lvar-single-value-p (node-lvar node))
(give-up-ir1-transform))
(setf (node-derived-type node)
(make-short-values-type (list (single-value-type
(node-derived-type node)))))
(principal-lvar-single-valuify (node-lvar node))
(if vals
(let ((dummies (make-gensym-list (length (cdr vals)))))
`(lambda (val ,@dummies)
(declare (ignore ,@dummies))
val))
nil))
;;; TODO:
;;; - CAST chains;
(defun delete-cast (cast)
(declare (type cast cast))
(let ((value (cast-value cast))
(lvar (node-lvar cast)))
(delete-filter cast lvar value)
(when lvar
(reoptimize-lvar lvar)
(when (lvar-single-value-p lvar)
(note-single-valuified-lvar lvar)))
(values)))
(defun ir1-optimize-cast (cast &optional do-not-optimize)
(declare (type cast cast))
(let ((value (cast-value cast))
(atype (cast-asserted-type cast)))
(when (not do-not-optimize)
(let ((lvar (node-lvar cast)))
(when (values-subtypep (lvar-derived-type value)
(cast-asserted-type cast))
(delete-cast cast)
(return-from ir1-optimize-cast t))
(when (and (listp (lvar-uses value))
lvar)
Pathwise removing of CAST
(let ((ctran (node-next cast))
(dest (lvar-dest lvar))
next-block)
(collect ((merges))
(do-uses (use value)
(when (and (values-subtypep (node-derived-type use) atype)
(immediately-used-p value use))
(unless next-block
(when ctran (ensure-block-start ctran))
(setq next-block (first (block-succ (node-block cast))))
(ensure-block-start (node-prev cast))
(reoptimize-lvar lvar)
(setf (lvar-%derived-type value) nil))
(%delete-lvar-use use)
(add-lvar-use use lvar)
(unlink-blocks (node-block use) (node-block cast))
(link-blocks (node-block use) next-block)
(when (and (return-p dest)
(basic-combination-p use)
(eq (basic-combination-kind use) :local))
(merges use))))
(dolist (use (merges))
(merge-tail-sets use)))))))
(let* ((value-type (lvar-derived-type value))
(int (values-type-intersection value-type atype)))
(derive-node-type cast int)
(when (eq int *empty-type*)
(unless (eq value-type *empty-type*)
FIXME : Do it in one step .
(let ((context (cons (node-source-form cast)
(lvar-source (cast-value cast)))))
(filter-lvar
value
(if (cast-single-value-p cast)
`(list 'dummy)
`(multiple-value-call #'list 'dummy)))
(filter-lvar
(cast-value cast)
;; FIXME: Derived type.
`(%compile-time-type-error 'dummy
',(type-specifier atype)
',(type-specifier value-type)
',context)))
: FILTER - LVAR does not work for non - returning
;; functions, so we declare the return type of
;; %COMPILE-TIME-TYPE-ERROR to be * and derive the real type
;; here.
(setq value (cast-value cast))
(derive-node-type (lvar-uses value) *empty-type*)
(maybe-terminate-block (lvar-uses value) nil)
;; FIXME: Is it necessary?
(aver (null (block-pred (node-block cast))))
(delete-block-lazily (node-block cast))
(return-from ir1-optimize-cast)))
(when (eq (node-derived-type cast) *empty-type*)
(maybe-terminate-block cast nil))
(when (and (cast-%type-check cast)
(values-subtypep value-type
(cast-type-to-check cast)))
(setf (cast-%type-check cast) nil))))
(unless do-not-optimize
(setf (node-reoptimize cast) nil)))
(deftransform make-symbol ((string) (simple-string))
`(%make-symbol string))
| null | https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/src/compiler/ir1opt.lisp | lisp | This file implements the IR1 optimization phase of the compiler.
IR1 optimization is a grab-bag of optimizations that don't make
major changes to the block-level control flow and don't use flow
analysis. These optimizations can mostly be classified as
"meta-evaluation", but there is a sizable top-down component as
well.
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
interface for obtaining results of constant folding
constant leaf.
node.
interface for obtaining results of type inference
may be VALUES or FUNCTION type, which cannot be passed as an
slot is true, just return that value, otherwise recompute and
stash the value there.
not to be a VALUES or FUNCTION type.
Certain types refer to the contents of an object, which can
change without type derivation noticing: CONS types and ARRAY
types suffer from this:
(let ((x (the (cons fixnum fixnum) (cons a b))))
does the same -- so there is no way to use the derived information in
general.
So, the conservative option is to use the derived type if the leaf has
only a single ref -- in which case there cannot be a prior call that
mutates it. Otherwise we use the declared type or punt to the most general
type we know to be correct for sure.
necessary -- picking off some easy cases up front.
ADJUST-ARRAY may change dimensions, but rank stays same.
Element type cannot change.
Simple arrays cannot change at all.
Catch-all.
If the type contains some CONS types, the conservative type contains all
of them.
Similarly for non-simple arrays -- it should be possible to preserve
more information here, but really...
Excluding T is necessary, because we do want type derivation to
be able to narrow it down in case someone (most like a macro-expansion...)
actually declares something as having type T.
Covered by the next case as well, but this is a quick test.
TODO: MV-COMBINATION
FUN-TYPE might be (AND FUNCTION (SATISFIES ...)).
interface routines used by optimizers
This function is called by optimizers to indicate that something
make sure that they don't call for reoptimization when nothing has
happened, since optimization will fail to terminate.
on everything in sight.
Since this may be called during IR1 conversion,
PREV may be missing.
Annotate NODE to indicate that its result has been proven to be
only correct way to supply information discovered about a node's
type. If you screw with the NODE-DERIVED-TYPE directly, then
information may be lost and reoptimization may not happen.
intersection is different from the old type, then we do a
node with a constant reference.
This is similar to DERIVE-NODE-TYPE, but asserts that it is an
old LVAR will deliver values
IR1-OPTIMIZE
and doing IR1 optimizations. We can ignore all blocks that don't
have the REOPTIMIZE flag set. If COMPONENT-REOPTIMIZE is true when
we are done, then another iteration would be beneficial.
We delete blocks when there is either no predecessor or the
block is in a lambda that has been deleted. These blocks
it here immediately makes the effect available to IR1
optimization.
Preserve the BLOCK-SUCC invariant that almost every block has
exception).
Loop over the nodes in BLOCK, acting on (and clearing) REOPTIMIZE
flags.
Note that although they are cleared here, REOPTIMIZE flags might
still be set upon return from this function, meaning that further
optimization is wanted (as a consequence of optimizations we did).
We clear the node and block REOPTIMIZE flags before doing the
optimization, not after. This ensures that the node or block will
be reoptimized if necessary.
As above, we clear the node REOPTIMIZE flag before optimizing.
With a COMBINATION, we call PROPAGATE-FUN-CHANGE whenever
the function changes, and call IR1-OPTIMIZE-COMBINATION if
any argument changes.
IR1-OPTIMIZE-RETURN, since IR1-OPTIMIZE-RETURN wants to
type.
is accurate till the node actually has been reoptimized.
Try to join with a successor block. If we succeed, we return true,
otherwise false.
We cannot combine with a successor block if:
the successor is the current block (infinite loop);
the next block has a different cleanup, and thus
we may want to insert cleanup code between the
the next block has a different home lambda, and
thus the control transfer is a non-local exit.
Delete any nodes in BLOCK whose value is unused and which have no
side effects. We can delete sets of lexical variables when the set
variable has no references.
local call return type propagation
This function is called on RETURN nodes that have their REOPTIMIZE
flag set. It iterates over the uses of the RESULT, looking for
interesting stuff to update the TAIL-SET. If a use isn't a local
call, then we union its type together with the types of other such
uses. We assign to the RETURN-RESULT-TYPE the intersection of this
type with the RESULT's asserted type. We can make this
intersection now (potentially before type checking) because this
assertion on the result will eventually be checked (if
appropriate.)
We call MAYBE-CONVERT-TAIL-LOCAL-CALL on each local non-MV
combination, which may change the successor of the call to be the
called function, and if so, checks if the call can become an
assignment. If we convert to an assignment, we abort, since the
RETURN has been deleted.
(values-type-intersection
FIXME -- APD , 2002 - 01 - 26
)
Do stuff to realize that something has changed about the value
delivered to a return node. Since we consider the return values of
all functions in the tail set to be equivalent, this amounts to
bringing the entire tail set up to date. We iterate over the
returns for all the functions in the tail set, reanalyzing them
When we are done, we check whether the new type is different from
the old TAIL-SET-TYPE. If so, we set the type and also reoptimize
all the lvars for references to functions in the tail set. This
will cause IR1-OPTIMIZE-COMBINATION to derive the new type as the
results of the calls.
IF optimization
Utility: return T if both argument cblocks are equivalent. For now,
continue to the same block.
Check whether the predicate is known to be true or false,
deleting the IF node in favor of the appropriate branch when this
is the case.
Similarly, when both branches are equivalent, branch directly to either
of them.
Also, if the test has multiple uses, replicate the node when possible.
Create a new copy of an IF node that tests the value of the node
block-start = if-test).
This optimization has an effect semantically similar to the
source-to-source transformation:
(IF (IF A B C) D E) ==>
(IF A (IF B D E) (IF C D E))
We clobber the NODE-SOURCE-PATH of both the original and the new
node so that dead code deletion notes will definitely not consider
become unreachable, resulting in a spurious note.
exit IR1 optimization
This function attempts to delete an exit node, returning true if
it deletes the block as a consequence:
-- If the exit is degenerate (has no ENTRY), then we don't do
anything, since there is nothing to be done.
-- If the exit node and its ENTRY have the same home lambda then
we know the exit is local, and can delete the exit. We change
then unlink the node. If the exit is to a TR context, then we
must do MERGE-TAIL-SETS on any local calls which delivered
their value to this exit.
-- If there is no value (as in a GO), then we skip the value
semantics.
This function is also called by environment analysis, since it
wants all exits to be optimized even if normal optimization was
omitted.
combination IR1 optimization
Report as we try each transform?
Do IR1 optimizations on a COMBINATION node.
Check against the DEFINED-TYPE unless TYPE is already good.
If somebody is really sure that they want to modify
constants, let them.
only suppressing constant-folding of functions with
CALL attributes when they're actually passed
function arguments. -- WHN 19990918
The VM knows how to handle this.
The VM mostly knows how to handle this. We need
to massage the call slightly, though.
Let transforms have a crack at it.
the block there, and link it to the component tail.
Except when called during IR1 convertion, we delete the
continuation if it has no other uses. (If it does have other uses,
we reoptimize.)
Termination on the basis of a continuation type is
inhibited when:
-- The continuation is deleted (hence the assertion is spurious), or
-- We are in IR1 conversion (where THE assertions are subject to
weakening.) FIXME: Now THE assertions are not weakened, but new
Even if the combination will never return, don't terminate if this
is the tail call of a XEP: doing that would inhibit TCO.
This is called both by IR1 conversion and IR1 optimization when
they have verified the type signature for the call, and are
wondering if something should be done to special-case the call. If
CALL is a call to a global function, then see whether it defined
or known:
-- If a DEFINED-FUN should be inline expanded, then convert
the expansion and change the call to call it. Expansion is
enabled if :INLINE or if SPACE=0. If the FUNCTIONAL slot is
true, we never expand, since this function has already been
converted. Local call analysis will duplicate the definition
if necessary. We claim that the parent form is LABELS for
context declarations, since we don't want it to be considered
a real global function.
-- If it is a known function, mark it as such by setting the KIND.
We return the leaf referenced (NIL if not a leaf) and the
FUN-INFO assigned.
Inline: if the function has already been converted at another call
we convert the expansion.
For :INLINE case local call analysis will copy the expansion later,
expansion per component.
is it for?
Allow backward references to this function from following
forms. (Reused only if policy matches.)
Convert.
If we've already converted, change ref to the converted
functional.
Check whether CALL satisfies TYPE. If so, apply the type to the
call, and do MAYBE-TERMINATE-BLOCK and return the values of
RECOGNIZE-KNOWN-CALL. If an error, set the combination kind and
syntax check, arg/result type processing, but still call
RECOGNIZE-KNOWN-CALL, since the call might be to a known lambda,
and that checking is done by local call analysis.
Using the defined-type too early is a bit of a waste: during
Don't validate multiple times against the same leaf --
it doesn't add any information, but may generate the same warning
multiple times.
This is called by IR1-OPTIMIZE when the function for a call has
changed. If the call is local, we try to LET-convert it, and
derive the result type. If it is a :FULL call, we validate it
against the type, which recognizes known calls, does inline
expansion, etc. If a call to a predicate in a non-conditional
position or to a function with a source transform, then we
reconvert the form to give IR1 another chance.
known function optimization
replace it, otherwise add a new one.
call type constraint TRANSFORM-TYPE. If we are inhibited from
make a note of the message in FAILED-OPTIMIZATIONS for IR1
finalize to pick up. We return true if the transform failed, and
thus further transformation should be attempted. We return false
if either the transform succeeded or was aborted.
When we don't like an IR1 transform, we throw the severity/reason
and args.
GIVE-UP-IR1-TRANSFORM is used to throw out of an IR1 transform,
aborting this attempt to transform the call, but admitting the
possibility that this or some other transform will later succeed.
If arguments are supplied, they are format arguments for an
efficiency note.
ABORT-IR1-TRANSFORM is used to throw out of an IR1 transform and
force a normal call to the function at run time. No further
optimizations will be attempted.
DELAY-IR1-TRANSFORM is used to throw out of an IR1 transform, and
delay the transform on the node until later. REASONS specifies
when the transform will be later retried. The :OPTIMIZE reason
causes the transform to be delayed until after the current IR1
be delayed until after constraint propagation.
Clear any delayed transform with no reasons - these should have
been tried in the last pass. Then remove the reason from the
delayed transform reasons, and if any become empty then set
reoptimize flags for the node. Return true if any transforms are
to be retried.
environment, and then install it as the function for the call
integrated into the control flow.
We require the original function source name in order to generate
a meaningful debug name for the lambda we set up. (It'd be
possible to do this starting from debug names as well as source
generality, since source names are always known to our callers.)
The internal variables of a transform are not going to be
interesting to the debugger, so there's no sense in
(the extra variables can slow down constraint propagation).
This needs to be done before the WITH-IR1-ENVIRONMENT-FROM-NODE,
so that it will bind *LEXENV* to the right environment.
Replace a call to a foldable function of constant arguments with
the result of evaluating the form. If there is an error during the
evaluation, we give a warning and leave the call alone, making the
call a :ERROR call.
VALUES form.
seems more natural, but it's probably not.
Expressions like
(COND (END
(UNLESS (OR UNSAFE? (<= END SIZE)))
...))
can cause constant-folding TYPE-ERRORs (in
#'<=) when END can be proved to be NIL, even
though the code is perfectly legal and safe
because a NIL value of END means that the
#'<= will never be executed.
quite-possibly-valid code like
(COND ((NONINLINED-PREDICATE END)
(UNLESS (<= END SIZE))
...))
(where NONINLINED-PREDICATE is something the
compiler can't do at compile time, but which
turns out to make the #'<= expression
unreachable when END=NIL) could cause errors
when the compiler tries to constant-fold (<=
END SIZE).
unnecessarily evil to do a full
On the other hand, for code we control, we
should be able to work around any bug
want to be alerted to calls to our own
functions which aren't being folded away; a
local call optimization
If the leaf type is a function type, then just leave it alone, since TYPE
is never going to be more specific than that (and TYPE-INTERSECTION would
choke.)
Also, if the type is one requiring special care don't touch it if the leaf
(let ((var initial))
...
(setq var (+ var step))
...)
the initial and the step are of different types,
and the step is less contagious.
Figure out the type of a LET variable that has sets. We compute
the union of the INITIAL-TYPE and the types of all the set
values and to a PROPAGATE-TO-REFS with this type.
If a LET variable, find the initial value's type and do
type.
thus legal to substitute.)
If we have a non-set LET var with a single use, then (if possible)
let it be flushed as dead code. A side effect of this substitution
is to delete the variable.
is with dynamic-extent.
If the destinatation is dynamic extent, don't substitute unless
the source is as well.
we should not change lifetime of unknown values lvars
they have their own complications, such as
Delete a LET, removing the call and bind nodes, and warning about
any unreferenced variables. Note that FLUSH-DEAD-CODE will come
flush the FUN lvar.
changes. We look at each changed argument. If the corresponding
variable is set, then we call PROPAGATE-FROM-SETS. Otherwise, we
consider substituting for the variable, and also propagate
Substitution is inhibited when the arg leaf's derived type isn't a
subtype of the argument's leaf type. This prevents type checking
from being defeated, and also ensures that the best representation
for the variable can be used.
Substitution of individual references is inhibited if the
reference is in a different component from the home. This can only
happen with closures over top level lambda vars. In such cases,
the references may have already been compiled, and thus can't be
retroactively modified.
If all of the variables are deleted (have no references) when we
flags.
(NODE-DERIVED-TYPE USE) would
call changes. For each changed argument corresponding to an unset
variable, we compute the union of the types across all calls and
propagate this type information to the var's refs.
If the function has an entry-fun, then we don't do anything: since
it has a XEP we would not discover anything.
If the function is an optional-entry-point, we will just make sure
&REST lists are known to be lists. Doing the regular rigamarole
can erronously propagate too strict types into refs: see
corresponding to changed arguments in CALL, since the only use in
IR1 optimization of the REOPTIMIZE flag for local call args is
right here.
We can still make sure &REST is known to be a list.
The normal case.
multiple values optimization
Do stuff to notice a change to a MV combination node. There are
-- If the call is local, then it is already a MV let, or should
become one. Note that although all :LOCAL MV calls must eventually
is local, but has not been LET converted yet. This is because
the entry-point lambdas may have stray references (in other
entry points) that have not been deleted yet.
-- The call is full. This case is somewhat similar to the non-MV
combination optimization: we propagate return type information and
notice non-returning calls. We also have an optimization
this if:
-- The function has a known fixed number of arguments, or
-- The argument yields a known fixed number of values.
What we do is change the function in the MV-CALL to be a lambda
IR1-OPTIMIZE-MV-COMBINATION to notice that this call can be
converted (the next time around.) This new lambda just calls the
going to be stray references from the entry-point functions until
they get deleted.
In order to avoid loss of argument count checking, we only do the
transformation according to a known number of expected argument if
safety is unimportant. We can always convert if we know the number
of actual values, since the normal call that we build will still
do any appropriate argument count checking.
We only attempt the transformation if the called function is a
constant reference. This allows us to just splice the leaf into
the new function, instead of trying to somehow bind the function
expression. The leaf must be constant because we are evaluating it
again in a different place. This also has the effect of squelching
multiple warnings when there is an argument count error.
If we see:
(multiple-value-bind
(x y)
...)
Convert to:
(let ((x xx)
(y yy))
...)
What we actually do is convert the VALUES combination into a
there are extra args to VALUES, discard the corresponding
Propagate derived types from the VALUES call to its args:
transforms can leave the VALUES call with a better type
than its args have, so make sure not to throw that away.
If we see:
(values-list (list x y z))
Convert to:
(values x y z)
In implementation, this is somewhat similar to
(allowing the LIST to be flushed.)
FIXME: Thus we lose possible type assertions on (LIST ...).
If VALUES appears in a non-MV context, then effectively convert it
to become dead code.
TODO:
- CAST chains;
FIXME: Derived type.
functions, so we declare the return type of
%COMPILE-TIME-TYPE-ERROR to be * and derive the real type
here.
FIXME: Is it necessary? |
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB!C")
Return true for an LVAR whose sole use is a reference to a
(defun constant-lvar-p (thing)
(declare (type (or lvar null) thing))
(and (lvar-p thing)
(or (let ((use (principal-lvar-use thing)))
(and (ref-p use) (constant-p (ref-leaf use))))
check for EQL types ( but not singleton numeric types )
(let ((type (lvar-type thing)))
(values (type-singleton-p type))))))
Return the constant value for an LVAR whose only use is a constant
(declaim (ftype (function (lvar) t) lvar-value))
(defun lvar-value (lvar)
(let ((use (principal-lvar-use lvar))
(type (lvar-type lvar))
leaf)
(if (and (ref-p use)
(constant-p (setf leaf (ref-leaf use))))
(constant-value leaf)
(multiple-value-bind (constantp value) (type-singleton-p type)
(unless constantp
(error "~S used on non-constant LVAR ~S" 'lvar-value lvar))
value))))
Our best guess for the type of this lvar 's value . Note that this
argument to the normal type operations . See LVAR - TYPE .
The result value is cached in the - TYPE slot . If the
(eval-when (:compile-toplevel :execute)
(#+sb-xc-host cl:defmacro
#-sb-xc-host sb!xc:defmacro
lvar-type-using (lvar accessor)
`(let ((uses (lvar-uses ,lvar)))
(cond ((null uses) *empty-type*)
((listp uses)
(do ((res (,accessor (first uses))
(values-type-union (,accessor (first current))
res))
(current (rest uses) (rest current)))
((or (null current) (eq res *wild-type*))
res)))
(t
(,accessor uses))))))
#!-sb-fluid (declaim (inline lvar-derived-type))
(defun lvar-derived-type (lvar)
(declare (type lvar lvar))
(or (lvar-%derived-type lvar)
(setf (lvar-%derived-type lvar)
(%lvar-derived-type lvar))))
(defun %lvar-derived-type (lvar)
(lvar-type-using lvar node-derived-type))
Return the derived type for LVAR 's first value . This is guaranteed
(declaim (ftype (sfunction (lvar) ctype) lvar-type))
(defun lvar-type (lvar)
(single-value-type (lvar-derived-type lvar)))
LVAR - CONSERVATIVE - TYPE
( setf ( car x ) c )
( + ( car x ) ) ) )
Python does n't realize that the SETF CAR can change the type of X -- so we
can not use LVAR - TYPE which gets the derived results . Worse , still , instead
of ( SETF CAR ) we might have a call to a user - defined function FOO which
(defun lvar-conservative-type (lvar)
(let ((derived-type (lvar-type lvar))
(t-type *universal-type*))
Recompute using NODE - CONSERVATIVE - TYPE instead of derived type if
(cond ((or (eq derived-type t-type)
Ca n't use CSUBTYPEP !
(type= derived-type (specifier-type 'list))
(type= derived-type (specifier-type 'null)))
derived-type)
((and (cons-type-p derived-type)
(eq t-type (cons-type-car-type derived-type))
(eq t-type (cons-type-cdr-type derived-type)))
derived-type)
((and (array-type-p derived-type)
(or (not (array-type-complexp derived-type))
(let ((dimensions (array-type-dimensions derived-type)))
(or (eq '* dimensions)
(every (lambda (dim) (eq '* dim)) dimensions)))))
derived-type)
((type-needs-conservation-p derived-type)
(single-value-type (lvar-type-using lvar node-conservative-type)))
(t
derived-type))))
(defun node-conservative-type (node)
(let* ((derived-values-type (node-derived-type node))
(derived-type (single-value-type derived-values-type)))
(if (ref-p node)
(let ((leaf (ref-leaf node)))
(if (and (basic-var-p leaf)
(cdr (leaf-refs leaf)))
(coerce-to-values
(if (eq :declared (leaf-where-from leaf))
(leaf-type leaf)
(conservative-type derived-type)))
derived-values-type))
derived-values-type)))
(defun conservative-type (type)
(cond ((or (eq type *universal-type*)
(eq type (specifier-type 'list))
(eq type (specifier-type 'null)))
type)
((cons-type-p type)
(specifier-type 'cons))
((array-type-p type)
(if (array-type-complexp type)
(make-array-type
:dimensions
(let ((old (array-type-dimensions type)))
(if (eq '* old)
old
(mapcar (constantly '*) old)))
Complexity can not change .
:complexp (array-type-complexp type)
:element-type (array-type-element-type type)
:specialized-element-type (array-type-specialized-element-type type))
type))
((union-type-p type)
Conservative union type is an union of conservative types .
(let ((res *empty-type*))
(dolist (part (union-type-types type) res)
(setf res (type-union res (conservative-type part))))))
(t
(when (types-equal-or-intersect type (specifier-type 'cons))
(setf type (type-union type (specifier-type 'cons))))
(let ((non-simple-arrays (specifier-type '(and array (not simple-array)))))
(when (types-equal-or-intersect type non-simple-arrays)
(setf type (type-union type non-simple-arrays))))
type)))
(defun type-needs-conservation-p (type)
(cond ((eq type *universal-type*)
nil)
((or (cons-type-p type) (and (array-type-p type) (array-type-complexp type)))
t)
((types-equal-or-intersect type (specifier-type '(or cons (and array (not simple-array)))))
t)))
If LVAR is an argument of a function , return a type which the
function checks LVAR for .
#!-sb-fluid (declaim (inline lvar-externally-checkable-type))
(defun lvar-externally-checkable-type (lvar)
(or (lvar-%externally-checkable-type lvar)
(%lvar-%externally-checkable-type lvar)))
(defun %lvar-%externally-checkable-type (lvar)
(declare (type lvar lvar))
(let ((dest (lvar-dest lvar)))
(if (not (and dest (combination-p dest)))
(setf (lvar-%externally-checkable-type lvar) *wild-type*)
(let* ((fun (combination-fun dest))
(args (combination-args dest))
(fun-type (lvar-type fun)))
(setf (lvar-%externally-checkable-type fun) *wild-type*)
(if (or (not (call-full-like-p dest))
(not (fun-type-p fun-type))
(fun-type-wild-args fun-type))
(dolist (arg args)
(when arg
(setf (lvar-%externally-checkable-type arg)
*wild-type*)))
(map-combination-args-and-types
(lambda (arg type)
(setf (lvar-%externally-checkable-type arg)
(acond ((lvar-%externally-checkable-type arg)
(values-type-intersection
it (coerce-to-values type)))
(t (coerce-to-values type)))))
dest)))))
(or (lvar-%externally-checkable-type lvar) *wild-type*))
#!-sb-fluid(declaim (inline flush-lvar-externally-checkable-type))
(defun flush-lvar-externally-checkable-type (lvar)
(declare (type lvar lvar))
(setf (lvar-%externally-checkable-type lvar) nil))
(declaim (inline reoptimize-component))
(defun reoptimize-component (component kind)
(declare (type component component)
(type (member nil :maybe t) kind))
(aver kind)
(unless (eq (component-reoptimize component) t)
(setf (component-reoptimize component) kind)))
interesting has happened to the value of LVAR . Optimizers must
We clear any cached type for the lvar and set the reoptimize flags
(defun reoptimize-lvar (lvar)
(declare (type (or lvar null) lvar))
(when lvar
(setf (lvar-%derived-type lvar) nil)
(let ((dest (lvar-dest lvar)))
(when dest
(setf (lvar-reoptimize lvar) t)
(setf (node-reoptimize dest) t)
(prev (node-prev dest) :exit-if-null)
(block (ctran-block prev))
(component (block-component block)))
(when (typep dest 'cif)
(setf (block-test-modified block) t))
(setf (block-reoptimize block) t)
(reoptimize-component component :maybe))))
(do-uses (node lvar)
(setf (block-type-check (node-block node)) t)))
(values))
(defun reoptimize-lvar-uses (lvar)
(declare (type lvar lvar))
(do-uses (use lvar)
(setf (node-reoptimize use) t)
(setf (block-reoptimize (node-block use)) t)
(reoptimize-component (node-component use) :maybe)))
TYPEP to RTYPE . After IR1 conversion has happened , this is the
What we do is intersect RTYPE with NODE 's DERIVED - TYPE . If the
REOPTIMIZE - LVAR on the NODE - LVAR .
(defun derive-node-type (node rtype)
(declare (type valued-node node) (type ctype rtype))
(let ((node-type (node-derived-type node)))
(unless (eq node-type rtype)
(let ((int (values-type-intersection node-type rtype))
(lvar (node-lvar node)))
(when (type/= node-type int)
(when (and *check-consistency*
(eq int *empty-type*)
(not (eq rtype *empty-type*)))
(let ((*compiler-error-context* node))
(compiler-warn
"New inferred type ~S conflicts with old type:~
~% ~S~%*** possible internal error? Please report this."
(type-specifier rtype) (type-specifier node-type))))
(setf (node-derived-type node) int)
If the new type consists of only one object , replace the
(when (and (ref-p node)
(lambda-var-p (ref-leaf node)))
(let ((type (single-value-type int)))
(when (and (member-type-p type)
(eql 1 (member-type-size type)))
(change-ref-leaf node (find-constant
(first (member-type-members type)))))))
(reoptimize-lvar lvar)))))
(values))
error for LVAR 's value not to be TYPEP to TYPE . We implement it
to CAST . If we improve the assertion , we set TYPE - CHECK and
TYPE - ASSERTED to guarantee that the new assertion will be checked .
(defun assert-lvar-type (lvar type policy)
(declare (type lvar lvar) (type ctype type))
(unless (values-subtypep (lvar-derived-type lvar) type)
(let ((internal-lvar (make-lvar))
(dest (lvar-dest lvar)))
(substitute-lvar internal-lvar lvar)
(let ((cast (insert-cast-before dest lvar type policy)))
(use-lvar cast internal-lvar)
t))))
Do one forward pass over COMPONENT , deleting unreachable blocks
(defun ir1-optimize (component fastp)
(declare (type component component))
(setf (component-reoptimize component) nil)
(loop with block = (block-next (component-head component))
with tail = (component-tail component)
for last-block = block
until (eq block tail)
do (cond
would eventually be deleted by DFO recomputation , but doing
((or (block-delete-p block)
(null (block-pred block)))
(delete-block-lazily block)
(setq block (clean-component component block)))
((eq (functional-kind (block-home-lambda block)) :deleted)
one successor ( and a block with DELETE - P set is an acceptable
(mark-for-deletion block)
(setq block (clean-component component block)))
(t
(loop
(let ((succ (block-succ block)))
(unless (singleton-p succ)
(return)))
(let ((last (block-last block)))
(typecase last
(cif
(flush-dest (if-test last))
(when (unlink-node last)
(return)))
(exit
(when (maybe-delete-exit last)
(return)))))
(unless (join-successor-if-possible block)
(return)))
(when (and (not fastp) (block-reoptimize block) (block-component block))
(aver (not (block-delete-p block)))
(ir1-optimize-block block))
(cond ((and (block-delete-p block) (block-component block))
(setq block (clean-component component block)))
((and (block-flush-p block) (block-component block))
(flush-dead-code block)))))
do (when (eq block last-block)
(setq block (block-next block))))
(values))
(defun ir1-optimize-block (block)
(declare (type cblock block))
(setf (block-reoptimize block) nil)
(do-nodes (node nil block :restart-p t)
(when (node-reoptimize node)
(setf (node-reoptimize node) nil)
(typecase node
(ref)
(combination
(ir1-optimize-combination node))
(cif
(ir1-optimize-if node))
(creturn
: We leave the NODE - OPTIMIZE flag set going into
clear the flag itself . -- WHN 2002 - 02 - 02 , quoting original
CMU CL comments
(setf (node-reoptimize node) t)
(ir1-optimize-return node))
(mv-combination
(ir1-optimize-mv-combination node))
(exit
With an EXIT , we derive the node 's type from the VALUE 's
(let ((value (exit-value node)))
(when value
(derive-node-type node (lvar-derived-type value)))))
(cset
PROPAGATE - FROM - SETS can do a better job if NODE - REOPTIMIZE
(setf (node-reoptimize node) t)
(ir1-optimize-set node))
(cast
(ir1-optimize-cast node)))))
(values))
(defun join-successor-if-possible (block)
(declare (type cblock block))
(let ((next (first (block-succ block))))
NEXT is not an END - OF - COMPONENT marker
(or
(rest (block-pred next))
(eq next block)
(not (eq (block-end-cleanup block)
(block-start-cleanup next)))
(not (eq (block-home-lambda block)
(block-home-lambda next)))
Stack analysis phase wants ENTRY to start a block ...
(entry-p (block-start-node next))
(let ((last (block-last block)))
(and (valued-node-p last)
(awhen (node-lvar last)
(or
... and a DX - allocator to end a block .
(lvar-dynamic-extent it)
FIXME : This is a partial workaround for bug 303 .
(consp (lvar-uses it)))))))
nil)
(t
(join-blocks block next)
t)))))
Join together two blocks . The code in BLOCK2 is moved into BLOCK1
and BLOCK2 is deleted from the DFO . We combine the optimize flags
for the two blocks so that any indicated optimization gets done .
(defun join-blocks (block1 block2)
(declare (type cblock block1 block2))
(let* ((last1 (block-last block1))
(last2 (block-last block2))
(succ (block-succ block2))
(start2 (block-start block2)))
(do ((ctran start2 (node-next (ctran-next ctran))))
((not ctran))
(setf (ctran-block ctran) block1))
(unlink-blocks block1 block2)
(dolist (block succ)
(unlink-blocks block2 block)
(link-blocks block1 block))
(setf (ctran-kind start2) :inside-block)
(setf (node-next last1) start2)
(setf (ctran-use start2) last1)
(setf (block-last block1) last2))
(setf (block-flags block1)
(attributes-union (block-flags block1)
(block-flags block2)
(block-attributes type-asserted test-modified)))
(let ((next (block-next block2))
(prev (block-prev block2)))
(setf (block-next prev) next)
(setf (block-prev next) prev))
(values))
(defun flush-dead-code (block)
(declare (type cblock block))
(setf (block-flush-p block) nil)
(do-nodes-backwards (node lvar block :restart-p t)
(unless lvar
(typecase node
(ref
(delete-ref node)
(unlink-node node))
(combination
(when (flushable-combination-p node)
(flush-combination node)))
(mv-combination
(when (eq (basic-combination-kind node) :local)
(let ((fun (combination-lambda node)))
(when (dolist (var (lambda-vars fun) t)
(when (or (leaf-refs var)
(lambda-var-sets var))
(return nil)))
(flush-dest (first (basic-combination-args node)))
(delete-let fun)))))
(exit
(let ((value (exit-value node)))
(when value
(flush-dest value)
(setf (exit-value node) nil))))
(cset
(let ((var (set-var node)))
(when (and (lambda-var-p var)
(null (leaf-refs var)))
(flush-dest (set-value node))
(setf (basic-var-sets var)
(delq node (basic-var-sets var)))
(unlink-node node))))
(cast
(unless (cast-type-check node)
(flush-dest (cast-value node))
(unlink-node node))))))
(values))
(defun find-result-type (node)
(declare (type creturn node))
(let ((result (return-result node)))
(collect ((use-union *empty-type* values-type-union))
(do-uses (use result)
(let ((use-home (node-home-lambda use)))
(cond ((or (eq (functional-kind use-home) :deleted)
(block-delete-p (node-block use))))
((and (basic-combination-p use)
(eq (basic-combination-kind use) :local))
(aver (eq (lambda-tail-set use-home)
(lambda-tail-set (combination-lambda use))))
(when (combination-p use)
(when (nth-value 1 (maybe-convert-tail-local-call use))
(return-from find-result-type t))))
(t
(use-union (node-derived-type use))))))
(let ((int
(use-union)
))
(setf (return-result-type node) int))))
nil)
all ( not treating NODE specially . )
(defun ir1-optimize-return (node)
(declare (type creturn node))
(tagbody
:restart
(let* ((tails (lambda-tail-set (return-lambda node)))
(funs (tail-set-funs tails)))
(collect ((res *empty-type* values-type-union))
(dolist (fun funs)
(let ((return (lambda-return fun)))
(when return
(when (node-reoptimize return)
(setf (node-reoptimize return) nil)
(when (find-result-type return)
(go :restart)))
(res (return-result-type return)))))
(when (type/= (res) (tail-set-type tails))
(setf (tail-set-type tails) (res))
(dolist (fun (tail-set-funs tails))
(dolist (ref (leaf-refs fun))
(reoptimize-lvar (node-lvar ref))))))))
(values))
detect only blocks that read the same leaf into the same lvar , and
(defun cblocks-equivalent-p (x y)
(declare (type cblock x y))
(and (ref-p (block-start-node x))
(eq (block-last x) (block-start-node x))
(ref-p (block-start-node y))
(eq (block-last y) (block-start-node y))
(equal (block-succ x) (block-succ y))
(eql (ref-lvar (block-start-node x)) (ref-lvar (block-start-node y)))
(eql (ref-leaf (block-start-node x)) (ref-leaf (block-start-node y)))))
(defun ir1-optimize-if (node)
(declare (type cif node))
(let ((test (if-test node))
(block (node-block node)))
(let* ((type (lvar-type test))
(consequent (if-consequent node))
(alternative (if-alternative node))
(victim
(cond ((constant-lvar-p test)
(if (lvar-value test) alternative consequent))
((not (types-equal-or-intersect type (specifier-type 'null)))
alternative)
((type= type (specifier-type 'null))
consequent)
((cblocks-equivalent-p alternative consequent)
alternative))))
(when victim
(flush-dest test)
(when (rest (block-succ block))
(unlink-blocks block victim))
(setf (component-reanalyze (node-component node)) t)
(unlink-node node)
(return-from ir1-optimize-if (values))))
(when (and (eq (block-start-node block) node)
(listp (lvar-uses test)))
(do-uses (use test)
(when (immediately-used-p test use)
(convert-if-if use node)
(when (not (listp (lvar-uses test))) (return))))))
(values))
USE . The test must have > 1 use , and must be immediately used by
USE . NODE must be the only node in its block ( implying that
either node to be part of the original source . One node might
(defun convert-if-if (use node)
(declare (type node use) (type cif node))
(with-ir1-environment-from-node node
(let* ((block (node-block node))
(test (if-test node))
(cblock (if-consequent node))
(ablock (if-alternative node))
(use-block (node-block use))
(new-ctran (make-ctran))
(new-lvar (make-lvar))
(new-node (make-if :test new-lvar
:consequent cblock
:alternative ablock))
(new-block (ctran-starts-block new-ctran)))
(link-node-to-previous-ctran new-node new-ctran)
(setf (lvar-dest new-lvar) new-node)
(setf (block-last new-block) new-node)
(unlink-blocks use-block block)
(%delete-lvar-use use)
(add-lvar-use use new-lvar)
(link-blocks use-block new-block)
(link-blocks new-block cblock)
(link-blocks new-block ablock)
(push "<IF Duplication>" (node-source-path node))
(push "<IF Duplication>" (node-source-path new-node))
(reoptimize-lvar test)
(reoptimize-lvar new-lvar)
(setf (component-reanalyze *current-component*) t)))
(values))
uses of the Exit - Value to be uses of the original lvar ,
(defun maybe-delete-exit (node)
(declare (type exit node))
(let ((value (exit-value node))
(entry (exit-entry node)))
(when (and entry
(eq (node-home-lambda node) (node-home-lambda entry)))
(setf (entry-exits entry) (delq node (entry-exits entry)))
(if value
(delete-filter node (node-lvar node) value)
(unlink-node node)))))
#!+sb-show
(defvar *show-transforms-p* nil)
(defun check-important-result (node info)
(when (and (null (node-lvar node))
(ir1-attributep (fun-info-attributes info) important-result))
(let ((*compiler-error-context* node))
(compiler-style-warn
"The return value of ~A should not be discarded."
(lvar-fun-name (basic-combination-fun node))))))
(declaim (ftype (function (combination) (values)) ir1-optimize-combination))
(defun ir1-optimize-combination (node)
(when (lvar-reoptimize (basic-combination-fun node))
(propagate-fun-change node)
(maybe-terminate-block node nil))
(let ((args (basic-combination-args node))
(kind (basic-combination-kind node))
(info (basic-combination-fun-info node)))
(ecase kind
(:local
(let ((fun (combination-lambda node)))
(if (eq (functional-kind fun) :let)
(propagate-let-args node fun)
(propagate-local-call-args node fun))))
(:error
(dolist (arg args)
(when arg
(setf (lvar-reoptimize arg) nil))))
(:full
(dolist (arg args)
(when arg
(setf (lvar-reoptimize arg) nil)))
(cond (info
(check-important-result node info)
(let ((fun (fun-info-destroyed-constant-args info)))
(when fun
(let ((destroyed-constant-args (funcall fun args)))
(when destroyed-constant-args
(let ((*compiler-error-context* node))
(warn 'constant-modified
:fun-name (lvar-fun-name
(basic-combination-fun node)))
(setf (basic-combination-kind node) :error)
(return-from ir1-optimize-combination))))))
(let ((fun (fun-info-derive-type info)))
(when fun
(let ((res (funcall fun node)))
(when res
(derive-node-type node (coerce-to-values res))
(maybe-terminate-block node nil))))))
(t
(let* ((fun (basic-combination-fun node))
(uses (lvar-uses fun))
(leaf (when (ref-p uses) (ref-leaf uses))))
(multiple-value-bind (type defined-type)
(if (global-var-p leaf)
(values (leaf-type leaf) (leaf-defined-type leaf))
(values nil nil))
(when (and (not (fun-type-p type)) (fun-type-p defined-type))
(validate-call-type node type leaf)))))))
(:known
(aver info)
(dolist (arg args)
(when arg
(setf (lvar-reoptimize arg) nil)))
(check-important-result node info)
(let ((fun (fun-info-destroyed-constant-args info)))
(when (and fun
(policy node (> check-constant-modification 0)))
(let ((destroyed-constant-args (funcall fun args)))
(when destroyed-constant-args
(let ((*compiler-error-context* node))
(warn 'constant-modified
:fun-name (lvar-fun-name
(basic-combination-fun node)))
(setf (basic-combination-kind node) :error)
(return-from ir1-optimize-combination))))))
(let ((attr (fun-info-attributes info)))
(when (and (ir1-attributep attr foldable)
: The next test could be made more sensitive ,
(not (ir1-attributep attr call))
(every #'constant-lvar-p args)
(node-lvar node))
(constant-fold-call node)
(return-from ir1-optimize-combination)))
(let ((fun (fun-info-derive-type info)))
(when fun
(let ((res (funcall fun node)))
(when res
(derive-node-type node (coerce-to-values res))
(maybe-terminate-block node nil)))))
(let ((fun (fun-info-optimizer info)))
(unless (and fun (funcall fun node))
First give the VM a peek at the call
(multiple-value-bind (style transform)
(combination-implementation-style node)
(ecase style
(:direct
)
(:transform
(transform-call node transform (combination-fun-source-name node)))
(:default
(dolist (x (fun-info-transforms info))
#!+sb-show
(when *show-transforms-p*
(let* ((lvar (basic-combination-fun node))
(fname (lvar-fun-name lvar t)))
(/show "trying transform" x (transform-function x) "for" fname)))
(unless (ir1-transform node x)
#!+sb-show
(when *show-transforms-p*
(/show "quitting because IR1-TRANSFORM result was NIL"))
(return)))))))))))
(values))
(defun xep-tail-combination-p (node)
(and (combination-p node)
(let* ((lvar (combination-lvar node))
(dest (when (lvar-p lvar) (lvar-dest lvar)))
(lambda (when (return-p dest) (return-lambda dest))))
(and (lambda-p lambda)
(eq :external (lambda-kind lambda))))))
If NODE does n't return ( i.e. return type is NIL ) , then terminate
uses can ( ? ) be added later . -- APD , 2003 - 07 - 17
Why do we need to consider LVAR type ? -- APD , 2003 - 07 - 30
(defun maybe-terminate-block (node ir1-converting-not-optimizing-p)
(declare (type (or basic-combination cast ref) node))
(let* ((block (node-block node))
(lvar (node-lvar node))
(ctran (node-next node))
(tail (component-tail (block-component block)))
(succ (first (block-succ block))))
(declare (ignore lvar))
(unless (or (and (eq node (block-last block)) (eq succ tail))
(block-delete-p block))
(when (and (eq (node-derived-type node) *empty-type*)
(not (xep-tail-combination-p node)))
(cond (ir1-converting-not-optimizing-p
(cond
((block-last block)
(aver (eq (block-last block) node)))
(t
(setf (block-last block) node)
(setf (ctran-use ctran) nil)
(setf (ctran-kind ctran) :unused)
(setf (ctran-block ctran) nil)
(setf (node-next node) nil)
(link-blocks block (ctran-starts-block ctran)))))
(t
(node-ends-block node)))
(let ((succ (first (block-succ block))))
(unlink-blocks block succ)
(setf (component-reanalyze (block-component block)) t)
(aver (not (block-succ block)))
(link-blocks block tail)
(cond (ir1-converting-not-optimizing-p
(%delete-lvar-use node))
(t (delete-lvar-use node)
(when (null (block-pred succ))
(mark-for-deletion succ)))))
t))))
(defun recognize-known-call (call ir1-converting-not-optimizing-p)
(declare (type combination call))
(let* ((ref (lvar-uses (basic-combination-fun call)))
(leaf (when (ref-p ref) (ref-leaf ref)))
(inlinep (if (defined-fun-p leaf)
(defined-fun-inlinep leaf)
:no-chance)))
(cond
((eq inlinep :notinline)
(let ((info (info :function :info (leaf-source-name leaf))))
(when info
(setf (basic-combination-fun-info call) info))
(values nil nil)))
((not (and (global-var-p leaf)
(eq (global-var-kind leaf) :global-function)))
(values leaf nil))
((and (ecase inlinep
(:inline t)
(:no-chance nil)
((nil :maybe-inline) (policy call (zerop space))))
(defined-fun-p leaf)
(defined-fun-inline-expansion leaf)
(inline-expansion-ok call))
site in this component , we point this REF to the functional . If not ,
but for : MAYBE - INLINE and NIL cases we only get one copy of the
FIXME : We also convert in : INLINE & FUNCTIONAL - KIND case below . What
(flet ((frob ()
(let* ((name (leaf-source-name leaf))
(res (ir1-convert-inline-expansion
name
(defined-fun-inline-expansion leaf)
leaf
inlinep
(info :function :info name))))
(push res (defined-fun-functionals leaf))
(change-ref-leaf ref res))))
(let ((fun (defined-fun-functional leaf)))
(if (or (not fun)
(and (eq inlinep :inline) (functional-kind fun)))
(if ir1-converting-not-optimizing-p
(frob)
(with-ir1-environment-from-node call
(frob)
(locall-analyze-component *current-component*)))
(change-ref-leaf ref fun))))
(values (ref-leaf ref) nil))
(t
(let ((info (info :function :info (leaf-source-name leaf))))
(if info
(values leaf
(progn
(setf (basic-combination-kind call) :known)
(setf (basic-combination-fun-info call) info)))
(values leaf nil)))))))
return NIL , NIL . If the type is just FUNCTION , then skip the
(defun validate-call-type (call type fun &optional ir1-converting-not-optimizing-p)
(declare (type combination call) (type ctype type))
(let* ((where (when fun (leaf-where-from fun)))
(same-file-p (eq :defined-here where)))
(cond ((not (fun-type-p type))
(aver (multiple-value-bind (val win)
(csubtypep type (specifier-type 'function))
(or val (not win))))
conversion we can not use the untrusted ASSERT - CALL - TYPE , etc .
(when (and fun (not ir1-converting-not-optimizing-p))
(let ((defined-type (leaf-defined-type fun)))
(when (and (fun-type-p defined-type)
(neq fun (combination-type-validated-for-leaf call)))
(setf (combination-type-validated-for-leaf call) fun)
(when (and (valid-fun-use call defined-type
:argument-test #'always-subtypep
:result-test nil
:lossage-fun (if same-file-p
#'compiler-warn
#'compiler-style-warn)
:unwinnage-fun #'compiler-notify)
same-file-p)
(assert-call-type call defined-type nil)
(maybe-terminate-block call ir1-converting-not-optimizing-p)))))
(recognize-known-call call ir1-converting-not-optimizing-p))
((valid-fun-use call type
:argument-test #'always-subtypep
:result-test nil
:lossage-fun #'compiler-warn
:unwinnage-fun #'compiler-notify)
(assert-call-type call type)
(maybe-terminate-block call ir1-converting-not-optimizing-p)
(recognize-known-call call ir1-converting-not-optimizing-p))
(t
(setf (combination-kind call) :error)
(values nil nil)))))
(defun propagate-fun-change (call)
(declare (type combination call))
(let ((*compiler-error-context* call)
(fun-lvar (basic-combination-fun call)))
(setf (lvar-reoptimize fun-lvar) nil)
(case (combination-kind call)
(:local
(let ((fun (combination-lambda call)))
(maybe-let-convert fun)
(unless (member (functional-kind fun) '(:let :assignment :deleted))
(derive-node-type call (tail-set-type (lambda-tail-set fun))))))
(:full
(multiple-value-bind (leaf info)
(let* ((uses (lvar-uses fun-lvar))
(leaf (when (ref-p uses) (ref-leaf uses))))
(validate-call-type call (lvar-type fun-lvar) leaf))
(cond ((functional-p leaf)
(convert-call-if-possible
(lvar-uses (basic-combination-fun call))
call))
((not leaf))
((and (global-var-p leaf)
(eq (global-var-kind leaf) :global-function)
(leaf-has-source-name-p leaf)
(or (info :function :source-transform (leaf-source-name leaf))
(and info
(ir1-attributep (fun-info-attributes info)
predicate)
(let ((lvar (node-lvar call)))
(and lvar (not (if-p (lvar-dest lvar))))))))
(let ((name (leaf-source-name leaf))
(dummies (make-gensym-list
(length (combination-args call)))))
(transform-call call
`(lambda ,dummies
(,@(if (symbolp name)
`(,name)
`(funcall #',name))
,@dummies))
(leaf-source-name leaf)))))))))
(values))
Add a failed optimization note to FAILED - OPTIMZATIONS for NODE ,
FUN and ARGS . If there is already a note for NODE and TRANSFORM ,
(defun record-optimization-failure (node transform args)
(declare (type combination node) (type transform transform)
(type (or fun-type list) args))
(let* ((table (component-failed-optimizations *component-being-compiled*))
(found (assoc transform (gethash node table))))
(if found
(setf (cdr found) args)
(push (cons transform args) (gethash node table))))
(values))
Attempt to transform NODE using TRANSFORM - FUNCTION , subject to the
doing the transform for some reason and is true , then we
(defun ir1-transform (node transform)
(declare (type combination node) (type transform transform))
(let* ((type (transform-type transform))
(fun (transform-function transform))
(constrained (fun-type-p type))
(table (component-failed-optimizations *component-being-compiled*))
(flame (if (transform-important transform)
(policy node (>= speed inhibit-warnings))
(policy node (> speed inhibit-warnings))))
(*compiler-error-context* node))
(cond ((or (not constrained)
(valid-fun-use node type))
(multiple-value-bind (severity args)
(catch 'give-up-ir1-transform
(transform-call node
(funcall fun node)
(combination-fun-source-name node))
(values :none nil))
(ecase severity
(:none
(remhash node table)
nil)
(:aborted
(setf (combination-kind node) :error)
(when args
(apply #'warn args))
(remhash node table)
nil)
(:failure
(if args
(when flame
(record-optimization-failure node transform args))
(setf (gethash node table)
(remove transform (gethash node table) :key #'car)))
t)
(:delayed
(remhash node table)
nil))))
((and flame
(valid-fun-use node
type
:argument-test #'types-equal-or-intersect
:result-test #'values-types-equal-or-intersect))
(record-optimization-failure node transform type)
t)
(t
t))))
optimization pass . The : CONSTRAINT reason causes the transform to
FIXME : Now ( 0.6.11.44 ) that there are 4 variants of this ( GIVE - UP ,
ABORT , DELAY/:OPTIMIZE , ) and we 're starting to
do CASE operations on the various REASON values , it might be a
good idea to go OO , representing the reasons by objects , using
CLOS methods on the objects instead of CASE , and ( possibly ) using
SIGNAL instead of THROW .
(declaim (ftype (function (&rest t) nil) give-up-ir1-transform))
(defun give-up-ir1-transform (&rest args)
(throw 'give-up-ir1-transform (values :failure args)))
(defun abort-ir1-transform (&rest args)
(throw 'give-up-ir1-transform (values :aborted args)))
(defun delay-ir1-transform (node &rest reasons)
(let ((assoc (assoc node *delayed-ir1-transforms*)))
(cond ((not assoc)
(setf *delayed-ir1-transforms*
(acons node reasons *delayed-ir1-transforms*))
(throw 'give-up-ir1-transform :delayed))
((cdr assoc)
(dolist (reason reasons)
(pushnew reason (cdr assoc)))
(throw 'give-up-ir1-transform :delayed)))))
(defun retry-delayed-ir1-transforms (reason)
(setf *delayed-ir1-transforms*
(remove-if-not #'cdr *delayed-ir1-transforms*))
(let ((reoptimize nil))
(dolist (assoc *delayed-ir1-transforms*)
(let ((reasons (remove reason (cdr assoc))))
(setf (cdr assoc) reasons)
(unless reasons
(let ((node (car assoc)))
(unless (node-deleted node)
(setf reoptimize t)
(setf (node-reoptimize node) t)
(let ((block (node-block node)))
(setf (block-reoptimize block) t)
(reoptimize-component (block-component block) :maybe)))))))
reoptimize))
Take the lambda - expression RES , IR1 convert it in the proper
NODE . We do local call analysis so that the new function is
names , but as of sbcl-0.7.1.5 , there was no need for this
(defun transform-call (call res source-name)
(declare (type combination call) (list res))
(aver (and (legal-fun-name-p source-name)
(not (eql source-name '.anonymous.))))
(node-ends-block call)
suppressing the substitution of variables with only one use
(setf (combination-lexenv call)
(make-lexenv :default (combination-lexenv call)
:policy (process-optimize-decl
'(optimize
(preserve-single-use-debug-variables 0))
(lexenv-policy
(combination-lexenv call)))))
(with-ir1-environment-from-node call
(with-component-last-block (*current-component*
(block-next (node-block call)))
(let ((new-fun (ir1-convert-inline-lambda
res
:debug-name (debug-name 'lambda-inlined source-name)
:system-lambda t))
(ref (lvar-use (combination-fun call))))
(change-ref-leaf ref new-fun)
(setf (combination-kind call) :full)
(locall-analyze-component *current-component*))))
(values))
If there is more than one value , then we transform the call into a
(defun constant-fold-call (call)
(let ((args (mapcar #'lvar-value (combination-args call)))
(fun-name (combination-fun-source-name call)))
(multiple-value-bind (values win)
(careful-call fun-name
args
call
Note : CMU CL had COMPILER - WARN here , and that
It 's especially not while bug 173 exists :
Moreover , even without bug 173 ,
So , with or without bug 173 , it 'd be
COMPILER - WARNING ( and thus return FAILURE - P = T
from COMPILE - FILE ) for legal code , so we we
use a wimpier COMPILE - STYLE - WARNING instead .
#-sb-xc-host #'compiler-style-warn
173 - related problems , and in particular we
COMPILER - WARNING is butch enough to stop the
SBCL build itself in its tracks .
#+sb-xc-host #'compiler-warn
"constant folding")
(cond ((not win)
(setf (combination-kind call) :error))
((and (proper-list-of-length-p values 1))
(with-ir1-environment-from-node call
(let* ((lvar (node-lvar call))
(prev (node-prev call))
(intermediate-ctran (make-ctran)))
(%delete-lvar-use call)
(setf (ctran-next prev) nil)
(setf (node-prev call) nil)
(reference-constant prev intermediate-ctran lvar
(first values))
(link-node-to-previous-ctran call intermediate-ctran)
(reoptimize-lvar lvar)
(flush-combination call))))
(t (let ((dummies (make-gensym-list (length args))))
(transform-call
call
`(lambda ,dummies
(declare (ignore ,@dummies))
(values ,@(mapcar (lambda (x) `',x) values)))
fun-name))))))
(values))
Propagate TYPE to LEAF and its REFS , marking things changed .
has multiple references -- otherwise LVAR - CONSERVATIVE - TYPE is screwed .
(defun propagate-to-refs (leaf type)
(declare (type leaf leaf) (type ctype type))
(let ((var-type (leaf-type leaf))
(refs (leaf-refs leaf)))
(unless (or (fun-type-p var-type)
(and (cdr refs)
(eq :declared (leaf-where-from leaf))
(type-needs-conservation-p var-type)))
(let ((int (type-approx-intersection2 var-type type)))
(when (type/= int var-type)
(setf (leaf-type leaf) int)
(let ((s-int (make-single-value-type int)))
(dolist (ref refs)
(derive-node-type ref s-int)
: LET var substitution
(let* ((lvar (node-lvar ref)))
(when (and lvar (combination-p (lvar-dest lvar)))
(reoptimize-lvar lvar)))))))
(values))))
Iteration variable : exactly one SETQ of the form :
(defun maybe-infer-iteration-var-type (var initial-type)
(binding* ((sets (lambda-var-sets var) :exit-if-null)
(set (first sets))
(() (null (rest sets)) :exit-if-null)
(set-use (principal-lvar-use (set-value set)))
(() (and (combination-p set-use)
(eq (combination-kind set-use) :known)
(fun-info-p (combination-fun-info set-use))
(not (node-to-be-deleted-p set-use))
(or (eq (combination-fun-source-name set-use) '+)
(eq (combination-fun-source-name set-use) '-)))
:exit-if-null)
(minusp (eq (combination-fun-source-name set-use) '-))
(+-args (basic-combination-args set-use))
(() (and (proper-list-of-length-p +-args 2 2)
(let ((first (principal-lvar-use
(first +-args))))
(and (ref-p first)
(eq (ref-leaf first) var))))
:exit-if-null)
(step-type (lvar-type (second +-args)))
(set-type (lvar-type (set-value set))))
(when (and (numeric-type-p initial-type)
(numeric-type-p step-type)
(or (numeric-type-equal initial-type step-type)
Detect cases like ( LOOP FOR 1.0 to 5.0 ... ) , where
(numeric-type-equal initial-type
(numeric-contagion initial-type
step-type))))
(labels ((leftmost (x y cmp cmp=)
(cond ((eq x nil) nil)
((eq y nil) nil)
((listp x)
(let ((x1 (first x)))
(cond ((listp y)
(let ((y1 (first y)))
(if (funcall cmp x1 y1) x y)))
(t
(if (funcall cmp x1 y) x y)))))
((listp y)
(let ((y1 (first y)))
(if (funcall cmp= x y1) x y)))
(t (if (funcall cmp x y) x y))))
(max* (x y) (leftmost x y #'> #'>=))
(min* (x y) (leftmost x y #'< #'<=)))
(multiple-value-bind (low high)
(let ((step-type-non-negative (csubtypep step-type (specifier-type
'(real 0 *))))
(step-type-non-positive (csubtypep step-type (specifier-type
'(real * 0)))))
(cond ((or (and step-type-non-negative (not minusp))
(and step-type-non-positive minusp))
(values (numeric-type-low initial-type)
(when (and (numeric-type-p set-type)
(numeric-type-equal set-type initial-type))
(max* (numeric-type-high initial-type)
(numeric-type-high set-type)))))
((or (and step-type-non-positive (not minusp))
(and step-type-non-negative minusp))
(values (when (and (numeric-type-p set-type)
(numeric-type-equal set-type initial-type))
(min* (numeric-type-low initial-type)
(numeric-type-low set-type)))
(numeric-type-high initial-type)))
(t
(values nil nil))))
(modified-numeric-type initial-type
:low low
:high high
:enumerable nil))))))
(deftransform + ((x y) * * :result result)
"check for iteration variable reoptimization"
(let ((dest (principal-lvar-end result))
(use (principal-lvar-use x)))
(when (and (ref-p use)
(set-p dest)
(eq (ref-leaf use)
(set-var dest)))
(reoptimize-lvar (set-value dest))))
(give-up-ir1-transform))
(defun propagate-from-sets (var initial-type)
(let ((changes (not (csubtypep (lambda-var-last-initial-type var) initial-type)))
(types nil))
(dolist (set (lambda-var-sets var))
(let ((type (lvar-type (set-value set))))
(push type types)
(when (node-reoptimize set)
(let ((old-type (node-derived-type set)))
(unless (values-subtypep old-type type)
(derive-node-type set (make-single-value-type type))
(setf changes t)))
(setf (node-reoptimize set) nil))))
(when changes
(setf (lambda-var-last-initial-type var) initial-type)
(let ((res-type (or (maybe-infer-iteration-var-type var initial-type)
(apply #'type-union initial-type types))))
(propagate-to-refs var res-type))))
(values))
PROPAGATE - FROM - SETS . We also derive the VALUE 's type as the node 's
(defun ir1-optimize-set (node)
(declare (type cset node))
(let ((var (set-var node)))
(when (and (lambda-var-p var) (leaf-refs var))
(let ((home (lambda-var-home var)))
(when (eq (functional-kind home) :let)
(let* ((initial-value (let-var-initial-value var))
(initial-type (lvar-type initial-value)))
(setf (lvar-reoptimize initial-value) nil)
(propagate-from-sets var initial-type))))))
(derive-node-type node (make-single-value-type
(lvar-type (set-value node))))
(setf (node-reoptimize node) nil)
(values))
Return true if the value of REF will always be the same ( and is
(defun constant-reference-p (ref)
(declare (type ref ref))
(let ((leaf (ref-leaf ref)))
(typecase leaf
((or constant functional) t)
(lambda-var
(null (lambda-var-sets leaf)))
(defined-fun
(not (eq (defined-fun-inlinep leaf) :notinline)))
(global-var
(case (global-var-kind leaf)
(:global-function
(let ((name (leaf-source-name leaf)))
(or #-sb-xc-host
(eq (symbol-package (fun-name-block-name name))
*cl-package*)
(info :function :info name)))))))))
replace the variable reference 's LVAR with the arg lvar .
We change the REF to be a reference to NIL with unused value , and
(defun substitute-single-use-lvar (arg var)
(declare (type lvar arg) (type lambda-var var))
(binding* ((ref (first (leaf-refs var)))
(lvar (node-lvar ref) :exit-if-null)
(dest (lvar-dest lvar))
(dest-lvar (when (valued-node-p dest) (node-lvar dest))))
(when (and
Think about ( LET ( ( A ... ) ) ( IF ... A ... ) ): two
LVAR - USEs should not be met on one path . Another problem
(eq (lvar-uses lvar) ref)
(not (block-delete-p (node-block ref)))
(or (not dest-lvar)
(not (lvar-dynamic-extent dest-lvar))
(lvar-dynamic-extent lvar))
(typecase dest
(cast
(and (type-single-value-p (lvar-derived-type arg))
(multiple-value-bind (pdest pprev)
(principal-lvar-end lvar)
(declare (ignore pdest))
(lvar-single-value-p pprev))))
(mv-combination
(or (eq (basic-combination-fun dest) lvar)
(and (eq (basic-combination-kind dest) :local)
(type-single-value-p (lvar-derived-type arg)))))
((or creturn exit)
While CRETURN and EXIT nodes may be known - values ,
substitution into CRETURN may create new tail calls .
nil)
(t
(aver (lvar-single-value-p lvar))
t))
(eq (node-home-lambda ref)
(lambda-home (lambda-var-home var))))
(let ((ref-type (single-value-type (node-derived-type ref))))
(cond ((csubtypep (single-value-type (lvar-type arg)) ref-type)
(substitute-lvar-uses lvar arg
Really it is ( EQ ( LVAR - USES LVAR ) REF ):
t)
(delete-lvar-use ref))
(t
(let* ((value (make-lvar))
(cast (insert-cast-before ref value ref-type
: it should be ( TYPE - CHECK 0 )
*policy*)))
(setf (cast-type-to-check cast) *wild-type*)
(substitute-lvar-uses value arg
FIXME
t)
(%delete-lvar-use ref)
(add-lvar-use cast lvar)))))
(setf (node-derived-type ref) *wild-type*)
(change-ref-leaf ref (find-constant nil))
(delete-ref ref)
(unlink-node ref)
(reoptimize-lvar lvar)
t)))
along right away and delete the REF and then the lambda , since we
(defun delete-let (clambda)
(declare (type clambda clambda))
(aver (functional-letlike-p clambda))
(note-unreferenced-vars clambda)
(let ((call (let-combination clambda)))
(flush-dest (basic-combination-fun call))
(unlink-node call)
(unlink-node (lambda-bind clambda))
(setf (lambda-bind clambda) nil))
(setf (functional-kind clambda) :zombie)
(let ((home (lambda-home clambda)))
(setf (lambda-lets home) (delete clambda (lambda-lets home))))
(values))
This function is called when one of the arguments to a LET
derived - type information for the arg to all the VAR 's refs .
are done , then we delete the LET .
Note that we are responsible for clearing the LVAR - REOPTIMIZE
(defun propagate-let-args (call fun)
(declare (type combination call) (type clambda fun))
(loop for arg in (combination-args call)
and var in (lambda-vars fun) do
(when (and arg (lvar-reoptimize arg))
(setf (lvar-reoptimize arg) nil)
(cond
((lambda-var-sets var)
(propagate-from-sets var (lvar-type arg)))
((let ((use (lvar-uses arg)))
(when (ref-p use)
(let ((leaf (ref-leaf use)))
(when (and (constant-reference-p use)
(csubtypep (leaf-type leaf)
be better -- APD , 2003 - 05 - 15
(leaf-type var)))
(propagate-to-refs var (lvar-type arg))
(let ((use-component (node-component use)))
(prog1 (substitute-leaf-if
(lambda (ref)
(cond ((eq (node-component ref) use-component)
t)
(t
(aver (lambda-toplevelish-p (lambda-home fun)))
nil)))
leaf var)))
t)))))
((and (null (rest (leaf-refs var)))
(not (preserve-single-use-debug-var-p call var))
(substitute-single-use-lvar arg var)))
(t
(propagate-to-refs var (lvar-type arg))))))
(when (every #'not (combination-args call))
(delete-let fun))
(values))
This function is called when one of the args to a non - LET local
BUG-655203 - REGRESSION in tests / compiler.pure.lisp .
We can clear the LVAR - REOPTIMIZE flags for arguments in all calls
(defun propagate-local-call-args (call fun)
(declare (type combination call) (type clambda fun))
(unless (functional-entry-fun fun)
(if (lambda-optional-dispatch fun)
(loop for var in (lambda-vars fun)
do (let ((info (lambda-var-arg-info var)))
(when (and info (eq :rest (arg-info-kind info)))
(propagate-from-sets var (specifier-type 'list)))))
(let* ((vars (lambda-vars fun))
(union (mapcar (lambda (arg var)
(when (and arg
(lvar-reoptimize arg)
(null (basic-var-sets var)))
(lvar-type arg)))
(basic-combination-args call)
vars))
(this-ref (lvar-use (basic-combination-fun call))))
(dolist (arg (basic-combination-args call))
(when arg
(setf (lvar-reoptimize arg) nil)))
(dolist (ref (leaf-refs fun))
(let ((dest (node-dest ref)))
(unless (or (eq ref this-ref) (not dest))
(setq union
(mapcar (lambda (this-arg old)
(when old
(setf (lvar-reoptimize this-arg) nil)
(type-union (lvar-type this-arg) old)))
(basic-combination-args dest)
union)))))
(loop for var in vars
and type in union
when type do (propagate-to-refs var type)))))
(values))
two main branches here :
be converted to : MV - LETs , there can be a window when the call
which tries to convert MV - CALLs into MV - binds .
(defun ir1-optimize-mv-combination (node)
(ecase (basic-combination-kind node)
(:local
(let ((fun-lvar (basic-combination-fun node)))
(when (lvar-reoptimize fun-lvar)
(setf (lvar-reoptimize fun-lvar) nil)
(maybe-let-convert (combination-lambda node))))
(setf (lvar-reoptimize (first (basic-combination-args node))) nil)
(when (eq (functional-kind (combination-lambda node)) :mv-let)
(unless (convert-mv-bind-to-let node)
(ir1-optimize-mv-bind node))))
(:full
(let* ((fun (basic-combination-fun node))
(fun-changed (lvar-reoptimize fun))
(args (basic-combination-args node)))
(when fun-changed
(setf (lvar-reoptimize fun) nil)
(let ((type (lvar-type fun)))
(when (fun-type-p type)
(derive-node-type node (fun-type-returns type))))
(maybe-terminate-block node nil)
(let ((use (lvar-uses fun)))
(when (and (ref-p use) (functional-p (ref-leaf use)))
(convert-call-if-possible use node)
(when (eq (basic-combination-kind node) :local)
(maybe-let-convert (ref-leaf use))))))
(unless (or (eq (basic-combination-kind node) :local)
(eq (lvar-fun-name fun) '%throw))
(ir1-optimize-mv-call node))
(dolist (arg args)
(setf (lvar-reoptimize arg) nil))))
(:error))
(values))
Propagate derived type info from the values lvar to the vars .
(defun ir1-optimize-mv-bind (node)
(declare (type mv-combination node))
(let* ((arg (first (basic-combination-args node)))
(vars (lambda-vars (combination-lambda node)))
(n-vars (length vars))
(types (values-type-in (lvar-derived-type arg)
n-vars)))
(loop for var in vars
and type in types
do (if (basic-var-sets var)
(propagate-from-sets var type)
(propagate-to-refs var type)))
(setf (lvar-reoptimize arg) nil))
(values))
If possible , convert a general MV call to an MV - BIND . We can do
-- The call has only one argument , and
that " looks like an MV bind " , which allows
actual function with the MV - BIND variables as arguments . Note that
this new MV bind is not let - converted immediately , as there are
(defun ir1-optimize-mv-call (node)
(let ((fun (basic-combination-fun node))
(*compiler-error-context* node)
(ref (lvar-uses (basic-combination-fun node)))
(args (basic-combination-args node)))
(unless (and (ref-p ref) (constant-reference-p ref)
(singleton-p args))
(return-from ir1-optimize-mv-call))
(multiple-value-bind (min max)
(fun-type-nargs (lvar-type fun))
(let ((total-nvals
(multiple-value-bind (types nvals)
(values-types (lvar-derived-type (first args)))
(declare (ignore types))
(if (eq nvals :unknown) nil nvals))))
(when total-nvals
(when (and min (< total-nvals min))
(compiler-warn
"MULTIPLE-VALUE-CALL with ~R values when the function expects ~
at least ~R."
total-nvals min)
(setf (basic-combination-kind node) :error)
(return-from ir1-optimize-mv-call))
(when (and max (> total-nvals max))
(compiler-warn
"MULTIPLE-VALUE-CALL with ~R values when the function expects ~
at most ~R."
total-nvals max)
(setf (basic-combination-kind node) :error)
(return-from ir1-optimize-mv-call)))
(let ((count (cond (total-nvals)
((and (policy node (zerop verify-arg-count))
(eql min max))
min)
(t nil))))
(when count
(with-ir1-environment-from-node node
(let* ((dums (make-gensym-list count))
(ignore (gensym))
(leaf (ref-leaf ref))
(fun (ir1-convert-lambda
`(lambda (&optional ,@dums &rest ,ignore)
(declare (ignore ,ignore))
(%funcall ,leaf ,@dums))
:source-name (leaf-%source-name leaf)
:debug-name (leaf-%debug-name leaf))))
(change-ref-leaf ref fun)
(aver (eq (basic-combination-kind node) :full))
(locall-analyze-component *current-component*)
(aver (eq (basic-combination-kind node) :local)))))))))
(values))
( values )
normal LET combination calling the original : MV - LET lambda . If
lvars . If there are insufficient args , insert references to NIL .
(defun convert-mv-bind-to-let (call)
(declare (type mv-combination call))
(let* ((arg (first (basic-combination-args call)))
(use (lvar-uses arg)))
(when (and (combination-p use)
(eq (lvar-fun-name (combination-fun use))
'values))
(let* ((fun (combination-lambda call))
(vars (lambda-vars fun))
(vals (combination-args use))
(nvars (length vars))
(nvals (length vals)))
(cond ((> nvals nvars)
(mapc #'flush-dest (subseq vals nvars))
(setq vals (subseq vals 0 nvars)))
((< nvals nvars)
(with-ir1-environment-from-node use
(let ((node-prev (node-prev use)))
(setf (node-prev use) nil)
(setf (ctran-next node-prev) nil)
(collect ((res vals))
(loop for count below (- nvars nvals)
for prev = node-prev then ctran
for ctran = (make-ctran)
and lvar = (make-lvar use)
do (reference-constant prev ctran lvar nil)
(res lvar)
finally (link-node-to-previous-ctran
use ctran))
(setq vals (res)))))))
(setf (combination-args use) vals)
(flush-dest (combination-fun use))
(let ((fun-lvar (basic-combination-fun call)))
(setf (lvar-dest fun-lvar) use)
(setf (combination-fun use) fun-lvar)
(flush-lvar-externally-checkable-type fun-lvar))
(setf (combination-kind use) :local)
(setf (functional-kind fun) :let)
(flush-dest (first (basic-combination-args call)))
(unlink-node call)
(when vals
(reoptimize-lvar (first vals)))
(let ((types (values-type-types (node-derived-type use))))
(dolist (val vals)
(when types
(let ((type (pop types)))
(assert-lvar-type val type '((type-check . 0)))))))
Propagate declared types of MV - BIND variables .
(propagate-to-args use fun)
(reoptimize-call use))
t)))
CONVERT - MV - BIND - TO - LET . We grab the args of LIST and make them
args of the VALUES - LIST call , flushing the old argument
(defoptimizer (values-list optimizer) ((list) node)
(let ((use (lvar-uses list)))
(when (and (combination-p use)
(eq (lvar-fun-name (combination-fun use))
'list))
FIXME : VALUES might not satisfy an assertion on NODE - LVAR .
(change-ref-leaf (lvar-uses (combination-fun node))
(find-free-fun 'values "in a strange place"))
(setf (combination-kind node) :full)
(let ((args (combination-args use)))
(dolist (arg args)
(setf (lvar-dest arg) node)
(flush-lvar-externally-checkable-type arg))
(setf (combination-args use) nil)
(flush-dest list)
(setf (combination-args node) args))
t)))
to a PROG1 . This allows the computation of the additional values
(deftransform values ((&rest vals) * * :node node)
(unless (lvar-single-value-p (node-lvar node))
(give-up-ir1-transform))
(setf (node-derived-type node)
(make-short-values-type (list (single-value-type
(node-derived-type node)))))
(principal-lvar-single-valuify (node-lvar node))
(if vals
(let ((dummies (make-gensym-list (length (cdr vals)))))
`(lambda (val ,@dummies)
(declare (ignore ,@dummies))
val))
nil))
(defun delete-cast (cast)
(declare (type cast cast))
(let ((value (cast-value cast))
(lvar (node-lvar cast)))
(delete-filter cast lvar value)
(when lvar
(reoptimize-lvar lvar)
(when (lvar-single-value-p lvar)
(note-single-valuified-lvar lvar)))
(values)))
(defun ir1-optimize-cast (cast &optional do-not-optimize)
(declare (type cast cast))
(let ((value (cast-value cast))
(atype (cast-asserted-type cast)))
(when (not do-not-optimize)
(let ((lvar (node-lvar cast)))
(when (values-subtypep (lvar-derived-type value)
(cast-asserted-type cast))
(delete-cast cast)
(return-from ir1-optimize-cast t))
(when (and (listp (lvar-uses value))
lvar)
Pathwise removing of CAST
(let ((ctran (node-next cast))
(dest (lvar-dest lvar))
next-block)
(collect ((merges))
(do-uses (use value)
(when (and (values-subtypep (node-derived-type use) atype)
(immediately-used-p value use))
(unless next-block
(when ctran (ensure-block-start ctran))
(setq next-block (first (block-succ (node-block cast))))
(ensure-block-start (node-prev cast))
(reoptimize-lvar lvar)
(setf (lvar-%derived-type value) nil))
(%delete-lvar-use use)
(add-lvar-use use lvar)
(unlink-blocks (node-block use) (node-block cast))
(link-blocks (node-block use) next-block)
(when (and (return-p dest)
(basic-combination-p use)
(eq (basic-combination-kind use) :local))
(merges use))))
(dolist (use (merges))
(merge-tail-sets use)))))))
(let* ((value-type (lvar-derived-type value))
(int (values-type-intersection value-type atype)))
(derive-node-type cast int)
(when (eq int *empty-type*)
(unless (eq value-type *empty-type*)
FIXME : Do it in one step .
(let ((context (cons (node-source-form cast)
(lvar-source (cast-value cast)))))
(filter-lvar
value
(if (cast-single-value-p cast)
`(list 'dummy)
`(multiple-value-call #'list 'dummy)))
(filter-lvar
(cast-value cast)
`(%compile-time-type-error 'dummy
',(type-specifier atype)
',(type-specifier value-type)
',context)))
: FILTER - LVAR does not work for non - returning
(setq value (cast-value cast))
(derive-node-type (lvar-uses value) *empty-type*)
(maybe-terminate-block (lvar-uses value) nil)
(aver (null (block-pred (node-block cast))))
(delete-block-lazily (node-block cast))
(return-from ir1-optimize-cast)))
(when (eq (node-derived-type cast) *empty-type*)
(maybe-terminate-block cast nil))
(when (and (cast-%type-check cast)
(values-subtypep value-type
(cast-type-to-check cast)))
(setf (cast-%type-check cast) nil))))
(unless do-not-optimize
(setf (node-reoptimize cast) nil)))
(deftransform make-symbol ((string) (simple-string))
`(%make-symbol string))
|
7b1be3b1fafeea98c96b2e69be7a90577bbeebbcb4c00ae769bd19e7b70cd717 | functionally/pigy-genetics | Mint.hs | -----------------------------------------------------------------------------
--
-- Module : $Headers
Copyright : ( c ) 2021
License : MIT
--
Maintainer : < >
-- Stability : Experimental
Portability : Portable
--
-- | Minting image tokens.
--
-----------------------------------------------------------------------------
# LANGUAGE NumericUnderscores #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module Pigy.Chain.Mint (
-- * Minting
mint
-- * Validation
, checkValue
-- * Filtering
, pigFilter
, findPigs
) where
import Cardano.Api (AddressAny, AssetId(..), AssetName(..), CardanoEra(..), PolicyId(..), Quantity(..), ScriptHash, ShelleyBasedEra(..), ShelleyWitnessSigningKey(..), TxIn(..), TxMetadata(..), TxMetadataValue(..), TxOut(..), TxOutDatumHash(..), TxOutValue(..), Value, anyAddressInShelleyBasedEra, filterValue, getTxId, makeShelleyKeyWitness, makeSignedTransaction, makeTransactionBody, multiAssetSupportedInEra, negateValue, quantityToLovelace, selectAsset, selectLovelace, serialiseToRawBytesHexText, valueFromList, valueToList)
import Control.Monad.Error.Class (throwError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Maybe (mapMaybe)
import Mantra.Query (submitTransaction)
import Mantra.Script (mintingScript)
import Mantra.Transaction (includeFee, makeTransaction)
import Mantra.Types (MantraM, foistMantraEither, printMantra)
import Ouroboros.Network.Protocol.LocalTxSubmission.Type (SubmitResult(..))
import Pigy.Image (crossover, fromChromosome, newGenotype)
import Pigy.Ipfs (pinImage)
import Pigy.Types (Context(..), KeyedAddress(..))
import qualified Data.ByteString.Char8 as BS (ByteString, drop, isPrefixOf, pack, unpack)
import qualified Data.Map.Strict as M (fromList)
import qualified Data.Text as T (pack)
-- | Validate input value.
checkValue :: AssetId -- ^ The payment token.
-> ScriptHash -- ^ The policy for the image tokens.
-> Value -- ^ The value to be validated.
-> Bool -- ^ Whether minting can proceed.
checkValue token scriptHash value =
let
ada = selectLovelace value
pigy = selectAsset value token
pigs = maximum[1, length $ findPigs scriptHash value]
a = 1_500_000
b = 500_000
in
pigy > 0 && ada >= quantityToLovelace (Quantity $ a + b * fromIntegral pigs)
-- | Test whether an asset is a token image.
pigFilter :: ScriptHash -- ^ The policy for the image tokens.
-> AssetId -- ^ The asset in question.
-> Bool -- ^ Whether the asset is an image token.
pigFilter scriptHash (AssetId (PolicyId scriptHash') (AssetName name')) = scriptHash' == scriptHash && BS.isPrefixOf "PIG@" name'
pigFilter _ _ = False
-- | Find the tickers for the image tokens in a value.
findPigs :: ScriptHash -- ^ The policy.
-> Value -- ^ The value.
-> [BS.ByteString] -- ^ The image-token tickers.
findPigs scriptHash =
map (\(AssetId _ (AssetName name'), _) -> BS.drop 4 name')
. filter (pigFilter scriptHash . fst)
. valueToList
-- | Mint or burn an image token.
mint :: MonadFail m
=> MonadIO m
=> Context -- ^ The service context.
-> [TxIn] -- ^ The UTxOs to be spent.
-> AddressAny -- ^ The destination.
-> Value -- ^ The value to be spent.
-> [String] -- ^ The message to be embedded in the transaction.
-> MantraM m () -- ^ The action to mint or burn.
mint Context{..} txIns destination value message =
do
let
KeyedAddress{..} = keyedAddress
(script, scriptHash) = mintingScript verificationHash Nothing
pigs = findPigs scriptHash value
(metadata, minting) <-
if length pigs == 1
then do
printMantra $ " Burnt token: PIG@" ++ BS.unpack (head pigs)
return
(
Nothing
, negateValue $ filterValue (pigFilter scriptHash) value
)
else do
genotype <-
liftIO
$ if null pigs
then do
putStrLn " New token."
newGenotype gRandom
else do
putStrLn $ " Crossover token: " ++ show (("PIG@" ++) . BS.unpack <$> pigs)
crossover gRandom $ mapMaybe (fromChromosome . BS.unpack) pigs
(chromosome, cid) <- pinImage ipfsPin images genotype
let
name = "PIG@" ++ chromosome
return
(
Just
. TxMetadata
$ M.fromList
[
(
721
, TxMetaMap
[
(
TxMetaText . serialiseToRawBytesHexText $ scriptHash
, TxMetaMap
[
(
TxMetaText $ T.pack name
, TxMetaMap
[
(TxMetaText "name" , TxMetaText . T.pack $ "PIG " ++ chromosome )
, (TxMetaText "image" , TxMetaText $ "ipfs://" <> T.pack cid )
, (TxMetaText "ticker" , TxMetaText $ T.pack name )
, (TxMetaText "parents" , TxMetaList $ TxMetaText . T.pack . ("PIG@" ++) . BS.unpack <$> pigs)
, (TxMetaText "url" , TxMetaText "" )
]
)
]
)
]
)
, (
674
, TxMetaMap
[
(
TxMetaText "msg"
, TxMetaList $ TxMetaText . T.pack <$> message
)
]
)
]
, valueFromList [(AssetId (PolicyId scriptHash) (AssetName $ BS.pack name), 1)]
)
let
value' = value <> minting
Right supportedMultiAsset = multiAssetSupportedInEra AlonzoEra
destination' = anyAddressInShelleyBasedEra destination
txBody <- includeFee network pparams 1 1 1 0
$ makeTransaction
txIns
[TxOut destination' (TxOutValue supportedMultiAsset value') TxOutDatumHashNone]
Nothing
metadata
(Just (PolicyId scriptHash, script, minting))
txRaw <- foistMantraEither $ makeTransactionBody txBody
let
witness = makeShelleyKeyWitness txRaw
$ either WitnessPaymentKey WitnessPaymentExtendedKey signing
txSigned = makeSignedTransaction [witness] txRaw
result <- submitTransaction ShelleyBasedEraAlonzo socket protocol network txSigned
case result of
SubmitSuccess -> printMantra $ " Success: " ++ show (getTxId txRaw)
SubmitFail reason -> do
printMantra $ " Tx: " ++ show txRaw
throwError $ " Failure: " ++ show reason
| null | https://raw.githubusercontent.com/functionally/pigy-genetics/ed2784faabfa77d8a94a147e9f7b11cac0f545b6/app/Pigy/Chain/Mint.hs | haskell | ---------------------------------------------------------------------------
Module : $Headers
Stability : Experimental
| Minting image tokens.
---------------------------------------------------------------------------
# LANGUAGE OverloadedStrings #
* Minting
* Validation
* Filtering
| Validate input value.
^ The payment token.
^ The policy for the image tokens.
^ The value to be validated.
^ Whether minting can proceed.
| Test whether an asset is a token image.
^ The policy for the image tokens.
^ The asset in question.
^ Whether the asset is an image token.
| Find the tickers for the image tokens in a value.
^ The policy.
^ The value.
^ The image-token tickers.
| Mint or burn an image token.
^ The service context.
^ The UTxOs to be spent.
^ The destination.
^ The value to be spent.
^ The message to be embedded in the transaction.
^ The action to mint or burn. | Copyright : ( c ) 2021
License : MIT
Maintainer : < >
Portability : Portable
# LANGUAGE NumericUnderscores #
# LANGUAGE RecordWildCards #
module Pigy.Chain.Mint (
mint
, checkValue
, pigFilter
, findPigs
) where
import Cardano.Api (AddressAny, AssetId(..), AssetName(..), CardanoEra(..), PolicyId(..), Quantity(..), ScriptHash, ShelleyBasedEra(..), ShelleyWitnessSigningKey(..), TxIn(..), TxMetadata(..), TxMetadataValue(..), TxOut(..), TxOutDatumHash(..), TxOutValue(..), Value, anyAddressInShelleyBasedEra, filterValue, getTxId, makeShelleyKeyWitness, makeSignedTransaction, makeTransactionBody, multiAssetSupportedInEra, negateValue, quantityToLovelace, selectAsset, selectLovelace, serialiseToRawBytesHexText, valueFromList, valueToList)
import Control.Monad.Error.Class (throwError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Maybe (mapMaybe)
import Mantra.Query (submitTransaction)
import Mantra.Script (mintingScript)
import Mantra.Transaction (includeFee, makeTransaction)
import Mantra.Types (MantraM, foistMantraEither, printMantra)
import Ouroboros.Network.Protocol.LocalTxSubmission.Type (SubmitResult(..))
import Pigy.Image (crossover, fromChromosome, newGenotype)
import Pigy.Ipfs (pinImage)
import Pigy.Types (Context(..), KeyedAddress(..))
import qualified Data.ByteString.Char8 as BS (ByteString, drop, isPrefixOf, pack, unpack)
import qualified Data.Map.Strict as M (fromList)
import qualified Data.Text as T (pack)
checkValue token scriptHash value =
let
ada = selectLovelace value
pigy = selectAsset value token
pigs = maximum[1, length $ findPigs scriptHash value]
a = 1_500_000
b = 500_000
in
pigy > 0 && ada >= quantityToLovelace (Quantity $ a + b * fromIntegral pigs)
pigFilter scriptHash (AssetId (PolicyId scriptHash') (AssetName name')) = scriptHash' == scriptHash && BS.isPrefixOf "PIG@" name'
pigFilter _ _ = False
findPigs scriptHash =
map (\(AssetId _ (AssetName name'), _) -> BS.drop 4 name')
. filter (pigFilter scriptHash . fst)
. valueToList
mint :: MonadFail m
=> MonadIO m
mint Context{..} txIns destination value message =
do
let
KeyedAddress{..} = keyedAddress
(script, scriptHash) = mintingScript verificationHash Nothing
pigs = findPigs scriptHash value
(metadata, minting) <-
if length pigs == 1
then do
printMantra $ " Burnt token: PIG@" ++ BS.unpack (head pigs)
return
(
Nothing
, negateValue $ filterValue (pigFilter scriptHash) value
)
else do
genotype <-
liftIO
$ if null pigs
then do
putStrLn " New token."
newGenotype gRandom
else do
putStrLn $ " Crossover token: " ++ show (("PIG@" ++) . BS.unpack <$> pigs)
crossover gRandom $ mapMaybe (fromChromosome . BS.unpack) pigs
(chromosome, cid) <- pinImage ipfsPin images genotype
let
name = "PIG@" ++ chromosome
return
(
Just
. TxMetadata
$ M.fromList
[
(
721
, TxMetaMap
[
(
TxMetaText . serialiseToRawBytesHexText $ scriptHash
, TxMetaMap
[
(
TxMetaText $ T.pack name
, TxMetaMap
[
(TxMetaText "name" , TxMetaText . T.pack $ "PIG " ++ chromosome )
, (TxMetaText "image" , TxMetaText $ "ipfs://" <> T.pack cid )
, (TxMetaText "ticker" , TxMetaText $ T.pack name )
, (TxMetaText "parents" , TxMetaList $ TxMetaText . T.pack . ("PIG@" ++) . BS.unpack <$> pigs)
, (TxMetaText "url" , TxMetaText "" )
]
)
]
)
]
)
, (
674
, TxMetaMap
[
(
TxMetaText "msg"
, TxMetaList $ TxMetaText . T.pack <$> message
)
]
)
]
, valueFromList [(AssetId (PolicyId scriptHash) (AssetName $ BS.pack name), 1)]
)
let
value' = value <> minting
Right supportedMultiAsset = multiAssetSupportedInEra AlonzoEra
destination' = anyAddressInShelleyBasedEra destination
txBody <- includeFee network pparams 1 1 1 0
$ makeTransaction
txIns
[TxOut destination' (TxOutValue supportedMultiAsset value') TxOutDatumHashNone]
Nothing
metadata
(Just (PolicyId scriptHash, script, minting))
txRaw <- foistMantraEither $ makeTransactionBody txBody
let
witness = makeShelleyKeyWitness txRaw
$ either WitnessPaymentKey WitnessPaymentExtendedKey signing
txSigned = makeSignedTransaction [witness] txRaw
result <- submitTransaction ShelleyBasedEraAlonzo socket protocol network txSigned
case result of
SubmitSuccess -> printMantra $ " Success: " ++ show (getTxId txRaw)
SubmitFail reason -> do
printMantra $ " Tx: " ++ show txRaw
throwError $ " Failure: " ++ show reason
|
a3e0fb72bf497d70de0895f64bbcc362bb1d40ea22d6334281beb47c5f150fb5 | Bwooce/open-cgf | cdr_file_srv.erl | %%%-------------------------------------------------------------------
File : cdr_file_srv.erl
Author : < >
%%% Description :
%%%
Created : 27 Jan 2008 by < >
%%%
Copyright 2008
%%%
%%% This file is part of open-cgf.
%%%
%%% open-cgf is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation .
%%%
%%% open-cgf is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%%% GNU General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with open-cgf. If not, see </>.
%%%-------------------------------------------------------------------
-module(cdr_file_srv).
-behaviour(gen_server).
-define(SERVER, ?MODULE).
-include("open-cgf.hrl").
%% API
-export([start_link/0, check_duplicate/3, log/4, log_possible_dup/4, commit_possible_dup/4, remove_possible_dup/4, reset/2, flush_pending_duplicates/3]).
-export([print_state/0]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {cdr_loggers = []}).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
%% Description: Starts the server
%%--------------------------------------------------------------------
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
check_duplicate(SourceKey, OwnerAddress, Seq_num) ->
gen_server:call(?SERVER, {check_duplicate, SourceKey, OwnerAddress, Seq_num}).
log(Source, OwnerAddress, Seq_num, Data) ->
gen_server:call(?SERVER, {log, Source, OwnerAddress, Seq_num, Data}).
log_possible_dup(SourceKey, OwnerAddress, Seq_num, Data) ->
gen_server:cast(?SERVER, {log_possible_dup, SourceKey, OwnerAddress, Seq_num, Data}).
commit_possible_dup(SourceKey, OwnerAddress, Seq_num, Seq_nums) ->
gen_server:cast(?SERVER, {commit_possible_dup, SourceKey, OwnerAddress, Seq_num, Seq_nums}).
remove_possible_dup(SourceKey, OwnerAddress, Seq_num, Seq_nums) ->
gen_server:cast(?SERVER, {remove_possible_dup, SourceKey, OwnerAddress, Seq_num, Seq_nums}).
flush_pending_duplicates(SourceKey, OwnerAddress, Seq_nums) ->
gen_server:cast(?SERVER, {flush_pending_duplicates, SourceKey, OwnerAddress, Seq_nums}).
reset(SourceKey, OwnerAddress) ->
gen_server:cast(?SERVER, {reset, SourceKey, OwnerAddress}).
print_state() ->
gen_server:cast(?SERVER, {print_state}).
%%====================================================================
%% gen_server callbacks
%%====================================================================
%%--------------------------------------------------------------------
%% Function: init(Args) -> {ok, State} |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%% Description: Initiates the server
%%--------------------------------------------------------------------
init([]) ->
process_flag(trap_exit, true),
{ok, #state{cdr_loggers = []}}.
%%--------------------------------------------------------------------
Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} |
%% {stop, Reason, State}
%% Description: Handling call messages
%%--------------------------------------------------------------------
handle_call({check_duplicate, Source, OwnerAddress, Seq_num}, _From, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
Result = gen_server:call(PID, {check_duplicate, Seq_num}),
{reply, Result, State#state{cdr_loggers=NewCDRLoggers}};
handle_call({log, Source, OwnerAddress, Seq_num, Data}, _From, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
Result = gen_server:call(PID, {log, Seq_num, Data}),
?PRINTDEBUG2("Result from log was ~p", [Result]),
{reply, ok, State#state{cdr_loggers=NewCDRLoggers}};
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
%%--------------------------------------------------------------------
Function : handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling cast messages
%%--------------------------------------------------------------------
handle_cast({log, Source, OwnerAddress, Seq_num, Data}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {log, Seq_num, Data}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({log_possible_dup, Source, OwnerAddress, Seq_num, Data}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {log_possible_dup, Seq_num, Data}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({remove_possible_dup, Source, OwnerAddress, _Seq_num, Seq_nums}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {remove_possible_dup, Seq_nums}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({commit_possible_dup, Source, OwnerAddress, _Seq_num, Seq_nums}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {commit_possible_dup, Seq_nums}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({flush_pending_duplicates, Source, OwnerAddress, Seq_nums}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {flush_pending_duplicates, Seq_nums}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({reset, Source, OwnerAddress}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {reset}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({print_state}, State) ->
error_logger:info_msg("Requested state printout:~n~p~n",[State]),
{noreply, State};
handle_cast(Msg, State) ->
error_logger:warning_msg("Got unhandled cast in cdr_file_srv. Msg was ~p",[Msg]),
{noreply, State}.
%%--------------------------------------------------------------------
Function : handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling all non call/cast messages
%%--------------------------------------------------------------------
handle_info({newCDRPID, Source, NewPID}, State) ->
{noreply, State#state{cdr_loggers = update_logger(NewPID, Source, State#state.cdr_loggers)}};
handle_info(Info, State) ->
error_logger:warning_msg("Got unhandled info ~p while in state ~p",[Info, State]),
{noreply, State}.
%%--------------------------------------------------------------------
%% Function: terminate(Reason, State) -> void()
%% Description: This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any necessary
%% cleaning up. When it returns, the gen_server terminates with Reason.
%% The return value is ignored.
%%--------------------------------------------------------------------
terminate(Reason, _State) ->
error_logger:info_msg("cdr_file_srv is shutting down for reason: ~p",[Reason]),
ok.
%%--------------------------------------------------------------------
Func : code_change(OldVsn , State , Extra ) - > { ok , NewState }
%% Description: Convert process state when code is changed
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%--------------------------------------------------------------------
Internal functions
find_logger(Source, OwnerAddress, CDRLoggerList) ->
case proplists:get_value(Source, CDRLoggerList) of
undefined ->
{ok, NewPID} = 'open-cgf_cdr_sup':add(self(), self(), Source, OwnerAddress),
{NewPID, [{Source, NewPID} | CDRLoggerList]};
PID ->
{PID, CDRLoggerList}
end.
update_logger(PID, Source, CDRLoggerList) ->
lists:keyreplace(Source, 1, CDRLoggerList, {Source, PID}).
| null | https://raw.githubusercontent.com/Bwooce/open-cgf/929f7e280493ca4bc47be05bb931044ee1321594/src/cdr_file_srv.erl | erlang | -------------------------------------------------------------------
Description :
This file is part of open-cgf.
open-cgf is free software: you can redistribute it and/or modify
open-cgf is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with open-cgf. If not, see </>.
-------------------------------------------------------------------
API
gen_server callbacks
====================================================================
API
====================================================================
--------------------------------------------------------------------
Description: Starts the server
--------------------------------------------------------------------
====================================================================
gen_server callbacks
====================================================================
--------------------------------------------------------------------
Function: init(Args) -> {ok, State} |
ignore |
{stop, Reason}
Description: Initiates the server
--------------------------------------------------------------------
--------------------------------------------------------------------
% handle_call(Request , From , State ) - > { reply , Reply , State } |
{stop, Reason, Reply, State} |
{stop, Reason, State}
Description: Handling call messages
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
Description: Handling cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
Description: Handling all non call/cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: terminate(Reason, State) -> void()
Description: This function is called by a gen_server when it is about to
terminate. It should be the opposite of Module:init/1 and do any necessary
cleaning up. When it returns, the gen_server terminates with Reason.
The return value is ignored.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Convert process state when code is changed
--------------------------------------------------------------------
-------------------------------------------------------------------- | File : cdr_file_srv.erl
Author : < >
Created : 27 Jan 2008 by < >
Copyright 2008
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation .
You should have received a copy of the GNU General Public License
-module(cdr_file_srv).
-behaviour(gen_server).
-define(SERVER, ?MODULE).
-include("open-cgf.hrl").
-export([start_link/0, check_duplicate/3, log/4, log_possible_dup/4, commit_possible_dup/4, remove_possible_dup/4, reset/2, flush_pending_duplicates/3]).
-export([print_state/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {cdr_loggers = []}).
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
check_duplicate(SourceKey, OwnerAddress, Seq_num) ->
gen_server:call(?SERVER, {check_duplicate, SourceKey, OwnerAddress, Seq_num}).
log(Source, OwnerAddress, Seq_num, Data) ->
gen_server:call(?SERVER, {log, Source, OwnerAddress, Seq_num, Data}).
log_possible_dup(SourceKey, OwnerAddress, Seq_num, Data) ->
gen_server:cast(?SERVER, {log_possible_dup, SourceKey, OwnerAddress, Seq_num, Data}).
commit_possible_dup(SourceKey, OwnerAddress, Seq_num, Seq_nums) ->
gen_server:cast(?SERVER, {commit_possible_dup, SourceKey, OwnerAddress, Seq_num, Seq_nums}).
remove_possible_dup(SourceKey, OwnerAddress, Seq_num, Seq_nums) ->
gen_server:cast(?SERVER, {remove_possible_dup, SourceKey, OwnerAddress, Seq_num, Seq_nums}).
flush_pending_duplicates(SourceKey, OwnerAddress, Seq_nums) ->
gen_server:cast(?SERVER, {flush_pending_duplicates, SourceKey, OwnerAddress, Seq_nums}).
reset(SourceKey, OwnerAddress) ->
gen_server:cast(?SERVER, {reset, SourceKey, OwnerAddress}).
print_state() ->
gen_server:cast(?SERVER, {print_state}).
{ ok , State , Timeout } |
init([]) ->
process_flag(trap_exit, true),
{ok, #state{cdr_loggers = []}}.
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call({check_duplicate, Source, OwnerAddress, Seq_num}, _From, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
Result = gen_server:call(PID, {check_duplicate, Seq_num}),
{reply, Result, State#state{cdr_loggers=NewCDRLoggers}};
handle_call({log, Source, OwnerAddress, Seq_num, Data}, _From, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
Result = gen_server:call(PID, {log, Seq_num, Data}),
?PRINTDEBUG2("Result from log was ~p", [Result]),
{reply, ok, State#state{cdr_loggers=NewCDRLoggers}};
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
Function : handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_cast({log, Source, OwnerAddress, Seq_num, Data}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {log, Seq_num, Data}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({log_possible_dup, Source, OwnerAddress, Seq_num, Data}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {log_possible_dup, Seq_num, Data}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({remove_possible_dup, Source, OwnerAddress, _Seq_num, Seq_nums}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {remove_possible_dup, Seq_nums}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({commit_possible_dup, Source, OwnerAddress, _Seq_num, Seq_nums}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {commit_possible_dup, Seq_nums}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({flush_pending_duplicates, Source, OwnerAddress, Seq_nums}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {flush_pending_duplicates, Seq_nums}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({reset, Source, OwnerAddress}, State) ->
{PID, NewCDRLoggers} = find_logger(Source, OwnerAddress, State#state.cdr_loggers),
ok = gen_server:cast(PID, {reset}),
{noreply, State#state{cdr_loggers=NewCDRLoggers}};
handle_cast({print_state}, State) ->
error_logger:info_msg("Requested state printout:~n~p~n",[State]),
{noreply, State};
handle_cast(Msg, State) ->
error_logger:warning_msg("Got unhandled cast in cdr_file_srv. Msg was ~p",[Msg]),
{noreply, State}.
Function : handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_info({newCDRPID, Source, NewPID}, State) ->
{noreply, State#state{cdr_loggers = update_logger(NewPID, Source, State#state.cdr_loggers)}};
handle_info(Info, State) ->
error_logger:warning_msg("Got unhandled info ~p while in state ~p",[Info, State]),
{noreply, State}.
terminate(Reason, _State) ->
error_logger:info_msg("cdr_file_srv is shutting down for reason: ~p",[Reason]),
ok.
Func : code_change(OldVsn , State , Extra ) - > { ok , NewState }
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
find_logger(Source, OwnerAddress, CDRLoggerList) ->
case proplists:get_value(Source, CDRLoggerList) of
undefined ->
{ok, NewPID} = 'open-cgf_cdr_sup':add(self(), self(), Source, OwnerAddress),
{NewPID, [{Source, NewPID} | CDRLoggerList]};
PID ->
{PID, CDRLoggerList}
end.
update_logger(PID, Source, CDRLoggerList) ->
lists:keyreplace(Source, 1, CDRLoggerList, {Source, PID}).
|
36bea65150b1f17ca30ae9eb431aa7d87bf69fbd012c77ca41d16aefe1b89d79 | stopachka/bel-clojure | model.clj | (ns bel-clojure.model
(:refer-clojure :rename {type clj-type
symbol? clj-symbol?
string? clj-string?
char? clj-char?
number? clj-number?})
(:import
(java.util ArrayList)))
;; ----
;; Misc
(defn first-and-only [xs msg]
(assert (= (count xs) 1) msg)
(first xs))
;; -------------
;; Primitive Types
(def string? clj-string?)
(def char? clj-char?)
(def symbol? clj-symbol?)
(def number? clj-number?)
(def pair? (comp (partial = java.util.ArrayList) clj-type))
(def mut-map? (comp (partial = java.util.HashMap) clj-type))
(def imm-map? (comp (partial = clojure.lang.PersistentArrayMap) clj-type))
(def clj-err? (partial instance? Throwable))
(defn type-nilable [x]
(cond
(symbol? x) 'symbol
(string? x) 'string
(char? x) 'char
(number? x) 'number
(pair? x) 'pair
(mut-map? x) 'mut-map
(imm-map? x) 'imm-map
(clj-err? x) 'clj-err
:else
(let [v (and (seqable? x) (first x))]
(when (#{:splice :comma :backquote} v)
(symbol (name v))))))
(defn type [x]
(let [v (type-nilable x)]
(assert v (format "Unsupported type for form = %s" x))
v))
;; ---------
;; Pair Cons
(defn p
([a b]
(ArrayList. [a b])))
;; ---------
;; Constants
(def bel-quote 'quote)
(def bel-nil (symbol "nil"))
(def bel-t 't)
(def bel-err-sym 'err)
(def bel-dot [:dot "."])
(def bel-lit 'lit)
(def bel-prim 'prim)
(def bel-o 'o)
(def bel-a 'a)
(def bel-d 'd)
(def bel-apply 'apply)
(def bel-set 'set)
(def bel-clo 'clo)
(def bel-mac 'mac)
(def bel-globe 'globe)
(def bel-scope 'scope)
(def bel-if 'if)
(def bel-cont 'cont)
;; -------------
;; Pair Helpers
(defn quoted-p [a]
(p bel-quote (p a bel-nil)))
(defn seq->p
[xs]
(let [[x n & after-n] xs
after-x (rest xs)]
(if (empty? xs)
bel-nil
(p
x
(if (= bel-dot n)
(first-and-only after-n "dotted list _must_ have 1 exp after the dot")
(seq->p after-x))))))
(defn id [a b]
(let [id-f (if (pair? a) identical? =)]
(if (id-f a b) bel-t bel-nil)))
(defn join [a b]
(p a
(if (string? b) (seq->p b) b)))
(defn car [form]
(cond
(= bel-nil form) form
(string? form) (first form)
(not (pair? form))
(throw (Exception. (format "expected pair, got = %s" form)))
:else
(first form)))
(defn cdr [form]
(cond
(= bel-nil form) form
(string? form) (seq->p (rest form))
(not (pair? form))
(throw (Exception. (format "expected pair, got = %s" form)))
:else
(last form)))
(defn p->seq [form]
(if (= bel-nil form)
()
(cons
(car form)
(let [r (cdr form)]
(cond
(pair? r) (p->seq r)
(= bel-nil r) []
:else [r])))))
(defn xar [form y]
(.set form 0 y)
form)
(defn xdr [form y]
(.set form 1 y)
form)
(def sym symbol)
(def nom name)
(defn coin [] (rand-nth [bel-t bel-nil]))
(defn p-append [a b]
(cond
(= bel-nil a) b
(= bel-nil (cdr a)) (p (car a) b)
:else
(p
(car a)
(p-append (cdr a) b))))
;; ---------
;; Variable
(def bel-variable? symbol?)
;; ---------
;; Optional
(defn bel-optional? [[h]]
(= bel-o h))
(defn bel-optional-var [[_h [variable]]] variable)
(defn bel-optional-arg [[_h [_variable r]]] (car r))
;; ---------
(defn bel-typecheck? [[h]]
(= bel-t h))
(defn bel-typecheck-var [[_h [variable]]] variable)
(defn bel-typecheck-f [[_h [_variable r]]] (car r))
;; -------
Interop
(defn clj-bool->bel [x] (if x bel-t bel-nil))
;; ----
;; Maps
(defn map-get [m k]
(if (= m bel-nil)
bel-nil
(or (.get m k) bel-nil)))
(defn map-assoc [m k v]
(let [m' (if (= bel-nil m) {} m)]
(assoc m' k v)))
(defn map-dissoc [m k]
(if (= bel-nil m) bel-nil
(let [m' (dissoc m k)]
(if (empty? m') bel-nil m'))))
(defn mut-map []
(java.util.HashMap.))
(defn map-put [m k v]
(.put m k v))
(defn map-delete [m k]
(.remove m k))
| null | https://raw.githubusercontent.com/stopachka/bel-clojure/d1bb33d1cf498c5f7fd7e9a9bfb8d2c57e2fc5b3/src/bel_clojure/model.clj | clojure | ----
Misc
-------------
Primitive Types
---------
Pair Cons
---------
Constants
-------------
Pair Helpers
---------
Variable
---------
Optional
---------
-------
----
Maps | (ns bel-clojure.model
(:refer-clojure :rename {type clj-type
symbol? clj-symbol?
string? clj-string?
char? clj-char?
number? clj-number?})
(:import
(java.util ArrayList)))
(defn first-and-only [xs msg]
(assert (= (count xs) 1) msg)
(first xs))
(def string? clj-string?)
(def char? clj-char?)
(def symbol? clj-symbol?)
(def number? clj-number?)
(def pair? (comp (partial = java.util.ArrayList) clj-type))
(def mut-map? (comp (partial = java.util.HashMap) clj-type))
(def imm-map? (comp (partial = clojure.lang.PersistentArrayMap) clj-type))
(def clj-err? (partial instance? Throwable))
(defn type-nilable [x]
(cond
(symbol? x) 'symbol
(string? x) 'string
(char? x) 'char
(number? x) 'number
(pair? x) 'pair
(mut-map? x) 'mut-map
(imm-map? x) 'imm-map
(clj-err? x) 'clj-err
:else
(let [v (and (seqable? x) (first x))]
(when (#{:splice :comma :backquote} v)
(symbol (name v))))))
(defn type [x]
(let [v (type-nilable x)]
(assert v (format "Unsupported type for form = %s" x))
v))
(defn p
([a b]
(ArrayList. [a b])))
(def bel-quote 'quote)
(def bel-nil (symbol "nil"))
(def bel-t 't)
(def bel-err-sym 'err)
(def bel-dot [:dot "."])
(def bel-lit 'lit)
(def bel-prim 'prim)
(def bel-o 'o)
(def bel-a 'a)
(def bel-d 'd)
(def bel-apply 'apply)
(def bel-set 'set)
(def bel-clo 'clo)
(def bel-mac 'mac)
(def bel-globe 'globe)
(def bel-scope 'scope)
(def bel-if 'if)
(def bel-cont 'cont)
(defn quoted-p [a]
(p bel-quote (p a bel-nil)))
(defn seq->p
[xs]
(let [[x n & after-n] xs
after-x (rest xs)]
(if (empty? xs)
bel-nil
(p
x
(if (= bel-dot n)
(first-and-only after-n "dotted list _must_ have 1 exp after the dot")
(seq->p after-x))))))
(defn id [a b]
(let [id-f (if (pair? a) identical? =)]
(if (id-f a b) bel-t bel-nil)))
(defn join [a b]
(p a
(if (string? b) (seq->p b) b)))
(defn car [form]
(cond
(= bel-nil form) form
(string? form) (first form)
(not (pair? form))
(throw (Exception. (format "expected pair, got = %s" form)))
:else
(first form)))
(defn cdr [form]
(cond
(= bel-nil form) form
(string? form) (seq->p (rest form))
(not (pair? form))
(throw (Exception. (format "expected pair, got = %s" form)))
:else
(last form)))
(defn p->seq [form]
(if (= bel-nil form)
()
(cons
(car form)
(let [r (cdr form)]
(cond
(pair? r) (p->seq r)
(= bel-nil r) []
:else [r])))))
(defn xar [form y]
(.set form 0 y)
form)
(defn xdr [form y]
(.set form 1 y)
form)
(def sym symbol)
(def nom name)
(defn coin [] (rand-nth [bel-t bel-nil]))
(defn p-append [a b]
(cond
(= bel-nil a) b
(= bel-nil (cdr a)) (p (car a) b)
:else
(p
(car a)
(p-append (cdr a) b))))
(def bel-variable? symbol?)
(defn bel-optional? [[h]]
(= bel-o h))
(defn bel-optional-var [[_h [variable]]] variable)
(defn bel-optional-arg [[_h [_variable r]]] (car r))
(defn bel-typecheck? [[h]]
(= bel-t h))
(defn bel-typecheck-var [[_h [variable]]] variable)
(defn bel-typecheck-f [[_h [_variable r]]] (car r))
Interop
(defn clj-bool->bel [x] (if x bel-t bel-nil))
(defn map-get [m k]
(if (= m bel-nil)
bel-nil
(or (.get m k) bel-nil)))
(defn map-assoc [m k v]
(let [m' (if (= bel-nil m) {} m)]
(assoc m' k v)))
(defn map-dissoc [m k]
(if (= bel-nil m) bel-nil
(let [m' (dissoc m k)]
(if (empty? m') bel-nil m'))))
(defn mut-map []
(java.util.HashMap.))
(defn map-put [m k v]
(.put m k v))
(defn map-delete [m k]
(.remove m k))
|
dea4a90d5e6cf65ea7de2c7c704bed93620a9ca64a170777fdbeb6dd6ac19ccd | logseq/deprecated-github-backend | interceptors.clj | (ns app.interceptors
(:require [io.pedestal.interceptor :refer [interceptor]]
[io.pedestal.interceptor.helpers :as helpers]
[io.pedestal.http.ring-middlewares :as ring-middlewares]
[app.cookie :as cookie]
[app.jwt :as jwt]
[app.db.user :as u]
[app.db.repo :as repo]
[app.db.project :as project]
[app.util :as util]
[ring.util.response :as resp]
[app.config :as config]
[app.interceptor.etag :as etag]
[app.interceptor.gzip :as gzip]
[app.slack :as slack]))
;; move to a separate handler helper
(defn logout
[_req]
(-> (resp/redirect config/website-uri)
(assoc :cookies cookie/delete-token)))
(defonce users-cache
(atom {}))
(defn clear-user-cache
[user-id]
(swap! users-cache dissoc user-id))
(def cookie-interceptor
(interceptor
{:name ::cookie-authenticate
:enter
(fn [{:keys [request] :as context}]
(let [tokens (cookie/get-tokens request)]
(if tokens
(let [{:keys [access-token refresh-token]} tokens]
(if access-token
(try
(let [{:keys [id access-token]} (jwt/unsign access-token)
uid (some-> id util/->uuid)
user (when-let [user (u/get uid)]
(let [repos (map #(select-keys % [:id :url :branch :installation_id])
(repo/get-user-repos uid))
projects (map
(fn [project]
(let [repo-id (:repo_id project)
project (select-keys project [:name :description])]
(assoc project :repo
(:url (first (filter (fn [repo] (= (:id repo) repo-id)) repos))))))
(project/get-user-projects uid))
user (assoc user
:repos repos
:projects projects)
user (assoc user :preferred_format
(:preferred_format user))]
(swap! users-cache assoc uid user)
user))]
(if (:id user)
(-> context
(assoc-in [:request :app-context :uid] uid)
(assoc-in [:request :app-context :user] (assoc user :access-token access-token)))
context))
(catch Exception e ; token is expired
(when (= (ex-data e)
{:type :validation, :cause :exp})
(slack/debug "Jwt token expired: " {:token access-token
:e e})
(assoc context :response (logout request)))))))
context)))}))
(defn cache-control
[max-age]
{:name ::cache-control
:leave (fn [{:keys [response] :as context}]
(let [{:keys [status headers]} response
response (if (= 200 status)
(let [val (if (= :no-cache max-age)
"no-cache"
(str "public, max-age=" max-age))]
(assoc-in response [:headers "Cache-Control"] val))
response)]
(assoc context :response response)))})
(def etag-interceptor etag/etag-interceptor)
(def gzip-interceptor gzip/gzip-interceptor)
| null | https://raw.githubusercontent.com/logseq/deprecated-github-backend/7aa2f187f0f2d7b1e9c3f6a057bede939b4790b7/src/main/app/interceptors.clj | clojure | move to a separate handler helper
token is expired | (ns app.interceptors
(:require [io.pedestal.interceptor :refer [interceptor]]
[io.pedestal.interceptor.helpers :as helpers]
[io.pedestal.http.ring-middlewares :as ring-middlewares]
[app.cookie :as cookie]
[app.jwt :as jwt]
[app.db.user :as u]
[app.db.repo :as repo]
[app.db.project :as project]
[app.util :as util]
[ring.util.response :as resp]
[app.config :as config]
[app.interceptor.etag :as etag]
[app.interceptor.gzip :as gzip]
[app.slack :as slack]))
(defn logout
[_req]
(-> (resp/redirect config/website-uri)
(assoc :cookies cookie/delete-token)))
(defonce users-cache
(atom {}))
(defn clear-user-cache
[user-id]
(swap! users-cache dissoc user-id))
(def cookie-interceptor
(interceptor
{:name ::cookie-authenticate
:enter
(fn [{:keys [request] :as context}]
(let [tokens (cookie/get-tokens request)]
(if tokens
(let [{:keys [access-token refresh-token]} tokens]
(if access-token
(try
(let [{:keys [id access-token]} (jwt/unsign access-token)
uid (some-> id util/->uuid)
user (when-let [user (u/get uid)]
(let [repos (map #(select-keys % [:id :url :branch :installation_id])
(repo/get-user-repos uid))
projects (map
(fn [project]
(let [repo-id (:repo_id project)
project (select-keys project [:name :description])]
(assoc project :repo
(:url (first (filter (fn [repo] (= (:id repo) repo-id)) repos))))))
(project/get-user-projects uid))
user (assoc user
:repos repos
:projects projects)
user (assoc user :preferred_format
(:preferred_format user))]
(swap! users-cache assoc uid user)
user))]
(if (:id user)
(-> context
(assoc-in [:request :app-context :uid] uid)
(assoc-in [:request :app-context :user] (assoc user :access-token access-token)))
context))
(when (= (ex-data e)
{:type :validation, :cause :exp})
(slack/debug "Jwt token expired: " {:token access-token
:e e})
(assoc context :response (logout request)))))))
context)))}))
(defn cache-control
[max-age]
{:name ::cache-control
:leave (fn [{:keys [response] :as context}]
(let [{:keys [status headers]} response
response (if (= 200 status)
(let [val (if (= :no-cache max-age)
"no-cache"
(str "public, max-age=" max-age))]
(assoc-in response [:headers "Cache-Control"] val))
response)]
(assoc context :response response)))})
(def etag-interceptor etag/etag-interceptor)
(def gzip-interceptor gzip/gzip-interceptor)
|
b12f5adedcabc072eccc214d3a6bbaa0001b46447cd1031ea5ec331badd39cbd | Haskell-Things/HSlice | Motorcycles.hs | {- ORMOLU_DISABLE -}
- Copyright 2021
-
- This program is free software : you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation , either version 3 of the License , or
- ( at your option ) any later version .
-
- This program is distributed in the hope that it will be useful ,
- but WITHOUT ANY WARRANTY ; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
- GNU Affero General Public License for more details .
- You should have received a copy of the GNU Affero General Public License
- along with this program . If not , see < / > .
- Copyright 2021 Julia Longtin
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see </>.
-}
{- Purpose of this file: to hold the logic and routines required for coliding
motorcycles, making motorcycle graphs, and generally reasoning about
motorcycles.
-}
-- inherit instances when deriving.
# LANGUAGE DerivingStrategies #
module Graphics.Slicer.Math.Skeleton.Motorcycles (CollisionType(HeadOn), CrashTree(CrashTree), motorcycleToENode, Collision(Collision), motorcycleIntersectsAt, intersectionSameSide, crashMotorcycles, collisionResult, convexMotorcycles, lastCrashType, motorcyclesAreAntiCollinear, motorcyclesInDivision, motorcycleMightIntersectWith, motorcycleDivisor) where
import Prelude (Bool(True, False), Either(Left,Right), Eq((==)), Show(show), Ordering (EQ, GT, LT), (&&), (<>), ($), (>), (+), compare, error, fst, mempty, notElem, null, otherwise, snd, zip)
import Prelude as PL (init, last)
import Data.Maybe( Maybe(Just,Nothing), fromMaybe, mapMaybe)
import Data.List (sortBy)
import Slist (slist, safeLast, head, len)
import Slist as SL (filter)
import Slist.Type (Slist(Slist))
import Graphics.Slicer.Definitions (β)
import Graphics.Slicer.Math.Arcs (getInsideArc)
import Graphics.Slicer.Math.ContourIntersections (getMotorcycleContourIntersections, getMotorcycleSegSetIntersections)
import Graphics.Slicer.Math.Definitions (Contour, LineSeg, Point2, distance, mapWithNeighbors, startPoint, endPoint, makeLineSeg, pointsOfContour)
import Graphics.Slicer.Math.Intersections (noIntersection, intersectionBetweenArcsOf, isAntiCollinear, outputIntersectsLineSeg, outputIntersectsPLineAt)
import Graphics.Slicer.Math.Lossy (pPointBetweenPPoints, distanceBetweenPPoints, distanceBetweenPPointsWithErr, eToPLine2)
import Graphics.Slicer.Math.PGA (Arcable(outOf), PIntersection(IntersectsIn), PLine2Err, Pointable(canPoint, cPPointOf, ePointOf), ProjectiveLine, ProjectivePoint, cPPointAndErrOf, eToPL, eToPP, flipL, join2EP, join2PP, pLineIsLeft, pPointsOnSameSideOfPLine, translateL, oppositeDirection, outAndErrOf)
import Graphics.Slicer.Math.Skeleton.Definitions (Motorcycle(Motorcycle), ENode(ENode), getFirstLineSeg, linePairs, CellDivide(CellDivide), DividingMotorcycles(DividingMotorcycles), MotorcycleIntersection(WithLineSeg, WithENode, WithMotorcycle))
| The collision of two motorcycles . one lives , and one does n't , unless it 's a head on collision , in which case both die , and there is no survivor .
data Collision = Collision { _inMotorcycles :: !(Motorcycle, Motorcycle, Slist Motorcycle), _survivor :: !(Maybe Motorcycle), collisionResult :: !CollisionType }
deriving (Eq, Show)
-- | the type of collision.
-- only normal collisions (motorcycle intersects the other motorcycle's path) are survivable, and then only by the motorcycle who's path was collided with.
If two motorcycles collide at the same time .. the solution can not be found ?
data CollisionType =
Normal -- a motorcycle runs into the path of another motorcycle.
two motorcycles are anti - parallel , and do n't intersect the contour at any point other than each other 's origin .
two motorcycles arrive at the same time , in the same location .
deriving (Eq, Show)
-- | the resulting node graph for a given contour.
data CrashTree = CrashTree { _motorcycles :: !(Slist Motorcycle), _survivors :: !(Slist Motorcycle), _crashes :: !(Slist Collision) }
deriving (Eq, Show)
| convert a Motorcycle to an ENode
motorcycleToENode :: Motorcycle -> ENode
motorcycleToENode (Motorcycle (seg1,seg2) mcpath mcErr) = ENode (startPoint seg1, startPoint seg2, endPoint seg2) mcpath mcErr
-- | Find the point where the propogation from a motorcycle equals the propogation of what it impacts, taking into account the weight of a motorcycle, and the weight of what it impacts.
motorcycleDivisor :: Motorcycle -> MotorcycleIntersection -> ProjectivePoint
motorcycleDivisor motorcycle target = pPointBetweenPPoints (cPPointOf motorcycle) (fst pointOfTarget) (tSpeedOf target) (mSpeedOf motorcycle)
where
pointOfTarget = case target of
(WithLineSeg lineSeg) -> case outputIntersectsLineSeg motorcycle lineSeg of
(Right (IntersectsIn p (_,_, pErr))) -> (p, pErr)
v -> error $ "impossible!\n" <> show v <> "\n" <> show lineSeg <> "\n" <> show motorcycle <> "\n" <> show target <> "\n"
(WithENode eNode) -> cPPointAndErrOf eNode
(WithMotorcycle motorcycle2) -> cPPointAndErrOf motorcycle2
tSpeedOf :: MotorcycleIntersection -> β
tSpeedOf myTarget = case myTarget of
(WithLineSeg lineSeg) -> distanceBetweenPPointsWithErr
(fromMaybe (error "no outArc?") $ outputIntersectsPLineAt motorcycle (translateL (eToPLine2 lineSeg) 1))
(fromMaybe (error "no outArc?") $ outputIntersectsPLineAt motorcycle (eToPL lineSeg))
(WithENode eNode) -> distanceBetweenPPointsWithErr
(cPPointAndErrOf eNode)
(fromMaybe (error "no outArc?") $ outputIntersectsPLineAt eNode (translateL (eToPLine2 $ getFirstLineSeg eNode) 1))
(WithMotorcycle motorcycle2) -> mSpeedOf motorcycle2
mSpeedOf :: Motorcycle -> β
mSpeedOf myMotorcycle@(Motorcycle (seg1,_) _ _) = distanceBetweenPPointsWithErr
(cPPointAndErrOf myMotorcycle)
(fromMaybe (error "no outArc?") $ outputIntersectsPLineAt myMotorcycle (translateL (eToPLine2 seg1) 1))
-- | Create a crash tree for all of the motorcycles in the given contour, with the given holes.
-- FIXME: may fail, returning Nothing.
crashMotorcycles :: Contour -> [Contour] -> Maybe CrashTree
crashMotorcycles contour holes
| null holes = getCrashTree contour (slist firstMotorcycles) [] (slist []) False
| otherwise = Nothing
where
firstMotorcycles
| null holes = convexMotorcycles contour
| otherwise = error "cannot crash with holes yet."
-- FIXME: not yet used.
--firstMotorcyclesOfHoles = concaveMotorcycles <$> holes
-- | Get a crash tree of the motorcycles within a contour.
-- This Function is meant to be recursed, to give us a CrashTree. when it's complete... not yet.
-- For now, just cover the cases we know what to do with.
getCrashTree :: Contour -> Slist Motorcycle -> [Motorcycle] -> Slist Collision -> Bool -> Maybe CrashTree
getCrashTree contour inMotorcycles crashedMotorcycles inCrashes hasHoles
| hasHoles = error "do not support holes yet"
-- We're done.
| null findSurvivors = Just $ CrashTree inMotorcycles findSurvivors inCrashes
| null crashedMotorcycles = case inMotorcycles of
(Slist [] _) -> -- there is no-one to collide with.
Just $ CrashTree inMotorcycles inMotorcycles (slist [])
There is only one motorcycle .
Just $ CrashTree inMotorcycles inMotorcycles (slist [])
(Slist [firstMC, secondMC] 2) -> case crashOf firstMC secondMC of
Just collision ->
Just $ CrashTree inMotorcycles (slist []) (slist [collision])
Nothing ->
Just $ CrashTree inMotorcycles inMotorcycles (slist [])
(Slist (_:_) _) -> Nothing
-- Note that to solve this case, we will have to have a concept of speed of the motorcycle.
| otherwise = Nothing
where
-- determine the set of motorcycles have not yet had a crash.
findSurvivors = SL.filter (`notElem` crashedMotorcycles) inMotorcycles
Crash just two motorcycles . Returns Nothing when the motorcycles ca n't collide .
crashOf :: Motorcycle -> Motorcycle -> Maybe Collision
crashOf mot1 mot2@(Motorcycle (inSeg2, _) _ _)
-- If we have a clear path between mot1 and the origin of mot2
| isAntiCollinear (outAndErrOf mot1) (outAndErrOf mot2) && motorcycleIntersectsAt contour mot1 == (inSeg2, Left $ endPoint inSeg2) = Just $ Collision (mot1,mot2, slist []) Nothing HeadOn
| noIntersection (outAndErrOf mot1) (outAndErrOf mot2) = Nothing
| intersectionIsBehind mot1 = Nothing
| intersectionIsBehind mot2 = Nothing
-- FIXME: this should be providing a distance to intersectionPPoint along the motorcycle to check.
| otherwise = case getMotorcycleContourIntersections mot1 contour of
[] -> case distanceBetweenPPointsWithErr (cPPointAndErrOf mot1) intersectionPPoint `compare` distanceBetweenPPointsWithErr (cPPointAndErrOf mot2) intersectionPPoint of
GT -> Just $ Collision (mot1, mot2, slist []) (Just mot2) Normal
LT -> Just $ Collision (mot1, mot2, slist []) (Just mot1) Normal
EQ -> Just $ Collision (mot1, mot2, slist []) (Just mot1) SideSwipe
_ -> Nothing
where
intersectionPPoint = fromMaybe (error "has arcs, but no intersection?") $ intersectionBetweenArcsOf mot1 mot2
intersectionIsBehind m = oppositeDirection (outOf m) (fst $ join2PP (cPPointOf m) (fst intersectionPPoint))
| Find the non - reflex virtexes of a contour and draw motorcycles from them . Useful for contours that are a ' hole ' in a bigger contour .
-- This function is meant to be used on the exterior contour.
convexMotorcycles :: Contour -> [Motorcycle]
convexMotorcycles contour = mapMaybe onlyMotorcycles $ zip (rotateLeft $ linePairs contour) (mapWithNeighbors convexPLines $ pointsOfContour contour)
where
rotateLeft a = PL.last a : PL.init a
onlyMotorcycles :: ((LineSeg, LineSeg), Maybe (ProjectiveLine, PLine2Err, β)) -> Maybe Motorcycle
onlyMotorcycles ((seg1, seg2), maybePLine) = case maybePLine of
(Just (pLine, pLineErr, _)) -> Just $ Motorcycle (seg1, seg2) pLine pLineErr
Nothing -> Nothing
| Examine two line segments that are part of a Contour , and determine if they are convex from the perspective of the interior of the Contour . if they are , construct a PLine2 bisecting them , pointing toward the interior .
Note that we know that the inside is to the left of the first line given , and that the first line points toward the intersection .
convexPLines :: Point2 -> Point2 -> Point2 -> Maybe (ProjectiveLine, PLine2Err, β)
convexPLines p1 p2 p3
| pl1 `pLineIsLeft` pl2 == Just True = Nothing
| otherwise = Just (fst resPLine, snd resPLine, distance p1 p2 + distance p2 p3)
where
resPLine = motorcycleFromPoints p1 p2 p3
pl1 = eToPLine2 $ makeLineSeg p1 p2
pl2 = eToPLine2 $ makeLineSeg p2 p3
| generate the PLine2 of a motorcycle created by the three points given .
motorcycleFromPoints :: Point2 -> Point2 -> Point2 -> (ProjectiveLine, PLine2Err)
motorcycleFromPoints p1 p2 p3 = (flipL res, resErr)
where
(res, resErr) = getInsideArc firstLine secondLine
where
firstLine = join2EP p1 p2
secondLine = join2EP p2 p3
-- | Find where a motorcycle intersects a set of line segments, if it does.
motorcycleMightIntersectWith :: [LineSeg] -> Motorcycle -> Maybe (LineSeg, Either Point2 ProjectivePoint)
motorcycleMightIntersectWith lineSegs motorcycle
| null lineSegs = error "no line segments to intersect motorcycle with?"
| otherwise = case intersections of
[] -> Nothing
[a] -> filterIntersection a
(_:_) -> if len results > 0
then Just $ head results
else Nothing
where
intersections = getMotorcycleSegSetIntersections motorcycle lineSegs
results :: Slist (LineSeg, Either Point2 ProjectivePoint)
results = slist $ sortByDistance $ mapMaybe filterIntersection intersections
sortByDistance :: [(LineSeg, Either Point2 ProjectivePoint)] -> [(LineSeg, Either Point2 ProjectivePoint)]
sortByDistance = sortBy compareDistances
motorcyclePoint = cPPointAndErrOf motorcycle
compareDistances i1 i2 = case i1 of
(_, Right intersectionPPoint1) ->
case i2 of
(_, Right intersectionPPoint2) ->
distanceBetweenPPointsWithErr motorcyclePoint (intersectionPPoint1, mempty) `compare` distanceBetweenPPointsWithErr motorcyclePoint (intersectionPPoint2, mempty)
(_, Left intersectionPoint2) ->
distanceBetweenPPointsWithErr motorcyclePoint (intersectionPPoint1, mempty) `compare` distanceBetweenPPointsWithErr motorcyclePoint (eToPP intersectionPoint2, mempty)
(_, Left intersectionPoint1) ->
case i2 of
(_, Right intersectionPPoint2) ->
distanceBetweenPPointsWithErr motorcyclePoint (eToPP intersectionPoint1, mempty) `compare` distanceBetweenPPointsWithErr motorcyclePoint (intersectionPPoint2, mempty)
(_, Left intersectionPoint2) ->
distanceBetweenPPointsWithErr motorcyclePoint (eToPP intersectionPoint1, mempty) `compare` distanceBetweenPPointsWithErr motorcyclePoint (eToPP intersectionPoint2, mempty)
filterIntersection :: (LineSeg, Either Point2 ProjectivePoint) -> Maybe (LineSeg, Either Point2 ProjectivePoint)
filterIntersection intersection = case intersection of
(_, Right intersectionPPoint) -> if intersectionPPointIsBehind intersectionPPoint
then Nothing
else Just intersection
(_, Left intersectionPoint) -> if intersectionPointIsBehind intersectionPoint
then Nothing
else Just intersection
where
intersectionPointIsBehind point = oppositeDirection (outOf motorcycle) (eToPLine2 $ makeLineSeg (ePointOf motorcycle) point)
intersectionPPointIsBehind pPoint = oppositeDirection (outOf motorcycle) (fst $ join2PP (cPPointOf motorcycle) pPoint)
-- | Find the closest place where a motorcycle intersects a contour that is not the point where it ejects from.
If the motorcycle lands between two segments , return the second line segment , otherwise return the ProjectivePoint of the intersection with the first LineSeg .
motorcycleIntersectsAt :: Contour -> Motorcycle -> (LineSeg, Either Point2 ProjectivePoint)
motorcycleIntersectsAt contour motorcycle = case intersections of
[] -> error "no intersections?"
[a] -> fromMaybe (error $ "eliminated my only option\n" <> show a
) $ filterIntersection a
manyIntersections@(_:_) -> if len res > 0 then head res else error $ "no options: " <> show (len res) <> "\n" <> show res <> "\n"
where
res = slist $ sortBy compareDistances $ mapMaybe filterIntersection manyIntersections
compareDistances :: (LineSeg, Either Point2 ProjectivePoint) -> (LineSeg, Either Point2 ProjectivePoint) -> Ordering
compareDistances i1 i2 = case i1 of
(_, Right intersectionPPoint1) ->
case i2 of
(_, Right intersectionPPoint2) ->
distanceBetweenPPoints motorcyclePoint intersectionPPoint1 `compare` distanceBetweenPPoints motorcyclePoint intersectionPPoint2
(_, Left intersectionPoint2) ->
distanceBetweenPPoints motorcyclePoint intersectionPPoint1 `compare` distanceBetweenPPoints motorcyclePoint (eToPP intersectionPoint2)
(_, Left intersectionPoint1) ->
case i2 of
(_, Right intersectionPPoint2) ->
distanceBetweenPPoints motorcyclePoint (eToPP intersectionPoint1) `compare` distanceBetweenPPoints motorcyclePoint intersectionPPoint2
(_, Left intersectionPoint2) ->
distanceBetweenPPoints motorcyclePoint (eToPP intersectionPoint1) `compare` distanceBetweenPPoints motorcyclePoint (eToPP intersectionPoint2)
where
filterIntersection :: (LineSeg, Either Point2 ProjectivePoint) -> Maybe (LineSeg, Either Point2 ProjectivePoint)
filterIntersection intersection = case intersection of
(_, Right intersectionPPoint) -> if intersectionPPointIsBehind intersectionPPoint
then Nothing
else Just intersection
(_, Left intersectionPoint) -> if intersectionPointIsBehind intersectionPoint
then Nothing
else Just intersection
where
intersectionPointIsBehind point = oppositeDirection (outOf motorcycle) (fst $ join2PP (cPPointOf motorcycle) (eToPP point))
intersectionPPointIsBehind pPoint = oppositeDirection (outOf motorcycle) (fst $ join2PP (cPPointOf motorcycle) pPoint)
motorcyclePoint = cPPointOf motorcycle
intersections = getMotorcycleContourIntersections motorcycle contour
| Determine if a node is on one side of a motorcycle , or the other .
Assumes the starting point of the second line segment is a point on the path .
# INLINABLE intersectionSameSide #
intersectionSameSide :: (Pointable a) => ProjectivePoint -> a -> Motorcycle -> Maybe Bool
intersectionSameSide pointOnSide node (Motorcycle _ path _)
| canPoint node = pPointsOnSameSideOfPLine (cPPointOf node) pointOnSide path
| otherwise = error $ "cannot resolve provided item to a point: " <> show node <> "\n"
| Check if the output of two motorcycles are anti - collinear with each other .
motorcyclesAreAntiCollinear :: Motorcycle -> Motorcycle -> Bool
motorcyclesAreAntiCollinear motorcycle1 motorcycle2 = isAntiCollinear (outAndErrOf motorcycle1) (outAndErrOf motorcycle2)
| Return the total set of motorcycles in the given CellDivide
motorcyclesInDivision :: CellDivide -> [Motorcycle]
motorcyclesInDivision (CellDivide (DividingMotorcycles a (Slist b _)) _) = a : b
Determine the type of the last crash that occured in a crashtree . only useful when we 're dealing with a pair motorcycles , and want to find out if we can treat them like one motorcycle .
lastCrashType :: CrashTree -> Maybe CollisionType
lastCrashType crashTree = case lastCrash crashTree of
(Just crash) -> if collisionResult crash == HeadOn
then Just HeadOn
else Nothing
Nothing -> Nothing
where
lastCrash :: CrashTree -> Maybe Collision
lastCrash (CrashTree _ _ crashes) = case safeLast crashes of
Nothing -> Nothing
(Just crash) -> Just crash
| null | https://raw.githubusercontent.com/Haskell-Things/HSlice/09389e9f31d39e7f2fa126d2390028253bb43056/Graphics/Slicer/Math/Skeleton/Motorcycles.hs | haskell | ORMOLU_DISABLE
Purpose of this file: to hold the logic and routines required for coliding
motorcycles, making motorcycle graphs, and generally reasoning about
motorcycles.
inherit instances when deriving.
| the type of collision.
only normal collisions (motorcycle intersects the other motorcycle's path) are survivable, and then only by the motorcycle who's path was collided with.
a motorcycle runs into the path of another motorcycle.
| the resulting node graph for a given contour.
| Find the point where the propogation from a motorcycle equals the propogation of what it impacts, taking into account the weight of a motorcycle, and the weight of what it impacts.
| Create a crash tree for all of the motorcycles in the given contour, with the given holes.
FIXME: may fail, returning Nothing.
FIXME: not yet used.
firstMotorcyclesOfHoles = concaveMotorcycles <$> holes
| Get a crash tree of the motorcycles within a contour.
This Function is meant to be recursed, to give us a CrashTree. when it's complete... not yet.
For now, just cover the cases we know what to do with.
We're done.
there is no-one to collide with.
Note that to solve this case, we will have to have a concept of speed of the motorcycle.
determine the set of motorcycles have not yet had a crash.
If we have a clear path between mot1 and the origin of mot2
FIXME: this should be providing a distance to intersectionPPoint along the motorcycle to check.
This function is meant to be used on the exterior contour.
| Find where a motorcycle intersects a set of line segments, if it does.
| Find the closest place where a motorcycle intersects a contour that is not the point where it ejects from. |
- Copyright 2021
-
- This program is free software : you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation , either version 3 of the License , or
- ( at your option ) any later version .
-
- This program is distributed in the hope that it will be useful ,
- but WITHOUT ANY WARRANTY ; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
- GNU Affero General Public License for more details .
- You should have received a copy of the GNU Affero General Public License
- along with this program . If not , see < / > .
- Copyright 2021 Julia Longtin
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see </>.
-}
# LANGUAGE DerivingStrategies #
module Graphics.Slicer.Math.Skeleton.Motorcycles (CollisionType(HeadOn), CrashTree(CrashTree), motorcycleToENode, Collision(Collision), motorcycleIntersectsAt, intersectionSameSide, crashMotorcycles, collisionResult, convexMotorcycles, lastCrashType, motorcyclesAreAntiCollinear, motorcyclesInDivision, motorcycleMightIntersectWith, motorcycleDivisor) where
import Prelude (Bool(True, False), Either(Left,Right), Eq((==)), Show(show), Ordering (EQ, GT, LT), (&&), (<>), ($), (>), (+), compare, error, fst, mempty, notElem, null, otherwise, snd, zip)
import Prelude as PL (init, last)
import Data.Maybe( Maybe(Just,Nothing), fromMaybe, mapMaybe)
import Data.List (sortBy)
import Slist (slist, safeLast, head, len)
import Slist as SL (filter)
import Slist.Type (Slist(Slist))
import Graphics.Slicer.Definitions (β)
import Graphics.Slicer.Math.Arcs (getInsideArc)
import Graphics.Slicer.Math.ContourIntersections (getMotorcycleContourIntersections, getMotorcycleSegSetIntersections)
import Graphics.Slicer.Math.Definitions (Contour, LineSeg, Point2, distance, mapWithNeighbors, startPoint, endPoint, makeLineSeg, pointsOfContour)
import Graphics.Slicer.Math.Intersections (noIntersection, intersectionBetweenArcsOf, isAntiCollinear, outputIntersectsLineSeg, outputIntersectsPLineAt)
import Graphics.Slicer.Math.Lossy (pPointBetweenPPoints, distanceBetweenPPoints, distanceBetweenPPointsWithErr, eToPLine2)
import Graphics.Slicer.Math.PGA (Arcable(outOf), PIntersection(IntersectsIn), PLine2Err, Pointable(canPoint, cPPointOf, ePointOf), ProjectiveLine, ProjectivePoint, cPPointAndErrOf, eToPL, eToPP, flipL, join2EP, join2PP, pLineIsLeft, pPointsOnSameSideOfPLine, translateL, oppositeDirection, outAndErrOf)
import Graphics.Slicer.Math.Skeleton.Definitions (Motorcycle(Motorcycle), ENode(ENode), getFirstLineSeg, linePairs, CellDivide(CellDivide), DividingMotorcycles(DividingMotorcycles), MotorcycleIntersection(WithLineSeg, WithENode, WithMotorcycle))
| The collision of two motorcycles . one lives , and one does n't , unless it 's a head on collision , in which case both die , and there is no survivor .
data Collision = Collision { _inMotorcycles :: !(Motorcycle, Motorcycle, Slist Motorcycle), _survivor :: !(Maybe Motorcycle), collisionResult :: !CollisionType }
deriving (Eq, Show)
If two motorcycles collide at the same time .. the solution can not be found ?
data CollisionType =
two motorcycles are anti - parallel , and do n't intersect the contour at any point other than each other 's origin .
two motorcycles arrive at the same time , in the same location .
deriving (Eq, Show)
data CrashTree = CrashTree { _motorcycles :: !(Slist Motorcycle), _survivors :: !(Slist Motorcycle), _crashes :: !(Slist Collision) }
deriving (Eq, Show)
| convert a Motorcycle to an ENode
motorcycleToENode :: Motorcycle -> ENode
motorcycleToENode (Motorcycle (seg1,seg2) mcpath mcErr) = ENode (startPoint seg1, startPoint seg2, endPoint seg2) mcpath mcErr
motorcycleDivisor :: Motorcycle -> MotorcycleIntersection -> ProjectivePoint
motorcycleDivisor motorcycle target = pPointBetweenPPoints (cPPointOf motorcycle) (fst pointOfTarget) (tSpeedOf target) (mSpeedOf motorcycle)
where
pointOfTarget = case target of
(WithLineSeg lineSeg) -> case outputIntersectsLineSeg motorcycle lineSeg of
(Right (IntersectsIn p (_,_, pErr))) -> (p, pErr)
v -> error $ "impossible!\n" <> show v <> "\n" <> show lineSeg <> "\n" <> show motorcycle <> "\n" <> show target <> "\n"
(WithENode eNode) -> cPPointAndErrOf eNode
(WithMotorcycle motorcycle2) -> cPPointAndErrOf motorcycle2
tSpeedOf :: MotorcycleIntersection -> β
tSpeedOf myTarget = case myTarget of
(WithLineSeg lineSeg) -> distanceBetweenPPointsWithErr
(fromMaybe (error "no outArc?") $ outputIntersectsPLineAt motorcycle (translateL (eToPLine2 lineSeg) 1))
(fromMaybe (error "no outArc?") $ outputIntersectsPLineAt motorcycle (eToPL lineSeg))
(WithENode eNode) -> distanceBetweenPPointsWithErr
(cPPointAndErrOf eNode)
(fromMaybe (error "no outArc?") $ outputIntersectsPLineAt eNode (translateL (eToPLine2 $ getFirstLineSeg eNode) 1))
(WithMotorcycle motorcycle2) -> mSpeedOf motorcycle2
mSpeedOf :: Motorcycle -> β
mSpeedOf myMotorcycle@(Motorcycle (seg1,_) _ _) = distanceBetweenPPointsWithErr
(cPPointAndErrOf myMotorcycle)
(fromMaybe (error "no outArc?") $ outputIntersectsPLineAt myMotorcycle (translateL (eToPLine2 seg1) 1))
crashMotorcycles :: Contour -> [Contour] -> Maybe CrashTree
crashMotorcycles contour holes
| null holes = getCrashTree contour (slist firstMotorcycles) [] (slist []) False
| otherwise = Nothing
where
firstMotorcycles
| null holes = convexMotorcycles contour
| otherwise = error "cannot crash with holes yet."
getCrashTree :: Contour -> Slist Motorcycle -> [Motorcycle] -> Slist Collision -> Bool -> Maybe CrashTree
getCrashTree contour inMotorcycles crashedMotorcycles inCrashes hasHoles
| hasHoles = error "do not support holes yet"
| null findSurvivors = Just $ CrashTree inMotorcycles findSurvivors inCrashes
| null crashedMotorcycles = case inMotorcycles of
Just $ CrashTree inMotorcycles inMotorcycles (slist [])
There is only one motorcycle .
Just $ CrashTree inMotorcycles inMotorcycles (slist [])
(Slist [firstMC, secondMC] 2) -> case crashOf firstMC secondMC of
Just collision ->
Just $ CrashTree inMotorcycles (slist []) (slist [collision])
Nothing ->
Just $ CrashTree inMotorcycles inMotorcycles (slist [])
(Slist (_:_) _) -> Nothing
| otherwise = Nothing
where
findSurvivors = SL.filter (`notElem` crashedMotorcycles) inMotorcycles
Crash just two motorcycles . Returns Nothing when the motorcycles ca n't collide .
crashOf :: Motorcycle -> Motorcycle -> Maybe Collision
crashOf mot1 mot2@(Motorcycle (inSeg2, _) _ _)
| isAntiCollinear (outAndErrOf mot1) (outAndErrOf mot2) && motorcycleIntersectsAt contour mot1 == (inSeg2, Left $ endPoint inSeg2) = Just $ Collision (mot1,mot2, slist []) Nothing HeadOn
| noIntersection (outAndErrOf mot1) (outAndErrOf mot2) = Nothing
| intersectionIsBehind mot1 = Nothing
| intersectionIsBehind mot2 = Nothing
| otherwise = case getMotorcycleContourIntersections mot1 contour of
[] -> case distanceBetweenPPointsWithErr (cPPointAndErrOf mot1) intersectionPPoint `compare` distanceBetweenPPointsWithErr (cPPointAndErrOf mot2) intersectionPPoint of
GT -> Just $ Collision (mot1, mot2, slist []) (Just mot2) Normal
LT -> Just $ Collision (mot1, mot2, slist []) (Just mot1) Normal
EQ -> Just $ Collision (mot1, mot2, slist []) (Just mot1) SideSwipe
_ -> Nothing
where
intersectionPPoint = fromMaybe (error "has arcs, but no intersection?") $ intersectionBetweenArcsOf mot1 mot2
intersectionIsBehind m = oppositeDirection (outOf m) (fst $ join2PP (cPPointOf m) (fst intersectionPPoint))
| Find the non - reflex virtexes of a contour and draw motorcycles from them . Useful for contours that are a ' hole ' in a bigger contour .
convexMotorcycles :: Contour -> [Motorcycle]
convexMotorcycles contour = mapMaybe onlyMotorcycles $ zip (rotateLeft $ linePairs contour) (mapWithNeighbors convexPLines $ pointsOfContour contour)
where
rotateLeft a = PL.last a : PL.init a
onlyMotorcycles :: ((LineSeg, LineSeg), Maybe (ProjectiveLine, PLine2Err, β)) -> Maybe Motorcycle
onlyMotorcycles ((seg1, seg2), maybePLine) = case maybePLine of
(Just (pLine, pLineErr, _)) -> Just $ Motorcycle (seg1, seg2) pLine pLineErr
Nothing -> Nothing
| Examine two line segments that are part of a Contour , and determine if they are convex from the perspective of the interior of the Contour . if they are , construct a PLine2 bisecting them , pointing toward the interior .
Note that we know that the inside is to the left of the first line given , and that the first line points toward the intersection .
convexPLines :: Point2 -> Point2 -> Point2 -> Maybe (ProjectiveLine, PLine2Err, β)
convexPLines p1 p2 p3
| pl1 `pLineIsLeft` pl2 == Just True = Nothing
| otherwise = Just (fst resPLine, snd resPLine, distance p1 p2 + distance p2 p3)
where
resPLine = motorcycleFromPoints p1 p2 p3
pl1 = eToPLine2 $ makeLineSeg p1 p2
pl2 = eToPLine2 $ makeLineSeg p2 p3
| generate the PLine2 of a motorcycle created by the three points given .
motorcycleFromPoints :: Point2 -> Point2 -> Point2 -> (ProjectiveLine, PLine2Err)
motorcycleFromPoints p1 p2 p3 = (flipL res, resErr)
where
(res, resErr) = getInsideArc firstLine secondLine
where
firstLine = join2EP p1 p2
secondLine = join2EP p2 p3
motorcycleMightIntersectWith :: [LineSeg] -> Motorcycle -> Maybe (LineSeg, Either Point2 ProjectivePoint)
motorcycleMightIntersectWith lineSegs motorcycle
| null lineSegs = error "no line segments to intersect motorcycle with?"
| otherwise = case intersections of
[] -> Nothing
[a] -> filterIntersection a
(_:_) -> if len results > 0
then Just $ head results
else Nothing
where
intersections = getMotorcycleSegSetIntersections motorcycle lineSegs
results :: Slist (LineSeg, Either Point2 ProjectivePoint)
results = slist $ sortByDistance $ mapMaybe filterIntersection intersections
sortByDistance :: [(LineSeg, Either Point2 ProjectivePoint)] -> [(LineSeg, Either Point2 ProjectivePoint)]
sortByDistance = sortBy compareDistances
motorcyclePoint = cPPointAndErrOf motorcycle
compareDistances i1 i2 = case i1 of
(_, Right intersectionPPoint1) ->
case i2 of
(_, Right intersectionPPoint2) ->
distanceBetweenPPointsWithErr motorcyclePoint (intersectionPPoint1, mempty) `compare` distanceBetweenPPointsWithErr motorcyclePoint (intersectionPPoint2, mempty)
(_, Left intersectionPoint2) ->
distanceBetweenPPointsWithErr motorcyclePoint (intersectionPPoint1, mempty) `compare` distanceBetweenPPointsWithErr motorcyclePoint (eToPP intersectionPoint2, mempty)
(_, Left intersectionPoint1) ->
case i2 of
(_, Right intersectionPPoint2) ->
distanceBetweenPPointsWithErr motorcyclePoint (eToPP intersectionPoint1, mempty) `compare` distanceBetweenPPointsWithErr motorcyclePoint (intersectionPPoint2, mempty)
(_, Left intersectionPoint2) ->
distanceBetweenPPointsWithErr motorcyclePoint (eToPP intersectionPoint1, mempty) `compare` distanceBetweenPPointsWithErr motorcyclePoint (eToPP intersectionPoint2, mempty)
filterIntersection :: (LineSeg, Either Point2 ProjectivePoint) -> Maybe (LineSeg, Either Point2 ProjectivePoint)
filterIntersection intersection = case intersection of
(_, Right intersectionPPoint) -> if intersectionPPointIsBehind intersectionPPoint
then Nothing
else Just intersection
(_, Left intersectionPoint) -> if intersectionPointIsBehind intersectionPoint
then Nothing
else Just intersection
where
intersectionPointIsBehind point = oppositeDirection (outOf motorcycle) (eToPLine2 $ makeLineSeg (ePointOf motorcycle) point)
intersectionPPointIsBehind pPoint = oppositeDirection (outOf motorcycle) (fst $ join2PP (cPPointOf motorcycle) pPoint)
If the motorcycle lands between two segments , return the second line segment , otherwise return the ProjectivePoint of the intersection with the first LineSeg .
motorcycleIntersectsAt :: Contour -> Motorcycle -> (LineSeg, Either Point2 ProjectivePoint)
motorcycleIntersectsAt contour motorcycle = case intersections of
[] -> error "no intersections?"
[a] -> fromMaybe (error $ "eliminated my only option\n" <> show a
) $ filterIntersection a
manyIntersections@(_:_) -> if len res > 0 then head res else error $ "no options: " <> show (len res) <> "\n" <> show res <> "\n"
where
res = slist $ sortBy compareDistances $ mapMaybe filterIntersection manyIntersections
compareDistances :: (LineSeg, Either Point2 ProjectivePoint) -> (LineSeg, Either Point2 ProjectivePoint) -> Ordering
compareDistances i1 i2 = case i1 of
(_, Right intersectionPPoint1) ->
case i2 of
(_, Right intersectionPPoint2) ->
distanceBetweenPPoints motorcyclePoint intersectionPPoint1 `compare` distanceBetweenPPoints motorcyclePoint intersectionPPoint2
(_, Left intersectionPoint2) ->
distanceBetweenPPoints motorcyclePoint intersectionPPoint1 `compare` distanceBetweenPPoints motorcyclePoint (eToPP intersectionPoint2)
(_, Left intersectionPoint1) ->
case i2 of
(_, Right intersectionPPoint2) ->
distanceBetweenPPoints motorcyclePoint (eToPP intersectionPoint1) `compare` distanceBetweenPPoints motorcyclePoint intersectionPPoint2
(_, Left intersectionPoint2) ->
distanceBetweenPPoints motorcyclePoint (eToPP intersectionPoint1) `compare` distanceBetweenPPoints motorcyclePoint (eToPP intersectionPoint2)
where
filterIntersection :: (LineSeg, Either Point2 ProjectivePoint) -> Maybe (LineSeg, Either Point2 ProjectivePoint)
filterIntersection intersection = case intersection of
(_, Right intersectionPPoint) -> if intersectionPPointIsBehind intersectionPPoint
then Nothing
else Just intersection
(_, Left intersectionPoint) -> if intersectionPointIsBehind intersectionPoint
then Nothing
else Just intersection
where
intersectionPointIsBehind point = oppositeDirection (outOf motorcycle) (fst $ join2PP (cPPointOf motorcycle) (eToPP point))
intersectionPPointIsBehind pPoint = oppositeDirection (outOf motorcycle) (fst $ join2PP (cPPointOf motorcycle) pPoint)
motorcyclePoint = cPPointOf motorcycle
intersections = getMotorcycleContourIntersections motorcycle contour
| Determine if a node is on one side of a motorcycle , or the other .
Assumes the starting point of the second line segment is a point on the path .
# INLINABLE intersectionSameSide #
intersectionSameSide :: (Pointable a) => ProjectivePoint -> a -> Motorcycle -> Maybe Bool
intersectionSameSide pointOnSide node (Motorcycle _ path _)
| canPoint node = pPointsOnSameSideOfPLine (cPPointOf node) pointOnSide path
| otherwise = error $ "cannot resolve provided item to a point: " <> show node <> "\n"
| Check if the output of two motorcycles are anti - collinear with each other .
motorcyclesAreAntiCollinear :: Motorcycle -> Motorcycle -> Bool
motorcyclesAreAntiCollinear motorcycle1 motorcycle2 = isAntiCollinear (outAndErrOf motorcycle1) (outAndErrOf motorcycle2)
| Return the total set of motorcycles in the given CellDivide
motorcyclesInDivision :: CellDivide -> [Motorcycle]
motorcyclesInDivision (CellDivide (DividingMotorcycles a (Slist b _)) _) = a : b
Determine the type of the last crash that occured in a crashtree . only useful when we 're dealing with a pair motorcycles , and want to find out if we can treat them like one motorcycle .
lastCrashType :: CrashTree -> Maybe CollisionType
lastCrashType crashTree = case lastCrash crashTree of
(Just crash) -> if collisionResult crash == HeadOn
then Just HeadOn
else Nothing
Nothing -> Nothing
where
lastCrash :: CrashTree -> Maybe Collision
lastCrash (CrashTree _ _ crashes) = case safeLast crashes of
Nothing -> Nothing
(Just crash) -> Just crash
|