_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
|
---|---|---|---|---|---|---|---|---|
9d921d23ff27e51c5a53f95bd448859900d7e7fa238889f6d0efd515bdb737db | samply/blaze | graphql_test.clj | (ns blaze.fhir.operation.graphql-test
(:require
[blaze.db.api-stub :refer [mem-node-system with-system-data]]
[blaze.executors :as ex]
[blaze.fhir.operation.graphql :as graphql]
[blaze.fhir.operation.graphql.test-util :refer [wrap-error]]
[blaze.log]
[blaze.middleware.fhir.db :refer [wrap-db]]
[blaze.middleware.fhir.db-spec]
[blaze.test-util :as tu :refer [given-thrown with-system]]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as st]
[clojure.test :as test :refer [deftest is testing]]
[integrant.core :as ig]
[juxt.iota :refer [given]]
[taoensso.timbre :as log]))
(st/instrument)
(log/set-level! :trace)
(test/use-fixtures :each tu/fixture)
(deftest init-test
(testing "nil config"
(given-thrown (ig/init {::graphql/handler nil})
:key := ::graphql/handler
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `map?))
(testing "missing config"
(given-thrown (ig/init {::graphql/handler {}})
:key := ::graphql/handler
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :node))
[:explain ::s/problems 1 :pred] := `(fn ~'[%] (contains? ~'% :executor))))
(testing "invalid executor"
(given-thrown (ig/init {::graphql/handler {:executor ::invalid}})
:key := ::graphql/handler
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :node))
[:explain ::s/problems 1 :pred] := `ex/executor?
[:explain ::s/problems 1 :val] := ::invalid)))
(deftest executor-init-test
(testing "nil config"
(given-thrown (ig/init {::graphql/executor nil})
:key := ::graphql/executor
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `map?))
(testing "invalid num-threads"
(given-thrown (ig/init {::graphql/executor {:num-threads ::invalid}})
:key := ::graphql/executor
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `pos-int?
[:explain ::s/problems 0 :val] := ::invalid))
(testing "with default num-threads"
(with-system [{::graphql/keys [executor]}
{::graphql/executor {}}]
(is (ex/executor? executor)))))
(def system
(assoc mem-node-system
::graphql/handler
{:node (ig/ref :blaze.db/node)
:executor (ig/ref :blaze.test/executor)}
:blaze.test/executor {}))
(defmacro with-handler [[handler-binding] & more]
(let [[txs body] (tu/extract-txs-body more)]
`(with-system-data [{node# :blaze.db/node
handler# ::graphql/handler} system]
~txs
(let [~handler-binding (-> handler# (wrap-db node#) wrap-error)]
~@body))))
(deftest execute-query-test
(testing "query param"
(testing "invalid query"
(testing "via query param"
(with-handler [handler]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{"}})]
(is (= 200 status))
(given body
[:errors 0 :message] := "Failed to parse GraphQL query."))))
(testing "via body"
(with-handler [handler]
(let [{:keys [status body]}
@(handler
{:request-method :post
:body {:query "{"}})]
(is (= 200 status))
(given body
[:errors 0 :message] := "Failed to parse GraphQL query.")))))
(testing "success"
(testing "Patient"
(testing "empty result"
(testing "via query param"
(with-handler [handler]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{ PatientList { gender } }"}})]
(is (= 200 status))
(given body
[:data :PatientList] :? empty?
[:errors] :? empty?))))
(testing "via body"
(with-handler [handler]
(let [{:keys [status body]}
@(handler
{:request-method :post
:body {:query "{ PatientList { gender } }"}})]
(is (= 200 status))
(given body
[:data :PatientList] :? empty?
[:errors] :? empty?)))))
(testing "one Patient"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"
:gender #fhir/code"male"}]]]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{ PatientList { id gender } }"}})]
(is (= 200 status))
(given body
[:data :PatientList 0 :id] := "0"
[:data :PatientList 0 :gender] := "male"
[:errors] :? empty?)))))
(testing "Observation"
(testing "empty result"
(with-handler [handler]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{ ObservationList { subject { reference } } }"}})]
(is (= 200 status))
(given body
[:data :ObservationList] :? empty?
[:errors] :? empty?))))
(testing "one Observation"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "0"
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{ ObservationList { subject { reference } } }"}})]
(is (= 200 status))
(given body
[:data :ObservationList 0 :subject :reference] := "Patient/0"
[:errors] :? empty?))))
(testing "one Observation with code"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "0"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri""
:code #fhir/code"39156-5"}]}
:subject #fhir/Reference{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Observation :id "1"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri""
:code #fhir/code"29463-7"}]}
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{ ObservationList(code: \"39156-5\") { subject { reference } } }"}})]
(is (= 200 status))
(given body
[:data :ObservationList count] := 1
[:data :ObservationList 0 :subject :reference] := "Patient/0"
[:errors] :? empty?))))))))
| null | https://raw.githubusercontent.com/samply/blaze/948eee38021467fa343c522a644a7fd4b24b6467/modules/operation-graphql/test/blaze/fhir/operation/graphql_test.clj | clojure | (ns blaze.fhir.operation.graphql-test
(:require
[blaze.db.api-stub :refer [mem-node-system with-system-data]]
[blaze.executors :as ex]
[blaze.fhir.operation.graphql :as graphql]
[blaze.fhir.operation.graphql.test-util :refer [wrap-error]]
[blaze.log]
[blaze.middleware.fhir.db :refer [wrap-db]]
[blaze.middleware.fhir.db-spec]
[blaze.test-util :as tu :refer [given-thrown with-system]]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as st]
[clojure.test :as test :refer [deftest is testing]]
[integrant.core :as ig]
[juxt.iota :refer [given]]
[taoensso.timbre :as log]))
(st/instrument)
(log/set-level! :trace)
(test/use-fixtures :each tu/fixture)
(deftest init-test
(testing "nil config"
(given-thrown (ig/init {::graphql/handler nil})
:key := ::graphql/handler
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `map?))
(testing "missing config"
(given-thrown (ig/init {::graphql/handler {}})
:key := ::graphql/handler
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :node))
[:explain ::s/problems 1 :pred] := `(fn ~'[%] (contains? ~'% :executor))))
(testing "invalid executor"
(given-thrown (ig/init {::graphql/handler {:executor ::invalid}})
:key := ::graphql/handler
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :node))
[:explain ::s/problems 1 :pred] := `ex/executor?
[:explain ::s/problems 1 :val] := ::invalid)))
(deftest executor-init-test
(testing "nil config"
(given-thrown (ig/init {::graphql/executor nil})
:key := ::graphql/executor
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `map?))
(testing "invalid num-threads"
(given-thrown (ig/init {::graphql/executor {:num-threads ::invalid}})
:key := ::graphql/executor
:reason := ::ig/build-failed-spec
[:explain ::s/problems 0 :pred] := `pos-int?
[:explain ::s/problems 0 :val] := ::invalid))
(testing "with default num-threads"
(with-system [{::graphql/keys [executor]}
{::graphql/executor {}}]
(is (ex/executor? executor)))))
(def system
(assoc mem-node-system
::graphql/handler
{:node (ig/ref :blaze.db/node)
:executor (ig/ref :blaze.test/executor)}
:blaze.test/executor {}))
(defmacro with-handler [[handler-binding] & more]
(let [[txs body] (tu/extract-txs-body more)]
`(with-system-data [{node# :blaze.db/node
handler# ::graphql/handler} system]
~txs
(let [~handler-binding (-> handler# (wrap-db node#) wrap-error)]
~@body))))
(deftest execute-query-test
(testing "query param"
(testing "invalid query"
(testing "via query param"
(with-handler [handler]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{"}})]
(is (= 200 status))
(given body
[:errors 0 :message] := "Failed to parse GraphQL query."))))
(testing "via body"
(with-handler [handler]
(let [{:keys [status body]}
@(handler
{:request-method :post
:body {:query "{"}})]
(is (= 200 status))
(given body
[:errors 0 :message] := "Failed to parse GraphQL query.")))))
(testing "success"
(testing "Patient"
(testing "empty result"
(testing "via query param"
(with-handler [handler]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{ PatientList { gender } }"}})]
(is (= 200 status))
(given body
[:data :PatientList] :? empty?
[:errors] :? empty?))))
(testing "via body"
(with-handler [handler]
(let [{:keys [status body]}
@(handler
{:request-method :post
:body {:query "{ PatientList { gender } }"}})]
(is (= 200 status))
(given body
[:data :PatientList] :? empty?
[:errors] :? empty?)))))
(testing "one Patient"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"
:gender #fhir/code"male"}]]]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{ PatientList { id gender } }"}})]
(is (= 200 status))
(given body
[:data :PatientList 0 :id] := "0"
[:data :PatientList 0 :gender] := "male"
[:errors] :? empty?)))))
(testing "Observation"
(testing "empty result"
(with-handler [handler]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{ ObservationList { subject { reference } } }"}})]
(is (= 200 status))
(given body
[:data :ObservationList] :? empty?
[:errors] :? empty?))))
(testing "one Observation"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "0"
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{ ObservationList { subject { reference } } }"}})]
(is (= 200 status))
(given body
[:data :ObservationList 0 :subject :reference] := "Patient/0"
[:errors] :? empty?))))
(testing "one Observation with code"
(with-handler [handler]
[[[:put {:fhir/type :fhir/Patient :id "0"}]
[:put {:fhir/type :fhir/Observation :id "0"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri""
:code #fhir/code"39156-5"}]}
:subject #fhir/Reference{:reference "Patient/0"}}]
[:put {:fhir/type :fhir/Observation :id "1"
:code
#fhir/CodeableConcept
{:coding
[#fhir/Coding
{:system #fhir/uri""
:code #fhir/code"29463-7"}]}
:subject #fhir/Reference{:reference "Patient/0"}}]]]
(let [{:keys [status body]}
@(handler
{:request-method :get
:params {"query" "{ ObservationList(code: \"39156-5\") { subject { reference } } }"}})]
(is (= 200 status))
(given body
[:data :ObservationList count] := 1
[:data :ObservationList 0 :subject :reference] := "Patient/0"
[:errors] :? empty?))))))))
|
|
a6a0c537471ea18d1c444cf9c7dcbc010c4e19f6a95ce43662751495f839aa78 | metaocaml/ber-metaocaml | variant.ml | (* TEST
* expect
*)
PR#6394
module rec X : sig
type t = int * bool
end = struct
type t = A | B
let f = function A | B -> 0
end;;
[%%expect{|
Lines 3-6, characters 6-3:
3 | ......struct
4 | type t = A | B
5 | let f = function A | B -> 0
6 | end..
Error: Signature mismatch:
Modules do not match:
sig type t = X.t = A | B val f : t -> int end
is not included in
sig type t = int * bool end
Type declarations do not match:
type t = X.t = A | B
is not included in
type t = int * bool
|}];;
(* PR#7838 *)
module Make (X : sig val f : [ `A ] -> unit end) = struct
let make f1 f2 arg = match arg with `A -> f1 arg; f2 arg
let f = make X.f (fun _ -> ())
end;;
[%%expect{|
module Make :
functor (X : sig val f : [ `A ] -> unit end) ->
sig
val make : (([< `A ] as 'a) -> 'b) -> ('a -> 'c) -> 'a -> 'c
val f : [ `A ] -> unit
end
|}]
reexport
type ('a,'b) def = X of int constraint 'b = [> `A]
type arity = (int, [`A]) def = X of int;;
[%%expect{|
type ('a, 'b) def = X of int constraint 'b = [> `A ]
Line 3, characters 0-39:
3 | type arity = (int, [`A]) def = X of int;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type
(int, [ `A ]) def
They have different arities.
|}]
type ('a,'b) ct = (int,'b) def = X of int;;
[%%expect{|
Line 1, characters 0-41:
1 | type ('a,'b) ct = (int,'b) def = X of int;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type
(int, [> `A ]) def
Their constraints differ.
|}]
type ('a,'b) kind = ('a, 'b) def = {a:int} constraint 'b = [> `A];;
[%%expect{|
Line 1, characters 0-65:
1 | type ('a,'b) kind = ('a, 'b) def = {a:int} constraint 'b = [> `A];;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type
('a, [> `A ]) def
Their kinds differ.
|}]
type d = X of int | Y of int
type missing = d = X of int
[%%expect{|
type d = X of int | Y of int
Line 3, characters 0-27:
3 | type missing = d = X of int
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type d
The constructor Y is only present in the original definition.
|}]
type wrong_type = d = X of float
[%%expect{|
Line 1, characters 0-32:
1 | type wrong_type = d = X of float
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type d
Constructors do not match:
X of int
is not compatible with:
X of float
The types are not equal.
|}]
type unboxed = d = X of float [@@unboxed]
[%%expect{|
Line 1, characters 0-41:
1 | type unboxed = d = X of float [@@unboxed]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type d
Their internal representations differ:
this definition uses unboxed representation.
|}]
type perm = d = Y of int | X of int
[%%expect{|
Line 1, characters 0-35:
1 | type perm = d = Y of int | X of int
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type d
Constructors number 1 have different names, X and Y.
|}]
module M : sig
type t = Foo of int
end = struct
type t = Foo : int -> t
end;;
[%%expect{|
Lines 3-5, characters 6-3:
3 | ......struct
4 | type t = Foo : int -> t
5 | end..
Error: Signature mismatch:
Modules do not match:
sig type t = Foo : int -> t end
is not included in
sig type t = Foo of int end
Type declarations do not match:
type t = Foo : int -> t
is not included in
type t = Foo of int
Constructors do not match:
Foo : int -> t
is not compatible with:
Foo of int
The first has explicit return type and the second doesn't.
|}]
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/typing-misc/variant.ml | ocaml | TEST
* expect
PR#7838 |
PR#6394
module rec X : sig
type t = int * bool
end = struct
type t = A | B
let f = function A | B -> 0
end;;
[%%expect{|
Lines 3-6, characters 6-3:
3 | ......struct
4 | type t = A | B
5 | let f = function A | B -> 0
6 | end..
Error: Signature mismatch:
Modules do not match:
sig type t = X.t = A | B val f : t -> int end
is not included in
sig type t = int * bool end
Type declarations do not match:
type t = X.t = A | B
is not included in
type t = int * bool
|}];;
module Make (X : sig val f : [ `A ] -> unit end) = struct
let make f1 f2 arg = match arg with `A -> f1 arg; f2 arg
let f = make X.f (fun _ -> ())
end;;
[%%expect{|
module Make :
functor (X : sig val f : [ `A ] -> unit end) ->
sig
val make : (([< `A ] as 'a) -> 'b) -> ('a -> 'c) -> 'a -> 'c
val f : [ `A ] -> unit
end
|}]
reexport
type ('a,'b) def = X of int constraint 'b = [> `A]
type arity = (int, [`A]) def = X of int;;
[%%expect{|
type ('a, 'b) def = X of int constraint 'b = [> `A ]
Line 3, characters 0-39:
3 | type arity = (int, [`A]) def = X of int;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type
(int, [ `A ]) def
They have different arities.
|}]
type ('a,'b) ct = (int,'b) def = X of int;;
[%%expect{|
Line 1, characters 0-41:
1 | type ('a,'b) ct = (int,'b) def = X of int;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type
(int, [> `A ]) def
Their constraints differ.
|}]
type ('a,'b) kind = ('a, 'b) def = {a:int} constraint 'b = [> `A];;
[%%expect{|
Line 1, characters 0-65:
1 | type ('a,'b) kind = ('a, 'b) def = {a:int} constraint 'b = [> `A];;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type
('a, [> `A ]) def
Their kinds differ.
|}]
type d = X of int | Y of int
type missing = d = X of int
[%%expect{|
type d = X of int | Y of int
Line 3, characters 0-27:
3 | type missing = d = X of int
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type d
The constructor Y is only present in the original definition.
|}]
type wrong_type = d = X of float
[%%expect{|
Line 1, characters 0-32:
1 | type wrong_type = d = X of float
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type d
Constructors do not match:
X of int
is not compatible with:
X of float
The types are not equal.
|}]
type unboxed = d = X of float [@@unboxed]
[%%expect{|
Line 1, characters 0-41:
1 | type unboxed = d = X of float [@@unboxed]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type d
Their internal representations differ:
this definition uses unboxed representation.
|}]
type perm = d = Y of int | X of int
[%%expect{|
Line 1, characters 0-35:
1 | type perm = d = Y of int | X of int
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type d
Constructors number 1 have different names, X and Y.
|}]
module M : sig
type t = Foo of int
end = struct
type t = Foo : int -> t
end;;
[%%expect{|
Lines 3-5, characters 6-3:
3 | ......struct
4 | type t = Foo : int -> t
5 | end..
Error: Signature mismatch:
Modules do not match:
sig type t = Foo : int -> t end
is not included in
sig type t = Foo of int end
Type declarations do not match:
type t = Foo : int -> t
is not included in
type t = Foo of int
Constructors do not match:
Foo : int -> t
is not compatible with:
Foo of int
The first has explicit return type and the second doesn't.
|}]
|
45b37f0db9c6e328d15d99cb349a0798a90f020e00cde8e708a414ea0711e1c5 | MercuryTechnologies/ghc-specter | GHCCore.hs | module GHCSpecter.Render.Components.GHCCore (
renderTopBind,
) where
import Concur.Core (Widget)
import Data.List qualified as L
import Data.Text qualified as T
import GHCSpecter.Data.GHC.Core (
Alt (..),
AltCon (..),
Bind (..),
Expr (..),
Id (..),
Literal (..),
)
import GHCSpecter.Render.Util (divClass, spanClass)
import GHCSpecter.UI.ConcurReplica.DOM (
pre,
span,
text,
)
import GHCSpecter.UI.ConcurReplica.Types (IHTML)
import Prelude hiding (div, span)
isType :: Expr -> Bool
isType (Type _) = True
isType _ = False
isInlineable :: Expr -> Bool
isInlineable (Var _) = True
isInlineable (Lit _) = True
isInlineable (App e1 e2) = isInlineable e1 && isInlineable e2
isInlineable (Type _) = True
isInlineable _ = False
doesNeedParens :: Expr -> Bool
doesNeedParens (Var _) = False
doesNeedParens (Lit _) = False
doesNeedParens (Type _) = False
doesNeedParens _ = True
renderTopBind :: Bind -> Widget IHTML a
renderTopBind bind = goB 0 bind
where
cls l = if l == 0 then "core-expr top" else "core-expr"
space = spanClass "space" [] [text " "]
eqEl = spanClass "eq" [] [text "="]
parenLEl = spanClass "paren" [] [text "("]
parenREl = spanClass "paren" [] [text ")"]
wrapParen (e, rendered)
| doesNeedParens e = [parenLEl, rendered, parenREl]
| otherwise = [rendered]
goB :: Int -> Bind -> Widget IHTML a
goB lvl b =
case b of
NonRec var expr -> goB1 lvl (var, expr)
Rec bs -> divClass (cls lvl) [] (fmap (goB1 (lvl + 1)) bs)
where
goB1 lvl' (var', expr') =
let varEl = span [] [text (unId var')]
expEl = goE (lvl' + 1) expr'
in divClass (cls lvl') [] [varEl, space, eqEl, space, expEl]
goApp lvl e1 e2
-- suppress type, i.e. drop
-- TODO: handle this correctly and customizable.
| isType e2 = goE lvl e1
| isInlineable e1 =
let e1El = span [] $
case e1 of
-- simplify as curry
App e1' e2' -> [goApp lvl e1' e2']
_ -> [goE lvl e1]
in if isInlineable e2
then
let e2El = span [] [goE lvl e2]
in span [] ([e1El, space] ++ wrapParen (e2, e2El))
else
let e2El = goE (lvl + 2) e2
in divClass
(cls lvl)
[]
(wrapParen (e1, e1El) ++ [divClass (cls (lvl + 1)) [] (wrapParen (e2, e2El))])
| otherwise =
NOTE : Indent applied argument one level further than applying function .
let e1El = goE (lvl + 1) e1
e2El = goE (lvl + 2) e2
in divClass
(cls lvl)
[]
[ parenLEl
, e1El
, parenREl
, divClass
(cls (lvl + 1))
[]
[ parenLEl
, e2El
, parenREl
]
]
goAlt lvl (Alt con ids expr) =
let conTxt =
case con of
DataAlt txt -> txt
LitAlt (LitString txt) -> txt
LitAlt _ -> "LitOther"
DEFAULT -> "DEFAULT"
conEl = span [] [text conTxt]
idsEl = fmap (\i -> span [] [text (unId i)]) ids
arrowEl = spanClass "arrow" [] [text "->"]
expEl = goE (lvl + 1) expr
in divClass
(cls lvl)
[]
(L.intersperse space ((conEl : idsEl) ++ [arrowEl, expEl]))
goCase lvl scrut _i _t alts =
let caseEl = span [] [text "case"]
ofEl = span [] [text "of"]
scrutEl = goE (lvl + 1) scrut
altEls = fmap (goAlt (lvl + 1)) alts
in divClass (cls lvl) [] ([caseEl, space, scrutEl, space, ofEl] ++ altEls)
goE lvl expr =
case expr of
Var var -> span [] [text (unId var)]
-- special treatment for readability
Lit (LitString txt) ->
let txt' = "\"" <> txt <> "\"#"
in span [] [text txt']
Lit (LitNumber _ num) ->
let txt = T.pack (show num) <> "#"
in span [] [text txt]
Lit (LitOther e) ->
goE lvl e
App e1 e2 -> goApp lvl e1 e2
Lam var expr' ->
let lambdaEl = spanClass "lambda" [] [text "\\"]
varEl = span [] [text (unId var)]
arrowEl = spanClass "arrow" [] [text "->"]
expEl = goE (lvl + 1) expr'
in divClass (cls lvl) [] [lambdaEl, varEl, arrowEl, expEl]
Let bind' expr' ->
let letEl = span [] [text "let"]
bindEl = goB (lvl + 1) bind'
inEl = span [] [text "in"]
expEl = goE (lvl + 1) expr'
in divClass (cls lvl) [] [letEl, bindEl, inEl, expEl]
Case scrut id_ typ alts -> goCase lvl scrut id_ typ alts
-- ignore Coercion for now
-- TODO: will be available as user asks.
Cast e _ -> goE lvl e
-- ignore Type for now
-- TODO: will be available as user asks.
Type _ -> span [] [text "Type"]
Other (typ, val) ys ->
let content = pre [] [text (T.pack (show (typ, val)))]
in divClass (cls lvl) [] (content : fmap (goE (lvl + 1)) ys)
| null | https://raw.githubusercontent.com/MercuryTechnologies/ghc-specter/d911e610e0ee0fb43497dad9e762fec2abbf9e08/daemon/src/GHCSpecter/Render/Components/GHCCore.hs | haskell | suppress type, i.e. drop
TODO: handle this correctly and customizable.
simplify as curry
special treatment for readability
ignore Coercion for now
TODO: will be available as user asks.
ignore Type for now
TODO: will be available as user asks. | module GHCSpecter.Render.Components.GHCCore (
renderTopBind,
) where
import Concur.Core (Widget)
import Data.List qualified as L
import Data.Text qualified as T
import GHCSpecter.Data.GHC.Core (
Alt (..),
AltCon (..),
Bind (..),
Expr (..),
Id (..),
Literal (..),
)
import GHCSpecter.Render.Util (divClass, spanClass)
import GHCSpecter.UI.ConcurReplica.DOM (
pre,
span,
text,
)
import GHCSpecter.UI.ConcurReplica.Types (IHTML)
import Prelude hiding (div, span)
isType :: Expr -> Bool
isType (Type _) = True
isType _ = False
isInlineable :: Expr -> Bool
isInlineable (Var _) = True
isInlineable (Lit _) = True
isInlineable (App e1 e2) = isInlineable e1 && isInlineable e2
isInlineable (Type _) = True
isInlineable _ = False
doesNeedParens :: Expr -> Bool
doesNeedParens (Var _) = False
doesNeedParens (Lit _) = False
doesNeedParens (Type _) = False
doesNeedParens _ = True
renderTopBind :: Bind -> Widget IHTML a
renderTopBind bind = goB 0 bind
where
cls l = if l == 0 then "core-expr top" else "core-expr"
space = spanClass "space" [] [text " "]
eqEl = spanClass "eq" [] [text "="]
parenLEl = spanClass "paren" [] [text "("]
parenREl = spanClass "paren" [] [text ")"]
wrapParen (e, rendered)
| doesNeedParens e = [parenLEl, rendered, parenREl]
| otherwise = [rendered]
goB :: Int -> Bind -> Widget IHTML a
goB lvl b =
case b of
NonRec var expr -> goB1 lvl (var, expr)
Rec bs -> divClass (cls lvl) [] (fmap (goB1 (lvl + 1)) bs)
where
goB1 lvl' (var', expr') =
let varEl = span [] [text (unId var')]
expEl = goE (lvl' + 1) expr'
in divClass (cls lvl') [] [varEl, space, eqEl, space, expEl]
goApp lvl e1 e2
| isType e2 = goE lvl e1
| isInlineable e1 =
let e1El = span [] $
case e1 of
App e1' e2' -> [goApp lvl e1' e2']
_ -> [goE lvl e1]
in if isInlineable e2
then
let e2El = span [] [goE lvl e2]
in span [] ([e1El, space] ++ wrapParen (e2, e2El))
else
let e2El = goE (lvl + 2) e2
in divClass
(cls lvl)
[]
(wrapParen (e1, e1El) ++ [divClass (cls (lvl + 1)) [] (wrapParen (e2, e2El))])
| otherwise =
NOTE : Indent applied argument one level further than applying function .
let e1El = goE (lvl + 1) e1
e2El = goE (lvl + 2) e2
in divClass
(cls lvl)
[]
[ parenLEl
, e1El
, parenREl
, divClass
(cls (lvl + 1))
[]
[ parenLEl
, e2El
, parenREl
]
]
goAlt lvl (Alt con ids expr) =
let conTxt =
case con of
DataAlt txt -> txt
LitAlt (LitString txt) -> txt
LitAlt _ -> "LitOther"
DEFAULT -> "DEFAULT"
conEl = span [] [text conTxt]
idsEl = fmap (\i -> span [] [text (unId i)]) ids
arrowEl = spanClass "arrow" [] [text "->"]
expEl = goE (lvl + 1) expr
in divClass
(cls lvl)
[]
(L.intersperse space ((conEl : idsEl) ++ [arrowEl, expEl]))
goCase lvl scrut _i _t alts =
let caseEl = span [] [text "case"]
ofEl = span [] [text "of"]
scrutEl = goE (lvl + 1) scrut
altEls = fmap (goAlt (lvl + 1)) alts
in divClass (cls lvl) [] ([caseEl, space, scrutEl, space, ofEl] ++ altEls)
goE lvl expr =
case expr of
Var var -> span [] [text (unId var)]
Lit (LitString txt) ->
let txt' = "\"" <> txt <> "\"#"
in span [] [text txt']
Lit (LitNumber _ num) ->
let txt = T.pack (show num) <> "#"
in span [] [text txt]
Lit (LitOther e) ->
goE lvl e
App e1 e2 -> goApp lvl e1 e2
Lam var expr' ->
let lambdaEl = spanClass "lambda" [] [text "\\"]
varEl = span [] [text (unId var)]
arrowEl = spanClass "arrow" [] [text "->"]
expEl = goE (lvl + 1) expr'
in divClass (cls lvl) [] [lambdaEl, varEl, arrowEl, expEl]
Let bind' expr' ->
let letEl = span [] [text "let"]
bindEl = goB (lvl + 1) bind'
inEl = span [] [text "in"]
expEl = goE (lvl + 1) expr'
in divClass (cls lvl) [] [letEl, bindEl, inEl, expEl]
Case scrut id_ typ alts -> goCase lvl scrut id_ typ alts
Cast e _ -> goE lvl e
Type _ -> span [] [text "Type"]
Other (typ, val) ys ->
let content = pre [] [text (T.pack (show (typ, val)))]
in divClass (cls lvl) [] (content : fmap (goE (lvl + 1)) ys)
|
f9a9c9721daa2676b3d4fbf56b2334f2ece44ffa33add4d6bdd94360755f5679 | andorp/bead | EmailTemplate.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE CPP #
module Bead.View.EmailTemplate
( EmailTemplate
, emailTemplate
, runEmailTemplate
, RegTemplate(..)
, ForgottenPassword(..)
, Template
, registration
, forgottenPassword
#ifdef TEST
, runEmailTemplateTests
#endif
) where
import Data.Data
import qualified Data.Text.Lazy as DTL
import Text.Hastache
import Text.Hastache.Context
#ifdef TEST
import Test.Tasty.TestSet
import Test.Tasty.HUnit as HUnit
#endif
-- Email template is a function to an IO String computation
-- Interpretation: The email template is applied to a value
-- and produces a string value with the field filled up
-- the values from the given type.
newtype EmailTemplate a = EmailTemplate (a -> IO String)
emailTemplateCata :: ((a -> IO String) -> b) -> EmailTemplate a -> b
emailTemplateCata f (EmailTemplate g) = f g
emailTemplateAna :: (b -> (a -> IO String)) -> b -> EmailTemplate a
emailTemplateAna f x = EmailTemplate (f x)
-- | Produces a IO String computation, that represents the
-- evaluated template substituting the given value into the
-- template
runEmailTemplate :: EmailTemplate a -> a -> IO String
runEmailTemplate template v = emailTemplateCata id template v
-- Creates a simple email template using the given string
emailTemplate :: (Data a, Typeable a) => String -> EmailTemplate a
emailTemplate = emailTemplateAna
(\t x -> fmap DTL.unpack $ hastacheStr defaultConfig (encodeStr t) (mkGenericContext x))
-- * Templates
data RegTemplate = RegTemplate {
regUsername :: String
, regUrl :: String
} deriving (Data, Typeable)
data ForgottenPassword = ForgottenPassword {
fpUsername :: String
, fpNewPassword :: String
} deriving (Data, Typeable)
class (Data t, Typeable t) => Template t
instance Template RegTemplate
instance Template ForgottenPassword
fileTemplate :: (Data a, Typeable a) => FilePath -> IO (EmailTemplate a)
fileTemplate fp = do
content <- readFile fp
return $ emailTemplate content
registration :: FilePath -> IO (EmailTemplate RegTemplate)
registration = fileTemplate
forgottenPassword :: FilePath -> IO (EmailTemplate ForgottenPassword)
forgottenPassword = fileTemplate
#ifdef TEST
runEmailTemplateTests = group "runEmailTemplate" $ do
add $ HUnit.testCase "Registration template" $ do
found <- runEmailTemplate (emailTemplate "n {{regUsername}} u {{regUrl}}") (RegTemplate "n" "u")
HUnit.assertEqual "Registration template" "n n u u" found
add $ HUnit.testCase "Forgotten password" $ do
found <- runEmailTemplate (emailTemplate "n {{fpUsername}} p {{fpNewPassword}}") (ForgottenPassword "n" "p")
HUnit.assertEqual "Forgotten password template" "n n p p" found
#endif
| null | https://raw.githubusercontent.com/andorp/bead/280dc9c3d5cfe1b9aac0f2f802c705ae65f02ac2/src/Bead/View/EmailTemplate.hs | haskell | # LANGUAGE DeriveDataTypeable #
Email template is a function to an IO String computation
Interpretation: The email template is applied to a value
and produces a string value with the field filled up
the values from the given type.
| Produces a IO String computation, that represents the
evaluated template substituting the given value into the
template
Creates a simple email template using the given string
* Templates | # LANGUAGE CPP #
module Bead.View.EmailTemplate
( EmailTemplate
, emailTemplate
, runEmailTemplate
, RegTemplate(..)
, ForgottenPassword(..)
, Template
, registration
, forgottenPassword
#ifdef TEST
, runEmailTemplateTests
#endif
) where
import Data.Data
import qualified Data.Text.Lazy as DTL
import Text.Hastache
import Text.Hastache.Context
#ifdef TEST
import Test.Tasty.TestSet
import Test.Tasty.HUnit as HUnit
#endif
newtype EmailTemplate a = EmailTemplate (a -> IO String)
emailTemplateCata :: ((a -> IO String) -> b) -> EmailTemplate a -> b
emailTemplateCata f (EmailTemplate g) = f g
emailTemplateAna :: (b -> (a -> IO String)) -> b -> EmailTemplate a
emailTemplateAna f x = EmailTemplate (f x)
runEmailTemplate :: EmailTemplate a -> a -> IO String
runEmailTemplate template v = emailTemplateCata id template v
emailTemplate :: (Data a, Typeable a) => String -> EmailTemplate a
emailTemplate = emailTemplateAna
(\t x -> fmap DTL.unpack $ hastacheStr defaultConfig (encodeStr t) (mkGenericContext x))
data RegTemplate = RegTemplate {
regUsername :: String
, regUrl :: String
} deriving (Data, Typeable)
data ForgottenPassword = ForgottenPassword {
fpUsername :: String
, fpNewPassword :: String
} deriving (Data, Typeable)
class (Data t, Typeable t) => Template t
instance Template RegTemplate
instance Template ForgottenPassword
fileTemplate :: (Data a, Typeable a) => FilePath -> IO (EmailTemplate a)
fileTemplate fp = do
content <- readFile fp
return $ emailTemplate content
registration :: FilePath -> IO (EmailTemplate RegTemplate)
registration = fileTemplate
forgottenPassword :: FilePath -> IO (EmailTemplate ForgottenPassword)
forgottenPassword = fileTemplate
#ifdef TEST
runEmailTemplateTests = group "runEmailTemplate" $ do
add $ HUnit.testCase "Registration template" $ do
found <- runEmailTemplate (emailTemplate "n {{regUsername}} u {{regUrl}}") (RegTemplate "n" "u")
HUnit.assertEqual "Registration template" "n n u u" found
add $ HUnit.testCase "Forgotten password" $ do
found <- runEmailTemplate (emailTemplate "n {{fpUsername}} p {{fpNewPassword}}") (ForgottenPassword "n" "p")
HUnit.assertEqual "Forgotten password template" "n n p p" found
#endif
|
576a4b1adef7acdd41dc90533133e76ea7e1105118604240c8e57d3cae8699a9 | alanz/ghc-exactprint | Undefined8.hs | # LANGUAGE QuasiQuotes , TypeFamilies , PackageImports #
module Text.Markdown.Pap.Parser (
parseMrd
) where
import Control.Arrow
import "monads-tf" Control.Monad.State
import "monads-tf" Control.Monad.Error
import Data.Maybe
import Data.Char
import Text.Papillon
import Text.Markdown.Pap.Text
parseMrd :: String -> Maybe [Text]
parseMrd src = case flip runState (0, [- 1]) $ runErrorT $ markdown $ parse src of
(Right (r, _), _) -> Just r
_ -> Nothing
clear :: State (Int, [Int]) Bool
clear = put (0, [- 1]) >> return True
reset :: State (Int, [Int]) Bool
reset = modify (first $ const 0) >> return True
count :: State (Int, [Int]) ()
count = modify $ first (+ 1)
deeper :: State (Int, [Int]) Bool
deeper = do
(n, n0 : ns) <- get
if n > n0 then put (n, n : n0 : ns) >> return True else return False
same :: State (Int, [Int]) Bool
same = do
(n, n0 : _) <- get
return $ n == n0
shallow :: State (Int, [Int]) Bool
shallow = do
(n, n0 : ns) <- get
if n < n0 then put (n, ns) >> return True else return False
[papillon|
monad: State (Int, [Int])
markdown :: [Text]
= md:(m:markdown1 _:dmmy[clear] { return m })* { return md }
markdown1 :: Text
= h:header { return h }
/ l:link '\n'* { return l }
/ i:image '\n'* { return i }
/ l:list '\n'* { return $ List l }
/ c:code { return $ Code c }
/ p:paras { return $ Paras p }
header :: Text
= n:sharps _:<isSpace>* l:line '\n'+ { return $ Header n l }
/ l:line '\n' _:equals '\n'+ { return $ Header 1 l }
/ l:line '\n' _:hyphens '\n'+ { return $ Header 2 l }
sharps :: Int
= '#' n:sharps { return $ n + 1 }
/ '#' { return 1 }
equals :: ()
= '=' _:equals
/ '='
hyphens :: ()
= '-' _:hyphens
/ '-'
line :: String
= l:<(`notElem` "#\n")>+ { return l }
line' :: String
= l:<(`notElem` "\n")>+ { return l }
code :: String
= l:fourSpacesLine c:code { return $ l ++ c }
/ l:fourSpacesLine { return l }
fourSpacesLine :: String
= _:fourSpaces l:line' ns:('\n' { return '\n' })+ { return $ l ++ ns }
fourSpaces :: ()
= ' ' ' ' ' ' ' '
list :: List = _:cnt _:dmmy[deeper] l:list1 ls:list1'* _:shllw { return $ l : ls }
cnt :: () = _:dmmy[reset] _:(' ' { count })*
list1' :: List1
= _:cnt _:dmmy[same] l:list1 { return l }
list1 :: List1
= _:listHead ' ' l:line '\n' ls:list?
{ return $ BulItem l $ fromMaybe [] ls }
/ _:nListHead ' ' l:line '\n' ls:list?
{ return $ OrdItem l $ fromMaybe [] ls }
listHead :: ()
= '*' / '-' / '+'
nListHead :: ()
= _:<isDigit>+ '.'
paras :: [String]
= ps:para+ { return ps }
para :: String
= ls:(!_:('!') !_:listHead !_:nListHead !_:header !_:fourSpaces l:line '\n' { return l })+ _:('\n' / !_ / !_:para)
{ return $ unwords ls }
shllw :: ()
= _:dmmy[shallow]
/ !_
/ !_:list
dmmy :: () =
link :: Text
= '[' t:<(/= ']')>+ ']' ' '* '(' a:<(/= ')')>+ ')' { return $ Link t a "" }
image :: Text
= '!' '[' alt:<(/= ']')>+ ']' ' '* '(' addrs:<(`notElem` ")\" ")>+ ' '*
'"' t:<(/= '"')>+ '"' ')'
{ return $ Image alt addrs t }
|]
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/b6b75027811fa4c336b34122a7a7b1a8df462563/tests/examples/ghc710/Undefined8.hs | haskell | # LANGUAGE QuasiQuotes , TypeFamilies , PackageImports #
module Text.Markdown.Pap.Parser (
parseMrd
) where
import Control.Arrow
import "monads-tf" Control.Monad.State
import "monads-tf" Control.Monad.Error
import Data.Maybe
import Data.Char
import Text.Papillon
import Text.Markdown.Pap.Text
parseMrd :: String -> Maybe [Text]
parseMrd src = case flip runState (0, [- 1]) $ runErrorT $ markdown $ parse src of
(Right (r, _), _) -> Just r
_ -> Nothing
clear :: State (Int, [Int]) Bool
clear = put (0, [- 1]) >> return True
reset :: State (Int, [Int]) Bool
reset = modify (first $ const 0) >> return True
count :: State (Int, [Int]) ()
count = modify $ first (+ 1)
deeper :: State (Int, [Int]) Bool
deeper = do
(n, n0 : ns) <- get
if n > n0 then put (n, n : n0 : ns) >> return True else return False
same :: State (Int, [Int]) Bool
same = do
(n, n0 : _) <- get
return $ n == n0
shallow :: State (Int, [Int]) Bool
shallow = do
(n, n0 : ns) <- get
if n < n0 then put (n, ns) >> return True else return False
[papillon|
monad: State (Int, [Int])
markdown :: [Text]
= md:(m:markdown1 _:dmmy[clear] { return m })* { return md }
markdown1 :: Text
= h:header { return h }
/ l:link '\n'* { return l }
/ i:image '\n'* { return i }
/ l:list '\n'* { return $ List l }
/ c:code { return $ Code c }
/ p:paras { return $ Paras p }
header :: Text
= n:sharps _:<isSpace>* l:line '\n'+ { return $ Header n l }
/ l:line '\n' _:equals '\n'+ { return $ Header 1 l }
/ l:line '\n' _:hyphens '\n'+ { return $ Header 2 l }
sharps :: Int
= '#' n:sharps { return $ n + 1 }
/ '#' { return 1 }
equals :: ()
= '=' _:equals
/ '='
hyphens :: ()
= '-' _:hyphens
/ '-'
line :: String
= l:<(`notElem` "#\n")>+ { return l }
line' :: String
= l:<(`notElem` "\n")>+ { return l }
code :: String
= l:fourSpacesLine c:code { return $ l ++ c }
/ l:fourSpacesLine { return l }
fourSpacesLine :: String
= _:fourSpaces l:line' ns:('\n' { return '\n' })+ { return $ l ++ ns }
fourSpaces :: ()
= ' ' ' ' ' ' ' '
list :: List = _:cnt _:dmmy[deeper] l:list1 ls:list1'* _:shllw { return $ l : ls }
cnt :: () = _:dmmy[reset] _:(' ' { count })*
list1' :: List1
= _:cnt _:dmmy[same] l:list1 { return l }
list1 :: List1
= _:listHead ' ' l:line '\n' ls:list?
{ return $ BulItem l $ fromMaybe [] ls }
/ _:nListHead ' ' l:line '\n' ls:list?
{ return $ OrdItem l $ fromMaybe [] ls }
listHead :: ()
= '*' / '-' / '+'
nListHead :: ()
= _:<isDigit>+ '.'
paras :: [String]
= ps:para+ { return ps }
para :: String
= ls:(!_:('!') !_:listHead !_:nListHead !_:header !_:fourSpaces l:line '\n' { return l })+ _:('\n' / !_ / !_:para)
{ return $ unwords ls }
shllw :: ()
= _:dmmy[shallow]
/ !_
/ !_:list
dmmy :: () =
link :: Text
= '[' t:<(/= ']')>+ ']' ' '* '(' a:<(/= ')')>+ ')' { return $ Link t a "" }
image :: Text
= '!' '[' alt:<(/= ']')>+ ']' ' '* '(' addrs:<(`notElem` ")\" ")>+ ' '*
'"' t:<(/= '"')>+ '"' ')'
{ return $ Image alt addrs t }
|]
|
|
0e9396d05cfc10794a8381ffd7306b189e8c676d8181482cb219f361ddd994fa | kupl/LearnML | patch.ml | type aexp =
| Const of int
| Var of string
| Power of (string * int)
| Times of aexp list
| Sum of aexp list
let rec diff ((aexp : aexp), (x : string)) : aexp =
match aexp with
| Const i -> Const 0
| Var k -> if k != x then Const 0 else Const 1
| Power (k, i) ->
if k != x then Const 0 else Times [ Const i; Power (k, i - 1) ]
| Times l -> (
match l with
| [] -> Const 0
| h :: t ->
Sum [ Times (diff (h, x) :: t); Times [ h; diff (Times t, x) ] ] )
| Sum l -> (
match l with
| [] -> Const 0
| h :: t -> Sum [ diff (h, x); diff (Sum t, x) ] )
| null | https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/diff/sub63/patch.ml | ocaml | type aexp =
| Const of int
| Var of string
| Power of (string * int)
| Times of aexp list
| Sum of aexp list
let rec diff ((aexp : aexp), (x : string)) : aexp =
match aexp with
| Const i -> Const 0
| Var k -> if k != x then Const 0 else Const 1
| Power (k, i) ->
if k != x then Const 0 else Times [ Const i; Power (k, i - 1) ]
| Times l -> (
match l with
| [] -> Const 0
| h :: t ->
Sum [ Times (diff (h, x) :: t); Times [ h; diff (Times t, x) ] ] )
| Sum l -> (
match l with
| [] -> Const 0
| h :: t -> Sum [ diff (h, x); diff (Sum t, x) ] )
|
|
632d5f658bb11ee1d76ce73b60820ed49594b6fe29daf1bbeb12d7fe1f9b6cb2 | Smoltbob/Caml-Est-Belle | bsyntax.ml | open Printf;;
open List;;
* This module defines the type of the AST as well as functions
to display it .
to display it.*)
type t =
| Int of int
| Float of float
| Neg of Id.t
| Add of Id.t * t
| Sub of Id.t * t
| Land of Id.t * t
| Var of Id.t
| Eq of Id.t * t
| Call of Id.t * formal_args
| CallClo of Id.t * formal_args
| If of Id.t * t * asmt * asmt * string
| MemAcc of Id.t * t
| MemAff of Id.t * t * Id.t
| New of t
| Nop
and formal_args = Id.t list
and asmt =
(* | LetCls of Id.t * t * asmt *)
| Let of Id.t * t * asmt
| Expression of t
(* | Additional case for parenthesis ? Don't think so ? *)
and fundef = {
name : Id.t;
args : Id.t list;
body : asmt (* We will need the name, arguments and return type for functions *)
}
type toplevel =
| Fundefs of (fundef list) (* Once we implement functions we will have a list *)
(** Prints the functions arguments. They are stored in a list.
@param argu the list of arguments
*)
let rec to_string_args argu =
match argu with
| [] -> ""
| [x] -> Id.to_string x
| t::q -> sprintf "%s %s" t (to_string_args q)
let rec infix_to_string (to_s : 'a -> string) (l : 'a list) (op : string) : string =
match l with
| [] -> ""
| [x] -> to_s x
| hd :: tl -> (to_s hd) ^ op ^ (infix_to_string to_s tl op)
* Transforms comparison instructions into strings . Ex : " beq " into " = "
let rec comp_to_string comp =
match comp with
| "beq" -> sprintf "="
| "ble" -> sprintf "<="
| "bge" -> sprintf ">="
| _ -> failwith "Empty comparator"
(** Prints expressions occuring in the program.
@param exp The expression to print. *)
let rec exp_to_string exp =
match exp with
| Int i -> string_of_int i
| Float f -> sprintf "%.2f" f
| Neg id -> sprintf "(neg %s)" (Id.to_string id)
| MemAcc (id1, id2) -> sprintf "(mem(%s + %s))" (Id.to_string id1) (exp_to_string id2)
| MemAff (id1, id2, id3) -> sprintf "(mem(%s + %s)<-%s)" (Id.to_string id1) (exp_to_string id2) (Id.to_string id3)
| Add (e1, e2) -> sprintf "(add %s %s)" (Id.to_string e1) (exp_to_string e2)
| Sub (e1, e2) -> sprintf "(sub %s %s)" (Id.to_string e1) (exp_to_string e2)
| Land (e1, e2) -> sprintf "(land %s %s)" (Id.to_string e1) (exp_to_string e2)
| Var id -> Id.to_string id
| Eq (e1, e2) -> sprintf "(%s = %s)" (Id.to_string e1) (exp_to_string e2)
| If (id1, e1, asmt1, asmt2, comp) -> sprintf "(if %s %s %s then %s else %s)" (Id.to_string id1) (comp_to_string comp) (exp_to_string e1) (to_string_asm asmt1) (to_string_asm asmt2)
| Call (l1, a1) -> sprintf "(call %s %s)" (Id.to_string l1) (to_string_args a1)
| CallClo (l1, a1) -> sprintf "(applyclo %s %s)" (Id.to_string l1) (to_string_args a1)
| New (e1) -> sprintf "(new %s)" (exp_to_string e1)
| Nop -> sprintf "nop"
(** Prints an asmt. It can be an assignement (with a let) or an expression alone.
@param asm The asmt to print.
*)
and to_string_asm asm =
match asm with
| Let (id, e1, a) -> sprintf "(Let %s = %s in %s)" (Id.to_string id) (exp_to_string e1) (to_string_asm a)
| Expression e -> sprintf "(%s)" (exp_to_string e)
(** Prints the functions in the list of fundefs/
@param fund the list of function definitions.
*)
let rec to_string_fundef fund =
sprintf "(%s)" (to_string_asm fund.body)
(** Prints the root of the ast of an asml program. This is the function to call to print the whole tree.
@param top The ast as provided by the parser.
*)
let rec to_string_top top =
match top with
| Fundefs f -> sprintf "(%s)" (to_string_fundef (hd f))
let rec print_list_idx l i =
match i with
| i when i = 0 -> sprintf "%s" (Id.to_string (hd l))
| _ -> print_list_idx (tl l) (i - 1)
| null | https://raw.githubusercontent.com/Smoltbob/Caml-Est-Belle/3d6f53d4e8e01bbae57a0a402b7c0f02f4ed767c/compiler/bsyntax.ml | ocaml | | LetCls of Id.t * t * asmt
| Additional case for parenthesis ? Don't think so ?
We will need the name, arguments and return type for functions
Once we implement functions we will have a list
* Prints the functions arguments. They are stored in a list.
@param argu the list of arguments
* Prints expressions occuring in the program.
@param exp The expression to print.
* Prints an asmt. It can be an assignement (with a let) or an expression alone.
@param asm The asmt to print.
* Prints the functions in the list of fundefs/
@param fund the list of function definitions.
* Prints the root of the ast of an asml program. This is the function to call to print the whole tree.
@param top The ast as provided by the parser.
| open Printf;;
open List;;
* This module defines the type of the AST as well as functions
to display it .
to display it.*)
type t =
| Int of int
| Float of float
| Neg of Id.t
| Add of Id.t * t
| Sub of Id.t * t
| Land of Id.t * t
| Var of Id.t
| Eq of Id.t * t
| Call of Id.t * formal_args
| CallClo of Id.t * formal_args
| If of Id.t * t * asmt * asmt * string
| MemAcc of Id.t * t
| MemAff of Id.t * t * Id.t
| New of t
| Nop
and formal_args = Id.t list
and asmt =
| Let of Id.t * t * asmt
| Expression of t
and fundef = {
name : Id.t;
args : Id.t list;
}
type toplevel =
let rec to_string_args argu =
match argu with
| [] -> ""
| [x] -> Id.to_string x
| t::q -> sprintf "%s %s" t (to_string_args q)
let rec infix_to_string (to_s : 'a -> string) (l : 'a list) (op : string) : string =
match l with
| [] -> ""
| [x] -> to_s x
| hd :: tl -> (to_s hd) ^ op ^ (infix_to_string to_s tl op)
* Transforms comparison instructions into strings . Ex : " beq " into " = "
let rec comp_to_string comp =
match comp with
| "beq" -> sprintf "="
| "ble" -> sprintf "<="
| "bge" -> sprintf ">="
| _ -> failwith "Empty comparator"
let rec exp_to_string exp =
match exp with
| Int i -> string_of_int i
| Float f -> sprintf "%.2f" f
| Neg id -> sprintf "(neg %s)" (Id.to_string id)
| MemAcc (id1, id2) -> sprintf "(mem(%s + %s))" (Id.to_string id1) (exp_to_string id2)
| MemAff (id1, id2, id3) -> sprintf "(mem(%s + %s)<-%s)" (Id.to_string id1) (exp_to_string id2) (Id.to_string id3)
| Add (e1, e2) -> sprintf "(add %s %s)" (Id.to_string e1) (exp_to_string e2)
| Sub (e1, e2) -> sprintf "(sub %s %s)" (Id.to_string e1) (exp_to_string e2)
| Land (e1, e2) -> sprintf "(land %s %s)" (Id.to_string e1) (exp_to_string e2)
| Var id -> Id.to_string id
| Eq (e1, e2) -> sprintf "(%s = %s)" (Id.to_string e1) (exp_to_string e2)
| If (id1, e1, asmt1, asmt2, comp) -> sprintf "(if %s %s %s then %s else %s)" (Id.to_string id1) (comp_to_string comp) (exp_to_string e1) (to_string_asm asmt1) (to_string_asm asmt2)
| Call (l1, a1) -> sprintf "(call %s %s)" (Id.to_string l1) (to_string_args a1)
| CallClo (l1, a1) -> sprintf "(applyclo %s %s)" (Id.to_string l1) (to_string_args a1)
| New (e1) -> sprintf "(new %s)" (exp_to_string e1)
| Nop -> sprintf "nop"
and to_string_asm asm =
match asm with
| Let (id, e1, a) -> sprintf "(Let %s = %s in %s)" (Id.to_string id) (exp_to_string e1) (to_string_asm a)
| Expression e -> sprintf "(%s)" (exp_to_string e)
let rec to_string_fundef fund =
sprintf "(%s)" (to_string_asm fund.body)
let rec to_string_top top =
match top with
| Fundefs f -> sprintf "(%s)" (to_string_fundef (hd f))
let rec print_list_idx l i =
match i with
| i when i = 0 -> sprintf "%s" (Id.to_string (hd l))
| _ -> print_list_idx (tl l) (i - 1)
|
d6076f1e900fe1d5bdc84554e6f23ed3e2960854800f622616f1ce9c2aed5405 | janestreet/base | float0.ml | open! Import
(* Open replace_polymorphic_compare after including functor instantiations so they do not
shadow its definitions. This is here so that efficient versions of the comparison
functions are available within this module. *)
open! Float_replace_polymorphic_compare
let ceil = Stdlib.ceil
let floor = Stdlib.floor
let mod_float = Stdlib.mod_float
let modf = Stdlib.modf
let float_of_string = Stdlib.float_of_string
let float_of_string_opt = Stdlib.float_of_string_opt
let nan = Stdlib.nan
let infinity = Stdlib.infinity
let neg_infinity = Stdlib.neg_infinity
let max_finite_value = Stdlib.max_float
let epsilon_float = Stdlib.epsilon_float
let classify_float = Stdlib.classify_float
let abs_float = Stdlib.abs_float
let is_integer = Stdlib.Float.is_integer
let ( ** ) = Stdlib.( ** )
let ( %. ) a b =
(* Raise in case of a negative modulus, as does Int.( % ). *)
if b < 0.
then Printf.invalid_argf "%f %% %f in float0.ml: modulus should be positive" a b ();
let m = Stdlib.mod_float a b in
(* Produce a non-negative result in analogy with Int.( % ). *)
if m < 0. then m +. b else m
;;
The bits of INRIA 's [ Pervasives ] that we just want to expose in [ Float ] . Most are
already deprecated in [ Pervasives ] , and eventually all of them should be .
already deprecated in [Pervasives], and eventually all of them should be. *)
include (
Stdlib :
sig
external frexp : float -> float * int = "caml_frexp_float"
external ldexp
: (float[@unboxed])
-> (int[@untagged])
-> (float[@unboxed])
= "caml_ldexp_float" "caml_ldexp_float_unboxed"
[@@noalloc]
external log10 : float -> float = "caml_log10_float" "log10" [@@unboxed] [@@noalloc]
external expm1 : float -> float = "caml_expm1_float" "caml_expm1"
[@@unboxed] [@@noalloc]
external log1p : float -> float = "caml_log1p_float" "caml_log1p"
[@@unboxed] [@@noalloc]
external copysign : float -> float -> float = "caml_copysign_float" "caml_copysign"
[@@unboxed] [@@noalloc]
external cos : float -> float = "caml_cos_float" "cos" [@@unboxed] [@@noalloc]
external sin : float -> float = "caml_sin_float" "sin" [@@unboxed] [@@noalloc]
external tan : float -> float = "caml_tan_float" "tan" [@@unboxed] [@@noalloc]
external acos : float -> float = "caml_acos_float" "acos" [@@unboxed] [@@noalloc]
external asin : float -> float = "caml_asin_float" "asin" [@@unboxed] [@@noalloc]
external atan : float -> float = "caml_atan_float" "atan" [@@unboxed] [@@noalloc]
external acosh : float -> float = "caml_acosh_float" "caml_acosh"
[@@unboxed] [@@noalloc]
external asinh : float -> float = "caml_asinh_float" "caml_asinh"
[@@unboxed] [@@noalloc]
external atanh : float -> float = "caml_atanh_float" "caml_atanh"
[@@unboxed] [@@noalloc]
external atan2 : float -> float -> float = "caml_atan2_float" "atan2"
[@@unboxed] [@@noalloc]
external hypot : float -> float -> float = "caml_hypot_float" "caml_hypot"
[@@unboxed] [@@noalloc]
external cosh : float -> float = "caml_cosh_float" "cosh" [@@unboxed] [@@noalloc]
external sinh : float -> float = "caml_sinh_float" "sinh" [@@unboxed] [@@noalloc]
external tanh : float -> float = "caml_tanh_float" "tanh" [@@unboxed] [@@noalloc]
external sqrt : float -> float = "caml_sqrt_float" "sqrt" [@@unboxed] [@@noalloc]
external exp : float -> float = "caml_exp_float" "exp" [@@unboxed] [@@noalloc]
external log : float -> float = "caml_log_float" "log" [@@unboxed] [@@noalloc]
end)
(* We need this indirection because these are exposed as "val" instead of "external" *)
let frexp = frexp
let ldexp = ldexp
let is_nan x = (x : float) <> x
An order - preserving bijection between all floats except for NaNs , and 99.95 % of
int64s .
Note we do n't distinguish 0 . and -0 . as separate values here , they both map to , which
maps back to 0 .
This should work both on little - endian and high - endian CPUs . Wikipedia says : " on
modern standard computers ( i.e. , implementing IEEE 754 ) , one may in practice safely
assume that the endianness is the same for floating point numbers as for integers "
( #Floating-point_and_endianness ) .
int64s.
Note we don't distinguish 0. and -0. as separate values here, they both map to 0L, which
maps back to 0.
This should work both on little-endian and high-endian CPUs. Wikipedia says: "on
modern standard computers (i.e., implementing IEEE 754), one may in practice safely
assume that the endianness is the same for floating point numbers as for integers"
(#Floating-point_and_endianness).
*)
let to_int64_preserve_order t =
if is_nan t
then None
else if t = 0.
then (* also includes -0. *)
Some 0L
else if t > 0.
then Some (Stdlib.Int64.bits_of_float t)
else Some (Stdlib.Int64.neg (Stdlib.Int64.bits_of_float (-.t)))
;;
let to_int64_preserve_order_exn x = Option.value_exn (to_int64_preserve_order x)
let of_int64_preserve_order x =
if Int64_replace_polymorphic_compare.( >= ) x 0L
then Stdlib.Int64.float_of_bits x
else ~-.(Stdlib.Int64.float_of_bits (Stdlib.Int64.neg x))
;;
let one_ulp dir t =
match to_int64_preserve_order t with
| None -> Stdlib.nan
| Some x ->
of_int64_preserve_order
(Stdlib.Int64.add
x
(match dir with
| `Up -> 1L
| `Down -> -1L))
;;
[ upper_bound_for_int ] and [ lower_bound_for_int ] are for calculating the max / min float
that fits in a given - size integer when rounded towards 0 ( using [ int_of_float ] ) .
max_int / min_int depend on [ num_bits ] , e.g. + /- 2 ^ 30 , + /- 2 ^ 62 if 31 - bit , 63 - bit
( respectively ) while float is IEEE standard for double ( 52 significant bits ) .
In all cases , we want to guarantee that
[ lower_bound_for_int < = x < = upper_bound_for_int ]
iff [ int_of_float x ] fits in an int with [ num_bits ] bits .
[ 2 * * ( num_bits - 1 ) ] is the first float greater that max_int , we use the preceding
float as upper bound .
[ - ( 2 * * ( num_bits - 1 ) ) ] is equal to min_int .
For lower bound we look for the smallest float [ f ] satisfying [ f > min_int - 1 ] so that
[ f ] rounds toward zero to [ min_int ]
So in particular we will have :
[ lower_bound_for_int x < = - ( 2 * * ( 1 - x ) ) ]
[ upper_bound_for_int x < 2 * * ( 1 - x ) ]
that fits in a given-size integer when rounded towards 0 (using [int_of_float]).
max_int/min_int depend on [num_bits], e.g. +/- 2^30, +/- 2^62 if 31-bit, 63-bit
(respectively) while float is IEEE standard for double (52 significant bits).
In all cases, we want to guarantee that
[lower_bound_for_int <= x <= upper_bound_for_int]
iff [int_of_float x] fits in an int with [num_bits] bits.
[2 ** (num_bits - 1)] is the first float greater that max_int, we use the preceding
float as upper bound.
[- (2 ** (num_bits - 1))] is equal to min_int.
For lower bound we look for the smallest float [f] satisfying [f > min_int - 1] so that
[f] rounds toward zero to [min_int]
So in particular we will have:
[lower_bound_for_int x <= - (2 ** (1-x))]
[upper_bound_for_int x < 2 ** (1-x) ]
*)
let upper_bound_for_int num_bits =
let exp = Stdlib.float_of_int (num_bits - 1) in
one_ulp `Down (2. ** exp)
;;
let is_x_minus_one_exact x =
[ x = x - . 1 . ] does not work with x87 floating point arithmetic backend ( which is used
on 32 - bit ocaml ) because of 80 - bit register precision of intermediate computations .
An alternative way of computing this : [ x - . one_ulp ` Down x < = 1 . ] is also prone to
the same precision issues : you need to make sure [ x ] is 64 - bit .
on 32-bit ocaml) because of 80-bit register precision of intermediate computations.
An alternative way of computing this: [x -. one_ulp `Down x <= 1.] is also prone to
the same precision issues: you need to make sure [x] is 64-bit.
*)
let open Int64_replace_polymorphic_compare in
not (Stdlib.Int64.bits_of_float x = Stdlib.Int64.bits_of_float (x -. 1.))
;;
let lower_bound_for_int num_bits =
let exp = Stdlib.float_of_int (num_bits - 1) in
let min_int_as_float = ~-.(2. ** exp) in
let open Int_replace_polymorphic_compare in
53 = # bits in the float 's mantissa with sign included
then (
The smallest float that rounds towards zero to [ min_int ] is
[ min_int - 1 + epsilon ]
[min_int - 1 + epsilon] *)
assert (is_x_minus_one_exact min_int_as_float);
one_ulp `Up (min_int_as_float -. 1.))
else (
(* [min_int_as_float] is already the smallest float [f] satisfying [f > min_int - 1]. *)
assert (not (is_x_minus_one_exact min_int_as_float));
min_int_as_float)
;;
Float clamping is structured slightly differently than clamping for other types , so
that we get the behavior of [ clamp_unchecked nan ~min ~max ( for any [ min ] and
[ max ] ) for free .
that we get the behavior of [clamp_unchecked nan ~min ~max = nan] (for any [min] and
[max]) for free.
*)
let clamp_unchecked (t : float) ~min ~max =
if t < min then min else if max < t then max else t
;;
let box =
Prevent potential constant folding of [ + . 0 . ] in the near ocamlopt future .
let x = Sys0.opaque_identity 0. in
fun f -> f +. x
;;
(* Include type-specific [Replace_polymorphic_compare] at the end, after
including functor application that could shadow its definitions. This is
here so that efficient versions of the comparison functions are exported by
this module. *)
include Float_replace_polymorphic_compare
| null | https://raw.githubusercontent.com/janestreet/base/1462b7d5458e96569275a1c673df968ecbf3342f/src/float0.ml | ocaml | Open replace_polymorphic_compare after including functor instantiations so they do not
shadow its definitions. This is here so that efficient versions of the comparison
functions are available within this module.
Raise in case of a negative modulus, as does Int.( % ).
Produce a non-negative result in analogy with Int.( % ).
We need this indirection because these are exposed as "val" instead of "external"
also includes -0.
[min_int_as_float] is already the smallest float [f] satisfying [f > min_int - 1].
Include type-specific [Replace_polymorphic_compare] at the end, after
including functor application that could shadow its definitions. This is
here so that efficient versions of the comparison functions are exported by
this module. | open! Import
open! Float_replace_polymorphic_compare
let ceil = Stdlib.ceil
let floor = Stdlib.floor
let mod_float = Stdlib.mod_float
let modf = Stdlib.modf
let float_of_string = Stdlib.float_of_string
let float_of_string_opt = Stdlib.float_of_string_opt
let nan = Stdlib.nan
let infinity = Stdlib.infinity
let neg_infinity = Stdlib.neg_infinity
let max_finite_value = Stdlib.max_float
let epsilon_float = Stdlib.epsilon_float
let classify_float = Stdlib.classify_float
let abs_float = Stdlib.abs_float
let is_integer = Stdlib.Float.is_integer
let ( ** ) = Stdlib.( ** )
let ( %. ) a b =
if b < 0.
then Printf.invalid_argf "%f %% %f in float0.ml: modulus should be positive" a b ();
let m = Stdlib.mod_float a b in
if m < 0. then m +. b else m
;;
The bits of INRIA 's [ Pervasives ] that we just want to expose in [ Float ] . Most are
already deprecated in [ Pervasives ] , and eventually all of them should be .
already deprecated in [Pervasives], and eventually all of them should be. *)
include (
Stdlib :
sig
external frexp : float -> float * int = "caml_frexp_float"
external ldexp
: (float[@unboxed])
-> (int[@untagged])
-> (float[@unboxed])
= "caml_ldexp_float" "caml_ldexp_float_unboxed"
[@@noalloc]
external log10 : float -> float = "caml_log10_float" "log10" [@@unboxed] [@@noalloc]
external expm1 : float -> float = "caml_expm1_float" "caml_expm1"
[@@unboxed] [@@noalloc]
external log1p : float -> float = "caml_log1p_float" "caml_log1p"
[@@unboxed] [@@noalloc]
external copysign : float -> float -> float = "caml_copysign_float" "caml_copysign"
[@@unboxed] [@@noalloc]
external cos : float -> float = "caml_cos_float" "cos" [@@unboxed] [@@noalloc]
external sin : float -> float = "caml_sin_float" "sin" [@@unboxed] [@@noalloc]
external tan : float -> float = "caml_tan_float" "tan" [@@unboxed] [@@noalloc]
external acos : float -> float = "caml_acos_float" "acos" [@@unboxed] [@@noalloc]
external asin : float -> float = "caml_asin_float" "asin" [@@unboxed] [@@noalloc]
external atan : float -> float = "caml_atan_float" "atan" [@@unboxed] [@@noalloc]
external acosh : float -> float = "caml_acosh_float" "caml_acosh"
[@@unboxed] [@@noalloc]
external asinh : float -> float = "caml_asinh_float" "caml_asinh"
[@@unboxed] [@@noalloc]
external atanh : float -> float = "caml_atanh_float" "caml_atanh"
[@@unboxed] [@@noalloc]
external atan2 : float -> float -> float = "caml_atan2_float" "atan2"
[@@unboxed] [@@noalloc]
external hypot : float -> float -> float = "caml_hypot_float" "caml_hypot"
[@@unboxed] [@@noalloc]
external cosh : float -> float = "caml_cosh_float" "cosh" [@@unboxed] [@@noalloc]
external sinh : float -> float = "caml_sinh_float" "sinh" [@@unboxed] [@@noalloc]
external tanh : float -> float = "caml_tanh_float" "tanh" [@@unboxed] [@@noalloc]
external sqrt : float -> float = "caml_sqrt_float" "sqrt" [@@unboxed] [@@noalloc]
external exp : float -> float = "caml_exp_float" "exp" [@@unboxed] [@@noalloc]
external log : float -> float = "caml_log_float" "log" [@@unboxed] [@@noalloc]
end)
let frexp = frexp
let ldexp = ldexp
let is_nan x = (x : float) <> x
An order - preserving bijection between all floats except for NaNs , and 99.95 % of
int64s .
Note we do n't distinguish 0 . and -0 . as separate values here , they both map to , which
maps back to 0 .
This should work both on little - endian and high - endian CPUs . Wikipedia says : " on
modern standard computers ( i.e. , implementing IEEE 754 ) , one may in practice safely
assume that the endianness is the same for floating point numbers as for integers "
( #Floating-point_and_endianness ) .
int64s.
Note we don't distinguish 0. and -0. as separate values here, they both map to 0L, which
maps back to 0.
This should work both on little-endian and high-endian CPUs. Wikipedia says: "on
modern standard computers (i.e., implementing IEEE 754), one may in practice safely
assume that the endianness is the same for floating point numbers as for integers"
(#Floating-point_and_endianness).
*)
let to_int64_preserve_order t =
if is_nan t
then None
else if t = 0.
Some 0L
else if t > 0.
then Some (Stdlib.Int64.bits_of_float t)
else Some (Stdlib.Int64.neg (Stdlib.Int64.bits_of_float (-.t)))
;;
let to_int64_preserve_order_exn x = Option.value_exn (to_int64_preserve_order x)
let of_int64_preserve_order x =
if Int64_replace_polymorphic_compare.( >= ) x 0L
then Stdlib.Int64.float_of_bits x
else ~-.(Stdlib.Int64.float_of_bits (Stdlib.Int64.neg x))
;;
let one_ulp dir t =
match to_int64_preserve_order t with
| None -> Stdlib.nan
| Some x ->
of_int64_preserve_order
(Stdlib.Int64.add
x
(match dir with
| `Up -> 1L
| `Down -> -1L))
;;
[ upper_bound_for_int ] and [ lower_bound_for_int ] are for calculating the max / min float
that fits in a given - size integer when rounded towards 0 ( using [ int_of_float ] ) .
max_int / min_int depend on [ num_bits ] , e.g. + /- 2 ^ 30 , + /- 2 ^ 62 if 31 - bit , 63 - bit
( respectively ) while float is IEEE standard for double ( 52 significant bits ) .
In all cases , we want to guarantee that
[ lower_bound_for_int < = x < = upper_bound_for_int ]
iff [ int_of_float x ] fits in an int with [ num_bits ] bits .
[ 2 * * ( num_bits - 1 ) ] is the first float greater that max_int , we use the preceding
float as upper bound .
[ - ( 2 * * ( num_bits - 1 ) ) ] is equal to min_int .
For lower bound we look for the smallest float [ f ] satisfying [ f > min_int - 1 ] so that
[ f ] rounds toward zero to [ min_int ]
So in particular we will have :
[ lower_bound_for_int x < = - ( 2 * * ( 1 - x ) ) ]
[ upper_bound_for_int x < 2 * * ( 1 - x ) ]
that fits in a given-size integer when rounded towards 0 (using [int_of_float]).
max_int/min_int depend on [num_bits], e.g. +/- 2^30, +/- 2^62 if 31-bit, 63-bit
(respectively) while float is IEEE standard for double (52 significant bits).
In all cases, we want to guarantee that
[lower_bound_for_int <= x <= upper_bound_for_int]
iff [int_of_float x] fits in an int with [num_bits] bits.
[2 ** (num_bits - 1)] is the first float greater that max_int, we use the preceding
float as upper bound.
[- (2 ** (num_bits - 1))] is equal to min_int.
For lower bound we look for the smallest float [f] satisfying [f > min_int - 1] so that
[f] rounds toward zero to [min_int]
So in particular we will have:
[lower_bound_for_int x <= - (2 ** (1-x))]
[upper_bound_for_int x < 2 ** (1-x) ]
*)
let upper_bound_for_int num_bits =
let exp = Stdlib.float_of_int (num_bits - 1) in
one_ulp `Down (2. ** exp)
;;
let is_x_minus_one_exact x =
[ x = x - . 1 . ] does not work with x87 floating point arithmetic backend ( which is used
on 32 - bit ocaml ) because of 80 - bit register precision of intermediate computations .
An alternative way of computing this : [ x - . one_ulp ` Down x < = 1 . ] is also prone to
the same precision issues : you need to make sure [ x ] is 64 - bit .
on 32-bit ocaml) because of 80-bit register precision of intermediate computations.
An alternative way of computing this: [x -. one_ulp `Down x <= 1.] is also prone to
the same precision issues: you need to make sure [x] is 64-bit.
*)
let open Int64_replace_polymorphic_compare in
not (Stdlib.Int64.bits_of_float x = Stdlib.Int64.bits_of_float (x -. 1.))
;;
let lower_bound_for_int num_bits =
let exp = Stdlib.float_of_int (num_bits - 1) in
let min_int_as_float = ~-.(2. ** exp) in
let open Int_replace_polymorphic_compare in
53 = # bits in the float 's mantissa with sign included
then (
The smallest float that rounds towards zero to [ min_int ] is
[ min_int - 1 + epsilon ]
[min_int - 1 + epsilon] *)
assert (is_x_minus_one_exact min_int_as_float);
one_ulp `Up (min_int_as_float -. 1.))
else (
assert (not (is_x_minus_one_exact min_int_as_float));
min_int_as_float)
;;
Float clamping is structured slightly differently than clamping for other types , so
that we get the behavior of [ clamp_unchecked nan ~min ~max ( for any [ min ] and
[ max ] ) for free .
that we get the behavior of [clamp_unchecked nan ~min ~max = nan] (for any [min] and
[max]) for free.
*)
let clamp_unchecked (t : float) ~min ~max =
if t < min then min else if max < t then max else t
;;
let box =
Prevent potential constant folding of [ + . 0 . ] in the near ocamlopt future .
let x = Sys0.opaque_identity 0. in
fun f -> f +. x
;;
include Float_replace_polymorphic_compare
|
163537eedecbc6b605ced98b14ac3a891168f43e528fef2ed0bd23813b7ac36f | dinosaure/multipart_form | multipart_form.mli | (** {1 Multipart-form.}
The MIME type [multipart/form-data] is used to express values submitted
through a [<form>]. This module helps the user to extract these values from
an input. *)
module Field_name : sig
type t = private string
val compare : t -> t -> int
val equal : t -> t -> bool
val capitalize : t -> t
val canonicalize : t -> t
val of_string : string -> (t, [> `Msg of string ]) result
val of_string_exn : string -> t
val v : string -> t
val prefixed_by : string -> t -> bool
val content_type : t
val content_transfer_encoding : t
val content_disposition : t
val pp : t Fmt.t
end
module Content_type : sig
module Type : sig
type t =
[ `Text
| `Image
| `Audio
| `Video
| `Application
| `Multipart
| `Ietf_token of string
| `X_token of string ]
val pp : t Fmt.t
end
module Subtype : sig
type t =
[ `Ietf_token of string | `Iana_token of string | `X_token of string ]
val iana : string -> (t, [> `Msg of string ]) result
val pp : t Fmt.t
end
module Parameters : sig
module Map : module type of Map.Make (String)
type key = string
type value = String of string | Token of string
type t = value Map.t
val key : string -> (key, [> `Msg of string ]) result
val key_exn : string -> key
val k : string -> key
val value : string -> (value, [> `Msg of string ]) result
val value_exn : string -> value
val v : string -> value
val add : key -> value -> t -> t
val empty : t
val pp : t Fmt.t
val of_list : (key * value) list -> t
val to_list : t -> (key * value) list
end
type t = {
ty : Type.t;
subty : Subtype.t;
parameters : (string * Parameters.value) list;
}
val make : Type.t -> Subtype.t -> Parameters.value Parameters.Map.t -> t
val equal : t -> t -> bool
val pp : t Fmt.t
val of_string : string -> (t, [> `Msg of string ]) result
(** [of_string str] returns the [Content-Type] value from a string
which come from your HTTP stack. {b NOTE}: the string {b must}
finish with ["\r\n"]. If you are not sure about the value
returned by your HTTP stack, you should append it. *)
val to_string : t -> string
end
module Content_encoding : sig
type t =
[ `Bit7
| `Bit8
| `Binary
| `Quoted_printable
| `Base64
| `Ietf_token of string
| `X_token of string ]
val pp : t Fmt.t
val of_string : string -> (t, [> `Msg of string ]) result
val to_string : t -> string
end
module Content_disposition : sig
type t
val disposition_type :
t -> [ `Inline | `Attachment | `Ietf_token of string | `X_token of string ]
val name : t -> string option
val filename : t -> string option
val size : t -> int option
val pp : t Fmt.t
val v :
?filename:string ->
?kind:[ `Inline | `Attachment | `Ietf_token of string | `X_token of string ] ->
?size:int ->
string ->
t
val of_string : string -> (t, [> `Msg of string ]) result
val to_string : t -> string
end
module Field : sig
* { 2 HTTP fields . }
An HTTP header ( see { ! Header.t } ) is composed of several { i fields } . A
field is a { ! Field_name.t } with a ( typed or not ) value . This library
provides 4 kinds of values :
{ ul
{ - A { ! Content_type.t } value which is given by the
{ ! Field_name.content_type } field - name . It specifies the type of
contents . }
{ - A { ! Content_encoding.t } value which is given by the
{ ! Field_name.content_transfer_encoding } field - name . It specifies the
encoding used to transfer contents . }
{ - A { ! } value which is given by the
{ ! Field_name.content_disposition } field - name . It specifies some
{ i meta } information about contents . }
{ - Any others field - names where values are { i unstructured } . } }
An HTTP header (see {!Header.t}) is composed of several {i fields}. A
field is a {!Field_name.t} with a (typed or not) value. This library
provides 4 kinds of values:
{ul
{- A {!Content_type.t} value which is given by the
{!Field_name.content_type} field-name. It specifies the type of
contents.}
{- A {!Content_encoding.t} value which is given by the
{!Field_name.content_transfer_encoding} field-name. It specifies the
encoding used to transfer contents.}
{- A {!Content_disposition.t} value which is given by the
{!Field_name.content_disposition} field-name. It specifies some
{i meta} information about contents.}
{- Any others field-names where values are {i unstructured}.}} *)
type 'a t =
| Content_type : Content_type.t t
| Content_encoding : Content_encoding.t t
| Content_disposition : Content_disposition.t t
| Field : Unstrctrd.t t
type witness = Witness : 'a t -> witness
type field = Field : Field_name.t * 'a t * 'a -> field
end
module Header : sig
(** {2 HTTP Header.}
Any part of a [multipart/form-data] document has a HTTP header which
describes:
{ul
{- the type of contents.}
{- the encoding used to transfer contents.}
{- {i meta-data} such as the associated name/key of contents.}
{- some others {i meta} information.}}
We allow the user to introspect the given header with useful functions. *)
type t
val assoc : Field_name.t -> t -> Field.field list
val exists : Field_name.t -> t -> bool
val content_type : t -> Content_type.t
(** [content_type header] returns the {!Content_type} value of [header]. If
this value does not exists, it return default value. *)
val content_encoding : t -> Content_encoding.t
(** [content_encoding] returns the {!Content_encoding} value of [header]. If
this value does not exists, it return default value. *)
val content_disposition : t -> Content_disposition.t option
(** [content_disposition] returns the {!Content_disposition} value of [header]
if it exists. *)
val to_list : t -> Field.field list
(** [to_list hdr] returns the list of fields into the given [hdr] header. *)
val pp : t Fmt.t
module Decoder : sig
val header : t Angstrom.t
end
end
(** {2 Decoder.} *)
type 'id emitters = Header.t -> (string option -> unit) * 'id
(** Type of emitters.
An [emitters] is able to produce from the given header a {i pusher} which is
able to save contents and a unique ID to be able to get the content
furthermore. *)
type 'a elt = { header : Header.t; body : 'a }
(** Type of a simple element.
An element is a {i part} in sense of the [multipart/form-data] format. A
part can contains multiple parts. It has systematically a {!Header.t}. *)
* Type of [ multipart / form - data ] contents .
{ ul
{ - a [ Leaf ] is a content with a simple header . }
{ - a [ Multipart ] is a [ list ] of possibly empty ( [ option ] ) sub - elements -
indeed , we can have a multipart inside a multipart . } }
{ul
{- a [Leaf] is a content with a simple header.}
{- a [Multipart] is a [list] of possibly empty ([option]) sub-elements -
indeed, we can have a multipart inside a multipart.}} *)
type 'a t = Leaf of 'a elt | Multipart of 'a t option list elt
val map : ('a -> 'b) -> 'a t -> 'b t
val flatten : 'a t -> 'a elt list
(** {3 Streaming API.} *)
val parse :
emitters:'id emitters ->
Content_type.t ->
[ `String of string | `Eof ] ->
[ `Continue | `Done of 'id t | `Fail of string ]
* [ parse ~emitters content_type ] returns a function that can be called
repeatedly to feed it successive chunks of a [ multipart / form - data ] input
stream . It then allows streaming the output ( the contents of the parts )
through the [ emitters ] callback .
For each part , the parser calls [ emitters ] to be able to save contents and
get a { i reference } of it . Each part then corresponds to a [ Leaf ] in the
multipart document returned in the [ ` Done ] case , using the corresponding
reference .
As a simple example , one can use [ parse ] to generate an unique ID for each
part and associate it to a { ! Buffer.t } . The table [ tbl ] maintains the mapping
between the part IDs that can be found in the return value and the contents
of the parts .
{ [
let gen = let v = ref ( -1 ) in fun ( ) - > incr v ; ! v in
let = Hashtbl.create 0x10 in
let emitters ( ) =
let idx = gen ( ) in
let buf = Buffer.create 0x100 in
( function None - > ( )
| Some str - > Buffer.add_string ) , idx in
let step = parse ~emitters content_type in
let get_next_input_chunk ( ) = ... in
let rec loop ( ) =
match step ( get_next_input_chunk ( ) ) with
| ` Continue - > loop ( )
| ` Done tree - > Ok tree
| ` Fail msg - > Error msg
in
loop ( )
] }
As illustrated by the example above , the use of [ parse ] is somewhat
intricate . This is because [ parse ] handles the general case of parsing
streamed input and producing streamed output , and does not depend on any
concurrenty library . Simpler functions [ of_{stream , string}_to_{list , tree } ]
can be found below for when streaming is not needed . When using Lwt , the
[ Multipart_form_lwt ] module provides a more convenient API , both in the
streaming and non - streaming case .
repeatedly to feed it successive chunks of a [multipart/form-data] input
stream. It then allows streaming the output (the contents of the parts)
through the [emitters] callback.
For each part, the parser calls [emitters] to be able to save contents and
get a {i reference} of it. Each part then corresponds to a [Leaf] in the
multipart document returned in the [`Done] case, using the corresponding
reference.
As a simple example, one can use [parse] to generate an unique ID for each
part and associate it to a {!Buffer.t}. The table [tbl] maintains the mapping
between the part IDs that can be found in the return value and the contents
of the parts.
{[
let gen = let v = ref (-1) in fun () -> incr v ; !v in
let tbl = Hashtbl.create 0x10 in
let emitters () =
let idx = gen () in
let buf = Buffer.create 0x100 in
(function None -> ()
| Some str -> Buffer.add_string buf str), idx in
let step = parse ~emitters content_type in
let get_next_input_chunk () = ... in
let rec loop () =
match step (get_next_input_chunk ()) with
| `Continue -> loop ()
| `Done tree -> Ok tree
| `Fail msg -> Error msg
in
loop ()
]}
As illustrated by the example above, the use of [parse] is somewhat
intricate. This is because [parse] handles the general case of parsing
streamed input and producing streamed output, and does not depend on any
concurrenty library. Simpler functions [of_{stream,string}_to_{list,tree}]
can be found below for when streaming is not needed. When using Lwt, the
[Multipart_form_lwt] module provides a more convenient API, both in the
streaming and non-streaming case.
*)
val parser : emitters:'id emitters -> Content_type.t -> 'id t Angstrom.t
* [ parse ~emitters content_type ] gives access to the underlying [ ]
parser used internally by the [ parse ] function . This is useful when one
needs control over the parsing buffer used by .
parser used internally by the [parse] function. This is useful when one
needs control over the parsing buffer used by Angstrom. *)
* { 3 Non - streaming API . }
The functions below offer a simpler API for the case where streaming the
output is not needed . This means that the entire contents of the multipart
data will be stored in memory : they should not be used when dealing with
possibly large data .
The functions below offer a simpler API for the case where streaming the
output is not needed. This means that the entire contents of the multipart
data will be stored in memory: they should not be used when dealing with
possibly large data.
*)
type 'a stream = unit -> 'a option
val of_stream_to_list :
string stream ->
Content_type.t ->
(int t * (int * string) list, [> `Msg of string ]) result
* [ of_stream_to_list stream content_type ] returns , if it succeeds , a pair of a
value { ! t } and an associative list of contents . The multipart document { ! t }
references parts using unique IDs ( integers ) and associates these IDs to
the respective contents of each part , stored as a string .
value {!t} and an associative list of contents. The multipart document {!t}
references parts using unique IDs (integers) and associates these IDs to
the respective contents of each part, stored as a string. *)
val of_string_to_list :
string ->
Content_type.t ->
(int t * (int * string) list, [> `Msg of string ]) result
(** Similar to [of_stream_to_list], but takes the input as a string. *)
val of_stream_to_tree :
string stream -> Content_type.t -> (string t, [> `Msg of string ]) result
(** [of_stream_to_tree stream content_type] returns, if it succeeds, a value
{!t} representing the multipart document, where the contents of the parts are
stored as strings. It is equivalent to [of_stream_to_list] where references
have been replaced with their associated contents. *)
val of_string_to_tree :
string -> Content_type.t -> (string t, [> `Msg of string ]) result
(** Similar to [of_string_to_tree], but takes the input as a string. *)
* { 2 Encoder . }
type part
val part :
?header:Header.t ->
?disposition:Content_disposition.t ->
?encoding:Content_encoding.t ->
(string * int * int) stream ->
part
(** [part ?header ?disposition ?encoding stream] makes a new part from a body
stream [stream] and fields. [stream] while be mapped according to
[encoding]. *)
type multipart
val multipart :
rng:(?g:'g -> int -> string) ->
?g:'g ->
?header:Header.t ->
?boundary:string ->
part list ->
multipart
(** [multipart ~rng ?g ?header ?boundary parts] makes a new multipart from
a bunch of parts, [fields] and a specified [boundary]. If [boundary] is not
specified, we use [rng] to make a random boundary (we did not check that it
does not appear inside [parts]). *)
val to_stream : multipart -> Header.t * (string * int * int) stream
(** [to_stream ms] generates an HTTP header and a stream. *)
| null | https://raw.githubusercontent.com/dinosaure/multipart_form/98b8951bee66fe70c9793f9d3ca6d3957447defe/lib/multipart_form.mli | ocaml | * {1 Multipart-form.}
The MIME type [multipart/form-data] is used to express values submitted
through a [<form>]. This module helps the user to extract these values from
an input.
* [of_string str] returns the [Content-Type] value from a string
which come from your HTTP stack. {b NOTE}: the string {b must}
finish with ["\r\n"]. If you are not sure about the value
returned by your HTTP stack, you should append it.
* {2 HTTP Header.}
Any part of a [multipart/form-data] document has a HTTP header which
describes:
{ul
{- the type of contents.}
{- the encoding used to transfer contents.}
{- {i meta-data} such as the associated name/key of contents.}
{- some others {i meta} information.}}
We allow the user to introspect the given header with useful functions.
* [content_type header] returns the {!Content_type} value of [header]. If
this value does not exists, it return default value.
* [content_encoding] returns the {!Content_encoding} value of [header]. If
this value does not exists, it return default value.
* [content_disposition] returns the {!Content_disposition} value of [header]
if it exists.
* [to_list hdr] returns the list of fields into the given [hdr] header.
* {2 Decoder.}
* Type of emitters.
An [emitters] is able to produce from the given header a {i pusher} which is
able to save contents and a unique ID to be able to get the content
furthermore.
* Type of a simple element.
An element is a {i part} in sense of the [multipart/form-data] format. A
part can contains multiple parts. It has systematically a {!Header.t}.
* {3 Streaming API.}
* Similar to [of_stream_to_list], but takes the input as a string.
* [of_stream_to_tree stream content_type] returns, if it succeeds, a value
{!t} representing the multipart document, where the contents of the parts are
stored as strings. It is equivalent to [of_stream_to_list] where references
have been replaced with their associated contents.
* Similar to [of_string_to_tree], but takes the input as a string.
* [part ?header ?disposition ?encoding stream] makes a new part from a body
stream [stream] and fields. [stream] while be mapped according to
[encoding].
* [multipart ~rng ?g ?header ?boundary parts] makes a new multipart from
a bunch of parts, [fields] and a specified [boundary]. If [boundary] is not
specified, we use [rng] to make a random boundary (we did not check that it
does not appear inside [parts]).
* [to_stream ms] generates an HTTP header and a stream. |
module Field_name : sig
type t = private string
val compare : t -> t -> int
val equal : t -> t -> bool
val capitalize : t -> t
val canonicalize : t -> t
val of_string : string -> (t, [> `Msg of string ]) result
val of_string_exn : string -> t
val v : string -> t
val prefixed_by : string -> t -> bool
val content_type : t
val content_transfer_encoding : t
val content_disposition : t
val pp : t Fmt.t
end
module Content_type : sig
module Type : sig
type t =
[ `Text
| `Image
| `Audio
| `Video
| `Application
| `Multipart
| `Ietf_token of string
| `X_token of string ]
val pp : t Fmt.t
end
module Subtype : sig
type t =
[ `Ietf_token of string | `Iana_token of string | `X_token of string ]
val iana : string -> (t, [> `Msg of string ]) result
val pp : t Fmt.t
end
module Parameters : sig
module Map : module type of Map.Make (String)
type key = string
type value = String of string | Token of string
type t = value Map.t
val key : string -> (key, [> `Msg of string ]) result
val key_exn : string -> key
val k : string -> key
val value : string -> (value, [> `Msg of string ]) result
val value_exn : string -> value
val v : string -> value
val add : key -> value -> t -> t
val empty : t
val pp : t Fmt.t
val of_list : (key * value) list -> t
val to_list : t -> (key * value) list
end
type t = {
ty : Type.t;
subty : Subtype.t;
parameters : (string * Parameters.value) list;
}
val make : Type.t -> Subtype.t -> Parameters.value Parameters.Map.t -> t
val equal : t -> t -> bool
val pp : t Fmt.t
val of_string : string -> (t, [> `Msg of string ]) result
val to_string : t -> string
end
module Content_encoding : sig
type t =
[ `Bit7
| `Bit8
| `Binary
| `Quoted_printable
| `Base64
| `Ietf_token of string
| `X_token of string ]
val pp : t Fmt.t
val of_string : string -> (t, [> `Msg of string ]) result
val to_string : t -> string
end
module Content_disposition : sig
type t
val disposition_type :
t -> [ `Inline | `Attachment | `Ietf_token of string | `X_token of string ]
val name : t -> string option
val filename : t -> string option
val size : t -> int option
val pp : t Fmt.t
val v :
?filename:string ->
?kind:[ `Inline | `Attachment | `Ietf_token of string | `X_token of string ] ->
?size:int ->
string ->
t
val of_string : string -> (t, [> `Msg of string ]) result
val to_string : t -> string
end
module Field : sig
* { 2 HTTP fields . }
An HTTP header ( see { ! Header.t } ) is composed of several { i fields } . A
field is a { ! Field_name.t } with a ( typed or not ) value . This library
provides 4 kinds of values :
{ ul
{ - A { ! Content_type.t } value which is given by the
{ ! Field_name.content_type } field - name . It specifies the type of
contents . }
{ - A { ! Content_encoding.t } value which is given by the
{ ! Field_name.content_transfer_encoding } field - name . It specifies the
encoding used to transfer contents . }
{ - A { ! } value which is given by the
{ ! Field_name.content_disposition } field - name . It specifies some
{ i meta } information about contents . }
{ - Any others field - names where values are { i unstructured } . } }
An HTTP header (see {!Header.t}) is composed of several {i fields}. A
field is a {!Field_name.t} with a (typed or not) value. This library
provides 4 kinds of values:
{ul
{- A {!Content_type.t} value which is given by the
{!Field_name.content_type} field-name. It specifies the type of
contents.}
{- A {!Content_encoding.t} value which is given by the
{!Field_name.content_transfer_encoding} field-name. It specifies the
encoding used to transfer contents.}
{- A {!Content_disposition.t} value which is given by the
{!Field_name.content_disposition} field-name. It specifies some
{i meta} information about contents.}
{- Any others field-names where values are {i unstructured}.}} *)
type 'a t =
| Content_type : Content_type.t t
| Content_encoding : Content_encoding.t t
| Content_disposition : Content_disposition.t t
| Field : Unstrctrd.t t
type witness = Witness : 'a t -> witness
type field = Field : Field_name.t * 'a t * 'a -> field
end
module Header : sig
type t
val assoc : Field_name.t -> t -> Field.field list
val exists : Field_name.t -> t -> bool
val content_type : t -> Content_type.t
val content_encoding : t -> Content_encoding.t
val content_disposition : t -> Content_disposition.t option
val to_list : t -> Field.field list
val pp : t Fmt.t
module Decoder : sig
val header : t Angstrom.t
end
end
type 'id emitters = Header.t -> (string option -> unit) * 'id
type 'a elt = { header : Header.t; body : 'a }
* Type of [ multipart / form - data ] contents .
{ ul
{ - a [ Leaf ] is a content with a simple header . }
{ - a [ Multipart ] is a [ list ] of possibly empty ( [ option ] ) sub - elements -
indeed , we can have a multipart inside a multipart . } }
{ul
{- a [Leaf] is a content with a simple header.}
{- a [Multipart] is a [list] of possibly empty ([option]) sub-elements -
indeed, we can have a multipart inside a multipart.}} *)
type 'a t = Leaf of 'a elt | Multipart of 'a t option list elt
val map : ('a -> 'b) -> 'a t -> 'b t
val flatten : 'a t -> 'a elt list
val parse :
emitters:'id emitters ->
Content_type.t ->
[ `String of string | `Eof ] ->
[ `Continue | `Done of 'id t | `Fail of string ]
* [ parse ~emitters content_type ] returns a function that can be called
repeatedly to feed it successive chunks of a [ multipart / form - data ] input
stream . It then allows streaming the output ( the contents of the parts )
through the [ emitters ] callback .
For each part , the parser calls [ emitters ] to be able to save contents and
get a { i reference } of it . Each part then corresponds to a [ Leaf ] in the
multipart document returned in the [ ` Done ] case , using the corresponding
reference .
As a simple example , one can use [ parse ] to generate an unique ID for each
part and associate it to a { ! Buffer.t } . The table [ tbl ] maintains the mapping
between the part IDs that can be found in the return value and the contents
of the parts .
{ [
let gen = let v = ref ( -1 ) in fun ( ) - > incr v ; ! v in
let = Hashtbl.create 0x10 in
let emitters ( ) =
let idx = gen ( ) in
let buf = Buffer.create 0x100 in
( function None - > ( )
| Some str - > Buffer.add_string ) , idx in
let step = parse ~emitters content_type in
let get_next_input_chunk ( ) = ... in
let rec loop ( ) =
match step ( get_next_input_chunk ( ) ) with
| ` Continue - > loop ( )
| ` Done tree - > Ok tree
| ` Fail msg - > Error msg
in
loop ( )
] }
As illustrated by the example above , the use of [ parse ] is somewhat
intricate . This is because [ parse ] handles the general case of parsing
streamed input and producing streamed output , and does not depend on any
concurrenty library . Simpler functions [ of_{stream , string}_to_{list , tree } ]
can be found below for when streaming is not needed . When using Lwt , the
[ Multipart_form_lwt ] module provides a more convenient API , both in the
streaming and non - streaming case .
repeatedly to feed it successive chunks of a [multipart/form-data] input
stream. It then allows streaming the output (the contents of the parts)
through the [emitters] callback.
For each part, the parser calls [emitters] to be able to save contents and
get a {i reference} of it. Each part then corresponds to a [Leaf] in the
multipart document returned in the [`Done] case, using the corresponding
reference.
As a simple example, one can use [parse] to generate an unique ID for each
part and associate it to a {!Buffer.t}. The table [tbl] maintains the mapping
between the part IDs that can be found in the return value and the contents
of the parts.
{[
let gen = let v = ref (-1) in fun () -> incr v ; !v in
let tbl = Hashtbl.create 0x10 in
let emitters () =
let idx = gen () in
let buf = Buffer.create 0x100 in
(function None -> ()
| Some str -> Buffer.add_string buf str), idx in
let step = parse ~emitters content_type in
let get_next_input_chunk () = ... in
let rec loop () =
match step (get_next_input_chunk ()) with
| `Continue -> loop ()
| `Done tree -> Ok tree
| `Fail msg -> Error msg
in
loop ()
]}
As illustrated by the example above, the use of [parse] is somewhat
intricate. This is because [parse] handles the general case of parsing
streamed input and producing streamed output, and does not depend on any
concurrenty library. Simpler functions [of_{stream,string}_to_{list,tree}]
can be found below for when streaming is not needed. When using Lwt, the
[Multipart_form_lwt] module provides a more convenient API, both in the
streaming and non-streaming case.
*)
val parser : emitters:'id emitters -> Content_type.t -> 'id t Angstrom.t
* [ parse ~emitters content_type ] gives access to the underlying [ ]
parser used internally by the [ parse ] function . This is useful when one
needs control over the parsing buffer used by .
parser used internally by the [parse] function. This is useful when one
needs control over the parsing buffer used by Angstrom. *)
* { 3 Non - streaming API . }
The functions below offer a simpler API for the case where streaming the
output is not needed . This means that the entire contents of the multipart
data will be stored in memory : they should not be used when dealing with
possibly large data .
The functions below offer a simpler API for the case where streaming the
output is not needed. This means that the entire contents of the multipart
data will be stored in memory: they should not be used when dealing with
possibly large data.
*)
type 'a stream = unit -> 'a option
val of_stream_to_list :
string stream ->
Content_type.t ->
(int t * (int * string) list, [> `Msg of string ]) result
* [ of_stream_to_list stream content_type ] returns , if it succeeds , a pair of a
value { ! t } and an associative list of contents . The multipart document { ! t }
references parts using unique IDs ( integers ) and associates these IDs to
the respective contents of each part , stored as a string .
value {!t} and an associative list of contents. The multipart document {!t}
references parts using unique IDs (integers) and associates these IDs to
the respective contents of each part, stored as a string. *)
val of_string_to_list :
string ->
Content_type.t ->
(int t * (int * string) list, [> `Msg of string ]) result
val of_stream_to_tree :
string stream -> Content_type.t -> (string t, [> `Msg of string ]) result
val of_string_to_tree :
string -> Content_type.t -> (string t, [> `Msg of string ]) result
* { 2 Encoder . }
type part
val part :
?header:Header.t ->
?disposition:Content_disposition.t ->
?encoding:Content_encoding.t ->
(string * int * int) stream ->
part
type multipart
val multipart :
rng:(?g:'g -> int -> string) ->
?g:'g ->
?header:Header.t ->
?boundary:string ->
part list ->
multipart
val to_stream : multipart -> Header.t * (string * int * int) stream
|
fc88c748b7ced789abd0cfe39a3b92ad724ab9a118412973e8afd6d7a08f9b54 | inhabitedtype/ocaml-aws | addTagsToResource.ml | open Types
open Aws
type input = AddTagsToResourceMessage.t
type output = unit
type error = Errors_internal.t
let service = "rds"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2014-10-31" ]; "Action", [ "AddTagsToResource" ] ]
(Util.drop_empty
(Uri.query_of_encoded (Query.render (AddTagsToResourceMessage.to_query req)))))
in
`POST, uri, []
let of_http body = `Ok ()
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
| null | https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/b6d5554c5d201202b5de8d0b0253871f7b66dab6/libraries/rds/lib/addTagsToResource.ml | ocaml | open Types
open Aws
type input = AddTagsToResourceMessage.t
type output = unit
type error = Errors_internal.t
let service = "rds"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2014-10-31" ]; "Action", [ "AddTagsToResource" ] ]
(Util.drop_empty
(Uri.query_of_encoded (Query.render (AddTagsToResourceMessage.to_query req)))))
in
`POST, uri, []
let of_http body = `Ok ()
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
|
|
3045833c16a41d8dd950123bbda37ed08e01e0685bc544758a0e01010f00d69f | rtoy/cmucl | vm-macs.lisp | ;;; -*- Package: VM -*-
;;;
;;; **********************************************************************
This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
;;;
(ext:file-comment
"$Header: src/compiler/generic/vm-macs.lisp $")
;;;
;;; **********************************************************************
;;;
;;; This file contains some macros and constants that are object-format
;;; specific or are used for defining the object format.
;;;
Written by and .
;;;
(in-package "VM")
(intl:textdomain "cmucl")
;;;; Other random stuff.
PAD - DATA - BLOCK -- Internal Interface .
;;;
;;; This returns a form that returns a dual-word aligned number of bytes when
;;; given a number of words.
;;;
(defmacro pad-data-block (words)
`(logandc2 (+ (ash ,words word-shift) #+amd64 15 #-amd64 lowtag-mask)
#+amd64 15 #-amd64 lowtag-mask))
DEFENUM -- Internal Interface .
;;;
(defmacro defenum ((&key (prefix "") (suffix "") (start 0) (step 1))
&rest identifiers)
(let ((results nil)
(index 0)
(start (eval start))
(step (eval step)))
(dolist (id identifiers)
(when id
(multiple-value-bind
(root docs)
(if (consp id)
(values (car id) (cdr id))
(values id nil))
(push `(defconstant ,(intern (concatenate 'simple-string
(string prefix)
(string root)
(string suffix)))
,(+ start (* step index))
,@docs)
results)))
(incf index))
`(eval-when (compile load eval)
,@(nreverse results))))
;;;; Primitive object definition stuff.
(export '(primitive-object primitive-object-p
primitive-object-name primitive-object-header
primitive-object-lowtag primitive-object-options
primitive-object-slots primitive-object-size
primitive-object-variable-length slot-name slot-docs slot-rest-p
slot-offset slot-length slot-options *primitive-objects*))
(defun remove-keywords (options keywords)
(cond ((null options) nil)
((member (car options) keywords)
(remove-keywords (cddr options) keywords))
(t
(list* (car options) (cadr options)
(remove-keywords (cddr options) keywords)))))
(defstruct (prim-object-slot
(:conc-name slot-)
(:constructor make-slot (name docs rest-p offset length options))
(:make-load-form-fun :just-dump-it-normally))
(name nil :type symbol)
(docs nil :type (or null simple-string))
(rest-p nil :type (member t nil))
(offset 0 :type fixnum)
(length 1 :type fixnum)
(options nil :type list))
(defstruct (primitive-object
(:make-load-form-fun :just-dump-it-normally))
(name nil :type symbol)
(header nil :type symbol)
(lowtag nil :type symbol)
(options nil :type list)
(slots nil :type list)
(size 0 :type fixnum)
(variable-length nil :type (member t nil)))
(defvar *primitive-objects* nil)
(defun %define-primitive-object (primobj)
(let ((name (primitive-object-name primobj)))
(setf *primitive-objects*
(cons primobj
(remove name *primitive-objects*
:key #'primitive-object-name :test #'eq)))
name))
(defmacro define-primitive-object
((name &key header lowtag alloc-trans (type t))
&rest slot-specs)
(collect ((slots) (exports) (constants) (forms) (inits))
(let ((offset (if header 1 0))
(variable-length nil))
(dolist (spec slot-specs)
(when variable-length
(error (intl:gettext "No more slots can follow a :rest-p slot.")))
(destructuring-bind
(slot-name &rest options
&key docs rest-p (length (if rest-p 0 1))
((:type slot-type) t) init
(ref-known nil ref-known-p) ref-trans
(set-known nil set-known-p) set-trans
&allow-other-keys)
(if (atom spec) (list spec) spec)
(slots (make-slot slot-name docs rest-p offset length
(remove-keywords options
'(:docs :rest-p :length))))
(let ((offset-sym (symbolicate name "-" slot-name
(if rest-p "-OFFSET" "-SLOT"))))
(constants `(defconstant ,offset-sym ,offset
,@(when docs (list docs))))
(exports offset-sym))
(when ref-trans
(when ref-known-p
(forms `(defknown ,ref-trans (,type) ,slot-type ,ref-known)))
(forms `(def-reffer ,ref-trans ,offset ,lowtag)))
(when set-trans
(when set-known-p
(forms `(defknown ,set-trans
,(if (listp set-trans)
(list slot-type type)
(list type slot-type))
,slot-type
,set-known)))
(forms `(def-setter ,set-trans ,offset ,lowtag)))
(when init
(inits (cons init offset)))
(when rest-p
(setf variable-length t))
(incf offset length)))
(unless variable-length
(let ((size (symbolicate name "-SIZE")))
(constants `(defconstant ,size ,offset
,(format nil
(intl:gettext "Number of slots used by each ~S~
~@[~* including the header~].")
name header)))
(exports size)))
(when alloc-trans
(forms `(def-alloc ,alloc-trans ,offset ,variable-length ,header
,lowtag ',(inits))))
`(progn
(eval-when (compile load eval)
(export ',(exports))
(%define-primitive-object
',(make-primitive-object :name name
:header header
:lowtag lowtag
:slots (slots)
:size offset
:variable-length variable-length))
,@(constants))
,@(forms)))))
;;;; reffer and setter definition stuff.
(in-package :c)
(export '(def-reffer def-setter def-alloc))
(defun %def-reffer (name offset lowtag)
(let ((info (function-info-or-lose name)))
(setf (function-info-ir2-convert info)
#'(lambda (node block)
(ir2-convert-reffer node block name offset lowtag))))
name)
(defmacro def-reffer (name offset lowtag)
`(%def-reffer ',name ,offset ,lowtag))
(defun %def-setter (name offset lowtag)
(let ((info (function-info-or-lose name)))
(setf (function-info-ir2-convert info)
(if (listp name)
#'(lambda (node block)
(ir2-convert-setfer node block name offset lowtag))
#'(lambda (node block)
(ir2-convert-setter node block name offset lowtag)))))
name)
(defmacro def-setter (name offset lowtag)
`(%def-setter ',name ,offset ,lowtag))
(defun %def-alloc (name words variable-length header lowtag inits)
(let ((info (function-info-or-lose name)))
(setf (function-info-ir2-convert info)
(if variable-length
#'(lambda (node block)
(ir2-convert-variable-allocation node block name words header
lowtag inits))
#'(lambda (node block)
(ir2-convert-fixed-allocation node block name words header
lowtag inits)))))
name)
(defmacro def-alloc (name words variable-length header lowtag inits)
`(%def-alloc ',name ,words ,variable-length ,header ,lowtag ,inits))
;;;; Some general constant definitions:
(in-package "C")
(export '(fasl-file-implementations
pmax-fasl-file-implementation
sparc-fasl-file-implementation
rt-fasl-file-implementation
rt-afpa-fasl-file-implementation
x86-fasl-file-implementation
hppa-fasl-file-implementation
big-endian-fasl-file-implementation
little-endian-fasl-file-implementation
alpha-fasl-file-implementation
sgi-fasl-file-implementation
ppc-fasl-file-implementation
amd64-fasl-file-implementation))
;;; Constants for the different implementations. These are all defined in
one place to make sure they are all unique .
(defparameter fasl-file-implementations
'(nil "Pmax" "Sparc" "RT" "RT/AFPA" "x86" "HPPA"
"Big-endian byte-code" "Little-endian byte-code" "Alpha" "SGI" "PPC" "AMD64"))
(defconstant pmax-fasl-file-implementation 1)
(defconstant sparc-fasl-file-implementation 2)
(defconstant rt-fasl-file-implementation 3)
(defconstant rt-afpa-fasl-file-implementation 4)
(defconstant x86-fasl-file-implementation 5)
(defconstant hppa-fasl-file-implementation 6)
(defconstant big-endian-fasl-file-implementation 7)
(defconstant little-endian-fasl-file-implementation 8)
(defconstant alpha-fasl-file-implementation 9)
(defconstant sgi-fasl-file-implementation 10)
(defconstant ppc-fasl-file-implementation 11)
(defconstant amd64-fasl-file-implementation 12)
;;; The maximum number of SCs in any implementation.
(defconstant sc-number-limit 32)
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/compiler/generic/vm-macs.lisp | lisp | -*- Package: VM -*-
**********************************************************************
**********************************************************************
This file contains some macros and constants that are object-format
specific or are used for defining the object format.
Other random stuff.
This returns a form that returns a dual-word aligned number of bytes when
given a number of words.
Primitive object definition stuff.
reffer and setter definition stuff.
Some general constant definitions:
Constants for the different implementations. These are all defined in
The maximum number of SCs in any implementation. | This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
(ext:file-comment
"$Header: src/compiler/generic/vm-macs.lisp $")
Written by and .
(in-package "VM")
(intl:textdomain "cmucl")
PAD - DATA - BLOCK -- Internal Interface .
(defmacro pad-data-block (words)
`(logandc2 (+ (ash ,words word-shift) #+amd64 15 #-amd64 lowtag-mask)
#+amd64 15 #-amd64 lowtag-mask))
DEFENUM -- Internal Interface .
(defmacro defenum ((&key (prefix "") (suffix "") (start 0) (step 1))
&rest identifiers)
(let ((results nil)
(index 0)
(start (eval start))
(step (eval step)))
(dolist (id identifiers)
(when id
(multiple-value-bind
(root docs)
(if (consp id)
(values (car id) (cdr id))
(values id nil))
(push `(defconstant ,(intern (concatenate 'simple-string
(string prefix)
(string root)
(string suffix)))
,(+ start (* step index))
,@docs)
results)))
(incf index))
`(eval-when (compile load eval)
,@(nreverse results))))
(export '(primitive-object primitive-object-p
primitive-object-name primitive-object-header
primitive-object-lowtag primitive-object-options
primitive-object-slots primitive-object-size
primitive-object-variable-length slot-name slot-docs slot-rest-p
slot-offset slot-length slot-options *primitive-objects*))
(defun remove-keywords (options keywords)
(cond ((null options) nil)
((member (car options) keywords)
(remove-keywords (cddr options) keywords))
(t
(list* (car options) (cadr options)
(remove-keywords (cddr options) keywords)))))
(defstruct (prim-object-slot
(:conc-name slot-)
(:constructor make-slot (name docs rest-p offset length options))
(:make-load-form-fun :just-dump-it-normally))
(name nil :type symbol)
(docs nil :type (or null simple-string))
(rest-p nil :type (member t nil))
(offset 0 :type fixnum)
(length 1 :type fixnum)
(options nil :type list))
(defstruct (primitive-object
(:make-load-form-fun :just-dump-it-normally))
(name nil :type symbol)
(header nil :type symbol)
(lowtag nil :type symbol)
(options nil :type list)
(slots nil :type list)
(size 0 :type fixnum)
(variable-length nil :type (member t nil)))
(defvar *primitive-objects* nil)
(defun %define-primitive-object (primobj)
(let ((name (primitive-object-name primobj)))
(setf *primitive-objects*
(cons primobj
(remove name *primitive-objects*
:key #'primitive-object-name :test #'eq)))
name))
(defmacro define-primitive-object
((name &key header lowtag alloc-trans (type t))
&rest slot-specs)
(collect ((slots) (exports) (constants) (forms) (inits))
(let ((offset (if header 1 0))
(variable-length nil))
(dolist (spec slot-specs)
(when variable-length
(error (intl:gettext "No more slots can follow a :rest-p slot.")))
(destructuring-bind
(slot-name &rest options
&key docs rest-p (length (if rest-p 0 1))
((:type slot-type) t) init
(ref-known nil ref-known-p) ref-trans
(set-known nil set-known-p) set-trans
&allow-other-keys)
(if (atom spec) (list spec) spec)
(slots (make-slot slot-name docs rest-p offset length
(remove-keywords options
'(:docs :rest-p :length))))
(let ((offset-sym (symbolicate name "-" slot-name
(if rest-p "-OFFSET" "-SLOT"))))
(constants `(defconstant ,offset-sym ,offset
,@(when docs (list docs))))
(exports offset-sym))
(when ref-trans
(when ref-known-p
(forms `(defknown ,ref-trans (,type) ,slot-type ,ref-known)))
(forms `(def-reffer ,ref-trans ,offset ,lowtag)))
(when set-trans
(when set-known-p
(forms `(defknown ,set-trans
,(if (listp set-trans)
(list slot-type type)
(list type slot-type))
,slot-type
,set-known)))
(forms `(def-setter ,set-trans ,offset ,lowtag)))
(when init
(inits (cons init offset)))
(when rest-p
(setf variable-length t))
(incf offset length)))
(unless variable-length
(let ((size (symbolicate name "-SIZE")))
(constants `(defconstant ,size ,offset
,(format nil
(intl:gettext "Number of slots used by each ~S~
~@[~* including the header~].")
name header)))
(exports size)))
(when alloc-trans
(forms `(def-alloc ,alloc-trans ,offset ,variable-length ,header
,lowtag ',(inits))))
`(progn
(eval-when (compile load eval)
(export ',(exports))
(%define-primitive-object
',(make-primitive-object :name name
:header header
:lowtag lowtag
:slots (slots)
:size offset
:variable-length variable-length))
,@(constants))
,@(forms)))))
(in-package :c)
(export '(def-reffer def-setter def-alloc))
(defun %def-reffer (name offset lowtag)
(let ((info (function-info-or-lose name)))
(setf (function-info-ir2-convert info)
#'(lambda (node block)
(ir2-convert-reffer node block name offset lowtag))))
name)
(defmacro def-reffer (name offset lowtag)
`(%def-reffer ',name ,offset ,lowtag))
(defun %def-setter (name offset lowtag)
(let ((info (function-info-or-lose name)))
(setf (function-info-ir2-convert info)
(if (listp name)
#'(lambda (node block)
(ir2-convert-setfer node block name offset lowtag))
#'(lambda (node block)
(ir2-convert-setter node block name offset lowtag)))))
name)
(defmacro def-setter (name offset lowtag)
`(%def-setter ',name ,offset ,lowtag))
(defun %def-alloc (name words variable-length header lowtag inits)
(let ((info (function-info-or-lose name)))
(setf (function-info-ir2-convert info)
(if variable-length
#'(lambda (node block)
(ir2-convert-variable-allocation node block name words header
lowtag inits))
#'(lambda (node block)
(ir2-convert-fixed-allocation node block name words header
lowtag inits)))))
name)
(defmacro def-alloc (name words variable-length header lowtag inits)
`(%def-alloc ',name ,words ,variable-length ,header ,lowtag ,inits))
(in-package "C")
(export '(fasl-file-implementations
pmax-fasl-file-implementation
sparc-fasl-file-implementation
rt-fasl-file-implementation
rt-afpa-fasl-file-implementation
x86-fasl-file-implementation
hppa-fasl-file-implementation
big-endian-fasl-file-implementation
little-endian-fasl-file-implementation
alpha-fasl-file-implementation
sgi-fasl-file-implementation
ppc-fasl-file-implementation
amd64-fasl-file-implementation))
one place to make sure they are all unique .
(defparameter fasl-file-implementations
'(nil "Pmax" "Sparc" "RT" "RT/AFPA" "x86" "HPPA"
"Big-endian byte-code" "Little-endian byte-code" "Alpha" "SGI" "PPC" "AMD64"))
(defconstant pmax-fasl-file-implementation 1)
(defconstant sparc-fasl-file-implementation 2)
(defconstant rt-fasl-file-implementation 3)
(defconstant rt-afpa-fasl-file-implementation 4)
(defconstant x86-fasl-file-implementation 5)
(defconstant hppa-fasl-file-implementation 6)
(defconstant big-endian-fasl-file-implementation 7)
(defconstant little-endian-fasl-file-implementation 8)
(defconstant alpha-fasl-file-implementation 9)
(defconstant sgi-fasl-file-implementation 10)
(defconstant ppc-fasl-file-implementation 11)
(defconstant amd64-fasl-file-implementation 12)
(defconstant sc-number-limit 32)
|
3fbd2cef500577dd52c9ed87b5f6db1f00852b0d21879a0fec1cd155c2699925 | mcandre/genetics | HelloGenetics.hs | {-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE FlexibleInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Main where
import System.Random as Rand
import Genetics
import Control.Monad (replicateM)
target :: String
target = "Hello World!"
generations :: Int
generations = (2 :: Int) ^ (16 :: Int)
randomIndex :: IO Int
randomIndex = getStdRandom $ randomR (0, length target - 1)
randomChar :: IO Char
randomChar = getStdRandom $ randomR (' ', '~')
randomGene :: IO String
randomGene = replicateM (length target) randomChar
instance Gene String where
fitness gene = sum correctScore / fromIntegral (length target)
where correctScore = zipWith (\t g -> if t == g then 1 else 0) target gene
mutate gene = do
i <- randomIndex
c <- randomChar
return $ take i gene ++ [c] ++ drop (i + 1) gene
species _ = 8
main :: IO ()
main = do
pool <- replicateM (species [""]) randomGene
pool' <- evolve generations pool
putStrLn $ best pool'
| null | https://raw.githubusercontent.com/mcandre/genetics/02426bd4087e8913ae24d813d2260d7d7079a8a0/src/HelloGenetics.hs | haskell | # LANGUAGE TypeSynonymInstances # | # LANGUAGE FlexibleInstances #
# OPTIONS_GHC -fno - warn - orphans #
module Main where
import System.Random as Rand
import Genetics
import Control.Monad (replicateM)
target :: String
target = "Hello World!"
generations :: Int
generations = (2 :: Int) ^ (16 :: Int)
randomIndex :: IO Int
randomIndex = getStdRandom $ randomR (0, length target - 1)
randomChar :: IO Char
randomChar = getStdRandom $ randomR (' ', '~')
randomGene :: IO String
randomGene = replicateM (length target) randomChar
instance Gene String where
fitness gene = sum correctScore / fromIntegral (length target)
where correctScore = zipWith (\t g -> if t == g then 1 else 0) target gene
mutate gene = do
i <- randomIndex
c <- randomChar
return $ take i gene ++ [c] ++ drop (i + 1) gene
species _ = 8
main :: IO ()
main = do
pool <- replicateM (species [""]) randomGene
pool' <- evolve generations pool
putStrLn $ best pool'
|
05e38f810c4e7d45cee9b1fe6b5917a2adccfecb30416c3d9aee89908bc11633 | ekmett/category-extras | State.hs | -----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Indexed.State
Copyright : ( C ) 2008
-- License : BSD-style (see the file LICENSE)
--
Maintainer : < >
-- Stability : experimental
Portability : portable ( although the MTL instances are n't ! )
--
----------------------------------------------------------------------------
module Control.Monad.Indexed.State
( IxMonadState(..)
, imodify
, igets
, IxStateT(..)
, IxState(..)
) where
import Control.Applicative
import Control.Category.Hask
import Control . Category . Cartesian
import Control.Functor
import Control.Monad.Indexed
import Control.Monad.Indexed.Trans
import Control.Monad.Indexed.Fix
import Control.Monad.State
import Control.Monad.Writer
import Control.Monad.Reader
import Control.Monad.Cont
import Control.Monad.Error.Class
class IxMonad m => IxMonadState m where
iget :: m i i i
iput :: j -> m i j ()
imodify :: IxMonadState m => (i -> j) -> m i j ()
imodify f = iget >>>= iput . f
igets :: IxMonadState m => (i -> a) -> m i i a
igets f = iget >>>= ireturn . f
-- Indexed State Monad
newtype IxState i j a = IxState { runIxState :: i -> (a, j) }
instance Functor (IxState i j) where
fmap = imap
instance IxFunctor IxState where
imap f m = IxState (first f . runIxState m)
instance IxPointed IxState where
ireturn = IxState . (,)
instance IxApplicative IxState where
iap = iapIxMonad
instance IxMonad IxState where
ibind f m = IxState $ \s1 -> let (a,s2) = runIxState m s1 in runIxState (f a) s2
instance IxMonadState IxState where
iget = IxState (\x -> (x,x))
iput x = IxState (\_ -> ((),x))
instance PFunctor (IxState i) Hask Hask where
first = first'
instance QFunctor (IxState i) Hask Hask where
second = second'
instance Bifunctor (IxState i) Hask Hask Hask where
bimap f g m = IxState $ bimap g f . runIxState m
instance Monad (IxState i i) where
return = ireturn
m >>= k = ibind k m
instance Applicative (IxState i i) where
pure = ireturn
(<*>) = iap
instance MonadState i (IxState i i) where
get = iget
put = iput
instance MonadFix (IxState i i) where
mfix = imfix
instance IxMonadFix IxState where
imfix f = IxState $ \s -> let (a, s') = runIxState (f a) s in (a, s')
Indexed State
newtype IxStateT m i j a = IxStateT { runIxStateT :: i -> m (a, j) }
instance Monad m => Functor (IxStateT m i j) where
fmap = imap
instance Monad m => IxFunctor (IxStateT m) where
imap f m = IxStateT $ \s -> runIxStateT m s >>= \(x,s') -> return (f x, s')
instance Monad m => IxPointed (IxStateT m) where
ireturn a = IxStateT $ \s -> return (a, s)
instance Monad m => IxApplicative (IxStateT m) where
iap = iapIxMonad
instance Monad m => IxMonad (IxStateT m) where
ibind k m = IxStateT $ \s -> runIxStateT m s >>= \ ~(a, s') -> runIxStateT (k a) s'
instance Monad m => PFunctor (IxStateT m i) Hask Hask where
first = first'
instance Monad m => QFunctor (IxStateT m i) Hask Hask where
second = second'
instance Monad m => Bifunctor (IxStateT m i) Hask Hask Hask where
bimap f g m = IxStateT $ liftM (bimap g f) . runIxStateT m
instance Monad m => IxMonadState (IxStateT m) where
iget = IxStateT $ \s -> return (s, s)
iput s = IxStateT $ \_ -> return ((), s)
instance MonadPlus m => IxMonadZero (IxStateT m) where
imzero = IxStateT $ const mzero
instance MonadPlus m => IxMonadPlus (IxStateT m) where
m `implus` n = IxStateT $ \s -> runIxStateT m s `mplus` runIxStateT n s
instance MonadFix m => IxMonadFix (IxStateT m) where
imfix f = IxStateT $ \s -> mfix $ \ ~(a, _) -> runIxStateT (f a) s
instance MonadFix m => MonadFix (IxStateT m i i) where
mfix = imfix
instance Monad m => Monad (IxStateT m i i) where
return = ireturn
m >>= k = ibind k m
instance Monad m => Applicative (IxStateT m i i) where
pure = ireturn
(<*>) = iap
instance Monad m => MonadState i (IxStateT m i i) where
get = iget
put = iput
instance IxMonadTrans IxStateT where
ilift m = IxStateT $ \s -> m >>= \a -> return (a, s)
instance MonadIO m => MonadIO (IxStateT m i i) where
liftIO = ilift . liftIO
instance MonadReader r m => MonadReader r (IxStateT m i i) where
ask = ilift ask
local f m = IxStateT (local f . runIxStateT m)
instance MonadCont m => MonadCont (IxStateT m i i) where
callCC f = IxStateT $ \s -> callCC $ \k -> runIxStateT (f (\a -> IxStateT $ \s' -> k (a,s'))) s
instance MonadError e m => MonadError e (IxStateT m i i) where
throwError = ilift . throwError
m `catchError` h = IxStateT $ \s -> runIxStateT m s `catchError` \e -> runIxStateT (h e) s
instance MonadWriter w m => MonadWriter w (IxStateT m i i) where
tell = ilift . tell
listen m = IxStateT $ \s -> do
~((a,s'),w) <- listen (runIxStateT m s)
return ((a,w),s')
pass m = IxStateT $ \s -> pass $ do
~((a,f),s') <- runIxStateT m s
return ((a,s'),f)
| null | https://raw.githubusercontent.com/ekmett/category-extras/f0f3ca38a3dfcb49d39aa2bb5b31b719f2a5b1ae/Control/Monad/Indexed/State.hs | haskell | ---------------------------------------------------------------------------
|
Module : Control.Monad.Indexed.State
License : BSD-style (see the file LICENSE)
Stability : experimental
--------------------------------------------------------------------------
Indexed State Monad | Copyright : ( C ) 2008
Maintainer : < >
Portability : portable ( although the MTL instances are n't ! )
module Control.Monad.Indexed.State
( IxMonadState(..)
, imodify
, igets
, IxStateT(..)
, IxState(..)
) where
import Control.Applicative
import Control.Category.Hask
import Control . Category . Cartesian
import Control.Functor
import Control.Monad.Indexed
import Control.Monad.Indexed.Trans
import Control.Monad.Indexed.Fix
import Control.Monad.State
import Control.Monad.Writer
import Control.Monad.Reader
import Control.Monad.Cont
import Control.Monad.Error.Class
class IxMonad m => IxMonadState m where
iget :: m i i i
iput :: j -> m i j ()
imodify :: IxMonadState m => (i -> j) -> m i j ()
imodify f = iget >>>= iput . f
igets :: IxMonadState m => (i -> a) -> m i i a
igets f = iget >>>= ireturn . f
newtype IxState i j a = IxState { runIxState :: i -> (a, j) }
instance Functor (IxState i j) where
fmap = imap
instance IxFunctor IxState where
imap f m = IxState (first f . runIxState m)
instance IxPointed IxState where
ireturn = IxState . (,)
instance IxApplicative IxState where
iap = iapIxMonad
instance IxMonad IxState where
ibind f m = IxState $ \s1 -> let (a,s2) = runIxState m s1 in runIxState (f a) s2
instance IxMonadState IxState where
iget = IxState (\x -> (x,x))
iput x = IxState (\_ -> ((),x))
instance PFunctor (IxState i) Hask Hask where
first = first'
instance QFunctor (IxState i) Hask Hask where
second = second'
instance Bifunctor (IxState i) Hask Hask Hask where
bimap f g m = IxState $ bimap g f . runIxState m
instance Monad (IxState i i) where
return = ireturn
m >>= k = ibind k m
instance Applicative (IxState i i) where
pure = ireturn
(<*>) = iap
instance MonadState i (IxState i i) where
get = iget
put = iput
instance MonadFix (IxState i i) where
mfix = imfix
instance IxMonadFix IxState where
imfix f = IxState $ \s -> let (a, s') = runIxState (f a) s in (a, s')
Indexed State
newtype IxStateT m i j a = IxStateT { runIxStateT :: i -> m (a, j) }
instance Monad m => Functor (IxStateT m i j) where
fmap = imap
instance Monad m => IxFunctor (IxStateT m) where
imap f m = IxStateT $ \s -> runIxStateT m s >>= \(x,s') -> return (f x, s')
instance Monad m => IxPointed (IxStateT m) where
ireturn a = IxStateT $ \s -> return (a, s)
instance Monad m => IxApplicative (IxStateT m) where
iap = iapIxMonad
instance Monad m => IxMonad (IxStateT m) where
ibind k m = IxStateT $ \s -> runIxStateT m s >>= \ ~(a, s') -> runIxStateT (k a) s'
instance Monad m => PFunctor (IxStateT m i) Hask Hask where
first = first'
instance Monad m => QFunctor (IxStateT m i) Hask Hask where
second = second'
instance Monad m => Bifunctor (IxStateT m i) Hask Hask Hask where
bimap f g m = IxStateT $ liftM (bimap g f) . runIxStateT m
instance Monad m => IxMonadState (IxStateT m) where
iget = IxStateT $ \s -> return (s, s)
iput s = IxStateT $ \_ -> return ((), s)
instance MonadPlus m => IxMonadZero (IxStateT m) where
imzero = IxStateT $ const mzero
instance MonadPlus m => IxMonadPlus (IxStateT m) where
m `implus` n = IxStateT $ \s -> runIxStateT m s `mplus` runIxStateT n s
instance MonadFix m => IxMonadFix (IxStateT m) where
imfix f = IxStateT $ \s -> mfix $ \ ~(a, _) -> runIxStateT (f a) s
instance MonadFix m => MonadFix (IxStateT m i i) where
mfix = imfix
instance Monad m => Monad (IxStateT m i i) where
return = ireturn
m >>= k = ibind k m
instance Monad m => Applicative (IxStateT m i i) where
pure = ireturn
(<*>) = iap
instance Monad m => MonadState i (IxStateT m i i) where
get = iget
put = iput
instance IxMonadTrans IxStateT where
ilift m = IxStateT $ \s -> m >>= \a -> return (a, s)
instance MonadIO m => MonadIO (IxStateT m i i) where
liftIO = ilift . liftIO
instance MonadReader r m => MonadReader r (IxStateT m i i) where
ask = ilift ask
local f m = IxStateT (local f . runIxStateT m)
instance MonadCont m => MonadCont (IxStateT m i i) where
callCC f = IxStateT $ \s -> callCC $ \k -> runIxStateT (f (\a -> IxStateT $ \s' -> k (a,s'))) s
instance MonadError e m => MonadError e (IxStateT m i i) where
throwError = ilift . throwError
m `catchError` h = IxStateT $ \s -> runIxStateT m s `catchError` \e -> runIxStateT (h e) s
instance MonadWriter w m => MonadWriter w (IxStateT m i i) where
tell = ilift . tell
listen m = IxStateT $ \s -> do
~((a,s'),w) <- listen (runIxStateT m s)
return ((a,w),s')
pass m = IxStateT $ \s -> pass $ do
~((a,f),s') <- runIxStateT m s
return ((a,s'),f)
|
c9796fa0f23ce4503cf7105f6de9c7af242fa8d78b2958d5cf4f76ff30ff9dad | typelead/eta | tc033.hs | module ShouldSucceed where
data Twine = Twine2 Twist
data Twist = Twist2 Twine
type F = Twine
| null | https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/compile/tc033.hs | haskell | module ShouldSucceed where
data Twine = Twine2 Twist
data Twist = Twist2 Twine
type F = Twine
|
|
9fe60dc2429eb050f9cdf9f4595db8334011b0ed3e1ca122019ef2ffca58fc14 | shirok/Gauche | flonum.scm | ;;;
scheme.flonum - Flonums ( )
;;;
Copyright ( c ) 2019 - 2022 < >
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; 3. Neither the name of the authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this
;;; software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE 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 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
Originally
(define-module scheme.flonum
(use math.const :prefix const:)
(export fl-e fl-1/e fl-e-2 fl-e-pi/4 fl-log2-e fl-log10-e
fl-log-2 fl-1/log-2 fl-log-3 fl-log-pi fl-log-10 fl-1/log-10
fl-pi fl-1/pi fl-2pi fl-pi/2 fl-pi/4 fl-pi-squared
fl-degree fl-2/pi fl-2/sqrt-pi
fl-sqrt-2 fl-sqrt-3 fl-sqrt-5 fl-sqrt-10 fl-1/sqrt-2
fl-cbrt-2 fl-cbrt-3 fl-4thrt-2 fl-phi fl-log-phi
fl-1/log-phi fl-euler fl-e-euler fl-sin-1 fl-cos-1
fl-gamma-1/2 fl-gamma-1/3 fl-gamma-2/3
fl-greatest fl-least fl-epsilon fl-fast-fl+*
fl-integer-exponent-zero fl-integer-exponent-nan
flonum fladjacent flcopysign make-flonum
flinteger-fraction flexponent flinteger-exponent
flnormalized-fraction-exponent flsign-bit
flonum? fl=? fl<? fl>? fl<=? fl>=?
flunordered? flinteger? flzero? flpositive? flnegative?
flodd? fleven? flfinite? flinfinite? flnan?
flnormalized? fldenormalized?
flmax flmin fl+ fl* fl+* fl- fl/ flabs flabsdiff
flposdiff flsgn flnumerator fldenominator
flfloor flceiling flround fltruncate
flexp flexp2 flexp-1 flsquare flsqrt flcbrt flhypot flexpt fllog
fllog1+ fllog2 fllog10 make-fllog-base
flsin flcos fltan flasin flacos flatan
flsinh flcosh fltanh flasinh flacosh flatanh
flquotient flremainder flremquo
flgamma flloggamma flfirst-bessel flsecond-bessel
flerf flerfc
))
(select-module scheme.flonum)
(inline-stub
(.include <math.h>))
;;;
;;; Constants
;;;
(define-constant fl-e const:e)
(define-constant fl-1/e (/ const:e))
e*e yields 1ulp error
(define-constant fl-e-pi/4 (real-exp (/ const:pi 4)))
(define-constant fl-log2-e (/ (real-ln 2)))
( / ( real - ln 10 ) ) yiels 1ulp error
(define-constant fl-log-2 (real-ln 2))
(define-constant fl-1/log-2 (/ (real-ln 2)))
(define-constant fl-log-3 (real-ln 3))
(define-constant fl-log-pi (real-ln const:pi))
(define-constant fl-log-10 (real-ln 10))
( / ( % log 10 ) ) yiels 1ulp error
(define-constant fl-pi const:pi)
(define-constant fl-1/pi (/ const:pi))
(define-constant fl-2pi (* const:pi 2))
(define-constant fl-pi/2 const:pi/2)
(define-constant fl-pi/4 const:pi/4)
(define-constant fl-pi-squared (* const:pi const:pi))
(define-constant fl-degree const:pi/180)
(define-constant fl-2/pi (/ const:pi/2))
(define-constant fl-2/sqrt-pi (/ 2 (real-sqrt const:pi)))
(define-constant fl-sqrt-2 (real-sqrt 2))
(define-constant fl-sqrt-3 (real-sqrt 3))
(define-constant fl-sqrt-5 (real-sqrt 5))
(define-constant fl-sqrt-10 (real-sqrt 10))
(define-constant fl-1/sqrt-2 (/ (real-sqrt 2)))
(define-constant fl-cbrt-2 (real-expt 2 1/3))
(define-constant fl-cbrt-3 (real-expt 3 1/3))
(define-constant fl-4thrt-2 (real-expt 2 1/4))
(define-constant fl-phi (/ (+ 1 (real-sqrt 5)) 2))
(define-constant fl-log-phi (real-ln fl-phi))
( / fl - log - phi ) yields 1ulp error
(define-constant fl-euler 0.5772156649015329)
(define-constant fl-e-euler (exp fl-euler))
(define-constant fl-sin-1 (real-sin 1))
(define-constant fl-cos-1 (real-cos 1))
( gamma 1/2 ) yields 1ulp error on MinGW
( gamma 1/3 ) yields 1ulp error
(define-constant fl-gamma-2/3 (gamma 2/3))
(define-constant fl-greatest (encode-float `#(,(- (expt 2 53) 1) 971 1)))
(define-constant fl-least (encode-float '#(1 -1074 1)))
(define-constant fl-epsilon (flonum-epsilon))
(define-constant fl-fast-fl+* #t)
these two needs to be ' define - inline ' , for ilogb ca n't be used
;; before loading this module.
(define-inline fl-integer-exponent-zero (ilogb 0))
(define-inline fl-integer-exponent-nan (ilogb +nan.0))
;;;
;;; constructors
;;;
;; See post-finalization note in srfi about returning +nan.0
(define-inline (flonum n) (if (real? n) (inexact n) +nan.0))
(define-cproc fladjacent (x::<double> y::<double>)
::<double> :constant :fast-flonum
(return (nextafter x y)))
(define-cproc flcopysign (x::<double> y::<double>)
::<double> :constant :fast-flonum
(return (copysign x y)))
(define-inline (make-flonum x n) (ldexp x n))
;;;
;;; accessors
;;;
(define-cproc logb (x::<double>) ::<double> :constant :fast-flonum logb)
(define-cproc ilogb (x::<double>) ::<int> :constant :fast-flonum ilogb)
(define-inline (flinteger-fraction x)
(receive (r q) (modf x) (values q r)))
(define-inline (flexponent x) (logb x))
(define-inline (flinteger-exponent x) (ilogb x))
(define-inline (flnormalized-fraction-exponent x) (frexp x))
(define-cproc flsign-bit (x::<double>) ::<int> :constant :fast-flonum
(return (?: (signbit x) 1 0)))
;;;
;;; predicates
;;;
;; flonum? - built-in
;; we don't check types of arguments in these; the point of flonum-specific
;; ops is speed, so it's less useful if these ones are slower than the
;; generic version.
(define-inline (fl=? . args) (apply = args))
(define-inline (fl<? . args) (apply < args))
(define-inline (fl<=? . args) (apply <= args))
(define-inline (fl>? . args) (apply > args))
(define-inline (fl>=? . args) (apply >= args))
(define-inline (flunordered? x y) (or (nan? x) (nan? y)))
(define-inline (flinteger? x) (and (flonum? x) (integer? x)))
(define-inline (flzero? x) (and (flonum? x) (zero? x)))
(define-inline (flpositive? x) (and (flonum? x) (positive? x)))
(define-inline (flnegative? x) (and (flonum? x) (negative? x)))
(define-inline (flodd? x) (and (flonum? x) (odd? x)))
(define-inline (fleven? x) (and (flonum? x) (even? x)))
(define-inline (flfinite? x) (finite? x))
(define-inline (flinfinite? x) (infinite? x))
(define-inline (flnan? x) (nan? x))
(inline-stub
On MinGW 32bit , fpclassify is broken .
;; cf.
(define-cfn flonum_classify (d::double) ::int :static
(.if (and (defined __MINGW32__) (not (defined __MIGW64__)))
(return (__builtin_fpclassify FP_INFINITE FP_NAN FP_NORMAL FP_SUBNORMAL
FP_ZERO d))
(return (fpclassify d)))))
(define-cproc flnormalized? (x::<double>) ::<boolean> :constant :fast-flonum
(return (== (flonum_classify x) FP_NORMAL)))
(define-cproc fldenormalized? (x::<double>) ::<boolean> :constant :fast-flonum
(return (== (flonum_classify x) FP_SUBNORMAL)))
;;;
;;; Arithmetic
;;;
;; Again, we don't check the argument types for the sake of the speed.
(define-inline (flmax . args) (if (null? args) -inf.0 (apply max args)))
(define-inline (flmin . args) (if (null? args) +inf.0 (apply min args)))
(define-inline (fl+ . args) (apply +. args))
(define-inline (fl* . args) (apply *. args))
(define-cproc fl+* (x::<double> y::<double> z::<double>)
::<double> :fast-flonum :constant
(return (fma x y z)))
(define-inline (fl- x . args) (apply -. x args))
(define-inline (fl/ x . args) (apply /. x args))
(define-cproc flabs (x::<double>) ::<double> :fast-flonum :constant fabs)
(define-cproc flabsdiff (x::<double> y::<double>)
::<double> :fast-flonum :constant
(return (fabs (- x y))))
(define-cproc flposdiff (x::<double> y::<double>)
::<double> :fast-flonum :constant
(return (?: (> x y) (- x y) 0.0)))
(define-cproc flsgn (x::<double>) ::<double> :fast-flonum :constant
(return (?: (signbit x) -1.0 1.0)))
(define (flnumerator x)
(if (or (infinite? x) (nan? x) (zero? x))
x ; -0.0 is handled here
(inexact (numerator (exact x)))))
(define (fldenominator x)
(cond [(or (infinite? x) (zero? x)) 1.0]
[(nan? x) x]
[else (inexact (denominator (exact x)))]))
(define-cproc flfloor (x::<double>) ::<double> :fast-flonum :constant floor)
(define-cproc flceiling (x::<double>) ::<double> :fast-flonum :constant ceil)
(define (flround x) (assume (flonum? x)) (round x))
(define-cproc fltruncate (x::<double>) ::<double> :fast-flonum :constant trunc)
(define-inline (flexp x) (real-exp x))
(define-inline (flexp2 x) (real-expt 2.0 x))
(define-cproc flexp-1 (x::<double>) ::<double> :fast-flonum :constant expm1)
(define-inline (flsquare x) (*. x x))
(define-inline (flsqrt x) (real-sqrt x))
(define (flcbrt x)
(assume (real? x))
( % expt x 1/3 ) may give us a complex root , so we roll our own .
(if (or (nan? x) (infinite? x))
x
(let loop ([r (flcopysign (magnitude (real-expt x 1/3)) x)])
(if (zero? r)
r
(let1 r+ (- r (/ (- (* r r r) x)
(* 3 r r)))
(if (= r r+)
r
(loop r+)))))))
(define-cproc flhypot (x::<double> y::<double>)
::<double> :fast-flonum :constant hypot)
(define-inline (flexpt x y) (real-expt x y))
(define-inline (fllog x) (real-ln x))
(define-cproc fllog1+ (x::<double>) ::<double> :fast-flonum :constant log1p)
(define-cproc fllog2 (x::<double>) ::<double> :fast-flonum :constant log2)
(define-cproc fllog10 (x::<double>) ::<double> :fast-flonum :constant log10)
(define (make-fllog-base base) (^x (/. (real-ln x) (real-ln base))))
(define-inline (flsin x) (real-sin x))
(define-inline (flcos x) (real-cos x))
(define-inline (fltan x) (real-tan x))
(define-inline (flasin x) (real-asin x))
(define-inline (flacos x) (real-acos x))
(define-inline (flatan y . x) (apply real-atan y x))
(define-inline (flsinh x) (real-sinh x))
(define-inline (flcosh x) (real-cosh x))
(define-inline (fltanh x) (real-tanh x))
(define-cproc flasinh (x::<double>) ::<double> :fast-flonum :constant asinh)
(define-cproc flacosh (x::<double>) ::<double> :fast-flonum :constant acosh)
(define-cproc flatanh (x::<double>) ::<double> :fast-flonum :constant atanh)
(define (flquotient x y) (fltruncate (/. x y)))
(define (flremainder x y) (-. x (*. y (flquotient x y))))
(define-cproc flremquo (x::<double> y::<double>) ::(<double> <int>)
(let* ([quo::int]
[rem::double (remquo x y (& quo))])
(result rem quo)))
(define-inline (flgamma x) (gamma x))
(define (flloggamma x)
(values (lgamma x)
(cond [(<= 0 x) 1.0]
sign of ) undecidable
[(nan? x) +nan.0]
[(odd? (floor x)) -1.0]
[else 1.0])))
(define-cproc flfirst-bessel (n::<int> x::<double>)
::<double> :fast-flonum :constant
jn)
(define-cproc flsecond-bessel (n::<int> x::<double>)
::<double> :fast-flonum :constant
As of 2019 , NB : MinGW 's yn returns NaN if x = 0 , as opposed to the
;; POSIX definition that says -HUGE_VAL.
(.if (defined GAUCHE_WINDOWS)
(if (== x 0.0)
(return SCM_DBL_NEGATIVE_INFINITY)
(return (yn n x)))
(return (yn n x))))
(define-cproc flerf (x::<double>)
::<double> :fast-flonum :constant
erf)
(define-cproc flerfc (x::<double>)
::<double> :fast-flonum :constant
erfc)
| null | https://raw.githubusercontent.com/shirok/Gauche/88b013677a57614a05b2c1d0167dfb7059d457d3/ext/scheme/flonum.scm | scheme |
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the authors nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Constants
before loading this module.
constructors
See post-finalization note in srfi about returning +nan.0
accessors
predicates
flonum? - built-in
we don't check types of arguments in these; the point of flonum-specific
ops is speed, so it's less useful if these ones are slower than the
generic version.
cf.
Arithmetic
Again, we don't check the argument types for the sake of the speed.
-0.0 is handled here
POSIX definition that says -HUGE_VAL. | scheme.flonum - Flonums ( )
Copyright ( c ) 2019 - 2022 < >
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
Originally
(define-module scheme.flonum
(use math.const :prefix const:)
(export fl-e fl-1/e fl-e-2 fl-e-pi/4 fl-log2-e fl-log10-e
fl-log-2 fl-1/log-2 fl-log-3 fl-log-pi fl-log-10 fl-1/log-10
fl-pi fl-1/pi fl-2pi fl-pi/2 fl-pi/4 fl-pi-squared
fl-degree fl-2/pi fl-2/sqrt-pi
fl-sqrt-2 fl-sqrt-3 fl-sqrt-5 fl-sqrt-10 fl-1/sqrt-2
fl-cbrt-2 fl-cbrt-3 fl-4thrt-2 fl-phi fl-log-phi
fl-1/log-phi fl-euler fl-e-euler fl-sin-1 fl-cos-1
fl-gamma-1/2 fl-gamma-1/3 fl-gamma-2/3
fl-greatest fl-least fl-epsilon fl-fast-fl+*
fl-integer-exponent-zero fl-integer-exponent-nan
flonum fladjacent flcopysign make-flonum
flinteger-fraction flexponent flinteger-exponent
flnormalized-fraction-exponent flsign-bit
flonum? fl=? fl<? fl>? fl<=? fl>=?
flunordered? flinteger? flzero? flpositive? flnegative?
flodd? fleven? flfinite? flinfinite? flnan?
flnormalized? fldenormalized?
flmax flmin fl+ fl* fl+* fl- fl/ flabs flabsdiff
flposdiff flsgn flnumerator fldenominator
flfloor flceiling flround fltruncate
flexp flexp2 flexp-1 flsquare flsqrt flcbrt flhypot flexpt fllog
fllog1+ fllog2 fllog10 make-fllog-base
flsin flcos fltan flasin flacos flatan
flsinh flcosh fltanh flasinh flacosh flatanh
flquotient flremainder flremquo
flgamma flloggamma flfirst-bessel flsecond-bessel
flerf flerfc
))
(select-module scheme.flonum)
(inline-stub
(.include <math.h>))
(define-constant fl-e const:e)
(define-constant fl-1/e (/ const:e))
e*e yields 1ulp error
(define-constant fl-e-pi/4 (real-exp (/ const:pi 4)))
(define-constant fl-log2-e (/ (real-ln 2)))
( / ( real - ln 10 ) ) yiels 1ulp error
(define-constant fl-log-2 (real-ln 2))
(define-constant fl-1/log-2 (/ (real-ln 2)))
(define-constant fl-log-3 (real-ln 3))
(define-constant fl-log-pi (real-ln const:pi))
(define-constant fl-log-10 (real-ln 10))
( / ( % log 10 ) ) yiels 1ulp error
(define-constant fl-pi const:pi)
(define-constant fl-1/pi (/ const:pi))
(define-constant fl-2pi (* const:pi 2))
(define-constant fl-pi/2 const:pi/2)
(define-constant fl-pi/4 const:pi/4)
(define-constant fl-pi-squared (* const:pi const:pi))
(define-constant fl-degree const:pi/180)
(define-constant fl-2/pi (/ const:pi/2))
(define-constant fl-2/sqrt-pi (/ 2 (real-sqrt const:pi)))
(define-constant fl-sqrt-2 (real-sqrt 2))
(define-constant fl-sqrt-3 (real-sqrt 3))
(define-constant fl-sqrt-5 (real-sqrt 5))
(define-constant fl-sqrt-10 (real-sqrt 10))
(define-constant fl-1/sqrt-2 (/ (real-sqrt 2)))
(define-constant fl-cbrt-2 (real-expt 2 1/3))
(define-constant fl-cbrt-3 (real-expt 3 1/3))
(define-constant fl-4thrt-2 (real-expt 2 1/4))
(define-constant fl-phi (/ (+ 1 (real-sqrt 5)) 2))
(define-constant fl-log-phi (real-ln fl-phi))
( / fl - log - phi ) yields 1ulp error
(define-constant fl-euler 0.5772156649015329)
(define-constant fl-e-euler (exp fl-euler))
(define-constant fl-sin-1 (real-sin 1))
(define-constant fl-cos-1 (real-cos 1))
( gamma 1/2 ) yields 1ulp error on MinGW
( gamma 1/3 ) yields 1ulp error
(define-constant fl-gamma-2/3 (gamma 2/3))
(define-constant fl-greatest (encode-float `#(,(- (expt 2 53) 1) 971 1)))
(define-constant fl-least (encode-float '#(1 -1074 1)))
(define-constant fl-epsilon (flonum-epsilon))
(define-constant fl-fast-fl+* #t)
these two needs to be ' define - inline ' , for ilogb ca n't be used
(define-inline fl-integer-exponent-zero (ilogb 0))
(define-inline fl-integer-exponent-nan (ilogb +nan.0))
(define-inline (flonum n) (if (real? n) (inexact n) +nan.0))
(define-cproc fladjacent (x::<double> y::<double>)
::<double> :constant :fast-flonum
(return (nextafter x y)))
(define-cproc flcopysign (x::<double> y::<double>)
::<double> :constant :fast-flonum
(return (copysign x y)))
(define-inline (make-flonum x n) (ldexp x n))
(define-cproc logb (x::<double>) ::<double> :constant :fast-flonum logb)
(define-cproc ilogb (x::<double>) ::<int> :constant :fast-flonum ilogb)
(define-inline (flinteger-fraction x)
(receive (r q) (modf x) (values q r)))
(define-inline (flexponent x) (logb x))
(define-inline (flinteger-exponent x) (ilogb x))
(define-inline (flnormalized-fraction-exponent x) (frexp x))
(define-cproc flsign-bit (x::<double>) ::<int> :constant :fast-flonum
(return (?: (signbit x) 1 0)))
(define-inline (fl=? . args) (apply = args))
(define-inline (fl<? . args) (apply < args))
(define-inline (fl<=? . args) (apply <= args))
(define-inline (fl>? . args) (apply > args))
(define-inline (fl>=? . args) (apply >= args))
(define-inline (flunordered? x y) (or (nan? x) (nan? y)))
(define-inline (flinteger? x) (and (flonum? x) (integer? x)))
(define-inline (flzero? x) (and (flonum? x) (zero? x)))
(define-inline (flpositive? x) (and (flonum? x) (positive? x)))
(define-inline (flnegative? x) (and (flonum? x) (negative? x)))
(define-inline (flodd? x) (and (flonum? x) (odd? x)))
(define-inline (fleven? x) (and (flonum? x) (even? x)))
(define-inline (flfinite? x) (finite? x))
(define-inline (flinfinite? x) (infinite? x))
(define-inline (flnan? x) (nan? x))
(inline-stub
On MinGW 32bit , fpclassify is broken .
(define-cfn flonum_classify (d::double) ::int :static
(.if (and (defined __MINGW32__) (not (defined __MIGW64__)))
(return (__builtin_fpclassify FP_INFINITE FP_NAN FP_NORMAL FP_SUBNORMAL
FP_ZERO d))
(return (fpclassify d)))))
(define-cproc flnormalized? (x::<double>) ::<boolean> :constant :fast-flonum
(return (== (flonum_classify x) FP_NORMAL)))
(define-cproc fldenormalized? (x::<double>) ::<boolean> :constant :fast-flonum
(return (== (flonum_classify x) FP_SUBNORMAL)))
(define-inline (flmax . args) (if (null? args) -inf.0 (apply max args)))
(define-inline (flmin . args) (if (null? args) +inf.0 (apply min args)))
(define-inline (fl+ . args) (apply +. args))
(define-inline (fl* . args) (apply *. args))
(define-cproc fl+* (x::<double> y::<double> z::<double>)
::<double> :fast-flonum :constant
(return (fma x y z)))
(define-inline (fl- x . args) (apply -. x args))
(define-inline (fl/ x . args) (apply /. x args))
(define-cproc flabs (x::<double>) ::<double> :fast-flonum :constant fabs)
(define-cproc flabsdiff (x::<double> y::<double>)
::<double> :fast-flonum :constant
(return (fabs (- x y))))
(define-cproc flposdiff (x::<double> y::<double>)
::<double> :fast-flonum :constant
(return (?: (> x y) (- x y) 0.0)))
(define-cproc flsgn (x::<double>) ::<double> :fast-flonum :constant
(return (?: (signbit x) -1.0 1.0)))
(define (flnumerator x)
(if (or (infinite? x) (nan? x) (zero? x))
(inexact (numerator (exact x)))))
(define (fldenominator x)
(cond [(or (infinite? x) (zero? x)) 1.0]
[(nan? x) x]
[else (inexact (denominator (exact x)))]))
(define-cproc flfloor (x::<double>) ::<double> :fast-flonum :constant floor)
(define-cproc flceiling (x::<double>) ::<double> :fast-flonum :constant ceil)
(define (flround x) (assume (flonum? x)) (round x))
(define-cproc fltruncate (x::<double>) ::<double> :fast-flonum :constant trunc)
(define-inline (flexp x) (real-exp x))
(define-inline (flexp2 x) (real-expt 2.0 x))
(define-cproc flexp-1 (x::<double>) ::<double> :fast-flonum :constant expm1)
(define-inline (flsquare x) (*. x x))
(define-inline (flsqrt x) (real-sqrt x))
(define (flcbrt x)
(assume (real? x))
( % expt x 1/3 ) may give us a complex root , so we roll our own .
(if (or (nan? x) (infinite? x))
x
(let loop ([r (flcopysign (magnitude (real-expt x 1/3)) x)])
(if (zero? r)
r
(let1 r+ (- r (/ (- (* r r r) x)
(* 3 r r)))
(if (= r r+)
r
(loop r+)))))))
(define-cproc flhypot (x::<double> y::<double>)
::<double> :fast-flonum :constant hypot)
(define-inline (flexpt x y) (real-expt x y))
(define-inline (fllog x) (real-ln x))
(define-cproc fllog1+ (x::<double>) ::<double> :fast-flonum :constant log1p)
(define-cproc fllog2 (x::<double>) ::<double> :fast-flonum :constant log2)
(define-cproc fllog10 (x::<double>) ::<double> :fast-flonum :constant log10)
(define (make-fllog-base base) (^x (/. (real-ln x) (real-ln base))))
(define-inline (flsin x) (real-sin x))
(define-inline (flcos x) (real-cos x))
(define-inline (fltan x) (real-tan x))
(define-inline (flasin x) (real-asin x))
(define-inline (flacos x) (real-acos x))
(define-inline (flatan y . x) (apply real-atan y x))
(define-inline (flsinh x) (real-sinh x))
(define-inline (flcosh x) (real-cosh x))
(define-inline (fltanh x) (real-tanh x))
(define-cproc flasinh (x::<double>) ::<double> :fast-flonum :constant asinh)
(define-cproc flacosh (x::<double>) ::<double> :fast-flonum :constant acosh)
(define-cproc flatanh (x::<double>) ::<double> :fast-flonum :constant atanh)
(define (flquotient x y) (fltruncate (/. x y)))
(define (flremainder x y) (-. x (*. y (flquotient x y))))
(define-cproc flremquo (x::<double> y::<double>) ::(<double> <int>)
(let* ([quo::int]
[rem::double (remquo x y (& quo))])
(result rem quo)))
(define-inline (flgamma x) (gamma x))
(define (flloggamma x)
(values (lgamma x)
(cond [(<= 0 x) 1.0]
sign of ) undecidable
[(nan? x) +nan.0]
[(odd? (floor x)) -1.0]
[else 1.0])))
(define-cproc flfirst-bessel (n::<int> x::<double>)
::<double> :fast-flonum :constant
jn)
(define-cproc flsecond-bessel (n::<int> x::<double>)
::<double> :fast-flonum :constant
As of 2019 , NB : MinGW 's yn returns NaN if x = 0 , as opposed to the
(.if (defined GAUCHE_WINDOWS)
(if (== x 0.0)
(return SCM_DBL_NEGATIVE_INFINITY)
(return (yn n x)))
(return (yn n x))))
(define-cproc flerf (x::<double>)
::<double> :fast-flonum :constant
erf)
(define-cproc flerfc (x::<double>)
::<double> :fast-flonum :constant
erfc)
|
2476ff7d7b70f18b8c9fe5d11113067ebceed884a095f8d66e7fcd02f3795bf8 | xapi-project/xenopsd | bootloader.mli |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
(** Raised when we can't parse the output of the bootloader *)
exception Bad_sexpr of string
(** Raised when we can't parse the error from the bootloader *)
exception Bad_error of string
(** Raised when the bootloader returns an error *)
exception Error_from_bootloader of string
(** Raised when an unknown bootloader is used *)
exception Unknown_bootloader of string
val supported_bootloaders : string list
* which are known to the system
* representation of bootloader 's stdout , as used by xend
type t = {kernel_path: string; initrd_path: string option; kernel_args: string}
val extract :
Xenops_task.Xenops_task.task_handle
-> bootloader:string
-> disk:string
-> ?legacy_args:string
-> ?extra_args:string
-> ?pv_bootloader_args:string
-> vm:string
-> unit
-> t
(** Extract the default kernel from the disk *)
val delete : t -> unit
(** Delete the extracted kernel *)
| null | https://raw.githubusercontent.com/xapi-project/xenopsd/f4da21a4ead7c6a7082af5ec32f778faf368cf1c/lib/bootloader.mli | ocaml | * Raised when we can't parse the output of the bootloader
* Raised when we can't parse the error from the bootloader
* Raised when the bootloader returns an error
* Raised when an unknown bootloader is used
* Extract the default kernel from the disk
* Delete the extracted kernel |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
exception Bad_sexpr of string
exception Bad_error of string
exception Error_from_bootloader of string
exception Unknown_bootloader of string
val supported_bootloaders : string list
* which are known to the system
* representation of bootloader 's stdout , as used by xend
type t = {kernel_path: string; initrd_path: string option; kernel_args: string}
val extract :
Xenops_task.Xenops_task.task_handle
-> bootloader:string
-> disk:string
-> ?legacy_args:string
-> ?extra_args:string
-> ?pv_bootloader_args:string
-> vm:string
-> unit
-> t
val delete : t -> unit
|
52dd5f112f87b786f217759e0fe003b5ad3a3b2a7a422c09ba9a65ae8686259d | starburstdata/metabase-driver | unprepare.clj | ;;
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;; -2.0
;; Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns metabase.driver.implementation.unprepare"Unprepare implementation for Starburst driver."
(:require [buddy.core.codecs :as codecs]
[java-time :as t]
[metabase.driver.sql.util :as sql.u]
[metabase.driver.sql.util.unprepare :as unprepare])
(:import [java.sql Time]
java.sql.Time
[java.time OffsetDateTime ZonedDateTime]))
(def ^:dynamic *param-splice-style*
"How we should splice params into SQL (i.e. 'unprepare' the SQL). Either `:friendly` (the default) or `:paranoid`.
`:friendly` makes a best-effort attempt to escape strings and generate SQL that is nice to look at, but should not
be considered safe against all SQL injection -- use this for 'convert to SQL' functionality. `:paranoid` hex-encodes
strings so SQL injection is impossible; this isn't nice to look at, so use this for actually running a query."
:friendly)
(defmethod unprepare/unprepare-value [:starburst String]
[_ ^String s]
(case *param-splice-style*
:friendly (str \' (sql.u/escape-sql s :ansi) \')
:paranoid (format "from_utf8(from_hex('%s'))" (codecs/bytes->hex (.getBytes s "UTF-8")))))
(defmethod unprepare/unprepare-value [:starburst Time]
[driver t]
;; This is only needed for test purposes, because some of the sample data still uses legacy types
;; Convert time to Local time, then unprepare.
(unprepare/unprepare-value driver (t/local-time t)))
(defmethod unprepare/unprepare-value [:starburst OffsetDateTime]
[_ t]
(format "timestamp '%s %s %s'" (t/local-date t) (t/local-time t) (t/zone-offset t)))
(defmethod unprepare/unprepare-value [:starburst ZonedDateTime]
[_ t]
(format "timestamp '%s %s %s'" (t/local-date t) (t/local-time t) (t/zone-id t)))
| null | https://raw.githubusercontent.com/starburstdata/metabase-driver/7cfdf39bf3afd47405d6a98d746fa169ec3101bc/drivers/starburst/src/metabase/driver/implementation/unprepare.clj | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
this isn't nice to look at, so use this for actually running a query."
This is only needed for test purposes, because some of the sample data still uses legacy types
Convert time to Local time, then unprepare. |
distributed under the License is distributed on an " AS IS " BASIS ,
(ns metabase.driver.implementation.unprepare"Unprepare implementation for Starburst driver."
(:require [buddy.core.codecs :as codecs]
[java-time :as t]
[metabase.driver.sql.util :as sql.u]
[metabase.driver.sql.util.unprepare :as unprepare])
(:import [java.sql Time]
java.sql.Time
[java.time OffsetDateTime ZonedDateTime]))
(def ^:dynamic *param-splice-style*
"How we should splice params into SQL (i.e. 'unprepare' the SQL). Either `:friendly` (the default) or `:paranoid`.
`:friendly` makes a best-effort attempt to escape strings and generate SQL that is nice to look at, but should not
be considered safe against all SQL injection -- use this for 'convert to SQL' functionality. `:paranoid` hex-encodes
:friendly)
(defmethod unprepare/unprepare-value [:starburst String]
[_ ^String s]
(case *param-splice-style*
:friendly (str \' (sql.u/escape-sql s :ansi) \')
:paranoid (format "from_utf8(from_hex('%s'))" (codecs/bytes->hex (.getBytes s "UTF-8")))))
(defmethod unprepare/unprepare-value [:starburst Time]
[driver t]
(unprepare/unprepare-value driver (t/local-time t)))
(defmethod unprepare/unprepare-value [:starburst OffsetDateTime]
[_ t]
(format "timestamp '%s %s %s'" (t/local-date t) (t/local-time t) (t/zone-offset t)))
(defmethod unprepare/unprepare-value [:starburst ZonedDateTime]
[_ t]
(format "timestamp '%s %s %s'" (t/local-date t) (t/local-time t) (t/zone-id t)))
|
876f44ddcd68ed4b7b24cdc6a8022d2fb97446b8d974aa6c74182e31db2f9c05 | BoeingX/haskell-programming-from-first-principles | SemigroupExercisesSpec.hs | module Monoid.ChapterExercises.SemigroupExercisesSpec where
import Test.Hspec
import Test.QuickCheck
import Monoid.ChapterExercises.SemigroupExercises
semigroupAssoc :: (Eq m, Semigroup m) => m -> m -> m -> Bool
semigroupAssoc a b c = (a <> (b <> c)) == ((a <> b) <> c)
spec :: Spec
spec = do
describe "Test Semigroup implementations" $ do
it "Trivial" $ do
property (semigroupAssoc :: Trivial -> Trivial -> Trivial -> Bool)
it "Identity a" $ do
property (semigroupAssoc :: Identity String -> Identity String -> Identity String -> Bool)
it "Two a b" $ do
property (semigroupAssoc :: Two String String -> Two String String ->Two String String -> Bool)
it "BoolConj" $ do
property (semigroupAssoc :: BoolConj -> BoolConj -> BoolConj -> Bool)
it "BoolDisj" $ do
property (semigroupAssoc :: BoolDisj -> BoolDisj -> BoolDisj -> Bool)
it "Or a b" $ do
property (semigroupAssoc :: Or Integer Integer -> Or Integer Integer -> Or Integer Integer -> Bool)
it "Validation a b" $ do
property (semigroupAssoc :: Validation String String -> Validation String String -> Validation String String -> Bool)
it "AccumulateRight a b" $ do
property (semigroupAssoc :: AccumulateRight String String -> AccumulateRight String String -> AccumulateRight String String -> Bool)
it "AccumulateBoth a b" $ do
property (semigroupAssoc :: AccumulateBoth String String -> AccumulateBoth String String -> AccumulateBoth String String -> Bool)
| null | https://raw.githubusercontent.com/BoeingX/haskell-programming-from-first-principles/ffb637f536597f552a4e4567fee848ed27f3ba74/test/Monoid/ChapterExercises/SemigroupExercisesSpec.hs | haskell | module Monoid.ChapterExercises.SemigroupExercisesSpec where
import Test.Hspec
import Test.QuickCheck
import Monoid.ChapterExercises.SemigroupExercises
semigroupAssoc :: (Eq m, Semigroup m) => m -> m -> m -> Bool
semigroupAssoc a b c = (a <> (b <> c)) == ((a <> b) <> c)
spec :: Spec
spec = do
describe "Test Semigroup implementations" $ do
it "Trivial" $ do
property (semigroupAssoc :: Trivial -> Trivial -> Trivial -> Bool)
it "Identity a" $ do
property (semigroupAssoc :: Identity String -> Identity String -> Identity String -> Bool)
it "Two a b" $ do
property (semigroupAssoc :: Two String String -> Two String String ->Two String String -> Bool)
it "BoolConj" $ do
property (semigroupAssoc :: BoolConj -> BoolConj -> BoolConj -> Bool)
it "BoolDisj" $ do
property (semigroupAssoc :: BoolDisj -> BoolDisj -> BoolDisj -> Bool)
it "Or a b" $ do
property (semigroupAssoc :: Or Integer Integer -> Or Integer Integer -> Or Integer Integer -> Bool)
it "Validation a b" $ do
property (semigroupAssoc :: Validation String String -> Validation String String -> Validation String String -> Bool)
it "AccumulateRight a b" $ do
property (semigroupAssoc :: AccumulateRight String String -> AccumulateRight String String -> AccumulateRight String String -> Bool)
it "AccumulateBoth a b" $ do
property (semigroupAssoc :: AccumulateBoth String String -> AccumulateBoth String String -> AccumulateBoth String String -> Bool)
|
|
99f4078e64199d286776fde314ae0686f59e06880fb6c9cea6f0e8e8415d2f60 | racket/plai | test-framework.rkt | #lang plai/mutator
(allocator-setup "../good-collectors/good-collector.rkt" 28)
(halt-on-errors #t)
(test/value=? 12 12)
| null | https://raw.githubusercontent.com/racket/plai/164f3b763116fcfa7bd827be511650e71fa04319/plai-lib/tests/gc/good-mutators/test-framework.rkt | racket | #lang plai/mutator
(allocator-setup "../good-collectors/good-collector.rkt" 28)
(halt-on-errors #t)
(test/value=? 12 12)
|
|
65a7bfb36389b32c963332891353ca91a915729db82acbcf48814e05f443e480 | IxpertaSolutions/freer-effects | State.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE NoImplicitPrelude #
module Tests.State (tests)
where
import Prelude ((+))
import Control.Applicative (pure)
import Control.Monad ((>>))
import Data.Eq ((==))
import Data.Function (($), (.))
import Data.Int (Int)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
import Control.Monad.Freer (run)
import Control.Monad.Freer.State (evalState, execState, get, put, runState)
import Control.Monad.Freer.StateRW (ask, runStateR, tell)
tests :: TestTree
tests = testGroup "State tests"
[ testProperty "get after put n yields (n, n)"
$ \n -> testPutGet n 0 == (n, n)
, testProperty "Final put determines stored state"
$ \p1 p2 start -> testPutGetPutGetPlus p1 p2 start == (p1 + p2, p2)
, testProperty "If only getting, start state determines outcome"
$ \start -> testGetStart start == (start, start)
, testProperty "testPutGet: State == StateRW"
$ \n -> testPutGet n 0 == testPutGetRW n 0
, testProperty "testPutGetPutGetPlus: State == StateRW"
$ \p1 p2 start ->
testPutGetPutGetPlus p1 p2 start
== testPutGetPutGetPlusRW p1 p2 start
, testProperty "testGetStart: State == StateRW"
$ \n -> testGetStart n == testGetStartRW n
, testProperty "testEvalState: evalState discards final state"
$ \n -> testEvalState n == n
, testProperty "testExecState: execState returns final state"
$ \n -> testExecState n == n
]
testPutGet :: Int -> Int -> (Int, Int)
testPutGet n start = run $ runState go start
where
go = put n >> get
testPutGetRW :: Int -> Int -> (Int, Int)
testPutGetRW n start = run $ runStateR go start
where
go = tell n >> ask
testPutGetPutGetPlus :: Int -> Int -> Int -> (Int, Int)
testPutGetPutGetPlus p1 p2 start = run $ runState go start
where
go = do
put p1
x <- get
put p2
y <- get
pure (x + y)
testPutGetPutGetPlusRW :: Int -> Int -> Int -> (Int, Int)
testPutGetPutGetPlusRW p1 p2 start = run $ runStateR go start
where
go = do
tell p1
x <- ask
tell p2
y <- ask
pure (x+y)
testGetStart :: Int -> (Int, Int)
testGetStart = run . runState get
testGetStartRW :: Int -> (Int, Int)
testGetStartRW = run . runStateR ask
testEvalState :: Int -> Int
testEvalState = run . evalState go
where
go = do
x <- get
-- Destroy the previous state.
put (0 :: Int)
pure x
testExecState :: Int -> Int
testExecState n = run $ execState (put n) 0
| null | https://raw.githubusercontent.com/IxpertaSolutions/freer-effects/39a7e62cc049d43d36ece4ac24ba19e545f0b726/tests/Tests/State.hs | haskell | Destroy the previous state. | # LANGUAGE FlexibleContexts #
# LANGUAGE NoImplicitPrelude #
module Tests.State (tests)
where
import Prelude ((+))
import Control.Applicative (pure)
import Control.Monad ((>>))
import Data.Eq ((==))
import Data.Function (($), (.))
import Data.Int (Int)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
import Control.Monad.Freer (run)
import Control.Monad.Freer.State (evalState, execState, get, put, runState)
import Control.Monad.Freer.StateRW (ask, runStateR, tell)
tests :: TestTree
tests = testGroup "State tests"
[ testProperty "get after put n yields (n, n)"
$ \n -> testPutGet n 0 == (n, n)
, testProperty "Final put determines stored state"
$ \p1 p2 start -> testPutGetPutGetPlus p1 p2 start == (p1 + p2, p2)
, testProperty "If only getting, start state determines outcome"
$ \start -> testGetStart start == (start, start)
, testProperty "testPutGet: State == StateRW"
$ \n -> testPutGet n 0 == testPutGetRW n 0
, testProperty "testPutGetPutGetPlus: State == StateRW"
$ \p1 p2 start ->
testPutGetPutGetPlus p1 p2 start
== testPutGetPutGetPlusRW p1 p2 start
, testProperty "testGetStart: State == StateRW"
$ \n -> testGetStart n == testGetStartRW n
, testProperty "testEvalState: evalState discards final state"
$ \n -> testEvalState n == n
, testProperty "testExecState: execState returns final state"
$ \n -> testExecState n == n
]
testPutGet :: Int -> Int -> (Int, Int)
testPutGet n start = run $ runState go start
where
go = put n >> get
testPutGetRW :: Int -> Int -> (Int, Int)
testPutGetRW n start = run $ runStateR go start
where
go = tell n >> ask
testPutGetPutGetPlus :: Int -> Int -> Int -> (Int, Int)
testPutGetPutGetPlus p1 p2 start = run $ runState go start
where
go = do
put p1
x <- get
put p2
y <- get
pure (x + y)
testPutGetPutGetPlusRW :: Int -> Int -> Int -> (Int, Int)
testPutGetPutGetPlusRW p1 p2 start = run $ runStateR go start
where
go = do
tell p1
x <- ask
tell p2
y <- ask
pure (x+y)
testGetStart :: Int -> (Int, Int)
testGetStart = run . runState get
testGetStartRW :: Int -> (Int, Int)
testGetStartRW = run . runStateR ask
testEvalState :: Int -> Int
testEvalState = run . evalState go
where
go = do
x <- get
put (0 :: Int)
pure x
testExecState :: Int -> Int
testExecState n = run $ execState (put n) 0
|
e265921a51e51034d8167f45febfbf52b55c436dac7e8a97ac19b925a05cb9c2 | thheller/shadow-cljsjs | sw.cljs | (ns cljsjs.moment.locale.sw
(:require ["moment/locale/sw"]))
| null | https://raw.githubusercontent.com/thheller/shadow-cljsjs/eaf350d29d45adb85c0753dff77e276e7925a744/src/main/cljsjs/moment/locale/sw.cljs | clojure | (ns cljsjs.moment.locale.sw
(:require ["moment/locale/sw"]))
|
|
76966a214b31b36a64258595bd19e6bca198447c4790d7c2c7f92aa61d038535 | SKS-Keyserver/sks-keyserver | cMarshal.mli | val marshal_string :
< upcast : #Channel.out_channel_obj; write_byte : int -> unit;
write_char : char -> unit; write_float : float -> unit;
write_int : int -> unit; write_int32 : int32 -> unit;
write_int64 : int64 -> unit; write_string : string -> unit;
write_string_pos : buf:string -> pos:int -> len:int -> unit; .. > ->
string -> unit
val unmarshal_string : < read_int : 'a; read_string : 'a -> 'b; .. > -> 'b
val marshal_list :
f:((< write_int : int -> 'b; .. > as 'a) -> 'c -> unit) ->
'a -> 'c list -> unit
val unmarshal_list :
f:((< read_int : int; .. > as 'a) -> 'b) -> 'a -> 'b list
val marshal_lstring : < write_string : 'a -> 'b; .. > -> 'a -> 'b
val unmarshal_lstring : 'a -> < read_string : 'a -> 'b; .. > -> 'b
val marshal_array :
f:((< write_int : int -> 'b; .. > as 'a) -> 'c -> unit) ->
'a -> 'c array -> unit
val unmarshal_array :
f:((< read_int : int; .. > as 'a) -> 'b) -> 'a -> 'b array
val marshal_bitstring :
< upcast : #Channel.out_channel_obj; write_byte : int -> unit;
write_char : char -> unit; write_float : float -> unit;
write_int : int -> unit; write_int32 : int32 -> unit;
write_int64 : int64 -> unit; write_string : string -> unit;
write_string_pos : buf:string -> pos:int -> len:int -> unit; .. > ->
Bitstring.t -> unit
val unmarshal_bitstring :
< read_int : int; read_string : int -> string; .. > -> Bitstring.t
val marshal_fixed_sarray :
< write_int : int -> 'a; write_string : string -> unit; .. > ->
string array -> unit
val unmarshal_fixed_sarray :
< read_int : int; read_string : int -> 'a; .. > -> 'b -> 'a array
val marshal_set :
f:((< write_int : int -> 'b; .. > as 'a) -> ZZp.zz -> unit) ->
'a -> ZZp.Set.t -> unit
val unmarshal_set :
f:((< read_int : int; .. > as 'a) -> ZZp.zz) -> 'a -> ZZp.Set.t
val marshal_sockaddr :
< upcast : #Channel.out_channel_obj; write_byte : int -> unit;
write_char : char -> unit; write_float : float -> unit;
write_int : int -> unit; write_int32 : int32 -> unit;
write_int64 : int64 -> unit; write_string : string -> unit;
write_string_pos : buf:string -> pos:int -> len:int -> unit; .. > ->
Unix.sockaddr -> unit
val unmarshal_sockaddr :
< read_byte : int; read_int : int; read_string : int -> string; .. > ->
Unix.sockaddr
val marshal_to_string :
f:(Channel.buffer_out_channel -> 'a -> 'b) -> 'a -> string
val unmarshal_from_string :
f:(Channel.string_in_channel -> 'a) -> string -> 'a
val int_to_string : int -> string
val int_of_string : string -> int
| null | https://raw.githubusercontent.com/SKS-Keyserver/sks-keyserver/a4e5267d817cddbdfee13d07a7fb38a9b94b3eee/cMarshal.mli | ocaml | val marshal_string :
< upcast : #Channel.out_channel_obj; write_byte : int -> unit;
write_char : char -> unit; write_float : float -> unit;
write_int : int -> unit; write_int32 : int32 -> unit;
write_int64 : int64 -> unit; write_string : string -> unit;
write_string_pos : buf:string -> pos:int -> len:int -> unit; .. > ->
string -> unit
val unmarshal_string : < read_int : 'a; read_string : 'a -> 'b; .. > -> 'b
val marshal_list :
f:((< write_int : int -> 'b; .. > as 'a) -> 'c -> unit) ->
'a -> 'c list -> unit
val unmarshal_list :
f:((< read_int : int; .. > as 'a) -> 'b) -> 'a -> 'b list
val marshal_lstring : < write_string : 'a -> 'b; .. > -> 'a -> 'b
val unmarshal_lstring : 'a -> < read_string : 'a -> 'b; .. > -> 'b
val marshal_array :
f:((< write_int : int -> 'b; .. > as 'a) -> 'c -> unit) ->
'a -> 'c array -> unit
val unmarshal_array :
f:((< read_int : int; .. > as 'a) -> 'b) -> 'a -> 'b array
val marshal_bitstring :
< upcast : #Channel.out_channel_obj; write_byte : int -> unit;
write_char : char -> unit; write_float : float -> unit;
write_int : int -> unit; write_int32 : int32 -> unit;
write_int64 : int64 -> unit; write_string : string -> unit;
write_string_pos : buf:string -> pos:int -> len:int -> unit; .. > ->
Bitstring.t -> unit
val unmarshal_bitstring :
< read_int : int; read_string : int -> string; .. > -> Bitstring.t
val marshal_fixed_sarray :
< write_int : int -> 'a; write_string : string -> unit; .. > ->
string array -> unit
val unmarshal_fixed_sarray :
< read_int : int; read_string : int -> 'a; .. > -> 'b -> 'a array
val marshal_set :
f:((< write_int : int -> 'b; .. > as 'a) -> ZZp.zz -> unit) ->
'a -> ZZp.Set.t -> unit
val unmarshal_set :
f:((< read_int : int; .. > as 'a) -> ZZp.zz) -> 'a -> ZZp.Set.t
val marshal_sockaddr :
< upcast : #Channel.out_channel_obj; write_byte : int -> unit;
write_char : char -> unit; write_float : float -> unit;
write_int : int -> unit; write_int32 : int32 -> unit;
write_int64 : int64 -> unit; write_string : string -> unit;
write_string_pos : buf:string -> pos:int -> len:int -> unit; .. > ->
Unix.sockaddr -> unit
val unmarshal_sockaddr :
< read_byte : int; read_int : int; read_string : int -> string; .. > ->
Unix.sockaddr
val marshal_to_string :
f:(Channel.buffer_out_channel -> 'a -> 'b) -> 'a -> string
val unmarshal_from_string :
f:(Channel.string_in_channel -> 'a) -> string -> 'a
val int_to_string : int -> string
val int_of_string : string -> int
|
|
52b7eff9323999597ef6e48fc7aa7b7f12593b7d5660699997f138b35881caec | jyh/metaprl | hol_core.mli |
* HOL theory .
*
* ----------------------------------------------------------------
*
* @begin[license ]
* Copyright ( C ) 2004 Mojave Group , Caltech
*
* This program is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
*
* Author :
* @email{ }
* @end[license ]
* HOL theory.
*
* ----------------------------------------------------------------
*
* @begin[license]
* Copyright (C) 2004 Mojave Group, Caltech
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Author: Jason Hickey
* @email{}
* @end[license]
*)
(*!
* @docoff
*
* -*-
* Local Variables:
* Caml-master: "compile"
* End:
* -*-
*)
| null | https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/hol/hol_core.mli | ocaml | !
* @docoff
*
* -*-
* Local Variables:
* Caml-master: "compile"
* End:
* -*-
|
* HOL theory .
*
* ----------------------------------------------------------------
*
* @begin[license ]
* Copyright ( C ) 2004 Mojave Group , Caltech
*
* This program is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
*
* Author :
* @email{ }
* @end[license ]
* HOL theory.
*
* ----------------------------------------------------------------
*
* @begin[license]
* Copyright (C) 2004 Mojave Group, Caltech
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Author: Jason Hickey
* @email{}
* @end[license]
*)
|
76752d54d5181e911dad5bbac7f90e0393c74c433c856d727b30e73b4f786f02 | inaka/beam_olympics | bo_stats_SUITE.erl | -module(bo_stats_SUITE).
-author('').
-export([all/0]).
-export([init_per_suite/1, end_per_suite/1]).
-export([ initial_stats/1
, players_playing/1
]).
-type config() :: proplists:proplist().
-spec all() -> [atom()].
all() -> [initial_stats, players_playing].
-spec init_per_suite(config()) -> config().
init_per_suite(Config) ->
case net_kernel:start(['[email protected]']) of
{ok, _} -> ok;
{error, {already_started, _}} -> ok;
{error, Error} -> throw(Error)
end,
_ = application:load(beam_olympics),
application:set_env(
beam_olympics, all_tasks, [bo_first_task, simple_task1, simple_task2]),
{ok, _} = bo:start(),
_ = sumo:delete_all(players),
{ok, Client} = bo_test_client:start(stats_suite),
[{client, Client} | Config].
-spec end_per_suite(config()) -> config().
end_per_suite(Config) ->
{client, Client} = lists:keyfind(client, 1, Config),
ok = bo_test_client:stop(Client),
_ = sumo:delete_all(players),
application:unset_env(beam_olympics, all_tasks),
ok = bo:stop(),
Config.
-spec initial_stats(config()) -> {comment, string()}.
initial_stats(Config) ->
{client, Client} = lists:keyfind(client, 1, Config),
ct:comment("Initial stats include no player"),
#{ tasks := 3
, players := []
} = bo_test_client:stats(Client),
{comment, ""}.
-spec players_playing(config()) -> {comment, string()}.
players_playing(Config) ->
{client, Client} = lists:keyfind(client, 1, Config),
{ok, #{name := FirstTask}} = bo_test_client:signup(Client, <<"pp1">>),
{ok, #{name := FirstTask}} = bo_test_client:signup(Client, <<"pp2">>),
ct:comment("All players in first task"),
#{ tasks := 3
, players := [ #{ name := <<$p, $p, _>>
, done := 0
, score := 0
}
, #{ name := <<$p, $p, _>>
, done := 0
, score := 0
}
]
} = bo_test_client:stats(Client),
ct:comment("After solving first task, the player changes"),
{ok, _} = bo_test_client:submit(Client, <<"pp2">>, fun id/1),
SolveScore = bo_task:score(FirstTask),
#{ tasks := 3
, players := [ #{ name := <<"pp2">>
, done := 1
, score := SolveScore
}
, #{ name := <<"pp1">>
, done := 0
, score := 0
}
]
} = bo_test_client:stats(Client),
ct:comment("After skipping task, the player changes"),
{ok, _} = bo_test_client:skip(Client, <<"pp1">>),
SkipScore = round(-0.5 * SolveScore),
#{ tasks := 3
, players := [ #{ name := <<"pp2">>
, done := 1
, score := SolveScore
}
, #{ name := <<"pp1">>
, done := 1
, score := SkipScore
}
]
} = bo_test_client:stats(Client),
{comment, ""}.
id(X) ->
ct:log("id evaluated for ~p", [X]),
X.
| null | https://raw.githubusercontent.com/inaka/beam_olympics/9b16afd54f25c0996430139e9646c3cfdfbdf86b/test/bo_stats_SUITE.erl | erlang | -module(bo_stats_SUITE).
-author('').
-export([all/0]).
-export([init_per_suite/1, end_per_suite/1]).
-export([ initial_stats/1
, players_playing/1
]).
-type config() :: proplists:proplist().
-spec all() -> [atom()].
all() -> [initial_stats, players_playing].
-spec init_per_suite(config()) -> config().
init_per_suite(Config) ->
case net_kernel:start(['[email protected]']) of
{ok, _} -> ok;
{error, {already_started, _}} -> ok;
{error, Error} -> throw(Error)
end,
_ = application:load(beam_olympics),
application:set_env(
beam_olympics, all_tasks, [bo_first_task, simple_task1, simple_task2]),
{ok, _} = bo:start(),
_ = sumo:delete_all(players),
{ok, Client} = bo_test_client:start(stats_suite),
[{client, Client} | Config].
-spec end_per_suite(config()) -> config().
end_per_suite(Config) ->
{client, Client} = lists:keyfind(client, 1, Config),
ok = bo_test_client:stop(Client),
_ = sumo:delete_all(players),
application:unset_env(beam_olympics, all_tasks),
ok = bo:stop(),
Config.
-spec initial_stats(config()) -> {comment, string()}.
initial_stats(Config) ->
{client, Client} = lists:keyfind(client, 1, Config),
ct:comment("Initial stats include no player"),
#{ tasks := 3
, players := []
} = bo_test_client:stats(Client),
{comment, ""}.
-spec players_playing(config()) -> {comment, string()}.
players_playing(Config) ->
{client, Client} = lists:keyfind(client, 1, Config),
{ok, #{name := FirstTask}} = bo_test_client:signup(Client, <<"pp1">>),
{ok, #{name := FirstTask}} = bo_test_client:signup(Client, <<"pp2">>),
ct:comment("All players in first task"),
#{ tasks := 3
, players := [ #{ name := <<$p, $p, _>>
, done := 0
, score := 0
}
, #{ name := <<$p, $p, _>>
, done := 0
, score := 0
}
]
} = bo_test_client:stats(Client),
ct:comment("After solving first task, the player changes"),
{ok, _} = bo_test_client:submit(Client, <<"pp2">>, fun id/1),
SolveScore = bo_task:score(FirstTask),
#{ tasks := 3
, players := [ #{ name := <<"pp2">>
, done := 1
, score := SolveScore
}
, #{ name := <<"pp1">>
, done := 0
, score := 0
}
]
} = bo_test_client:stats(Client),
ct:comment("After skipping task, the player changes"),
{ok, _} = bo_test_client:skip(Client, <<"pp1">>),
SkipScore = round(-0.5 * SolveScore),
#{ tasks := 3
, players := [ #{ name := <<"pp2">>
, done := 1
, score := SolveScore
}
, #{ name := <<"pp1">>
, done := 1
, score := SkipScore
}
]
} = bo_test_client:stats(Client),
{comment, ""}.
id(X) ->
ct:log("id evaluated for ~p", [X]),
X.
|
|
33c3d54a798f45b50b4ce677513061fd697232483742868fa30bff1fdfd2581e | nd/sicp | 4.11.scm | (define (make-binding var val) (cons var val))
(define (binding-var binding) (car binding))
(define (binding-val binding) (cdr binding))
(define (set-binding-val! binding value) (set-cdr! binding value))
(define (make-frame bindings) (list bindings))
(define (frame-bindings frame) (car frame))
(define (set-frame-bindings! frame bindings) (set-car! frame bindings))
(define (frame-variables frame) (map binding-var (frame-bindings frame)))
(define (frame-values frame) (map binding-val (frame-bindings frame)))
(define (add-binding-to-frame! binding frame)
(set-frame-bindings! frame (cons binding (frame-bindings frame))))
(define (extend-environment bindings base-env) (cons (make-frame bindings) base-env))
(define (lookup-variable-value var env)
(define (env-loop env)
(define (scan bindings)
(cond ((null? bindings) (evn-loop (enclosing-environment env)))
((eq? var (binding-var (car bindings))) (binding-val (car bindings)))
(else (scan (cdr bindings)))))
(if (eq? env the-empty-environment)
(error "Unbounded var" var)
(let ((frame (first-frame env)))
(scan (frame-bindings frame)))))
(env-loop env))
(define (set-variable-value! var val env)
(define (env-loop env)
(define (scan bindings)
(cond ((null? bindings) (env-loop (enclosing-environment env)))
((eq? var (binding-var (car bindings))) (set-binding-val! (car bindings) val))
(else (scan (cdr bindings)))))
(if (eq? env the-empty-environment)
(error "Unknown variable" var)
(let ((frame (first-frame env)))
(scan (frame-bindings frame)))))
(env-loop env))
(define (define-variable! var val env)
(let ((frame (first-frame env)))
(define (scan bindings)
(cond ((null? bindings) (add-binding-to-frame! (make-binding var val) frame))
((eq? var (binding-var (car bindings))) (set-binding-val! (car bindings) val))
(else (scan (cdr bindings)))))
(scan (frame-bindings frame))))
| null | https://raw.githubusercontent.com/nd/sicp/d8587a0403d95af7c7bcf59b812f98c4f8550afd/ch04/4.11.scm | scheme | (define (make-binding var val) (cons var val))
(define (binding-var binding) (car binding))
(define (binding-val binding) (cdr binding))
(define (set-binding-val! binding value) (set-cdr! binding value))
(define (make-frame bindings) (list bindings))
(define (frame-bindings frame) (car frame))
(define (set-frame-bindings! frame bindings) (set-car! frame bindings))
(define (frame-variables frame) (map binding-var (frame-bindings frame)))
(define (frame-values frame) (map binding-val (frame-bindings frame)))
(define (add-binding-to-frame! binding frame)
(set-frame-bindings! frame (cons binding (frame-bindings frame))))
(define (extend-environment bindings base-env) (cons (make-frame bindings) base-env))
(define (lookup-variable-value var env)
(define (env-loop env)
(define (scan bindings)
(cond ((null? bindings) (evn-loop (enclosing-environment env)))
((eq? var (binding-var (car bindings))) (binding-val (car bindings)))
(else (scan (cdr bindings)))))
(if (eq? env the-empty-environment)
(error "Unbounded var" var)
(let ((frame (first-frame env)))
(scan (frame-bindings frame)))))
(env-loop env))
(define (set-variable-value! var val env)
(define (env-loop env)
(define (scan bindings)
(cond ((null? bindings) (env-loop (enclosing-environment env)))
((eq? var (binding-var (car bindings))) (set-binding-val! (car bindings) val))
(else (scan (cdr bindings)))))
(if (eq? env the-empty-environment)
(error "Unknown variable" var)
(let ((frame (first-frame env)))
(scan (frame-bindings frame)))))
(env-loop env))
(define (define-variable! var val env)
(let ((frame (first-frame env)))
(define (scan bindings)
(cond ((null? bindings) (add-binding-to-frame! (make-binding var val) frame))
((eq? var (binding-var (car bindings))) (set-binding-val! (car bindings) val))
(else (scan (cdr bindings)))))
(scan (frame-bindings frame))))
|
|
6c22939dc9365cada4030c390e9fba15f6defb1f8fe83413d09e64ab4327ed84 | BU-CS320/Fall-2018 | Lang0Test.hs | module Lang0Test where
import Data.Char
import Test.Tasty (testGroup)
import Test.Tasty.HUnit (assertEqual, assertBool, testCase)
import Test.Tasty.QuickCheck
import Lang0(Ast(AstInt,Plus), eval)
import Lang0Parser(unsafeParser, parser)
-- if some hero wants to write these for all data, I'm sure the class will appreciate it!
instance Arbitrary Ast where
arbitrary = sized arbitrarySizedAst
arbitrarySizedAst :: Int -> Gen Ast
arbitrarySizedAst m | m < 1 = do i <- arbitrary
return $ AstInt i
arbitrarySizedAst m | otherwise = do l <- arbitrarySizedAst (m `div` 2)
r <- arbitrarySizedAst (m `div` 2)
return $ Plus l r
-- See: -quickcheck-tutorial-generators
unitTests =
testGroup
"Lang0Test"
[instructorTests
-- TODO: your tests here
]
instructorTests = testGroup
"instructorTests"
[
testCase "show should show the pre evaluated expression" $ assertEqual [] "(1+2)" $ show $ (AstInt 1) `Plus` (AstInt 2),
testProperty "show is never empty" $ ((\ x -> 0 < (length $ show x)) :: Ast -> Bool),
testProperty "for all x. x == x" $ ((\ x -> x == x) :: Ast -> Bool),
testCase "eval ((AstInt 2) `Plus` (AstInt 3)) == 5" $ assertEqual [] 5 $ eval ((AstInt 2) `Plus` (AstInt 3)),
testCase "testParser1" $ assertEqual [] (eval (unsafeParser "5")) $ eval (unsafeParser "2 + 3"),
testCase "testParser2" $ assertEqual [] (Just (Plus (AstInt 1) (Plus (AstInt 2) (Plus (AstInt 3) (Plus (AstInt 4) (Plus (AstInt 5) (AstInt 6))))),"")) $ (parser "1+2+3+4+5+6"),
testCase "testParser3" $ assertEqual [] (Just (Plus (AstInt 1) (Plus (AstInt 2) (Plus (Plus (AstInt 3) (AstInt 4)) (Plus (AstInt 5) (AstInt 6)))),"")) $ (parser "1+2+(3+((4)))+5+6" ),
testProperty "show should match parse" $ ((\ x -> Just (x , "") == (parser $ show x)) :: Ast -> Bool)
]
TODO : test other Eq laws too , better descriptions
| null | https://raw.githubusercontent.com/BU-CS320/Fall-2018/beec3ca88be5c5a62271a45c8053fb1b092e0af1/assignments/week7/hw/tests/Lang0Test.hs | haskell | if some hero wants to write these for all data, I'm sure the class will appreciate it!
See: -quickcheck-tutorial-generators
TODO: your tests here
| module Lang0Test where
import Data.Char
import Test.Tasty (testGroup)
import Test.Tasty.HUnit (assertEqual, assertBool, testCase)
import Test.Tasty.QuickCheck
import Lang0(Ast(AstInt,Plus), eval)
import Lang0Parser(unsafeParser, parser)
instance Arbitrary Ast where
arbitrary = sized arbitrarySizedAst
arbitrarySizedAst :: Int -> Gen Ast
arbitrarySizedAst m | m < 1 = do i <- arbitrary
return $ AstInt i
arbitrarySizedAst m | otherwise = do l <- arbitrarySizedAst (m `div` 2)
r <- arbitrarySizedAst (m `div` 2)
return $ Plus l r
unitTests =
testGroup
"Lang0Test"
[instructorTests
]
instructorTests = testGroup
"instructorTests"
[
testCase "show should show the pre evaluated expression" $ assertEqual [] "(1+2)" $ show $ (AstInt 1) `Plus` (AstInt 2),
testProperty "show is never empty" $ ((\ x -> 0 < (length $ show x)) :: Ast -> Bool),
testProperty "for all x. x == x" $ ((\ x -> x == x) :: Ast -> Bool),
testCase "eval ((AstInt 2) `Plus` (AstInt 3)) == 5" $ assertEqual [] 5 $ eval ((AstInt 2) `Plus` (AstInt 3)),
testCase "testParser1" $ assertEqual [] (eval (unsafeParser "5")) $ eval (unsafeParser "2 + 3"),
testCase "testParser2" $ assertEqual [] (Just (Plus (AstInt 1) (Plus (AstInt 2) (Plus (AstInt 3) (Plus (AstInt 4) (Plus (AstInt 5) (AstInt 6))))),"")) $ (parser "1+2+3+4+5+6"),
testCase "testParser3" $ assertEqual [] (Just (Plus (AstInt 1) (Plus (AstInt 2) (Plus (Plus (AstInt 3) (AstInt 4)) (Plus (AstInt 5) (AstInt 6)))),"")) $ (parser "1+2+(3+((4)))+5+6" ),
testProperty "show should match parse" $ ((\ x -> Just (x , "") == (parser $ show x)) :: Ast -> Bool)
]
TODO : test other Eq laws too , better descriptions
|
b74d5ec12f503db5d25a7340594327e49ce705578e85a562c6117fcf42cad4e2 | skypher/paktahn | tests.lisp | (defpackage :paktahn-tests
(:use :cl :paktahn :fiveam)
(:export #:run!))
(in-package :paktahn-tests)
;; It will make sense to split this up into several suites as we get more tests.
i.e. ( libalpm , pkgbuild , customizepkg , argv , etc )
(def-suite :pak)
(in-suite :pak)
(test t-is-not-null
(is (not (null t))))
| null | https://raw.githubusercontent.com/skypher/paktahn/ab2d3f91675bd658f7eec9186d3fd6db588ef413/tests/tests.lisp | lisp | It will make sense to split this up into several suites as we get more tests. | (defpackage :paktahn-tests
(:use :cl :paktahn :fiveam)
(:export #:run!))
(in-package :paktahn-tests)
i.e. ( libalpm , pkgbuild , customizepkg , argv , etc )
(def-suite :pak)
(in-suite :pak)
(test t-is-not-null
(is (not (null t))))
|
df683841ddcc5cbc5a8b2655cb8fb0dec05668aecdb9bd40eed60ce286ece80a | andrejbauer/clerical | type.ml | (* Value types *)
type valty =
| Boolean
| Integer
| Real
(* Command types *)
type cmdty =
| Data of valty
| Command
(* Function types *)
type funty = valty list * cmdty
(** Print a value type *)
let print_valty dt ppf =
match dt with
| Boolean -> Format.fprintf ppf "boolean"
| Integer -> Format.fprintf ppf "integer"
| Real -> Format.fprintf ppf "real"
(** Print a command type *)
let print_cmdty t ppf =
match t with
| Data dt -> print_valty dt ppf
| Command -> Format.fprintf ppf "command"
let print_funty (ts, t) ppf =
Format.fprintf ppf "(%t) -> %t"
(fun ppf ->
Format.pp_print_list
~pp_sep:(fun ppf () -> Format.fprintf ppf ", ")
(fun ppf dt -> print_valty dt ppf)
ppf
ts)
(print_cmdty t)
| null | https://raw.githubusercontent.com/andrejbauer/clerical/6916f1de50f812921fe187bdaec830e06f4dcde8/src/type.ml | ocaml | Value types
Command types
Function types
* Print a value type
* Print a command type | type valty =
| Boolean
| Integer
| Real
type cmdty =
| Data of valty
| Command
type funty = valty list * cmdty
let print_valty dt ppf =
match dt with
| Boolean -> Format.fprintf ppf "boolean"
| Integer -> Format.fprintf ppf "integer"
| Real -> Format.fprintf ppf "real"
let print_cmdty t ppf =
match t with
| Data dt -> print_valty dt ppf
| Command -> Format.fprintf ppf "command"
let print_funty (ts, t) ppf =
Format.fprintf ppf "(%t) -> %t"
(fun ppf ->
Format.pp_print_list
~pp_sep:(fun ppf () -> Format.fprintf ppf ", ")
(fun ppf dt -> print_valty dt ppf)
ppf
ts)
(print_cmdty t)
|
0ff6dabc13ee01ab967620a19d2dc1f6c05d3ddb27e98c01ed1b6c51de21a66d | patricoferris/ocaml-ipld | test.ml | let ipld = Alcotest.testable Ipld.pp Stdlib.( = )
let cbor =
Alcotest.testable
(fun ppf v -> Fmt.pf ppf "%s" (CBOR.Simple.to_diagnostic v))
Stdlib.( = )
let read_file fpath =
let ic = open_in fpath in
let rec read acc =
try read (input_line ic :: acc)
with End_of_file -> List.rev acc |> String.concat "\n"
in
let s = read [] in
close_in ic;
s
let ( / ) = Filename.concat
(* CBOR is having a hard time of integers *)
let disable_list =
[
"int-9223372036854775807";
"int-11959030306112471731";
"int--9223372036854775808";
"int-18446744073709551615";
"int--11959030306112471732";
]
let test_fixtures () =
let fixtures = "../codec-fixtures/fixtures" in
let files = Sys.readdir fixtures |> Array.to_list in
let get_data fpath =
let cid = Filename.chop_extension fpath in
let data = read_file fpath in
(cid, data)
in
let make_test fpath =
let dir = fixtures / fpath in
if (not (Sys.is_directory dir)) || List.mem fpath disable_list then None
else
let codec_files = Sys.readdir dir in
match
Array.find_opt (fun c -> Filename.extension c = ".dag-cbor") codec_files
with
| None -> assert false
| Some f ->
let test () =
let _cid, data = get_data (fixtures / fpath / f) in
let c = CBOR.Simple.decode data in
let i = Dag_cbor.encode c in
let c' = Dag_cbor.decode i in
let i' = Dag_cbor.encode c' in
Alcotest.(check cbor) "same cbor" c c';
Alcotest.(check ipld) "same ipld" i i'
in
Some (fpath, `Quick, test)
in
List.filter_map (fun f -> make_test f) files
let () = Alcotest.run "ipld-dag-cbor" [ ("fixtures", test_fixtures ()) ]
| null | https://raw.githubusercontent.com/patricoferris/ocaml-ipld/84a035dd42b9392a0cb9070ee3ddf18816fce8c1/test/dag-cbor/test.ml | ocaml | CBOR is having a hard time of integers | let ipld = Alcotest.testable Ipld.pp Stdlib.( = )
let cbor =
Alcotest.testable
(fun ppf v -> Fmt.pf ppf "%s" (CBOR.Simple.to_diagnostic v))
Stdlib.( = )
let read_file fpath =
let ic = open_in fpath in
let rec read acc =
try read (input_line ic :: acc)
with End_of_file -> List.rev acc |> String.concat "\n"
in
let s = read [] in
close_in ic;
s
let ( / ) = Filename.concat
let disable_list =
[
"int-9223372036854775807";
"int-11959030306112471731";
"int--9223372036854775808";
"int-18446744073709551615";
"int--11959030306112471732";
]
let test_fixtures () =
let fixtures = "../codec-fixtures/fixtures" in
let files = Sys.readdir fixtures |> Array.to_list in
let get_data fpath =
let cid = Filename.chop_extension fpath in
let data = read_file fpath in
(cid, data)
in
let make_test fpath =
let dir = fixtures / fpath in
if (not (Sys.is_directory dir)) || List.mem fpath disable_list then None
else
let codec_files = Sys.readdir dir in
match
Array.find_opt (fun c -> Filename.extension c = ".dag-cbor") codec_files
with
| None -> assert false
| Some f ->
let test () =
let _cid, data = get_data (fixtures / fpath / f) in
let c = CBOR.Simple.decode data in
let i = Dag_cbor.encode c in
let c' = Dag_cbor.decode i in
let i' = Dag_cbor.encode c' in
Alcotest.(check cbor) "same cbor" c c';
Alcotest.(check ipld) "same ipld" i i'
in
Some (fpath, `Quick, test)
in
List.filter_map (fun f -> make_test f) files
let () = Alcotest.run "ipld-dag-cbor" [ ("fixtures", test_fixtures ()) ]
|
c17155634613345baa3cc2bee428613fdaf83973adfd24003a97fc51113473ab | geophf/1HaskellADay | Exercise.hs | # LANGUAGE OverloadedStrings , QuasiQuotes #
module Y2018.M04.D11.Exercise where
-
Like we 've done before , we need to download packets of information ( articles )
and ( eventually ) store those articles , but also store the packet information
that we used to download the articles
see also : Y2017.M12.D20.Exercise .
But this is different : the exercise from last year , the packet contained
information about the packet , itself . This REST endpoint has no such packet
information , so , we 'll just store what we know about this packet : the count ,
the start and end article IDs and the time dowloaded .
... but we do n't have to store the article ids , as those are all derived
from the associated join table .
We 'll look at downloading a packet of articles in another exercise ( spoiler :
Y2018.M04.D12.Exercise ) , for today , given the below structures , upload the
packet information to the PostgreSQL database .
-
Like we've done before, we need to download packets of information (articles)
and (eventually) store those articles, but also store the packet information
that we used to download the articles
see also: Y2017.M12.D20.Exercise.
But this is different: the exercise from last year, the packet contained
information about the packet, itself. This REST endpoint has no such packet
information, so, we'll just store what we know about this packet: the count,
the start and end article IDs and the time dowloaded.
... but we don't have to store the article ids, as those are all derived
from the associated join table.
We'll look at downloading a packet of articles in another exercise (spoiler:
Y2018.M04.D12.Exercise), for today, given the below structures, upload the
packet information to the PostgreSQL database.
--}
import Data.Aeson (Value)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple.ToRow
below imports available via 1HaskellADay git repository
import Data.Time.Stamped
import Store.SQL.Connection
import Store.SQL.Util.Indexed
type PageNumber = Int
type Count = Int
data Protec = Pro { page :: PageNumber, count :: Count, arts :: [Value] }
deriving Show
-- (I call it Protec for 'reasons' ... yes, I'm weird)
instance ToRow Protec where
toRow p = undefined
protecStmt :: Query
protecStmt = [sql|INSERT INTO package (time, page, count)
VALUES (?, ?, ?) returning id|]
insertProtec :: Connection -> Protec -> IO Index
insertProtec conn prot = undefined
-- Note, we want to insert a Stamped Protec at the time of insert, hint-hint
protec :: Protec
protec = Pro 1 100 []
-- insert the above value. What value do you get in return?
-- we'll do article insertion from Protec values and article-packet join later
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2018/M04/D11/Exercise.hs | haskell | }
(I call it Protec for 'reasons' ... yes, I'm weird)
Note, we want to insert a Stamped Protec at the time of insert, hint-hint
insert the above value. What value do you get in return?
we'll do article insertion from Protec values and article-packet join later | # LANGUAGE OverloadedStrings , QuasiQuotes #
module Y2018.M04.D11.Exercise where
-
Like we 've done before , we need to download packets of information ( articles )
and ( eventually ) store those articles , but also store the packet information
that we used to download the articles
see also : Y2017.M12.D20.Exercise .
But this is different : the exercise from last year , the packet contained
information about the packet , itself . This REST endpoint has no such packet
information , so , we 'll just store what we know about this packet : the count ,
the start and end article IDs and the time dowloaded .
... but we do n't have to store the article ids , as those are all derived
from the associated join table .
We 'll look at downloading a packet of articles in another exercise ( spoiler :
Y2018.M04.D12.Exercise ) , for today , given the below structures , upload the
packet information to the PostgreSQL database .
-
Like we've done before, we need to download packets of information (articles)
and (eventually) store those articles, but also store the packet information
that we used to download the articles
see also: Y2017.M12.D20.Exercise.
But this is different: the exercise from last year, the packet contained
information about the packet, itself. This REST endpoint has no such packet
information, so, we'll just store what we know about this packet: the count,
the start and end article IDs and the time dowloaded.
... but we don't have to store the article ids, as those are all derived
from the associated join table.
We'll look at downloading a packet of articles in another exercise (spoiler:
Y2018.M04.D12.Exercise), for today, given the below structures, upload the
packet information to the PostgreSQL database.
import Data.Aeson (Value)
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple.ToRow
below imports available via 1HaskellADay git repository
import Data.Time.Stamped
import Store.SQL.Connection
import Store.SQL.Util.Indexed
type PageNumber = Int
type Count = Int
data Protec = Pro { page :: PageNumber, count :: Count, arts :: [Value] }
deriving Show
instance ToRow Protec where
toRow p = undefined
protecStmt :: Query
protecStmt = [sql|INSERT INTO package (time, page, count)
VALUES (?, ?, ?) returning id|]
insertProtec :: Connection -> Protec -> IO Index
insertProtec conn prot = undefined
protec :: Protec
protec = Pro 1 100 []
|
5a4034123fc77d6e50955ea93e01be203c0409977cc4136792181c542268582e | dhess/hpio | MockSpec.hs | # OPTIONS_GHC -fno - warn - incomplete - patterns -fno - warn - incomplete - uni - patterns #
{-# LANGUAGE OverloadedStrings #-}
module Test.System.GPIO.Linux.Sysfs.MockSpec (spec) where
import Protolude hiding (readFile, writeFile)
import GHC.IO.Exception (IOErrorType(..))
import System.GPIO.Linux.Sysfs.Mock
import System.GPIO.Types (Pin(..), PinValue(..))
import System.IO.Error
(IOError, ioeGetErrorType, isDoesNotExistError, isPermissionError)
import Test.Hspec
isInappropriateTypeErrorType :: IOErrorType -> Bool
isInappropriateTypeErrorType InappropriateType = True
isInappropriateTypeErrorType _ = False
isInappropriateTypeError :: IOError -> Bool
isInappropriateTypeError = isInappropriateTypeErrorType . ioeGetErrorType
evalSysfsMock' :: SysfsMock a -> MockWorld -> [MockGpioChip] -> Either (Maybe IOError) a
evalSysfsMock' a w c = either (Left . fromException) Right $ evalSysfsMock a w c
evalSysfsMockME :: SysfsMock a -> MockWorld -> [MockGpioChip] -> Either (Maybe MockFSException) a
evalSysfsMockME a w c = either (Left . fromException) Right $ evalSysfsMock a w c
execSysfsMock' :: SysfsMock a -> MockWorld -> [MockGpioChip] -> Either (Maybe IOError) MockWorld
execSysfsMock' a w c = either (Left . fromException) Right $ execSysfsMock a w c
spec :: Spec
spec =
do
describe "MockPinState" $ do
it "logicalValue returns the correct pin value" $
let pinState = defaultMockPinState {_value = Low, _activeLow = False}
in do
logicalValue pinState `shouldBe` Low
logicalValue (pinState {_value = High}) `shouldBe` High
logicalValue (pinState {_activeLow = True}) `shouldBe` High
logicalValue (pinState {_value = High, _activeLow = True}) `shouldBe` Low
it "setLogicalValue sets the correct pin value" $
let pinState = defaultMockPinState {_value = Low, _activeLow = False}
activeLowPinState = defaultMockPinState {_value = Low, _activeLow = True}
in do
setLogicalValue Low pinState `shouldBe` pinState
setLogicalValue High pinState `shouldBe` pinState {_value = High}
setLogicalValue Low activeLowPinState `shouldBe` activeLowPinState {_value = High}
setLogicalValue High activeLowPinState `shouldBe` activeLowPinState {_value = Low}
describe "SysfsMockT" $ do
context "doesDirectoryExist" $ do
it "relative paths are relative to the initial zipper's working directory" $ do
evalSysfsMock' (doesDirectoryExist "sys/class/gpio") initialMockWorld [] `shouldBe` Right True
it "absolute paths work regardless of the initial zipper's working directory" $ do
evalSysfsMock' (doesDirectoryExist "/sys/class/gpio") initialMockWorld [] `shouldBe` Right True
it "doesn't change the initial zipper's state" $ do
execSysfsMock' (doesDirectoryExist "/sys/class/gpio") initialMockWorld [] `shouldBe` Right initialMockWorld
it "returns False on files" $ do
evalSysfsMock' (doesDirectoryExist "/sys/class/gpio/export") initialMockWorld [] `shouldBe` Right False
it "returns False on non-existent names" $ do
evalSysfsMock' (doesDirectoryExist "/sys/class/foobar") initialMockWorld [] `shouldBe` Right False
context "doesFileExist" $ do
it "relative paths are relative to the initial zipper's working directory" $ do
evalSysfsMock' (doesFileExist "sys/class/gpio/export") initialMockWorld [] `shouldBe` Right True
it "absolute paths work regardless of the initial zipper's working directory" $ do
evalSysfsMock' (doesFileExist "/sys/class/gpio/export") initialMockWorld [] `shouldBe` Right True
it "doesn't change the initial zipper's state" $ do
execSysfsMock' (doesFileExist "/sys/class/gpio/export") initialMockWorld [] `shouldBe` Right initialMockWorld
it "returns False on directories" $ do
evalSysfsMock' (doesFileExist "/sys/class/gpio") initialMockWorld [] `shouldBe` Right False
it "returns False on non-existent names" $ do
evalSysfsMock' (doesFileExist "/sys/class/foobar") initialMockWorld [] `shouldBe` Right False
context "getDirectoryContents" $ do
it "relative paths are relative to the initial zipper's working directory" $ do
fmap sort (evalSysfsMock' (getDirectoryContents "sys/class") initialMockWorld []) `shouldBe` Right ["gpio"]
fmap sort (evalSysfsMock' (getDirectoryContents "sys/class/gpio") initialMockWorld []) `shouldBe` (Right $ sort ["export", "unexport"])
it "absolute paths work regardless of the initial zipper's working directory" $ do
fmap sort (evalSysfsMock' (getDirectoryContents "/sys/class") initialMockWorld []) `shouldBe` Right ["gpio"]
fmap sort (evalSysfsMock' (getDirectoryContents "/sys/class/gpio") initialMockWorld []) `shouldBe` (Right $ sort ["export", "unexport"])
it "doesn't change the initial zipper's state" $ do
execSysfsMock' (getDirectoryContents "/sys/class/gpio") initialMockWorld [] `shouldBe` Right initialMockWorld
it "returns failure on files" $ do
do let Left (Just result) = evalSysfsMock' (getDirectoryContents "/sys/class/gpio/export") initialMockWorld []
isInappropriateTypeError result `shouldBe` True
it "returns failure on non-existent names" $ do
do let Left (Just result) = evalSysfsMock' (getDirectoryContents "/sys/class/foobar") initialMockWorld []
isDoesNotExistError result `shouldBe` True
context "readFile" $ do
-- Note: most interesting cases are already checked by the
-- tests in 'SysfsGpioMockSpec.hs' and it would be a bit silly
-- to try to test them here due to the amount of setup
-- required to get the filesystem into the necessary state.
-- (We would basically end up rewriting large chunks of the
mock GPIO code . )
it "works with 'constant' files" $
let chip0 = MockGpioChip "chip0" 0 (replicate 16 defaultMockPinState)
in evalSysfsMock' (readFile "/sys/class/gpio/gpiochip0/base") initialMockWorld [chip0] `shouldBe` Right "0\n"
it "fails on /sys/class/gpio/export" $
do let Left (Just result) = evalSysfsMock' (readFile "/sys/class/gpio/export") initialMockWorld []
isPermissionError result `shouldBe` True
it "fails on /sys/class/gpio/unexport" $
do let Left (Just result) = evalSysfsMock' (readFile "/sys/class/gpio/unexport") initialMockWorld []
isPermissionError result `shouldBe` True
it "fails on non-existent file" $
do let Left (Just result) = evalSysfsMock' (readFile "/sys/class/gpio/foo") initialMockWorld []
isDoesNotExistError result `shouldBe` True
it "fails on a directory" $
do let Left (Just result) = evalSysfsMock' (readFile "/sys/class/gpio") initialMockWorld []
isInappropriateTypeError result `shouldBe` True
context "writeFile" $
it "does the right thing" $
pendingWith "Not implemented" -- See notes for 'readFile'
-- above.
context "runSysfsMockT" $ do
let chip0 = MockGpioChip "chip0" 0 (replicate 16 defaultMockPinState)
chip16 = MockGpioChip "xyz" 16 (replicate 32 defaultMockPinState)
chip64 = MockGpioChip "abc" 64 (replicate 16 defaultMockPinState)
invalidChip32 = MockGpioChip "invalid" 32 (replicate 16 defaultMockPinState)
it "creates the specified gpiochip directories" $ do
fmap sort (evalSysfsMock' (getDirectoryContents "/sys/class/gpio") initialMockWorld [chip0, chip16, chip64]) `shouldBe` Right ["export", "gpiochip0", "gpiochip16", "gpiochip64", "unexport"]
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip0/base") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "0\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip0/ngpio") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "16\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip0/label") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "chip0\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip16/base") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "16\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip16/ngpio") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "32\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip16/label") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "xyz\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip64/base") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "64\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip64/ngpio") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "16\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip64/label") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "abc\n"
it "fails when MockGpioChips overlap" $ do
evalSysfsMockME (readFile "/sys/class/gpio/gpiochip16/ngpio") initialMockWorld [chip0, chip16, invalidChip32] `shouldBe` Left (Just $ GpioChipOverlap $ Pin 47)
| null | https://raw.githubusercontent.com/dhess/hpio/27004ef379db5d35e240222d6ba4cf91da9ec14d/test/Test/System/GPIO/Linux/Sysfs/MockSpec.hs | haskell | # LANGUAGE OverloadedStrings #
Note: most interesting cases are already checked by the
tests in 'SysfsGpioMockSpec.hs' and it would be a bit silly
to try to test them here due to the amount of setup
required to get the filesystem into the necessary state.
(We would basically end up rewriting large chunks of the
See notes for 'readFile'
above. | # OPTIONS_GHC -fno - warn - incomplete - patterns -fno - warn - incomplete - uni - patterns #
module Test.System.GPIO.Linux.Sysfs.MockSpec (spec) where
import Protolude hiding (readFile, writeFile)
import GHC.IO.Exception (IOErrorType(..))
import System.GPIO.Linux.Sysfs.Mock
import System.GPIO.Types (Pin(..), PinValue(..))
import System.IO.Error
(IOError, ioeGetErrorType, isDoesNotExistError, isPermissionError)
import Test.Hspec
isInappropriateTypeErrorType :: IOErrorType -> Bool
isInappropriateTypeErrorType InappropriateType = True
isInappropriateTypeErrorType _ = False
isInappropriateTypeError :: IOError -> Bool
isInappropriateTypeError = isInappropriateTypeErrorType . ioeGetErrorType
evalSysfsMock' :: SysfsMock a -> MockWorld -> [MockGpioChip] -> Either (Maybe IOError) a
evalSysfsMock' a w c = either (Left . fromException) Right $ evalSysfsMock a w c
evalSysfsMockME :: SysfsMock a -> MockWorld -> [MockGpioChip] -> Either (Maybe MockFSException) a
evalSysfsMockME a w c = either (Left . fromException) Right $ evalSysfsMock a w c
execSysfsMock' :: SysfsMock a -> MockWorld -> [MockGpioChip] -> Either (Maybe IOError) MockWorld
execSysfsMock' a w c = either (Left . fromException) Right $ execSysfsMock a w c
spec :: Spec
spec =
do
describe "MockPinState" $ do
it "logicalValue returns the correct pin value" $
let pinState = defaultMockPinState {_value = Low, _activeLow = False}
in do
logicalValue pinState `shouldBe` Low
logicalValue (pinState {_value = High}) `shouldBe` High
logicalValue (pinState {_activeLow = True}) `shouldBe` High
logicalValue (pinState {_value = High, _activeLow = True}) `shouldBe` Low
it "setLogicalValue sets the correct pin value" $
let pinState = defaultMockPinState {_value = Low, _activeLow = False}
activeLowPinState = defaultMockPinState {_value = Low, _activeLow = True}
in do
setLogicalValue Low pinState `shouldBe` pinState
setLogicalValue High pinState `shouldBe` pinState {_value = High}
setLogicalValue Low activeLowPinState `shouldBe` activeLowPinState {_value = High}
setLogicalValue High activeLowPinState `shouldBe` activeLowPinState {_value = Low}
describe "SysfsMockT" $ do
context "doesDirectoryExist" $ do
it "relative paths are relative to the initial zipper's working directory" $ do
evalSysfsMock' (doesDirectoryExist "sys/class/gpio") initialMockWorld [] `shouldBe` Right True
it "absolute paths work regardless of the initial zipper's working directory" $ do
evalSysfsMock' (doesDirectoryExist "/sys/class/gpio") initialMockWorld [] `shouldBe` Right True
it "doesn't change the initial zipper's state" $ do
execSysfsMock' (doesDirectoryExist "/sys/class/gpio") initialMockWorld [] `shouldBe` Right initialMockWorld
it "returns False on files" $ do
evalSysfsMock' (doesDirectoryExist "/sys/class/gpio/export") initialMockWorld [] `shouldBe` Right False
it "returns False on non-existent names" $ do
evalSysfsMock' (doesDirectoryExist "/sys/class/foobar") initialMockWorld [] `shouldBe` Right False
context "doesFileExist" $ do
it "relative paths are relative to the initial zipper's working directory" $ do
evalSysfsMock' (doesFileExist "sys/class/gpio/export") initialMockWorld [] `shouldBe` Right True
it "absolute paths work regardless of the initial zipper's working directory" $ do
evalSysfsMock' (doesFileExist "/sys/class/gpio/export") initialMockWorld [] `shouldBe` Right True
it "doesn't change the initial zipper's state" $ do
execSysfsMock' (doesFileExist "/sys/class/gpio/export") initialMockWorld [] `shouldBe` Right initialMockWorld
it "returns False on directories" $ do
evalSysfsMock' (doesFileExist "/sys/class/gpio") initialMockWorld [] `shouldBe` Right False
it "returns False on non-existent names" $ do
evalSysfsMock' (doesFileExist "/sys/class/foobar") initialMockWorld [] `shouldBe` Right False
context "getDirectoryContents" $ do
it "relative paths are relative to the initial zipper's working directory" $ do
fmap sort (evalSysfsMock' (getDirectoryContents "sys/class") initialMockWorld []) `shouldBe` Right ["gpio"]
fmap sort (evalSysfsMock' (getDirectoryContents "sys/class/gpio") initialMockWorld []) `shouldBe` (Right $ sort ["export", "unexport"])
it "absolute paths work regardless of the initial zipper's working directory" $ do
fmap sort (evalSysfsMock' (getDirectoryContents "/sys/class") initialMockWorld []) `shouldBe` Right ["gpio"]
fmap sort (evalSysfsMock' (getDirectoryContents "/sys/class/gpio") initialMockWorld []) `shouldBe` (Right $ sort ["export", "unexport"])
it "doesn't change the initial zipper's state" $ do
execSysfsMock' (getDirectoryContents "/sys/class/gpio") initialMockWorld [] `shouldBe` Right initialMockWorld
it "returns failure on files" $ do
do let Left (Just result) = evalSysfsMock' (getDirectoryContents "/sys/class/gpio/export") initialMockWorld []
isInappropriateTypeError result `shouldBe` True
it "returns failure on non-existent names" $ do
do let Left (Just result) = evalSysfsMock' (getDirectoryContents "/sys/class/foobar") initialMockWorld []
isDoesNotExistError result `shouldBe` True
context "readFile" $ do
mock GPIO code . )
it "works with 'constant' files" $
let chip0 = MockGpioChip "chip0" 0 (replicate 16 defaultMockPinState)
in evalSysfsMock' (readFile "/sys/class/gpio/gpiochip0/base") initialMockWorld [chip0] `shouldBe` Right "0\n"
it "fails on /sys/class/gpio/export" $
do let Left (Just result) = evalSysfsMock' (readFile "/sys/class/gpio/export") initialMockWorld []
isPermissionError result `shouldBe` True
it "fails on /sys/class/gpio/unexport" $
do let Left (Just result) = evalSysfsMock' (readFile "/sys/class/gpio/unexport") initialMockWorld []
isPermissionError result `shouldBe` True
it "fails on non-existent file" $
do let Left (Just result) = evalSysfsMock' (readFile "/sys/class/gpio/foo") initialMockWorld []
isDoesNotExistError result `shouldBe` True
it "fails on a directory" $
do let Left (Just result) = evalSysfsMock' (readFile "/sys/class/gpio") initialMockWorld []
isInappropriateTypeError result `shouldBe` True
context "writeFile" $
it "does the right thing" $
context "runSysfsMockT" $ do
let chip0 = MockGpioChip "chip0" 0 (replicate 16 defaultMockPinState)
chip16 = MockGpioChip "xyz" 16 (replicate 32 defaultMockPinState)
chip64 = MockGpioChip "abc" 64 (replicate 16 defaultMockPinState)
invalidChip32 = MockGpioChip "invalid" 32 (replicate 16 defaultMockPinState)
it "creates the specified gpiochip directories" $ do
fmap sort (evalSysfsMock' (getDirectoryContents "/sys/class/gpio") initialMockWorld [chip0, chip16, chip64]) `shouldBe` Right ["export", "gpiochip0", "gpiochip16", "gpiochip64", "unexport"]
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip0/base") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "0\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip0/ngpio") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "16\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip0/label") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "chip0\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip16/base") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "16\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip16/ngpio") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "32\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip16/label") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "xyz\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip64/base") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "64\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip64/ngpio") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "16\n"
evalSysfsMock' (readFile "/sys/class/gpio/gpiochip64/label") initialMockWorld [chip0, chip16, chip64] `shouldBe` Right "abc\n"
it "fails when MockGpioChips overlap" $ do
evalSysfsMockME (readFile "/sys/class/gpio/gpiochip16/ngpio") initialMockWorld [chip0, chip16, invalidChip32] `shouldBe` Left (Just $ GpioChipOverlap $ Pin 47)
|
b67bd5de39fd605e5f1ffb5ad54d62e749b85ab5f0160dc5a61324e590029a5b | bsansouci/reasonglexampleproject | jpgmark.ml | (***********************************************************************)
(* *)
CamlImages
(* *)
(* Jun Furuse *)
(* *)
Copyright 1999 - 2013 ,
(* *)
(***********************************************************************)
$ I d : test.ml , v 1.32.2.1 2010/05/13 13:14:47 furuse Exp $
let dump path =
Format.eprintf "File: %s@." path;
let markers = Jpeg.read_markers path in
prerr_endline "markers loaded";
List.iter (fun t ->
Format.eprintf " %a@." Jpeg.Marker.format t)
markers
let images =
let images = ref [] in
Arg.parse [] (fun x -> images := x :: !images) "test images";
List.rev !images
let main () =
try
for _i = 0 to 10000 do
List.iter dump images
done
with
| Exit -> exit 0
| End_of_file -> exit 0
| Sys.Break -> exit 2
let () = main ()
| null | https://raw.githubusercontent.com/bsansouci/reasonglexampleproject/4ecef2cdad3a1a157318d1d64dba7def92d8a924/vendor/camlimages/test/jpgmark.ml | ocaml | *********************************************************************
Jun Furuse
********************************************************************* | CamlImages
Copyright 1999 - 2013 ,
$ I d : test.ml , v 1.32.2.1 2010/05/13 13:14:47 furuse Exp $
let dump path =
Format.eprintf "File: %s@." path;
let markers = Jpeg.read_markers path in
prerr_endline "markers loaded";
List.iter (fun t ->
Format.eprintf " %a@." Jpeg.Marker.format t)
markers
let images =
let images = ref [] in
Arg.parse [] (fun x -> images := x :: !images) "test images";
List.rev !images
let main () =
try
for _i = 0 to 10000 do
List.iter dump images
done
with
| Exit -> exit 0
| End_of_file -> exit 0
| Sys.Break -> exit 2
let () = main ()
|
6d02fbc176cb36d0dbbbb2a2471a0da4b67a03b56e6b4c45267818c62f9d3799 | metabase/metabase | expressions_test.clj | (ns metabase.query-processor-test.expressions-test
"Tests for expressions (calculated columns)."
(:require
[clojure.test :refer :all]
[java-time :as t]
[medley.core :as m]
[metabase.driver :as driver]
[metabase.models.field :refer [Field]]
[metabase.query-processor :as qp]
[metabase.test :as mt]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[toucan.db :as db]))
(deftest basic-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Do a basic query including an expression"
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 5.0]
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 4.0]
[3 "The Apple Pan" 11 34.0406 -118.428 2 4.0]
[4 "Wurstküche" 29 33.9997 -118.465 2 4.0]
[5 "Brite Spot Family Restaurant" 20 34.0778 -118.261 2 4.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:my_cool_new_field [:+ $price 2]}
:limit 5
:order-by [[:asc $id]]})))))))
(deftest floating-point-division-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Make sure FLOATING POINT division is done"
3 / 2 SHOULD BE 1.5 , NOT 1 ( ! )
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 1.0]
[3 "The Apple Pan" 11 34.0406 -118.428 2 1.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:my_cool_new_field [:/ $price 2]}
:limit 3
:order-by [[:asc $id]]})))))
(testing "Make sure FLOATING POINT division is done when dividing by expressions/fields"
(is (= [[0.6]
[0.5]
[0.5]]
(mt/formatted-rows [1.0]
(mt/run-mbql-query venues
{:expressions {:big_price [:+ $price 2]
:my_cool_new_field [:/ $price [:expression "big_price"]]}
:fields [[:expression "my_cool_new_field"]]
:limit 3
:order-by [[:asc $id]]})))))))
(deftest nested-expressions-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we do NESTED EXPRESSIONS ?"
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 3.0]
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 2.0]
[3 "The Apple Pan" 11 34.0406 -118.428 2 2.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:wow [:- [:* $price 2] [:+ $price 0]]}
:limit 3
:order-by [[:asc $id]]})))))))
(deftest multiple-expressions-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we have MULTIPLE EXPRESSIONS?"
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 2.0 4.0]
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 1.0 3.0]
[3 "The Apple Pan" 11 34.0406 -118.428 2 1.0 3.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float float]
(mt/run-mbql-query venues
{:expressions {:x [:- $price 1]
:y [:+ $price 1]}
:limit 3
:order-by [[:asc $id]]})))))))
(deftest expressions-in-fields-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we refer to expressions inside a FIELDS clause?"
(is (= [[4] [4] [5]]
(mt/formatted-rows [int]
(mt/run-mbql-query venues
{:expressions {:x [:+ $price $id]}
:fields [[:expression :x]]
:limit 3
:order-by [[:asc $id]]})))))))
(deftest dont-return-expressions-if-fields-is-explicit-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
;; bigquery doesn't let you have hypthens in field, table, etc names
(let [priceplusone (if (= driver/*driver* :bigquery-cloud-sdk) "price_plus_1" "Price + 1")
oneplusone (if (= driver/*driver* :bigquery-cloud-sdk) "one_plus_one" "1 + 1")
query (mt/mbql-query venues
{:expressions {priceplusone [:+ $price 1]
oneplusone [:+ 1 1]}
:fields [$price [:expression oneplusone]]
:order-by [[:asc $id]]
:limit 3})]
(testing "If an explicit `:fields` clause is present, expressions *not* in that clause should not come back"
(is (= [[3 2] [2 2] [2 2]]
(mt/formatted-rows [int int]
(qp/process-query query)))))
(testing "If `:fields` is not explicit, then return all the expressions"
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 4 2]
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 3 2]
[3 "The Apple Pan" 11 34.0406 -118.428 2 3 2]]
(mt/formatted-rows [int str int 4.0 4.0 int int int]
(qp/process-query (m/dissoc-in query [:query :fields]))))))
(testing "When aggregating, expressions that aren't used shouldn't come back"
(is (= [[2 22] [3 59] [4 13]]
(mt/formatted-rows [int int]
(mt/run-mbql-query venues
{:expressions {priceplusone [:+ $price 1]
oneplusone [:+ 1 1]}
:aggregation [:count]
:breakout [[:expression priceplusone]]
:order-by [[:asc [:expression priceplusone]]]
:limit 3}))))))))
(deftest expressions-in-order-by-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we refer to expressions inside an ORDER BY clause?"
(is (= [[100 "Mohawk Bend" 46 34.0777 -118.265 2 102.0]
[99 "Golden Road Brewing" 10 34.1505 -118.274 2 101.0]
[98 "Lucky Baldwin's Pub" 7 34.1454 -118.149 2 100.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:x [:+ $price $id]}
:limit 3
:order-by [[:desc [:expression :x]]]})))))
(testing "Can we refer to expressions inside an ORDER BY clause with a secondary order by?"
(is (= [[81 "Tanoshi Sushi & Sake Bar" 40 40.7677 -73.9533 4 85.0]
[79 "Sushi Yasuda" 40 40.7514 -73.9736 4 83.0]
[77 "Sushi Nakazawa" 40 40.7318 -74.0045 4 81.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:x [:+ $price $id]}
:limit 3
:order-by [[:desc $price] [:desc [:expression :x]]]})))))))
(deftest aggregate-breakout-expression-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we AGGREGATE + BREAKOUT by an EXPRESSION?"
(is (= [[2 22] [4 59] [6 13] [8 6]]
(mt/formatted-rows [int int]
(mt/run-mbql-query venues
{:expressions {:x [:* $price 2.0]}
:aggregation [[:count]]
:breakout [[:expression :x]]})))))))
(deftest expressions-should-include-type-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Custom aggregation expressions should include their type"
(let [cols (mt/cols
(mt/run-mbql-query venues
{:aggregation [[:aggregation-options [:sum [:* $price -1]] {:name "x"}]]
:breakout [$category_id]}))]
(testing (format "cols = %s" (u/pprint-to-str cols))
(is (= #{"x" (mt/format-name "category_id")}
(set (map :name cols))))
(let [name->base-type (into {} (map (juxt :name :base_type) cols))]
(testing "x"
(is (isa? (name->base-type "x")
:type/Number)))
(testing "category_id"
(is (isa? (name->base-type (mt/format-name "category_id"))
:type/Number)))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | HANDLING NULLS AND ZEROES |
;;; +----------------------------------------------------------------------------------------------------------------+
" bird scarcity " is a scientific metric based on the number of birds seen in a given day
;; (at least for the purposes of the tests below)
;;
e.g. scarcity = 100.0 / num - birds
(defn- calculate-bird-scarcity* [formula filter-clause]
(mt/formatted-rows [2.0]
(mt/dataset daily-bird-counts
(mt/run-mbql-query bird-count
{:expressions {"bird-scarcity" formula}
:fields [[:expression "bird-scarcity"]]
:filter filter-clause
:order-by [[:asc $date]]
:limit 10}))))
(defmacro ^:private calculate-bird-scarcity [formula & [filter-clause]]
`(mt/dataset ~'daily-bird-counts
(mt/$ids ~'bird-count
(calculate-bird-scarcity* ~formula ~filter-clause))))
(deftest ^:parallel nulls-and-zeroes-test
(mt/test-drivers (disj (mt/normal-drivers-with-feature :expressions)
;; bigquery doesn't let you have hypthens in field, table, etc names
;; therefore a different macro is tested in bigquery driver tests
:bigquery-cloud-sdk)
(testing (str "hey... expressions should work if they are just a Field! (Also, this lets us take a peek at the "
"raw values being used to calculate the formulas below, so we can tell at a glance if they're right "
"without referring to the EDN def)")
(is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]]
(calculate-bird-scarcity $count))))
(testing (str "do expressions automatically handle division by zero? Should return `nil` "
"in the results for places where that was attempted")
(is (= [[nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [9.09] [7.14]]
(calculate-bird-scarcity [:/ 100.0 $count]
[:!= $count nil]))))
(testing (str "do expressions handle division by `nil`? Should return `nil` in the results for places where that "
"was attempted")
(is (= [[nil] [10.0] [12.5] [20.0] [20.0] [nil] [9.09] [7.14] [12.5] [7.14]]
(calculate-bird-scarcity [:/ 100.0 $count]
[:or
[:= $count nil]
[:!= $count 0]]))))
(testing "can we handle BOTH NULLS AND ZEROES AT THE SAME TIME????"
(is (= [[nil] [nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [nil]]
(calculate-bird-scarcity [:/ 100.0 $count]))))
(testing "can we handle dividing by literal 0?"
(is (= [[nil] [nil] [nil] [nil] [nil] [nil] [nil] [nil] [nil] [nil]]
(calculate-bird-scarcity [:/ $count 0]))))
(testing "ok, what if we use multiple args to divide, and more than one is zero?"
(is (= [[nil] [nil] [nil] [1.0] [1.56] [4.0] [4.0] [nil] [nil] [nil]]
(calculate-bird-scarcity [:/ 100.0 $count $count]))))
(testing "are nulls/zeroes still handled appropriately when nested inside other expressions?"
(is (= [[nil] [nil] [nil] [20.0] [25.0] [40.0] [40.0] [nil] [nil] [nil]]
(calculate-bird-scarcity [:* [:/ 100.0 $count] 2]))))
(testing (str "if a zero is present in the NUMERATOR we should return ZERO and not NULL "
"(`0 / 10 = 0`; `10 / 0 = NULL`, at least as far as MBQL is concerned)")
(is (= [[nil] [0.0] [0.0] [1.0] [0.8] [0.5] [0.5] [nil] [0.0] [0.0]]
(calculate-bird-scarcity [:/ $count 10]))))
(testing "can addition handle nulls & zeroes?"
(is (= [[nil] [10.0] [10.0] [20.0] [18.0] [15.0] [15.0] [nil] [10.0] [10.0]]
(calculate-bird-scarcity [:+ $count 10]))))
(testing "can subtraction handle nulls & zeroes?"
(is (= [[nil] [10.0] [10.0] [0.0] [2.0] [5.0] [5.0] [nil] [10.0] [10.0]]
(calculate-bird-scarcity [:- 10 $count]))))
(testing "can multiplications handle nulls & zeros?"
(is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]]
(calculate-bird-scarcity [:* 1 $count]))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | DATETIME EXTRACTION AND MANIPULATION |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- robust-dates
[strs]
TIMEZONE FIXME — SQLite should n't return strings .
(let [format-fn (if (= driver/*driver* :sqlite)
#(u.date/format-sql (t/local-date-time %))
u.date/format)]
(for [s strs]
[(format-fn (u.date/parse s "UTC"))])))
(deftest temporal-arithmetic-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions :date-arithmetics)
(testing "Test that we can do datetime arithemtics using MBQL `:interval` clause in expressions"
(is (= (robust-dates
["2014-09-02T13:45:00"
"2014-07-02T09:30:00"
"2014-07-01T10:30:00"])
(mt/with-temporary-setting-values [report-timezone "UTC"]
(-> (mt/run-mbql-query users
{:expressions {:prev_month [:+ $last_login [:interval -31 :day]]}
:fields [[:expression :prev_month]]
:limit 3
:order-by [[:asc $name]]})
mt/rows)))))
(testing "Test interaction of datetime arithmetics with truncation"
(is (= (robust-dates
["2014-09-02T00:00:00"
"2014-07-02T00:00:00"
"2014-07-01T00:00:00"])
(mt/with-temporary-setting-values [report-timezone "UTC"]
(-> (mt/run-mbql-query users
{:expressions {:prev_month [:+ !day.last_login [:interval -31 :day]]}
:fields [[:expression :prev_month]]
:limit 3
:order-by [[:asc $name]]})
mt/rows)))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | JOINS |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest expressions+joins-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions :left-join :date-arithmetics)
(testing "Do calculated columns play well with joins"
(is (= "Simcha Yan"
(-> (mt/run-mbql-query checkins
{:expressions {:prev_month [:+ $date [:interval -31 :day]]}
:fields [[:field (mt/id :users :name) {:join-alias "users__via__user_id"}]
[:expression :prev_month]]
:limit 1
:order-by [[:asc $date]]
:joins [{:strategy :left-join
:source-table (mt/id :users)
:alias "users__via__user_id"
:condition [:=
$user_id
[:field (mt/id :users :id) {:join-alias "users__via__user_id"}]]}]})
mt/rows
ffirst))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | MISC BUG FIXES |
;;; +----------------------------------------------------------------------------------------------------------------+
;; need more fields than seq chunking size
(defrecord ^:private NoLazinessDatasetDefinition [num-fields])
(defn- no-laziness-dataset-definition-field-names [num-fields]
(for [i (range num-fields)]
(format "field_%04d" i)))
(defmethod mt/get-dataset-definition NoLazinessDatasetDefinition
[{:keys [num-fields]}]
(mt/dataset-definition
(format "no-laziness-%d" num-fields)
["lots-of-fields"
(concat
[{:field-name "a", :base-type :type/Integer}
{:field-name "b", :base-type :type/Integer}]
(for [field (no-laziness-dataset-definition-field-names num-fields)]
{:field-name (name field), :base-type :type/Integer}))
one row
[(range (+ num-fields 2))]]))
(defn- no-laziness-dataset-definition [num-fields]
(->NoLazinessDatasetDefinition num-fields))
;; Make sure no part of query compilation is lazy as that won't play well with dynamic bindings.
;; This is not an issue limited to expressions, but using expressions is the most straightforward
;; way to reproducing it.
(deftest no-lazyness-test
Sometimes Kondo thinks this is unused , depending on the state of the cache -- see comments in
;; [[hooks.metabase.test.data]] for more information. It's definitely used to.
#_{:clj-kondo/ignore [:unused-binding]}
(let [dataset-def (no-laziness-dataset-definition 300)]
(mt/dataset dataset-def
(let [query (mt/mbql-query lots-of-fields
{:expressions {:c [:+
[:field (mt/id :lots-of-fields :a) nil]
[:field (mt/id :lots-of-fields :b) nil]]}
:fields (into [[:expression "c"]]
(for [{:keys [id]} (db/select [Field :id]
:table_id (mt/id :lots-of-fields)
:id [:not-in #{(mt/id :lots-of-fields :a)
(mt/id :lots-of-fields :b)}]
{:order-by [[:name :asc]]})]
[:field id nil]))})]
(db/with-call-counting [call-count-fn]
(mt/with-native-query-testing-context query
(is (= 1
(-> (qp/process-query query) mt/rows ffirst))))
(testing "# of app DB calls should not be some insane number"
(is (< (call-count-fn) 20))))))))
(deftest expression-with-slashes
(mt/test-drivers (disj
(mt/normal-drivers-with-feature :expressions)
Slashes documented as not allowed in BQ
;; -sql/lexical
:bigquery-cloud-sdk)
(testing "Make sure an expression with a / in its name works (#12305)"
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 4.0]
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 3.0]
[3 "The Apple Pan" 11 34.0406 -118.428 2 3.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:TEST/my-cool-new-field [:+ $price 1]}
:limit 3
:order-by [[:asc $id]]})))))))
(deftest expression-using-aggregation-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we use aggregations from previous steps in expressions (#12762)"
(is (= [["20th Century Cafe" 2 2 0]
[ "25°" 2 2 0]
["33 Taps" 2 2 0]]
(mt/formatted-rows [str int int int]
(mt/run-mbql-query venues
{:source-query {:source-table (mt/id :venues)
:aggregation [[:min (mt/id :venues :price)]
[:max (mt/id :venues :price)]]
:breakout [[:field (mt/id :venues :name) nil]]
:limit 3}
:expressions {:price_range [:-
[:field "max" {:base-type :type/Number}]
[:field "min" {:base-type :type/Number}]]}})))))))
(deftest expression-with-duplicate-column-name
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we use expression with same column name as table (#14267)"
(mt/dataset sample-dataset
(let [query (mt/mbql-query products
{:expressions {:CATEGORY [:concat $category "2"]}
:breakout [:expression :CATEGORY]
:aggregation [:count]
:order-by [[:asc [:expression :CATEGORY]]]
:limit 1})]
(mt/with-native-query-testing-context query
(is (= [["Doohickey2" 42]]
(mt/formatted-rows [str int]
(qp/process-query query))))))))))
(deftest fk-field-and-duplicate-names-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions :foreign-keys)
(testing "Expressions with `fk->` fields and duplicate names should work correctly (#14854)"
(mt/dataset sample-dataset
(let [results (mt/run-mbql-query orders
{:expressions {"CE" [:case
[[[:> $discount 0] $created_at]]
{:default $product_id->products.created_at}]}
:order-by [[:asc $id]]
:limit 2})]
(is (= ["ID" "User ID" "Product ID" "Subtotal" "Tax" "Total" "Discount" "Created At" "Quantity" "CE"]
(map :display_name (mt/cols results))))
(is (= [[1 1 14 37.7 2.1 39.7 nil "2019-02-11T21:40:27.892Z" 2 "2017-12-31T14:41:56.87Z"]
[2 1 123 110.9 6.1 117.0 nil "2018-05-15T08:04:04.58Z" 3 "2017-11-16T13:53:14.232Z"]]
(mt/formatted-rows [int int int 1.0 1.0 1.0 identity str int str]
results))))))))
(deftest string-operations-from-subquery
(mt/test-drivers (mt/normal-drivers-with-feature :expressions :regex)
(testing "regex-match-first and replace work when evaluated against a subquery (#14873)"
(mt/dataset test-data
(let [r-word "r_word"
no-sp "no_spaces"
results (mt/run-mbql-query venues
{:expressions {r-word [:regex-match-first $name "^R[^ ]+"]
no-sp [:replace $name " " ""]}
:source-query {:source-table $$venues}
:fields [$name [:expression r-word] [:expression no-sp]]
:filter [:= $id 1 95]
:order-by [[:asc $id]]})]
(is (= ["Name" r-word no-sp]
(map :display_name (mt/cols results))))
(is (= [["Red Medicine" "Red" "RedMedicine"]
["Rush Street" "Rush" "RushStreet"]]
(mt/formatted-rows [str str str] results))))))))
(deftest expression-name-weird-characters-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "An expression whose name contains weird characters works properly"
(let [query (mt/mbql-query venues
{:expressions {"Refund Amount (?)" [:* $price -1]}
:limit 1
:order-by [[:asc $id]]})]
(mt/with-native-query-testing-context query
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 -3]]
(mt/formatted-rows [int str int 4.0 4.0 int int]
(qp/process-query query)))))))))
(deftest join-table-on-itself-with-custom-column-test
(testing "Should be able to join a source query against itself using an expression (#17770)"
(mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :expressions :left-join)
(mt/dataset sample-dataset
(let [query (mt/mbql-query nil
{:source-query {:source-query {:source-table $$products
:aggregation [[:count]]
:breakout [$products.category]}
:expressions {:CC [:+ 1 1]}}
:joins [{:source-query {:source-query {:source-table $$products
:aggregation [[:count]]
:breakout [$products.category]}
:expressions {:CC [:+ 1 1]}}
:alias "Q1"
:condition [:=
[:field "CC" {:base-type :type/Integer}]
[:field "CC" {:base-type :type/Integer, :join-alias "Q1"}]]
:fields :all}]
:order-by [[:asc $products.category]
[:desc [:field "count" {:base-type :type/Integer}]]
[:asc &Q1.products.category]]
:limit 1})]
(mt/with-native-query-testing-context query
source.category , source.count , source . CC , Q1.category , Q1.count ,
(is (= [["Doohickey" 42 2 "Doohickey" 42 2]]
(mt/formatted-rows [str int int str int int]
(qp/process-query query))))))))))
(deftest nested-expressions-with-existing-names-test
(testing "Expressions with the same name as existing columns should work correctly in nested queries (#21131)"
(mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :expressions)
(mt/dataset sample-dataset
(doseq [expression-name ["PRICE" "price"]]
(testing (format "Expression name = %s" (pr-str expression-name))
(let [query (mt/mbql-query products
{:source-query {:source-table $$products
:expressions {expression-name [:+ $price 2]}
:fields [$id $price [:expression expression-name]]
:order-by [[:asc $id]]
:limit 2}})]
(mt/with-native-query-testing-context query
(is (= [[1 29.46 31.46] [2 70.08 72.08]]
(mt/formatted-rows [int 2.0 2.0]
(qp/process-query query))))))))))))
| null | https://raw.githubusercontent.com/metabase/metabase/32854d3cb630cc406ab251e55d3688c3c8c1509f/test/metabase/query_processor_test/expressions_test.clj | clojure | bigquery doesn't let you have hypthens in field, table, etc names
+----------------------------------------------------------------------------------------------------------------+
| HANDLING NULLS AND ZEROES |
+----------------------------------------------------------------------------------------------------------------+
(at least for the purposes of the tests below)
bigquery doesn't let you have hypthens in field, table, etc names
therefore a different macro is tested in bigquery driver tests
+----------------------------------------------------------------------------------------------------------------+
| DATETIME EXTRACTION AND MANIPULATION |
+----------------------------------------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------------------------------------+
| JOINS |
+----------------------------------------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------------------------------------+
| MISC BUG FIXES |
+----------------------------------------------------------------------------------------------------------------+
need more fields than seq chunking size
Make sure no part of query compilation is lazy as that won't play well with dynamic bindings.
This is not an issue limited to expressions, but using expressions is the most straightforward
way to reproducing it.
[[hooks.metabase.test.data]] for more information. It's definitely used to.
-sql/lexical | (ns metabase.query-processor-test.expressions-test
"Tests for expressions (calculated columns)."
(:require
[clojure.test :refer :all]
[java-time :as t]
[medley.core :as m]
[metabase.driver :as driver]
[metabase.models.field :refer [Field]]
[metabase.query-processor :as qp]
[metabase.test :as mt]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[toucan.db :as db]))
(deftest basic-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Do a basic query including an expression"
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 5.0]
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 4.0]
[3 "The Apple Pan" 11 34.0406 -118.428 2 4.0]
[4 "Wurstküche" 29 33.9997 -118.465 2 4.0]
[5 "Brite Spot Family Restaurant" 20 34.0778 -118.261 2 4.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:my_cool_new_field [:+ $price 2]}
:limit 5
:order-by [[:asc $id]]})))))))
(deftest floating-point-division-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Make sure FLOATING POINT division is done"
3 / 2 SHOULD BE 1.5 , NOT 1 ( ! )
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 1.0]
[3 "The Apple Pan" 11 34.0406 -118.428 2 1.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:my_cool_new_field [:/ $price 2]}
:limit 3
:order-by [[:asc $id]]})))))
(testing "Make sure FLOATING POINT division is done when dividing by expressions/fields"
(is (= [[0.6]
[0.5]
[0.5]]
(mt/formatted-rows [1.0]
(mt/run-mbql-query venues
{:expressions {:big_price [:+ $price 2]
:my_cool_new_field [:/ $price [:expression "big_price"]]}
:fields [[:expression "my_cool_new_field"]]
:limit 3
:order-by [[:asc $id]]})))))))
(deftest nested-expressions-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we do NESTED EXPRESSIONS ?"
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 3.0]
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 2.0]
[3 "The Apple Pan" 11 34.0406 -118.428 2 2.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:wow [:- [:* $price 2] [:+ $price 0]]}
:limit 3
:order-by [[:asc $id]]})))))))
(deftest multiple-expressions-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we have MULTIPLE EXPRESSIONS?"
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 2.0 4.0]
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 1.0 3.0]
[3 "The Apple Pan" 11 34.0406 -118.428 2 1.0 3.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float float]
(mt/run-mbql-query venues
{:expressions {:x [:- $price 1]
:y [:+ $price 1]}
:limit 3
:order-by [[:asc $id]]})))))))
(deftest expressions-in-fields-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we refer to expressions inside a FIELDS clause?"
(is (= [[4] [4] [5]]
(mt/formatted-rows [int]
(mt/run-mbql-query venues
{:expressions {:x [:+ $price $id]}
:fields [[:expression :x]]
:limit 3
:order-by [[:asc $id]]})))))))
(deftest dont-return-expressions-if-fields-is-explicit-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(let [priceplusone (if (= driver/*driver* :bigquery-cloud-sdk) "price_plus_1" "Price + 1")
oneplusone (if (= driver/*driver* :bigquery-cloud-sdk) "one_plus_one" "1 + 1")
query (mt/mbql-query venues
{:expressions {priceplusone [:+ $price 1]
oneplusone [:+ 1 1]}
:fields [$price [:expression oneplusone]]
:order-by [[:asc $id]]
:limit 3})]
(testing "If an explicit `:fields` clause is present, expressions *not* in that clause should not come back"
(is (= [[3 2] [2 2] [2 2]]
(mt/formatted-rows [int int]
(qp/process-query query)))))
(testing "If `:fields` is not explicit, then return all the expressions"
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 4 2]
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 3 2]
[3 "The Apple Pan" 11 34.0406 -118.428 2 3 2]]
(mt/formatted-rows [int str int 4.0 4.0 int int int]
(qp/process-query (m/dissoc-in query [:query :fields]))))))
(testing "When aggregating, expressions that aren't used shouldn't come back"
(is (= [[2 22] [3 59] [4 13]]
(mt/formatted-rows [int int]
(mt/run-mbql-query venues
{:expressions {priceplusone [:+ $price 1]
oneplusone [:+ 1 1]}
:aggregation [:count]
:breakout [[:expression priceplusone]]
:order-by [[:asc [:expression priceplusone]]]
:limit 3}))))))))
(deftest expressions-in-order-by-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we refer to expressions inside an ORDER BY clause?"
(is (= [[100 "Mohawk Bend" 46 34.0777 -118.265 2 102.0]
[99 "Golden Road Brewing" 10 34.1505 -118.274 2 101.0]
[98 "Lucky Baldwin's Pub" 7 34.1454 -118.149 2 100.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:x [:+ $price $id]}
:limit 3
:order-by [[:desc [:expression :x]]]})))))
(testing "Can we refer to expressions inside an ORDER BY clause with a secondary order by?"
(is (= [[81 "Tanoshi Sushi & Sake Bar" 40 40.7677 -73.9533 4 85.0]
[79 "Sushi Yasuda" 40 40.7514 -73.9736 4 83.0]
[77 "Sushi Nakazawa" 40 40.7318 -74.0045 4 81.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:x [:+ $price $id]}
:limit 3
:order-by [[:desc $price] [:desc [:expression :x]]]})))))))
(deftest aggregate-breakout-expression-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we AGGREGATE + BREAKOUT by an EXPRESSION?"
(is (= [[2 22] [4 59] [6 13] [8 6]]
(mt/formatted-rows [int int]
(mt/run-mbql-query venues
{:expressions {:x [:* $price 2.0]}
:aggregation [[:count]]
:breakout [[:expression :x]]})))))))
(deftest expressions-should-include-type-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Custom aggregation expressions should include their type"
(let [cols (mt/cols
(mt/run-mbql-query venues
{:aggregation [[:aggregation-options [:sum [:* $price -1]] {:name "x"}]]
:breakout [$category_id]}))]
(testing (format "cols = %s" (u/pprint-to-str cols))
(is (= #{"x" (mt/format-name "category_id")}
(set (map :name cols))))
(let [name->base-type (into {} (map (juxt :name :base_type) cols))]
(testing "x"
(is (isa? (name->base-type "x")
:type/Number)))
(testing "category_id"
(is (isa? (name->base-type (mt/format-name "category_id"))
:type/Number)))))))))
" bird scarcity " is a scientific metric based on the number of birds seen in a given day
e.g. scarcity = 100.0 / num - birds
(defn- calculate-bird-scarcity* [formula filter-clause]
(mt/formatted-rows [2.0]
(mt/dataset daily-bird-counts
(mt/run-mbql-query bird-count
{:expressions {"bird-scarcity" formula}
:fields [[:expression "bird-scarcity"]]
:filter filter-clause
:order-by [[:asc $date]]
:limit 10}))))
(defmacro ^:private calculate-bird-scarcity [formula & [filter-clause]]
`(mt/dataset ~'daily-bird-counts
(mt/$ids ~'bird-count
(calculate-bird-scarcity* ~formula ~filter-clause))))
(deftest ^:parallel nulls-and-zeroes-test
(mt/test-drivers (disj (mt/normal-drivers-with-feature :expressions)
:bigquery-cloud-sdk)
(testing (str "hey... expressions should work if they are just a Field! (Also, this lets us take a peek at the "
"raw values being used to calculate the formulas below, so we can tell at a glance if they're right "
"without referring to the EDN def)")
(is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]]
(calculate-bird-scarcity $count))))
(testing (str "do expressions automatically handle division by zero? Should return `nil` "
"in the results for places where that was attempted")
(is (= [[nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [9.09] [7.14]]
(calculate-bird-scarcity [:/ 100.0 $count]
[:!= $count nil]))))
(testing (str "do expressions handle division by `nil`? Should return `nil` in the results for places where that "
"was attempted")
(is (= [[nil] [10.0] [12.5] [20.0] [20.0] [nil] [9.09] [7.14] [12.5] [7.14]]
(calculate-bird-scarcity [:/ 100.0 $count]
[:or
[:= $count nil]
[:!= $count 0]]))))
(testing "can we handle BOTH NULLS AND ZEROES AT THE SAME TIME????"
(is (= [[nil] [nil] [nil] [10.0] [12.5] [20.0] [20.0] [nil] [nil] [nil]]
(calculate-bird-scarcity [:/ 100.0 $count]))))
(testing "can we handle dividing by literal 0?"
(is (= [[nil] [nil] [nil] [nil] [nil] [nil] [nil] [nil] [nil] [nil]]
(calculate-bird-scarcity [:/ $count 0]))))
(testing "ok, what if we use multiple args to divide, and more than one is zero?"
(is (= [[nil] [nil] [nil] [1.0] [1.56] [4.0] [4.0] [nil] [nil] [nil]]
(calculate-bird-scarcity [:/ 100.0 $count $count]))))
(testing "are nulls/zeroes still handled appropriately when nested inside other expressions?"
(is (= [[nil] [nil] [nil] [20.0] [25.0] [40.0] [40.0] [nil] [nil] [nil]]
(calculate-bird-scarcity [:* [:/ 100.0 $count] 2]))))
(testing (str "if a zero is present in the NUMERATOR we should return ZERO and not NULL "
"(`0 / 10 = 0`; `10 / 0 = NULL`, at least as far as MBQL is concerned)")
(is (= [[nil] [0.0] [0.0] [1.0] [0.8] [0.5] [0.5] [nil] [0.0] [0.0]]
(calculate-bird-scarcity [:/ $count 10]))))
(testing "can addition handle nulls & zeroes?"
(is (= [[nil] [10.0] [10.0] [20.0] [18.0] [15.0] [15.0] [nil] [10.0] [10.0]]
(calculate-bird-scarcity [:+ $count 10]))))
(testing "can subtraction handle nulls & zeroes?"
(is (= [[nil] [10.0] [10.0] [0.0] [2.0] [5.0] [5.0] [nil] [10.0] [10.0]]
(calculate-bird-scarcity [:- 10 $count]))))
(testing "can multiplications handle nulls & zeros?"
(is (= [[nil] [0.0] [0.0] [10.0] [8.0] [5.0] [5.0] [nil] [0.0] [0.0]]
(calculate-bird-scarcity [:* 1 $count]))))))
(defn- robust-dates
[strs]
TIMEZONE FIXME — SQLite should n't return strings .
(let [format-fn (if (= driver/*driver* :sqlite)
#(u.date/format-sql (t/local-date-time %))
u.date/format)]
(for [s strs]
[(format-fn (u.date/parse s "UTC"))])))
(deftest temporal-arithmetic-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions :date-arithmetics)
(testing "Test that we can do datetime arithemtics using MBQL `:interval` clause in expressions"
(is (= (robust-dates
["2014-09-02T13:45:00"
"2014-07-02T09:30:00"
"2014-07-01T10:30:00"])
(mt/with-temporary-setting-values [report-timezone "UTC"]
(-> (mt/run-mbql-query users
{:expressions {:prev_month [:+ $last_login [:interval -31 :day]]}
:fields [[:expression :prev_month]]
:limit 3
:order-by [[:asc $name]]})
mt/rows)))))
(testing "Test interaction of datetime arithmetics with truncation"
(is (= (robust-dates
["2014-09-02T00:00:00"
"2014-07-02T00:00:00"
"2014-07-01T00:00:00"])
(mt/with-temporary-setting-values [report-timezone "UTC"]
(-> (mt/run-mbql-query users
{:expressions {:prev_month [:+ !day.last_login [:interval -31 :day]]}
:fields [[:expression :prev_month]]
:limit 3
:order-by [[:asc $name]]})
mt/rows)))))))
(deftest expressions+joins-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions :left-join :date-arithmetics)
(testing "Do calculated columns play well with joins"
(is (= "Simcha Yan"
(-> (mt/run-mbql-query checkins
{:expressions {:prev_month [:+ $date [:interval -31 :day]]}
:fields [[:field (mt/id :users :name) {:join-alias "users__via__user_id"}]
[:expression :prev_month]]
:limit 1
:order-by [[:asc $date]]
:joins [{:strategy :left-join
:source-table (mt/id :users)
:alias "users__via__user_id"
:condition [:=
$user_id
[:field (mt/id :users :id) {:join-alias "users__via__user_id"}]]}]})
mt/rows
ffirst))))))
(defrecord ^:private NoLazinessDatasetDefinition [num-fields])
(defn- no-laziness-dataset-definition-field-names [num-fields]
(for [i (range num-fields)]
(format "field_%04d" i)))
(defmethod mt/get-dataset-definition NoLazinessDatasetDefinition
[{:keys [num-fields]}]
(mt/dataset-definition
(format "no-laziness-%d" num-fields)
["lots-of-fields"
(concat
[{:field-name "a", :base-type :type/Integer}
{:field-name "b", :base-type :type/Integer}]
(for [field (no-laziness-dataset-definition-field-names num-fields)]
{:field-name (name field), :base-type :type/Integer}))
one row
[(range (+ num-fields 2))]]))
(defn- no-laziness-dataset-definition [num-fields]
(->NoLazinessDatasetDefinition num-fields))
(deftest no-lazyness-test
Sometimes Kondo thinks this is unused , depending on the state of the cache -- see comments in
#_{:clj-kondo/ignore [:unused-binding]}
(let [dataset-def (no-laziness-dataset-definition 300)]
(mt/dataset dataset-def
(let [query (mt/mbql-query lots-of-fields
{:expressions {:c [:+
[:field (mt/id :lots-of-fields :a) nil]
[:field (mt/id :lots-of-fields :b) nil]]}
:fields (into [[:expression "c"]]
(for [{:keys [id]} (db/select [Field :id]
:table_id (mt/id :lots-of-fields)
:id [:not-in #{(mt/id :lots-of-fields :a)
(mt/id :lots-of-fields :b)}]
{:order-by [[:name :asc]]})]
[:field id nil]))})]
(db/with-call-counting [call-count-fn]
(mt/with-native-query-testing-context query
(is (= 1
(-> (qp/process-query query) mt/rows ffirst))))
(testing "# of app DB calls should not be some insane number"
(is (< (call-count-fn) 20))))))))
(deftest expression-with-slashes
(mt/test-drivers (disj
(mt/normal-drivers-with-feature :expressions)
Slashes documented as not allowed in BQ
:bigquery-cloud-sdk)
(testing "Make sure an expression with a / in its name works (#12305)"
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 4.0]
[2 "Stout Burgers & Beers" 11 34.0996 -118.329 2 3.0]
[3 "The Apple Pan" 11 34.0406 -118.428 2 3.0]]
(mt/formatted-rows [int str int 4.0 4.0 int float]
(mt/run-mbql-query venues
{:expressions {:TEST/my-cool-new-field [:+ $price 1]}
:limit 3
:order-by [[:asc $id]]})))))))
(deftest expression-using-aggregation-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we use aggregations from previous steps in expressions (#12762)"
(is (= [["20th Century Cafe" 2 2 0]
[ "25°" 2 2 0]
["33 Taps" 2 2 0]]
(mt/formatted-rows [str int int int]
(mt/run-mbql-query venues
{:source-query {:source-table (mt/id :venues)
:aggregation [[:min (mt/id :venues :price)]
[:max (mt/id :venues :price)]]
:breakout [[:field (mt/id :venues :name) nil]]
:limit 3}
:expressions {:price_range [:-
[:field "max" {:base-type :type/Number}]
[:field "min" {:base-type :type/Number}]]}})))))))
(deftest expression-with-duplicate-column-name
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "Can we use expression with same column name as table (#14267)"
(mt/dataset sample-dataset
(let [query (mt/mbql-query products
{:expressions {:CATEGORY [:concat $category "2"]}
:breakout [:expression :CATEGORY]
:aggregation [:count]
:order-by [[:asc [:expression :CATEGORY]]]
:limit 1})]
(mt/with-native-query-testing-context query
(is (= [["Doohickey2" 42]]
(mt/formatted-rows [str int]
(qp/process-query query))))))))))
(deftest fk-field-and-duplicate-names-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions :foreign-keys)
(testing "Expressions with `fk->` fields and duplicate names should work correctly (#14854)"
(mt/dataset sample-dataset
(let [results (mt/run-mbql-query orders
{:expressions {"CE" [:case
[[[:> $discount 0] $created_at]]
{:default $product_id->products.created_at}]}
:order-by [[:asc $id]]
:limit 2})]
(is (= ["ID" "User ID" "Product ID" "Subtotal" "Tax" "Total" "Discount" "Created At" "Quantity" "CE"]
(map :display_name (mt/cols results))))
(is (= [[1 1 14 37.7 2.1 39.7 nil "2019-02-11T21:40:27.892Z" 2 "2017-12-31T14:41:56.87Z"]
[2 1 123 110.9 6.1 117.0 nil "2018-05-15T08:04:04.58Z" 3 "2017-11-16T13:53:14.232Z"]]
(mt/formatted-rows [int int int 1.0 1.0 1.0 identity str int str]
results))))))))
(deftest string-operations-from-subquery
(mt/test-drivers (mt/normal-drivers-with-feature :expressions :regex)
(testing "regex-match-first and replace work when evaluated against a subquery (#14873)"
(mt/dataset test-data
(let [r-word "r_word"
no-sp "no_spaces"
results (mt/run-mbql-query venues
{:expressions {r-word [:regex-match-first $name "^R[^ ]+"]
no-sp [:replace $name " " ""]}
:source-query {:source-table $$venues}
:fields [$name [:expression r-word] [:expression no-sp]]
:filter [:= $id 1 95]
:order-by [[:asc $id]]})]
(is (= ["Name" r-word no-sp]
(map :display_name (mt/cols results))))
(is (= [["Red Medicine" "Red" "RedMedicine"]
["Rush Street" "Rush" "RushStreet"]]
(mt/formatted-rows [str str str] results))))))))
(deftest expression-name-weird-characters-test
(mt/test-drivers (mt/normal-drivers-with-feature :expressions)
(testing "An expression whose name contains weird characters works properly"
(let [query (mt/mbql-query venues
{:expressions {"Refund Amount (?)" [:* $price -1]}
:limit 1
:order-by [[:asc $id]]})]
(mt/with-native-query-testing-context query
(is (= [[1 "Red Medicine" 4 10.0646 -165.374 3 -3]]
(mt/formatted-rows [int str int 4.0 4.0 int int]
(qp/process-query query)))))))))
(deftest join-table-on-itself-with-custom-column-test
(testing "Should be able to join a source query against itself using an expression (#17770)"
(mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :expressions :left-join)
(mt/dataset sample-dataset
(let [query (mt/mbql-query nil
{:source-query {:source-query {:source-table $$products
:aggregation [[:count]]
:breakout [$products.category]}
:expressions {:CC [:+ 1 1]}}
:joins [{:source-query {:source-query {:source-table $$products
:aggregation [[:count]]
:breakout [$products.category]}
:expressions {:CC [:+ 1 1]}}
:alias "Q1"
:condition [:=
[:field "CC" {:base-type :type/Integer}]
[:field "CC" {:base-type :type/Integer, :join-alias "Q1"}]]
:fields :all}]
:order-by [[:asc $products.category]
[:desc [:field "count" {:base-type :type/Integer}]]
[:asc &Q1.products.category]]
:limit 1})]
(mt/with-native-query-testing-context query
source.category , source.count , source . CC , Q1.category , Q1.count ,
(is (= [["Doohickey" 42 2 "Doohickey" 42 2]]
(mt/formatted-rows [str int int str int int]
(qp/process-query query))))))))))
(deftest nested-expressions-with-existing-names-test
(testing "Expressions with the same name as existing columns should work correctly in nested queries (#21131)"
(mt/test-drivers (mt/normal-drivers-with-feature :nested-queries :expressions)
(mt/dataset sample-dataset
(doseq [expression-name ["PRICE" "price"]]
(testing (format "Expression name = %s" (pr-str expression-name))
(let [query (mt/mbql-query products
{:source-query {:source-table $$products
:expressions {expression-name [:+ $price 2]}
:fields [$id $price [:expression expression-name]]
:order-by [[:asc $id]]
:limit 2}})]
(mt/with-native-query-testing-context query
(is (= [[1 29.46 31.46] [2 70.08 72.08]]
(mt/formatted-rows [int 2.0 2.0]
(qp/process-query query))))))))))))
|
e03c61bbad857b5361de968ed7f302fc4bb50c680f5fdce59b6c67826d4ea60f | singnet/snet-minting-policy | WritePlutus.hs | import Cardano.Api
import Cardano.Api.Shelley
import qualified Cardano.Ledger.Alonzo.Data as Alonzo
import OnChain . LockingScript
( apiExampleUntypedPlutusLockingScript ,
-- untypedLockingScriptAsShortBs,
-- )
import OnChain . MintingScript ( apiExamplePlutusMintingScript , curSymbol )
import OnChain . SimpleMintingScript ( serialisedScript )
import OnChain . PrivateToken ( serialisedScript , curSymbol )
import OnChain.MintingTokenWithOwner (apiExamplePlutusMintingScript)
import qualified Plutus.V1.Ledger.Api as Plutus
import System.Environment
import Prelude
writePlutusScript :: FilePath -> IO ()
writePlutusScript filename = do
result <- writeFileTextEnvelope filename Nothing apiExamplePlutusMintingScript
case result of
Left err -> print $ displayError err
Right () -> return ()
main :: IO ()
main = do
args <- getArgs
let argsLen = length args
let filename = if argsLen > 0 then head args else "token-with-owner.plutus"
putStrLn $ "Writing output to " ++ filename
writePlutusScript filename
putStrLn "Successfully written" | null | https://raw.githubusercontent.com/singnet/snet-minting-policy/1eb6ce64d408318e715d809cbe2e32a302aaabeb/pab/WritePlutus.hs | haskell | untypedLockingScriptAsShortBs,
) | import Cardano.Api
import Cardano.Api.Shelley
import qualified Cardano.Ledger.Alonzo.Data as Alonzo
import OnChain . LockingScript
( apiExampleUntypedPlutusLockingScript ,
import OnChain . MintingScript ( apiExamplePlutusMintingScript , curSymbol )
import OnChain . SimpleMintingScript ( serialisedScript )
import OnChain . PrivateToken ( serialisedScript , curSymbol )
import OnChain.MintingTokenWithOwner (apiExamplePlutusMintingScript)
import qualified Plutus.V1.Ledger.Api as Plutus
import System.Environment
import Prelude
writePlutusScript :: FilePath -> IO ()
writePlutusScript filename = do
result <- writeFileTextEnvelope filename Nothing apiExamplePlutusMintingScript
case result of
Left err -> print $ displayError err
Right () -> return ()
main :: IO ()
main = do
args <- getArgs
let argsLen = length args
let filename = if argsLen > 0 then head args else "token-with-owner.plutus"
putStrLn $ "Writing output to " ++ filename
writePlutusScript filename
putStrLn "Successfully written" |
258be461c000735cf1fd34ef0ff01639188a556562e881d5d4f6da2dc7d811e6 | ahrefs/atd | unique_name.mli | (**
Functions to translate an identifier into one that's not reserved
or already taken.
When necessary, identifiers are modified by adding prefixes or suffixes
that are compatible with Python syntax.
Important terminology:
- source space: ideal set of unique identifiers
- destination space: set of identifiers that were translated from the
source space and which guarantees no overlap with a set of reserved
identifiers.
The general goal in practice is to minimize the differences between
source and destination identifiers.
Things a user might want to do:
- Given a collection of objects with possibly non-unique names, assign
a unique identifier to each object, ideally resembling the original name.
For this, use the [create] function.
- Given a target language with a set of reserved identifiers, check that
a name is not a reserved identifier. If it is, modify the name such
that it's not reserved and is a valid identifier in the target language.
For this, use the [translate] function.
*)
(** The mutable container holding all translation data. *)
type t
* Initialize the translation tables by specifying the set of identifiers
already reserved in the destination space .
[ reserved_identifiers ] are forbidden identifiers , i.e. we guarantee
that a translation will never return one of these .
[ safe_prefix ] is a prefix that will be added to an identifier that
matches one of the reserved prefixes ( [ reserved_prefixes ] ) .
already reserved in the destination space.
[reserved_identifiers] are forbidden identifiers, i.e. we guarantee
that a translation will never return one of these.
[safe_prefix] is a prefix that will be added to an identifier that
matches one of the reserved prefixes ([reserved_prefixes]).
*)
val init :
reserved_identifiers: string list ->
reserved_prefixes: string list ->
safe_prefix: string ->
t
(** Reserve a new identifier in the source space. If the given name
is already an identifier in the source space, a new identifier is
created by appending an alphanumeric suffix and returned.
Repeated calls of this function on the same input will produce
a different output each time.
*)
val create : t -> string -> string
(** Translate an identifier from the source space to the destination space.
This registers the translation of a name if it's not already registered.
The translation is a name in the destination space that is not
reserved for other uses.
Repeated calls of this function on the same input will produce
the same output as the previous times.
*)
val translate :
?preferred_translation:string ->
t -> string -> string
(** Return whether a name exists in the source space. If it exists, return
its translation to the destination space. *)
val translate_only : t -> string -> string option
(** Return whether a name exists in the destination space. If it exists,
return its translation to the source space. *)
val reverse_translate : t -> string -> string option
* List all the registered identifiers in the source and destination spaces .
This is a one - to - one mapping sorted alphabetically .
This is meant for testing and for educational purposes .
This is a one-to-one mapping sorted alphabetically.
This is meant for testing and for educational purposes. *)
val all : t -> (string * string) list
| null | https://raw.githubusercontent.com/ahrefs/atd/1f2b3bcc54d14159a5e25e9b23b5c9bed163721c/atd/src/unique_name.mli | ocaml | *
Functions to translate an identifier into one that's not reserved
or already taken.
When necessary, identifiers are modified by adding prefixes or suffixes
that are compatible with Python syntax.
Important terminology:
- source space: ideal set of unique identifiers
- destination space: set of identifiers that were translated from the
source space and which guarantees no overlap with a set of reserved
identifiers.
The general goal in practice is to minimize the differences between
source and destination identifiers.
Things a user might want to do:
- Given a collection of objects with possibly non-unique names, assign
a unique identifier to each object, ideally resembling the original name.
For this, use the [create] function.
- Given a target language with a set of reserved identifiers, check that
a name is not a reserved identifier. If it is, modify the name such
that it's not reserved and is a valid identifier in the target language.
For this, use the [translate] function.
* The mutable container holding all translation data.
* Reserve a new identifier in the source space. If the given name
is already an identifier in the source space, a new identifier is
created by appending an alphanumeric suffix and returned.
Repeated calls of this function on the same input will produce
a different output each time.
* Translate an identifier from the source space to the destination space.
This registers the translation of a name if it's not already registered.
The translation is a name in the destination space that is not
reserved for other uses.
Repeated calls of this function on the same input will produce
the same output as the previous times.
* Return whether a name exists in the source space. If it exists, return
its translation to the destination space.
* Return whether a name exists in the destination space. If it exists,
return its translation to the source space. |
type t
* Initialize the translation tables by specifying the set of identifiers
already reserved in the destination space .
[ reserved_identifiers ] are forbidden identifiers , i.e. we guarantee
that a translation will never return one of these .
[ safe_prefix ] is a prefix that will be added to an identifier that
matches one of the reserved prefixes ( [ reserved_prefixes ] ) .
already reserved in the destination space.
[reserved_identifiers] are forbidden identifiers, i.e. we guarantee
that a translation will never return one of these.
[safe_prefix] is a prefix that will be added to an identifier that
matches one of the reserved prefixes ([reserved_prefixes]).
*)
val init :
reserved_identifiers: string list ->
reserved_prefixes: string list ->
safe_prefix: string ->
t
val create : t -> string -> string
val translate :
?preferred_translation:string ->
t -> string -> string
val translate_only : t -> string -> string option
val reverse_translate : t -> string -> string option
* List all the registered identifiers in the source and destination spaces .
This is a one - to - one mapping sorted alphabetically .
This is meant for testing and for educational purposes .
This is a one-to-one mapping sorted alphabetically.
This is meant for testing and for educational purposes. *)
val all : t -> (string * string) list
|
5cb9f2e63bbbe7cd5f55742cc69c9b42575afcdc594c45ca401e7c256b7a33b4 | adetokunbo/tmp-proc | Server.hs | {-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeOperators #-}
|
Copyright : ( c ) 2020 - 2021
SPDX - License - Identifier : : < >
Implements a demo service .
Copyright : (c) 2020-2021 Tim Emiola
SPDX-License-Identifier: BSD3
Maintainer : Tim Emiola <>
Implements a demo service.
-}
module TmpProc.Example2.Server
( -- * Server implementation
AppEnv(..)
, runServer'
, runServer
, waiApp
) where
import Control.Exception (try, throw)
import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Reader (MonadReader, ReaderT, asks,
runReaderT)
import Control.Monad.Trans.Except (ExceptT (..))
import Network.Wai (Application)
import Network.Wai.Handler.Warp (Port, run)
import Servant.API ((:<|>) (..))
import Servant.Server (Handler (..), ServerT,
err401, errBody, serve, hoistServer)
import TmpProc.Example2.Routes (ContactsAPI, contactsAPI)
import TmpProc.Example2.Schema (Contact, ContactID)
import qualified TmpProc.Example2.Cache as Cache
import qualified TmpProc.Example2.Database as DB
{-| Runs 'waiApp' on the given port. -}
runServer' :: IO AppEnv -> Port -> IO ()
runServer' mkEnv port = mkEnv >>= run port . waiApp
| An ' Application ' that runs the server using the given DB and Cache .
waiApp :: AppEnv -> Application
waiApp env =
let
hoist' = Handler . ExceptT . try . runApp' env
in
serve contactsAPI $ hoistServer contactsAPI hoist' server
{-| Runs 'waiApp' using defaults for local development. -}
runServer :: IO ()
runServer = runServer' defaultEnv 8000
fetchContact
:: (MonadIO m, MonadReader r m, Has DB.Locator r, Has Cache.Connection r)
=> ContactID -> m Contact
fetchContact cid = do
cache <- grab @Cache.Connection
(liftIO $ Cache.loadContact cache cid) >>= \case
Just contact -> pure contact
Nothing -> do
db <- grab @DB.Locator
(liftIO $ DB.fetch db cid) >>= \case
Just contact -> liftIO (Cache.saveContact cache cid contact) >> pure contact
Nothing -> throw $ err401 { errBody = "No Contact with this ID" }
createContact
:: (MonadIO m, MonadReader r m, Has DB.Locator r)
=> Contact -> m ContactID
createContact contact = do
db <- grab @DB.Locator
liftIO $ DB.create db contact
server
:: ( Has Cache.Connection r
, Has DB.Locator r
, MonadReader r m
, MonadIO m
)
=> ServerT ContactsAPI m
server = fetchContact :<|> createContact
| The application - level Monad , provides access to AppEnv via @Reader AppEnv@.
newtype App a = App
{ runApp :: ReaderT AppEnv IO a
} deriving ( Applicative
, Functor
, Monad
, MonadCatch
, MonadMask
, MonadThrow
, MonadReader AppEnv
, MonadIO
)
instance Has DB.Locator AppEnv where obtain = aeDbLocator
instance Has Cache.Connection AppEnv where obtain = aeCacheLocator
defaultEnv :: IO AppEnv
defaultEnv = AppEnv <$> (pure DB.defaultLoc) <*> Cache.defaultConn
-- | Run a 'App' computation with the given environment.
runApp' :: AppEnv -> App a -> IO a
runApp' env = flip runReaderT env . runApp
{-| An application-level environment suitable for storing in a Reader. -}
data AppEnv = AppEnv
{ aeDbLocator :: !(DB.Locator)
, aeCacheLocator :: !(Cache.Connection)
}
{- | General type class representing which @field@ is in @env@. -}
class Has field env where
obtain :: env -> field
-- | A combinator that simplifies accessing 'Has' fields.
grab :: forall field env m . (MonadReader env m, Has field env) => m field
grab = asks $ obtain @field
| null | https://raw.githubusercontent.com/adetokunbo/tmp-proc/0bb91505f24084ae488af274459fa49c87912033/tmp-proc-example/src/TmpProc/Example2/Server.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeOperators #
* Server implementation
| Runs 'waiApp' on the given port.
| Runs 'waiApp' using defaults for local development.
| Run a 'App' computation with the given environment.
| An application-level environment suitable for storing in a Reader.
| General type class representing which @field@ is in @env@.
| A combinator that simplifies accessing 'Has' fields. | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
|
Copyright : ( c ) 2020 - 2021
SPDX - License - Identifier : : < >
Implements a demo service .
Copyright : (c) 2020-2021 Tim Emiola
SPDX-License-Identifier: BSD3
Maintainer : Tim Emiola <>
Implements a demo service.
-}
module TmpProc.Example2.Server
AppEnv(..)
, runServer'
, runServer
, waiApp
) where
import Control.Exception (try, throw)
import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Reader (MonadReader, ReaderT, asks,
runReaderT)
import Control.Monad.Trans.Except (ExceptT (..))
import Network.Wai (Application)
import Network.Wai.Handler.Warp (Port, run)
import Servant.API ((:<|>) (..))
import Servant.Server (Handler (..), ServerT,
err401, errBody, serve, hoistServer)
import TmpProc.Example2.Routes (ContactsAPI, contactsAPI)
import TmpProc.Example2.Schema (Contact, ContactID)
import qualified TmpProc.Example2.Cache as Cache
import qualified TmpProc.Example2.Database as DB
runServer' :: IO AppEnv -> Port -> IO ()
runServer' mkEnv port = mkEnv >>= run port . waiApp
| An ' Application ' that runs the server using the given DB and Cache .
waiApp :: AppEnv -> Application
waiApp env =
let
hoist' = Handler . ExceptT . try . runApp' env
in
serve contactsAPI $ hoistServer contactsAPI hoist' server
runServer :: IO ()
runServer = runServer' defaultEnv 8000
fetchContact
:: (MonadIO m, MonadReader r m, Has DB.Locator r, Has Cache.Connection r)
=> ContactID -> m Contact
fetchContact cid = do
cache <- grab @Cache.Connection
(liftIO $ Cache.loadContact cache cid) >>= \case
Just contact -> pure contact
Nothing -> do
db <- grab @DB.Locator
(liftIO $ DB.fetch db cid) >>= \case
Just contact -> liftIO (Cache.saveContact cache cid contact) >> pure contact
Nothing -> throw $ err401 { errBody = "No Contact with this ID" }
createContact
:: (MonadIO m, MonadReader r m, Has DB.Locator r)
=> Contact -> m ContactID
createContact contact = do
db <- grab @DB.Locator
liftIO $ DB.create db contact
server
:: ( Has Cache.Connection r
, Has DB.Locator r
, MonadReader r m
, MonadIO m
)
=> ServerT ContactsAPI m
server = fetchContact :<|> createContact
| The application - level Monad , provides access to AppEnv via @Reader AppEnv@.
newtype App a = App
{ runApp :: ReaderT AppEnv IO a
} deriving ( Applicative
, Functor
, Monad
, MonadCatch
, MonadMask
, MonadThrow
, MonadReader AppEnv
, MonadIO
)
instance Has DB.Locator AppEnv where obtain = aeDbLocator
instance Has Cache.Connection AppEnv where obtain = aeCacheLocator
defaultEnv :: IO AppEnv
defaultEnv = AppEnv <$> (pure DB.defaultLoc) <*> Cache.defaultConn
runApp' :: AppEnv -> App a -> IO a
runApp' env = flip runReaderT env . runApp
data AppEnv = AppEnv
{ aeDbLocator :: !(DB.Locator)
, aeCacheLocator :: !(Cache.Connection)
}
class Has field env where
obtain :: env -> field
grab :: forall field env m . (MonadReader env m, Has field env) => m field
grab = asks $ obtain @field
|
1ac857d7cc19b1dc1b2cb15a92b0d0272a5232d89e97c9766dc1f208c2182a14 | Airini/FEECa | FiniteElementTest.hs | # LANGUAGE TemplateHaskell #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE FlexibleInstances #
module FEECa.FiniteElementTest where
import Control.Monad ( liftM )
import FEECa.Internal.Form hiding ( inner )
import FEECa.Internal.Spaces
import qualified FEECa.Internal.MultiIndex as MI
import qualified FEECa.Internal.Vector as V
import qualified FEECa.Internal.Simplex as S
import FEECa.Utility.Combinatorics
import FEECa.Utility.Print
import FEECa.Utility.Utility
import FEECa.FiniteElementSpace
import qualified FEECa.Polynomial as P
import qualified FEECa.PolynomialDifferentialForm as DF
import qualified FEECa.Bernstein as B
import FEECa.Utility.Test
import FEECa.Internal.SimplexTest
import qualified Test.QuickCheck as Q
import Test.QuickCheck ( (==>) )
import qualified Numeric.LinearAlgebra.HMatrix as M
--------------------------------------------------------------------------------
-- Random Finite Element Space
--------------------------------------------------------------------------------
max_n = 3
max_r = 3
max_k = 3
arbitraryPL :: (Int -> Int -> Simplex -> FiniteElementSpace)
-> Q.Gen FiniteElementSpace
arbitraryPL cpl = do
[n,r,k] <- mapM Q.choose [(1,max_n), (0,max_r), (0,max_k)]
liftM (cpl r k) (arbitrarySimplex n)
arbitraryPrLk :: Q.Gen FiniteElementSpace
arbitraryPrLk = arbitraryPL PrLk
arbitraryPrmLk :: Q.Gen FiniteElementSpace
arbitraryPrmLk = arbitraryPL PrmLk
instance Q.Arbitrary FiniteElementSpace where
arbitrary = arbitraryPrLk
n = 4
--------------------------------------------------------------------------------
-- Whitney Forms
--------------------------------------------------------------------------------
data WhitneyTest = WhitneyTest Simplex
deriving Show
instance Q.Arbitrary WhitneyTest where
arbitrary = do k <- Q.choose (1,n)
liftM WhitneyTest (arbitrarySubsimplex k n)
prop_whitney_integral :: WhitneyTest -> Bool
prop_whitney_integral (WhitneyTest t) =
abs (DF.integrate t (whitneyForm t [0..k]))
`eqNum` (1 / fromInt (factorial k))
where k = S.topologicalDimension t
--------------------------------------------------------------------------------
-- Psi Forms
--------------------------------------------------------------------------------
data PsiTest = PsiTest Simplex Simplex MI.MultiIndex Vector
deriving Show
instance Q.Arbitrary PsiTest where
arbitrary = do
k <- Q.choose (1,n)
t <- arbitrarySimplex n
f <- Q.elements $ S.subsimplices t k
r <- Q.choose (0,10)
mi <- liftM (MI.extend n (S.sigma f)) (arbitraryMI (k+1) r)
liftM (PsiTest t f mi) (arbitraryVector n)
prop_psi :: PsiTest -> Q.Property
prop_psi (PsiTest t f mi v) =
MI.degree mi > 0 ==> all (eqNum 0.0 . evaluate v) ps
where ps = [DF.apply (psi' t f mi i) [l] | i <- is, l <- axs]
axs = projectionAxes t f mi
is = S.sigma f
k = S.topologicalDimension f
convexCombination :: Simplex -> MI.MultiIndex -> Vector
convexCombination t mi = sumV (zipWith sclV mi' vs)
where vs = S.vertices t
zero = zeroV (head vs)
(l,r) = (MI.toList mi, fromInt $ MI.degree mi)
mi' = [ let i = fromInt (l !! s)
in i / r -- XXX: mulInv???...
| s <- S.sigma t]
projectionAxes :: Simplex -> Simplex -> MI.MultiIndex -> [Vector]
projectionAxes t f mi = map (subV xmi) (S.complement t f)
where xmi = convexCombination f mi
prop_basis :: FiniteElementSpace -> Q.Property
prop_basis s =
length bs > 0 ==> length bs == dim s && linearIndependent DF.inner bs
where bs = basis s
-- XXX: why the normalisation?? ... removed for now, seems unnecessary
-- ==> we use bs instead
bs ' = map ( \x - > fmap ( sclV ( mulInv ( sqrt ( DF.inner x x ) ) ) ) x ) bs
--n = vspaceDim s
--------------------------------------------------------------------------------
-- PrmLk Form associated to a face.
--------------------------------------------------------------------------------
linearIndependent :: Module v => (v -> v -> Double) -> [v] -> Bool
linearIndependent f bs = M.rank mat == n
where es = M.eigenvaluesSH' mat
-- TODO: changed eigenvaluesSH to eigenvaluesSH' for loading; check!
mat = M.matrix n [ f omega eta | omega <- bs, eta <- bs ]
n = length bs
--------------------------------------------------------------------------------
-- DoFs of PrLk space
--------------------------------------------------------------------------------
prop_dof_basis :: FiniteElementSpace -> Q.Property
prop_dof_basis s = dim s > 0 && degree s > 0 ==> M.rank mat == n
where mat = M.matrix (n) [d b | d <- dofs s, b <- basis s]
n = dim s
prop_ndofs :: FiniteElementSpace -> Q.Property
prop_ndofs s = degree s > 0 ==> length (dofs s) == sum [nDofs s k | k <- [0..n]]
where n = S.topologicalDimension $ simplex s
return []
testFiniteElement = $quickCheckWithAll
space = PrmLk 3 0 (S.referenceSimplex 3)
| null | https://raw.githubusercontent.com/Airini/FEECa/3ffae7177fca159d965b70e3763a20ab84cd8a8b/tests/FEECa/FiniteElementTest.hs | haskell | # LANGUAGE TypeSynonymInstances #
------------------------------------------------------------------------------
Random Finite Element Space
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Whitney Forms
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Psi Forms
------------------------------------------------------------------------------
XXX: mulInv???...
XXX: why the normalisation?? ... removed for now, seems unnecessary
==> we use bs instead
n = vspaceDim s
------------------------------------------------------------------------------
PrmLk Form associated to a face.
------------------------------------------------------------------------------
TODO: changed eigenvaluesSH to eigenvaluesSH' for loading; check!
------------------------------------------------------------------------------
DoFs of PrLk space
------------------------------------------------------------------------------ | # LANGUAGE TemplateHaskell #
# LANGUAGE FlexibleInstances #
module FEECa.FiniteElementTest where
import Control.Monad ( liftM )
import FEECa.Internal.Form hiding ( inner )
import FEECa.Internal.Spaces
import qualified FEECa.Internal.MultiIndex as MI
import qualified FEECa.Internal.Vector as V
import qualified FEECa.Internal.Simplex as S
import FEECa.Utility.Combinatorics
import FEECa.Utility.Print
import FEECa.Utility.Utility
import FEECa.FiniteElementSpace
import qualified FEECa.Polynomial as P
import qualified FEECa.PolynomialDifferentialForm as DF
import qualified FEECa.Bernstein as B
import FEECa.Utility.Test
import FEECa.Internal.SimplexTest
import qualified Test.QuickCheck as Q
import Test.QuickCheck ( (==>) )
import qualified Numeric.LinearAlgebra.HMatrix as M
max_n = 3
max_r = 3
max_k = 3
arbitraryPL :: (Int -> Int -> Simplex -> FiniteElementSpace)
-> Q.Gen FiniteElementSpace
arbitraryPL cpl = do
[n,r,k] <- mapM Q.choose [(1,max_n), (0,max_r), (0,max_k)]
liftM (cpl r k) (arbitrarySimplex n)
arbitraryPrLk :: Q.Gen FiniteElementSpace
arbitraryPrLk = arbitraryPL PrLk
arbitraryPrmLk :: Q.Gen FiniteElementSpace
arbitraryPrmLk = arbitraryPL PrmLk
instance Q.Arbitrary FiniteElementSpace where
arbitrary = arbitraryPrLk
n = 4
data WhitneyTest = WhitneyTest Simplex
deriving Show
instance Q.Arbitrary WhitneyTest where
arbitrary = do k <- Q.choose (1,n)
liftM WhitneyTest (arbitrarySubsimplex k n)
prop_whitney_integral :: WhitneyTest -> Bool
prop_whitney_integral (WhitneyTest t) =
abs (DF.integrate t (whitneyForm t [0..k]))
`eqNum` (1 / fromInt (factorial k))
where k = S.topologicalDimension t
data PsiTest = PsiTest Simplex Simplex MI.MultiIndex Vector
deriving Show
instance Q.Arbitrary PsiTest where
arbitrary = do
k <- Q.choose (1,n)
t <- arbitrarySimplex n
f <- Q.elements $ S.subsimplices t k
r <- Q.choose (0,10)
mi <- liftM (MI.extend n (S.sigma f)) (arbitraryMI (k+1) r)
liftM (PsiTest t f mi) (arbitraryVector n)
prop_psi :: PsiTest -> Q.Property
prop_psi (PsiTest t f mi v) =
MI.degree mi > 0 ==> all (eqNum 0.0 . evaluate v) ps
where ps = [DF.apply (psi' t f mi i) [l] | i <- is, l <- axs]
axs = projectionAxes t f mi
is = S.sigma f
k = S.topologicalDimension f
convexCombination :: Simplex -> MI.MultiIndex -> Vector
convexCombination t mi = sumV (zipWith sclV mi' vs)
where vs = S.vertices t
zero = zeroV (head vs)
(l,r) = (MI.toList mi, fromInt $ MI.degree mi)
mi' = [ let i = fromInt (l !! s)
| s <- S.sigma t]
projectionAxes :: Simplex -> Simplex -> MI.MultiIndex -> [Vector]
projectionAxes t f mi = map (subV xmi) (S.complement t f)
where xmi = convexCombination f mi
prop_basis :: FiniteElementSpace -> Q.Property
prop_basis s =
length bs > 0 ==> length bs == dim s && linearIndependent DF.inner bs
where bs = basis s
bs ' = map ( \x - > fmap ( sclV ( mulInv ( sqrt ( DF.inner x x ) ) ) ) x ) bs
linearIndependent :: Module v => (v -> v -> Double) -> [v] -> Bool
linearIndependent f bs = M.rank mat == n
where es = M.eigenvaluesSH' mat
mat = M.matrix n [ f omega eta | omega <- bs, eta <- bs ]
n = length bs
prop_dof_basis :: FiniteElementSpace -> Q.Property
prop_dof_basis s = dim s > 0 && degree s > 0 ==> M.rank mat == n
where mat = M.matrix (n) [d b | d <- dofs s, b <- basis s]
n = dim s
prop_ndofs :: FiniteElementSpace -> Q.Property
prop_ndofs s = degree s > 0 ==> length (dofs s) == sum [nDofs s k | k <- [0..n]]
where n = S.topologicalDimension $ simplex s
return []
testFiniteElement = $quickCheckWithAll
space = PrmLk 3 0 (S.referenceSimplex 3)
|
5b7aaaee264d1a536f07bb7a90319e16811011b625cddf82cd0568719d7cc6ca | txyyss/Project-Euler | Euler089.hs | The rules for writing Roman numerals allow for many ways of writing
-- each number (see About Roman Numerals...). However, there is always
-- a "best" way of writing a particular number.
-- For example, the following represent all of the legitimate ways of
writing the number sixteen :
IIIIIIIIIIIIIIII
VIIIIIIIIIII
VVIIIIII
XIIIIII
VVVI
-- XVI
-- The last example being considered the most efficient, as it uses
-- the least number of numerals.
The 11 K text file , roman.txt ( right click and ' Save Link / Target
As ... ' ) , contains one thousand numbers written in valid , but not
necessarily minimal , Roman numerals ; that is , they are arranged in
-- descending units and obey the subtractive pair rule (see About
-- Roman Numerals... for the definitive rules for this problem).
-- Find the number of characters saved by writing each of these in
-- their minimal form.
Note : You can assume that all the Roman numerals in the file
contain no more than four consecutive identical units .
module Euler089 where
import qualified Data.Text as T
reducedLen :: String -> Int
reducedLen input = T.length num - T.length result
where num = T.pack input
dcccc = T.pack "DCCCC"
lxxxx = T.pack "LXXXX"
viiii = T.pack "VIIII"
cccc = T.pack "CCCC"
xxxx = T.pack "XXXX"
iiii = T.pack "IIII"
rr = T.pack "RR"
result = T.replace iiii rr $ T.replace xxxx rr $ T.replace cccc rr $
T.replace viiii rr $ T.replace lxxxx rr $ T.replace dcccc rr num
result089 = fmap (sum . map reducedLen . lines) $ readFile "data/roman.txt"
| null | https://raw.githubusercontent.com/txyyss/Project-Euler/d2f41dad429013868445c1c9c1c270b951550ee9/Euler089.hs | haskell | each number (see About Roman Numerals...). However, there is always
a "best" way of writing a particular number.
For example, the following represent all of the legitimate ways of
XVI
The last example being considered the most efficient, as it uses
the least number of numerals.
descending units and obey the subtractive pair rule (see About
Roman Numerals... for the definitive rules for this problem).
Find the number of characters saved by writing each of these in
their minimal form. | The rules for writing Roman numerals allow for many ways of writing
writing the number sixteen :
IIIIIIIIIIIIIIII
VIIIIIIIIIII
VVIIIIII
XIIIIII
VVVI
The 11 K text file , roman.txt ( right click and ' Save Link / Target
As ... ' ) , contains one thousand numbers written in valid , but not
necessarily minimal , Roman numerals ; that is , they are arranged in
Note : You can assume that all the Roman numerals in the file
contain no more than four consecutive identical units .
module Euler089 where
import qualified Data.Text as T
reducedLen :: String -> Int
reducedLen input = T.length num - T.length result
where num = T.pack input
dcccc = T.pack "DCCCC"
lxxxx = T.pack "LXXXX"
viiii = T.pack "VIIII"
cccc = T.pack "CCCC"
xxxx = T.pack "XXXX"
iiii = T.pack "IIII"
rr = T.pack "RR"
result = T.replace iiii rr $ T.replace xxxx rr $ T.replace cccc rr $
T.replace viiii rr $ T.replace lxxxx rr $ T.replace dcccc rr num
result089 = fmap (sum . map reducedLen . lines) $ readFile "data/roman.txt"
|
8fcd7e96470cb879daf14fc7a39716db878442d1ff656001af28a28b895693fb | kupl/LearnML | original.ml | type formula =
| True
| False
| Not of formula
| AndAlso of (formula * formula)
| OrElse of (formula * formula)
| Imply of (formula * formula)
| Equal of (exp * exp)
and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp)
let rec eval (f : formula) : bool =
match f with
| True -> true
| False -> false
| Not a -> if a = True then false else true
| AndAlso (a, b) -> if a = True && b = True then true else false
| OrElse (a, b) -> if a = True || b = True then true else false
| Imply (a, b) -> if Not a = True || b = True then true else false
| Equal (a, b) ->
let rec evalexp (e : exp) : int =
match e with
| Num a -> a
| Plus (a, b) -> evalexp a + evalexp b
| Minus (a, b) -> evalexp a - evalexp b
in
if evalexp a = evalexp b then true else false
| null | https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/formula/sub51/original.ml | ocaml | type formula =
| True
| False
| Not of formula
| AndAlso of (formula * formula)
| OrElse of (formula * formula)
| Imply of (formula * formula)
| Equal of (exp * exp)
and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp)
let rec eval (f : formula) : bool =
match f with
| True -> true
| False -> false
| Not a -> if a = True then false else true
| AndAlso (a, b) -> if a = True && b = True then true else false
| OrElse (a, b) -> if a = True || b = True then true else false
| Imply (a, b) -> if Not a = True || b = True then true else false
| Equal (a, b) ->
let rec evalexp (e : exp) : int =
match e with
| Num a -> a
| Plus (a, b) -> evalexp a + evalexp b
| Minus (a, b) -> evalexp a - evalexp b
in
if evalexp a = evalexp b then true else false
|
|
b3d6fc68b7f3886a1b6094d35a30e4359826aceb6b74349d9ec0b0df7e59f291 | Simre1/haskell-game | TypeErrors.hs | # OPTIONS_GHC -fno - warn - missing - signatures #
module TypeErrors where
-- $setup
-- >>> default ()
-- >>> :m +Polysemy
-- >>> :m +Polysemy.Output
-- >>> :m +Polysemy.Reader
-- >>> :m +Polysemy.Resource
-- >>> :m +Polysemy.State
-- >>> :m +Polysemy.Trace
-- >>> :m +Data.Maybe
--------------------------------------------------------------------------------
-- |
-- >>> :{
-- foo :: Sem r ()
-- foo = put ()
-- :}
-- ...
... Ambiguous use of effect ' State '
-- ...
-- ... (Member (State ()) r) ...
-- ...
ambiguousMonoState = ()
--------------------------------------------------------------------------------
-- |
-- >>> :{
-- foo :: Sem r ()
foo = put 5
-- :}
-- ...
... Ambiguous use of effect ' State '
-- ...
-- ... (Member (State s0) r) ...
-- ...
-- ... 's0' directly...
-- ...
ambiguousPolyState = ()
--------------------------------------------------------------------------------
-- |
-- >>> :{
-- interpret @(Reader Bool) $ \case
-- Ask -> undefined
-- :}
-- ...
... ' Reader ' is higher - order , but ' interpret ' can help only
... with first - order effects .
-- ...
-- ... 'interpretH' instead.
-- ...
interpretBadFirstOrder = ()
--------------------------------------------------------------------------------
-- |
-- >>> :{
-- runOutputMonoid
-- :: forall o m r a
-- . Monoid m
-- => (o -> m)
-- -> Sem (Output o ': r) a
-- -> Sem r (m, a)
runOutputMonoid f = . reinterpret $ \case
-- Output o -> modify (`mappend` f o)
-- :}
-- ...
-- ... Probable cause: ...reinterpret... is applied to too few arguments
-- ...
tooFewArgumentsReinterpret = ()
--------------------------------------------------------------------------------
-- |
-- >>> :{
-- let reinterpretScrub :: Sem (Output Int ': m) a -> Sem (State Bool ': Trace ': m) a
-- reinterpretScrub = undefined
-- foo :: Sem '[Output Int] ()
-- foo = pure ()
foo ' = reinterpretScrub foo
-- foo'' = runState True foo'
-- foo''' = traceToIO foo''
-- in runM foo'''
-- :}
-- ...
-- ... Unhandled effect 'Embed IO'
-- ...
... Expected type : Sem ' [ Embed m ] ( , ( ) )
... Actual type : Sem ' [ ] ( , ( ) )
-- ...
runningTooManyEffects = ()
--------------------------------------------------------------------------------
-- |
-- >>> :{
-- foo :: Sem (State Int ': r) ()
-- foo = put ()
-- :}
-- ...
... Ambiguous use of effect ' State '
-- ...
-- ... (Member (State ()) (State Int : r)) ...
-- ...
ambiguousSendInConcreteR = ()
--------------------------------------------------------------------------------
-- |
-- >>> :{
-- let foo :: Member Resource r => Sem r ()
-- foo = undefined
-- in runM $ lowerResource foo
-- :}
-- ...
-- ... Couldn't match expected type ...
-- ... with actual type ...
-- ... Probable cause: ... is applied to too few arguments
-- ...
missingArgumentToRunResourceInIO = ()
--------------------------------------------------------------------------------
-- |
-- >>> :{
-- existsKV :: Member (State (Maybe Int)) r => Sem r Bool
-- existsKV = isJust get
-- :}
-- ...
... Ambiguous use of effect ' State '
-- ...
--
-- NOTE: This is fixed by enabling the plugin!
missingFmap'PLUGIN = ()
--------------------------------------------------------------------------------
-- |
-- >>> :{
foo : : Sem ' [ State Int , Embed IO ] ( )
-- foo = output ()
-- :}
-- ...
-- ... Unhandled effect 'Output ()'
-- ...
-- ... add an interpretation for 'Output ()'
-- ...
missingEffectInStack'WRONG = ()
| null | https://raw.githubusercontent.com/Simre1/haskell-game/272a0674157aedc7b0e0ee00da8d3a464903dc67/polysemy/test/TypeErrors.hs | haskell | $setup
>>> default ()
>>> :m +Polysemy
>>> :m +Polysemy.Output
>>> :m +Polysemy.Reader
>>> :m +Polysemy.Resource
>>> :m +Polysemy.State
>>> :m +Polysemy.Trace
>>> :m +Data.Maybe
------------------------------------------------------------------------------
|
>>> :{
foo :: Sem r ()
foo = put ()
:}
...
...
... (Member (State ()) r) ...
...
------------------------------------------------------------------------------
|
>>> :{
foo :: Sem r ()
:}
...
...
... (Member (State s0) r) ...
...
... 's0' directly...
...
------------------------------------------------------------------------------
|
>>> :{
interpret @(Reader Bool) $ \case
Ask -> undefined
:}
...
...
... 'interpretH' instead.
...
------------------------------------------------------------------------------
|
>>> :{
runOutputMonoid
:: forall o m r a
. Monoid m
=> (o -> m)
-> Sem (Output o ': r) a
-> Sem r (m, a)
Output o -> modify (`mappend` f o)
:}
...
... Probable cause: ...reinterpret... is applied to too few arguments
...
------------------------------------------------------------------------------
|
>>> :{
let reinterpretScrub :: Sem (Output Int ': m) a -> Sem (State Bool ': Trace ': m) a
reinterpretScrub = undefined
foo :: Sem '[Output Int] ()
foo = pure ()
foo'' = runState True foo'
foo''' = traceToIO foo''
in runM foo'''
:}
...
... Unhandled effect 'Embed IO'
...
...
------------------------------------------------------------------------------
|
>>> :{
foo :: Sem (State Int ': r) ()
foo = put ()
:}
...
...
... (Member (State ()) (State Int : r)) ...
...
------------------------------------------------------------------------------
|
>>> :{
let foo :: Member Resource r => Sem r ()
foo = undefined
in runM $ lowerResource foo
:}
...
... Couldn't match expected type ...
... with actual type ...
... Probable cause: ... is applied to too few arguments
...
------------------------------------------------------------------------------
|
>>> :{
existsKV :: Member (State (Maybe Int)) r => Sem r Bool
existsKV = isJust get
:}
...
...
NOTE: This is fixed by enabling the plugin!
------------------------------------------------------------------------------
|
>>> :{
foo = output ()
:}
...
... Unhandled effect 'Output ()'
...
... add an interpretation for 'Output ()'
... | # OPTIONS_GHC -fno - warn - missing - signatures #
module TypeErrors where
... Ambiguous use of effect ' State '
ambiguousMonoState = ()
foo = put 5
... Ambiguous use of effect ' State '
ambiguousPolyState = ()
... ' Reader ' is higher - order , but ' interpret ' can help only
... with first - order effects .
interpretBadFirstOrder = ()
runOutputMonoid f = . reinterpret $ \case
tooFewArgumentsReinterpret = ()
foo ' = reinterpretScrub foo
... Expected type : Sem ' [ Embed m ] ( , ( ) )
... Actual type : Sem ' [ ] ( , ( ) )
runningTooManyEffects = ()
... Ambiguous use of effect ' State '
ambiguousSendInConcreteR = ()
missingArgumentToRunResourceInIO = ()
... Ambiguous use of effect ' State '
missingFmap'PLUGIN = ()
foo : : Sem ' [ State Int , Embed IO ] ( )
missingEffectInStack'WRONG = ()
|
942d45b4685ee93857cbbe7b991033b0dc74b7b631065dabe3108106ffc2960b | nasa/Common-Metadata-Repository | service.clj | (ns cmr.ingest.services.ingest-service.service
(:require
[cmr.common.util :refer [defn-timed]]
[cmr.common.services.errors :as errors]
[cmr.common-app.services.kms-fetcher :as kms-fetcher]
[cmr.common.validations.core :as cm-validation]
[cmr.ingest.services.messages :as msg]
[cmr.ingest.validation.validation :as validation]
[cmr.transmit.metadata-db2 :as mdb2]
[cmr.umm-spec.umm-spec-core :as spec]
[cmr.umm-spec.validation.umm-spec-validation-core :as umm-spec-validation]))
(defn- add-extra-fields-for-service
"Returns service concept with fields necessary for ingest into metadata db
under :extra-fields."
[context concept service]
(assoc concept :extra-fields {:service-name (:Name service)
:service-type (:Type service)}))
(defn- add-top-fields-for-service
"Returns service concept with top level fields needed for ingest into metadata db"
[concept]
(assoc concept
:provider-id (:provider-id concept)
:native-id (:native-id concept)))
(defn if-errors-throw
"Throws an error if there are any errors."
[error-type errors]
(when (seq errors)
(errors/throw-service-errors error-type errors)))
(defn- match-kms-related-url-content-type-type-and-subtype
"Create a kms match validator for use by validation-service"
[context]
(let [kms-index (kms-fetcher/get-kms-index context)]
[{:RelatedURLs [(validation/match-kms-keywords-validation
kms-index
:related-urls
msg/related-url-content-type-type-subtype-not-matching-kms-keywords)
(cm-validation/every [{:Format (validation/match-kms-keywords-validation-single
kms-index
:granule-data-format
msg/getdata-format-not-matches-kms-keywords)}
{:MimeType (validation/match-kms-keywords-validation-single
kms-index
:mime-type
msg/mime-type-not-matches-kms-keywords)}])]}]))
(defn- validate-all-fields
"Check all fields that need to be validated. Currently this is the Related URL Content Type, Type, and
Subtype fields. Throws an error if errors are found"
[context service]
(let [errors (seq (umm-spec-validation/validate-service service (match-kms-related-url-content-type-type-and-subtype context)))]
(if-errors-throw :bad-request errors)))
(defn-timed save-service
"Store a service concept in mdb and indexer. Return concept-id, and revision-id."
[context concept]
(let [{:keys [:format :metadata]} concept
service (spec/parse-metadata context :service format metadata)
_ (validate-all-fields context service)
full-concept (as-> concept intermediate
(add-extra-fields-for-service context intermediate service)
(add-top-fields-for-service intermediate))
{:keys [concept-id revision-id]} (mdb2/save-concept context full-concept)]
{:concept-id concept-id
:revision-id revision-id}))
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/cbf54cc6757640f99b63bac18f63f7686ec21162/ingest-app/src/cmr/ingest/services/ingest_service/service.clj | clojure | (ns cmr.ingest.services.ingest-service.service
(:require
[cmr.common.util :refer [defn-timed]]
[cmr.common.services.errors :as errors]
[cmr.common-app.services.kms-fetcher :as kms-fetcher]
[cmr.common.validations.core :as cm-validation]
[cmr.ingest.services.messages :as msg]
[cmr.ingest.validation.validation :as validation]
[cmr.transmit.metadata-db2 :as mdb2]
[cmr.umm-spec.umm-spec-core :as spec]
[cmr.umm-spec.validation.umm-spec-validation-core :as umm-spec-validation]))
(defn- add-extra-fields-for-service
"Returns service concept with fields necessary for ingest into metadata db
under :extra-fields."
[context concept service]
(assoc concept :extra-fields {:service-name (:Name service)
:service-type (:Type service)}))
(defn- add-top-fields-for-service
"Returns service concept with top level fields needed for ingest into metadata db"
[concept]
(assoc concept
:provider-id (:provider-id concept)
:native-id (:native-id concept)))
(defn if-errors-throw
"Throws an error if there are any errors."
[error-type errors]
(when (seq errors)
(errors/throw-service-errors error-type errors)))
(defn- match-kms-related-url-content-type-type-and-subtype
"Create a kms match validator for use by validation-service"
[context]
(let [kms-index (kms-fetcher/get-kms-index context)]
[{:RelatedURLs [(validation/match-kms-keywords-validation
kms-index
:related-urls
msg/related-url-content-type-type-subtype-not-matching-kms-keywords)
(cm-validation/every [{:Format (validation/match-kms-keywords-validation-single
kms-index
:granule-data-format
msg/getdata-format-not-matches-kms-keywords)}
{:MimeType (validation/match-kms-keywords-validation-single
kms-index
:mime-type
msg/mime-type-not-matches-kms-keywords)}])]}]))
(defn- validate-all-fields
"Check all fields that need to be validated. Currently this is the Related URL Content Type, Type, and
Subtype fields. Throws an error if errors are found"
[context service]
(let [errors (seq (umm-spec-validation/validate-service service (match-kms-related-url-content-type-type-and-subtype context)))]
(if-errors-throw :bad-request errors)))
(defn-timed save-service
"Store a service concept in mdb and indexer. Return concept-id, and revision-id."
[context concept]
(let [{:keys [:format :metadata]} concept
service (spec/parse-metadata context :service format metadata)
_ (validate-all-fields context service)
full-concept (as-> concept intermediate
(add-extra-fields-for-service context intermediate service)
(add-top-fields-for-service intermediate))
{:keys [concept-id revision-id]} (mdb2/save-concept context full-concept)]
{:concept-id concept-id
:revision-id revision-id}))
|
|
777da259305e03ac4d6a2946b41210cdb304b103d5b33ba4959c88560c615072 | yomimono/stitchcraft | embellish_stitch.ml | open Cmdliner
let corner =
let doc = "Corner border image (oriented to upper-left corner)." in
Arg.(value & opt file "corner.pattern" & info ["corner"] ~docv:"CORNER" ~doc)
let rotate_corners =
let doc = "Rotate the corner image 90 degrees clockwise for each corner \
going clockwise from the upper left." in
Arg.(value & flag & info ["rotate"] ~docv:"ROTATE" ~doc)
let top =
let doc = "top border pattern (oriented horizontally). Will be repeated as necessary to fill the space needed, and rotated to form the left, bottom, and right borders." in
Arg.(value & opt file "top.pattern" & info ["top"] ~docv:"TOP" ~doc)
let fencepost =
let doc = "Pattern to interpose between repetitions of the border, and between the first and last repetition and the corners." in
Arg.(value & opt (some file) None & info ["fencepost"] ~docv:"FENCEPOST" ~doc)
let center =
let doc = "Center pattern. Corner and side will be inserted to surround this image." in
Arg.(value & opt file "center.pattern" & info ["center"] ~docv:"CENTER" ~doc)
let min_width =
let doc = "minimum width for the final pattern" in
Arg.(value & opt int 1 & info ["min_width"] ~docv:"MIN_WIDTH" ~doc)
let output =
let doc = "Where to output the finished, embellished pattern. -, the default, is stdout." in
Arg.(value & opt string "-" & info ["o"; "output"] ~docv:"OUTPUT" ~doc)
let info =
let doc = "embellish a pattern with corner and border images" in
Cmd.info "embellish" ~doc
let spoo output json =
if 0 = String.compare output "-" then Yojson.Safe.to_channel stdout json
else Yojson.Safe.to_file output json
let go fencepost rotate_corners corner top center min_width output =
let (corner, top, center) = try
Yojson.Safe.(from_file corner, from_file top, from_file center)
with
| _ -> failwith "couldn't read an input file"
in
let fencepost = match fencepost with
| None -> Ok None
| Some f ->
try Yojson.Safe.from_file f |>
Stitchy.Types.pattern_of_yojson |> function
| Ok fencepost -> Ok (Some fencepost)
| Error s -> Error s
with _ -> Error "couldn't read fencepost pattern"
in
match Stitchy.Types.(fencepost,
pattern_of_yojson corner,
pattern_of_yojson top,
pattern_of_yojson center) with
| Ok fencepost, Ok corner, Ok top, Ok center ->
Borders.embellish ~min_width ~fencepost ~rotate_corners ~center ~corner ~top
|> Stitchy.Types.pattern_to_yojson
|> spoo output
| _, _, _, _ -> failwith (Printf.sprintf "failed to parse input json")
let compose_t = Term.(const go $ fencepost $ rotate_corners $ corner $ top $ center $ min_width $ output)
let () = exit @@ Cmd.eval @@ Cmd.v info compose_t
| null | https://raw.githubusercontent.com/yomimono/stitchcraft/f2920cb13be030fecab1d23d9320ace051767158/embellish/src/embellish_stitch.ml | ocaml | open Cmdliner
let corner =
let doc = "Corner border image (oriented to upper-left corner)." in
Arg.(value & opt file "corner.pattern" & info ["corner"] ~docv:"CORNER" ~doc)
let rotate_corners =
let doc = "Rotate the corner image 90 degrees clockwise for each corner \
going clockwise from the upper left." in
Arg.(value & flag & info ["rotate"] ~docv:"ROTATE" ~doc)
let top =
let doc = "top border pattern (oriented horizontally). Will be repeated as necessary to fill the space needed, and rotated to form the left, bottom, and right borders." in
Arg.(value & opt file "top.pattern" & info ["top"] ~docv:"TOP" ~doc)
let fencepost =
let doc = "Pattern to interpose between repetitions of the border, and between the first and last repetition and the corners." in
Arg.(value & opt (some file) None & info ["fencepost"] ~docv:"FENCEPOST" ~doc)
let center =
let doc = "Center pattern. Corner and side will be inserted to surround this image." in
Arg.(value & opt file "center.pattern" & info ["center"] ~docv:"CENTER" ~doc)
let min_width =
let doc = "minimum width for the final pattern" in
Arg.(value & opt int 1 & info ["min_width"] ~docv:"MIN_WIDTH" ~doc)
let output =
let doc = "Where to output the finished, embellished pattern. -, the default, is stdout." in
Arg.(value & opt string "-" & info ["o"; "output"] ~docv:"OUTPUT" ~doc)
let info =
let doc = "embellish a pattern with corner and border images" in
Cmd.info "embellish" ~doc
let spoo output json =
if 0 = String.compare output "-" then Yojson.Safe.to_channel stdout json
else Yojson.Safe.to_file output json
let go fencepost rotate_corners corner top center min_width output =
let (corner, top, center) = try
Yojson.Safe.(from_file corner, from_file top, from_file center)
with
| _ -> failwith "couldn't read an input file"
in
let fencepost = match fencepost with
| None -> Ok None
| Some f ->
try Yojson.Safe.from_file f |>
Stitchy.Types.pattern_of_yojson |> function
| Ok fencepost -> Ok (Some fencepost)
| Error s -> Error s
with _ -> Error "couldn't read fencepost pattern"
in
match Stitchy.Types.(fencepost,
pattern_of_yojson corner,
pattern_of_yojson top,
pattern_of_yojson center) with
| Ok fencepost, Ok corner, Ok top, Ok center ->
Borders.embellish ~min_width ~fencepost ~rotate_corners ~center ~corner ~top
|> Stitchy.Types.pattern_to_yojson
|> spoo output
| _, _, _, _ -> failwith (Printf.sprintf "failed to parse input json")
let compose_t = Term.(const go $ fencepost $ rotate_corners $ corner $ top $ center $ min_width $ output)
let () = exit @@ Cmd.eval @@ Cmd.v info compose_t
|
|
e9defde719a3f6dcb1e11321737c89cc23b06a42215411db26f13494a355f367 | chaoxu/mgccl-haskell | mgap.hs | import Data.List
import Rosalind
main :: IO ()
main = do s <- getLine
t <- getLine
print $ length s + length t - (2 * length (lcs s t))
| null | https://raw.githubusercontent.com/chaoxu/mgccl-haskell/bb03e39ae43f410bd2a673ac2b438929ab8ef7a1/rosalind/mgap.hs | haskell | import Data.List
import Rosalind
main :: IO ()
main = do s <- getLine
t <- getLine
print $ length s + length t - (2 * length (lcs s t))
|
|
85ad955a7e6e99b6b4eaa26b875c99ca9112dcd6ffea7ff3f298772c0ee718ee | goldfirere/thesis | Sec211.hs | Adapted from 's ICFP ' 13 paper .
# LANGUAGE TypeInType , RebindableSyntax #
module Sec211 where
import Effects
import Effect.State
import Data.Nat
import Prelude ( Show, Ord(..), otherwise, foldl, flip )
data Tree a = Leaf
| Node (Tree a) a (Tree a)
deriving Show
tag :: Tree a -> Eff m '[STATE Nat] (Tree (Nat, a))
tag Leaf = return Leaf
tag (Node l x r)
= do l' <- tag l
lbl <- get
put (lbl + 1)
r' <- tag r
return (Node l' (lbl, x) r')
tagFrom :: Nat -> Tree a -> Tree (Nat, a)
tagFrom x t = runPure (x :> Empty) (tag t)
insert :: Ord a => a -> Tree a -> Tree a
insert x Leaf = Node Leaf x Leaf
insert x (Node l x' r)
| x < x' = Node (insert x l) x' r
| otherwise = Node l x' (insert x r)
inserts :: Ord a => [a] -> Tree a -> Tree a
inserts xs t = foldl (flip insert) t xs
tree :: Tree Nat
tree = inserts [4, 3, 8, 0, 2, 6, 7] Leaf
taggedTree :: Tree (Nat, Nat)
taggedTree = tagFrom 0 tree
| null | https://raw.githubusercontent.com/goldfirere/thesis/22f066bc26b1147530525aabb3df686416b3e4aa/effects/Sec211.hs | haskell | Adapted from 's ICFP ' 13 paper .
# LANGUAGE TypeInType , RebindableSyntax #
module Sec211 where
import Effects
import Effect.State
import Data.Nat
import Prelude ( Show, Ord(..), otherwise, foldl, flip )
data Tree a = Leaf
| Node (Tree a) a (Tree a)
deriving Show
tag :: Tree a -> Eff m '[STATE Nat] (Tree (Nat, a))
tag Leaf = return Leaf
tag (Node l x r)
= do l' <- tag l
lbl <- get
put (lbl + 1)
r' <- tag r
return (Node l' (lbl, x) r')
tagFrom :: Nat -> Tree a -> Tree (Nat, a)
tagFrom x t = runPure (x :> Empty) (tag t)
insert :: Ord a => a -> Tree a -> Tree a
insert x Leaf = Node Leaf x Leaf
insert x (Node l x' r)
| x < x' = Node (insert x l) x' r
| otherwise = Node l x' (insert x r)
inserts :: Ord a => [a] -> Tree a -> Tree a
inserts xs t = foldl (flip insert) t xs
tree :: Tree Nat
tree = inserts [4, 3, 8, 0, 2, 6, 7] Leaf
taggedTree :: Tree (Nat, Nat)
taggedTree = tagFrom 0 tree
|
|
2c372c21f02edf007865c4c740780c11a70c01112dfb98a3cbc89822f05a710b | Andromedans/andromeda | syntax.mli | * Annotated abstract syntax for type theory .
type name = string
type label = string
(** We use de Bruijn indices *)
type variable = Common.debruijn
type ty = ty' * Position.t
and ty' =
| Type
| El of term
| RecordTy of (label * (name * ty)) list
| Prod of name * ty * ty
| Id of ty * term * term
and term = term' * Position.t
and term' =
| Var of variable
| Ascribe of term * ty
| Lambda of name * ty * ty * term
| App of (name * ty * ty) * term * term
| Spine of variable * ty * term list
| Record of (label * (name * ty * term)) list
| Project of term * (label * (name * ty)) list * label
| Refl of ty * term
| NameType
| NameRecordTy of (label * (name * term)) list
| NameProd of name * term * term
| NameId of term * term * term
(*********************************)
(* Construction helper functions *)
(*********************************)
val mkType : ?loc:Position.t -> unit -> ty
val mkEl : ?loc:Position.t -> term -> ty
val mkRecordTy : ?loc:Position.t -> (label * (name * ty)) list -> ty
val mkProd : ?loc:Position.t -> name -> ty -> ty -> ty
val mkId : ?loc:Position.t -> ty -> term -> term -> ty
val make_arrow: ?loc:Position.t -> ty -> ty -> ty
val mkVar : ?loc:Position.t -> variable -> term
val mkAscribe : ?loc:Position.t -> term -> ty -> term
val mkLambda : ?loc:Position.t -> name -> ty -> ty -> term -> term
val mkApp : ?loc:Position.t -> name -> ty -> ty -> term -> term -> term
val mkSpine : ?loc:Position.t -> variable -> ty -> term list -> term
val mkRecord : ?loc:Position.t -> (label * (name * ty * term)) list -> term
val mkProject : ?loc:Position.t -> term -> (label * (name * ty)) list -> label -> term
val mkRefl : ?loc:Position.t -> ty -> term -> term
val mkNameRecordTy : ?loc:Position.t -> (label * (name * term)) list -> term
val mkNameProd : ?loc:Position.t -> name -> term -> term -> term
val mkNameType : ?loc:Position.t -> unit -> term
val mkNameId : ?loc:Position.t -> term -> term -> term -> term
(********)
(* Code *)
(********)
(** Anonymous identifier *)
val anonymous : name
(** alpha equality of terms, ignoring hints *)
val equal : term -> term -> bool
(** alpha equality of types, ignoring hints inside terms *)
val equal_ty : ty -> ty -> bool
(** [shift delta term] shifts the free variables in [term] by [delta],
raising [exn] if a negative variable is produced by the shift.
Variables whose index is below [bound] are considered bound and therefore
not shifted. *)
val shift : ?exn:exn -> ?bound:int -> int -> term -> term
* [ shift_ty delta ty ] shifts the free variables in [ ty ] by [ delta ] ,
raising [ exn ] if a negative variable is produced by the shift .
Variables whose index is below [ bound ] are considered bound and therefore
not shifted .
raising [exn] if a negative variable is produced by the shift.
Variables whose index is below [bound] are considered bound and therefore
not shifted. *)
val shift_ty : ?exn:exn -> ?bound:int -> int -> ty -> ty
(**
If [G, x:t |- body : ...] and [G |- arg : t] then
[beta body arg] is the substituted term [body[x->arg]].
This is exactly the substitution required, for example, to
beta-reduce a function application ([body] is the body of the lambda).
*)
val beta : term -> term -> term
*
If [ G , x : t |- body : type ] and [ G |- arg : t ] then
[ beta_ty body arg ] is the substituted type [ body[x->arg ] ] .
This is exactly the substitution required , for example , to
to substitute away the parameter in a [ Pi ] or [ Sigma ] type ( [ body ] is
the type of the codomain or second component , respectively ) .
If [G, x:t |- body : type] and [G |- arg : t] then
[beta_ty body arg] is the substituted type [body[x->arg]].
This is exactly the substitution required, for example, to
to substitute away the parameter in a [Pi] or [Sigma] type ([body] is
the type of the codomain or second component, respectively).
*)
val beta_ty : ty -> term -> ty
*
If [ G , x_1 : t_1 , .. , x_n : t_n |- body : type ] and [ G |- arg_i : t_i ]
[ betas_ty body [ arg_1 ; ... ; arg_n ] ] is the substituted type
[ G |- body[x_1->arg_1 , ... , x_n->arg_n ] ] .
If [G, x_1:t_1, .., x_n:t_n |- body : type] and [G |- arg_i : t_i]
[betas_ty body [arg_1; ...; arg_n]] is the substituted type
[G |- body[x_1->arg_1, ..., x_n->arg_n]].
*)
val betas_ty : ty -> term list -> ty
*
Suppose we have [ G , x_1 : t_1 , ... , x_n : t_n |- exp : ... ] and the inhabitants
[ e_1 ; ... ; e_n ] all well - formed in ( i.e. , indexed relative to ) [ G ] ( ! ) . Then
[ strengthen exp [ e_1, ... ,e_n ] ] is the result of substituting away the
[ x_i ] 's , resulting in a term well - formed in [ G ] .
In particular , [ strengthen eBody [ eArg ] ] is just [ beta eBody eArg ] .
Suppose we have [G, x_1:t_1, ..., x_n:t_n |- exp : ...] and the inhabitants
[e_1; ...; e_n] all well-formed in (i.e., indexed relative to) [G] (!). Then
[strengthen exp [e_1,...,e_n]] is the result of substituting away the
[x_i]'s, resulting in a term well-formed in [G].
In particular, [strengthen eBody [eArg]] is just [beta eBody eArg].
*)
val strengthen : term -> term list -> term
(** Like [strengthen], but for types *)
val strengthen_ty : ty -> term list -> ty
* If [ G |- exp ] then [ G ' |- weaken i exp ] , where [ G ' ] has
one extra ( unused ) variable inserted at former position [ i ] . The name of
that variable does n't matter , because we 're in de Bruijn notation .
E.g. , if [ x3 , x2 , x1 , t ] then
then [ x3 , x2 , z , x1 , ( weaken 2 e ) : ( weaken_ty 2 t ) ]
In particular , [ weaken 0 e ] is the same as [ shift 1 e ] .
one extra (unused) variable inserted at former position [i]. The name of
that variable doesn't matter, because we're in de Bruijn notation.
E.g., if [x3, x2, x1, x0 |- e : t] then
then [x3, x2, z, x1, x0 |- (weaken 2 e) : (weaken_ty 2 t)]
In particular, [weaken 0 e] is the same as [shift 1 e].
*)
val weaken : int -> term -> term
(** Like [weaken], but for types *)
val weaken_ty : int -> ty -> ty
(** Check for occurrences of a free variable in a term *)
val occurs : Common.debruijn -> term -> bool
(** Check for occurrences of a free variable in a type *)
val occurs_ty : Common.debruijn -> ty -> bool
(** Simplify a term *)
val simplify : term -> term
(** Simplify a type *)
val simplify_ty : ty -> ty
val from_spine : ?loc:Position.t -> variable -> ty -> term list -> term
val fold_left_spine : Position.t ->
(name -> ty -> ty -> 'b -> term -> 'b) ->
'b -> ty -> term list -> 'b
val fold_left2_spine : Position.t ->
(name -> ty -> ty -> 'b -> 'a -> term -> 'b) ->
'b -> ty -> 'a list -> term list -> 'b
val whnf : ty -> term -> term
val whnf_ty : ty -> ty
| null | https://raw.githubusercontent.com/Andromedans/andromeda/a5c678450e6c6d4a7cd5eee1196bde558541b994/archive/old-andromeda/syntax.mli | ocaml | * We use de Bruijn indices
*******************************
Construction helper functions
*******************************
******
Code
******
* Anonymous identifier
* alpha equality of terms, ignoring hints
* alpha equality of types, ignoring hints inside terms
* [shift delta term] shifts the free variables in [term] by [delta],
raising [exn] if a negative variable is produced by the shift.
Variables whose index is below [bound] are considered bound and therefore
not shifted.
*
If [G, x:t |- body : ...] and [G |- arg : t] then
[beta body arg] is the substituted term [body[x->arg]].
This is exactly the substitution required, for example, to
beta-reduce a function application ([body] is the body of the lambda).
* Like [strengthen], but for types
* Like [weaken], but for types
* Check for occurrences of a free variable in a term
* Check for occurrences of a free variable in a type
* Simplify a term
* Simplify a type | * Annotated abstract syntax for type theory .
type name = string
type label = string
type variable = Common.debruijn
type ty = ty' * Position.t
and ty' =
| Type
| El of term
| RecordTy of (label * (name * ty)) list
| Prod of name * ty * ty
| Id of ty * term * term
and term = term' * Position.t
and term' =
| Var of variable
| Ascribe of term * ty
| Lambda of name * ty * ty * term
| App of (name * ty * ty) * term * term
| Spine of variable * ty * term list
| Record of (label * (name * ty * term)) list
| Project of term * (label * (name * ty)) list * label
| Refl of ty * term
| NameType
| NameRecordTy of (label * (name * term)) list
| NameProd of name * term * term
| NameId of term * term * term
val mkType : ?loc:Position.t -> unit -> ty
val mkEl : ?loc:Position.t -> term -> ty
val mkRecordTy : ?loc:Position.t -> (label * (name * ty)) list -> ty
val mkProd : ?loc:Position.t -> name -> ty -> ty -> ty
val mkId : ?loc:Position.t -> ty -> term -> term -> ty
val make_arrow: ?loc:Position.t -> ty -> ty -> ty
val mkVar : ?loc:Position.t -> variable -> term
val mkAscribe : ?loc:Position.t -> term -> ty -> term
val mkLambda : ?loc:Position.t -> name -> ty -> ty -> term -> term
val mkApp : ?loc:Position.t -> name -> ty -> ty -> term -> term -> term
val mkSpine : ?loc:Position.t -> variable -> ty -> term list -> term
val mkRecord : ?loc:Position.t -> (label * (name * ty * term)) list -> term
val mkProject : ?loc:Position.t -> term -> (label * (name * ty)) list -> label -> term
val mkRefl : ?loc:Position.t -> ty -> term -> term
val mkNameRecordTy : ?loc:Position.t -> (label * (name * term)) list -> term
val mkNameProd : ?loc:Position.t -> name -> term -> term -> term
val mkNameType : ?loc:Position.t -> unit -> term
val mkNameId : ?loc:Position.t -> term -> term -> term -> term
val anonymous : name
val equal : term -> term -> bool
val equal_ty : ty -> ty -> bool
val shift : ?exn:exn -> ?bound:int -> int -> term -> term
* [ shift_ty delta ty ] shifts the free variables in [ ty ] by [ delta ] ,
raising [ exn ] if a negative variable is produced by the shift .
Variables whose index is below [ bound ] are considered bound and therefore
not shifted .
raising [exn] if a negative variable is produced by the shift.
Variables whose index is below [bound] are considered bound and therefore
not shifted. *)
val shift_ty : ?exn:exn -> ?bound:int -> int -> ty -> ty
val beta : term -> term -> term
*
If [ G , x : t |- body : type ] and [ G |- arg : t ] then
[ beta_ty body arg ] is the substituted type [ body[x->arg ] ] .
This is exactly the substitution required , for example , to
to substitute away the parameter in a [ Pi ] or [ Sigma ] type ( [ body ] is
the type of the codomain or second component , respectively ) .
If [G, x:t |- body : type] and [G |- arg : t] then
[beta_ty body arg] is the substituted type [body[x->arg]].
This is exactly the substitution required, for example, to
to substitute away the parameter in a [Pi] or [Sigma] type ([body] is
the type of the codomain or second component, respectively).
*)
val beta_ty : ty -> term -> ty
*
If [ G , x_1 : t_1 , .. , x_n : t_n |- body : type ] and [ G |- arg_i : t_i ]
[ betas_ty body [ arg_1 ; ... ; arg_n ] ] is the substituted type
[ G |- body[x_1->arg_1 , ... , x_n->arg_n ] ] .
If [G, x_1:t_1, .., x_n:t_n |- body : type] and [G |- arg_i : t_i]
[betas_ty body [arg_1; ...; arg_n]] is the substituted type
[G |- body[x_1->arg_1, ..., x_n->arg_n]].
*)
val betas_ty : ty -> term list -> ty
*
Suppose we have [ G , x_1 : t_1 , ... , x_n : t_n |- exp : ... ] and the inhabitants
[ e_1 ; ... ; e_n ] all well - formed in ( i.e. , indexed relative to ) [ G ] ( ! ) . Then
[ strengthen exp [ e_1, ... ,e_n ] ] is the result of substituting away the
[ x_i ] 's , resulting in a term well - formed in [ G ] .
In particular , [ strengthen eBody [ eArg ] ] is just [ beta eBody eArg ] .
Suppose we have [G, x_1:t_1, ..., x_n:t_n |- exp : ...] and the inhabitants
[e_1; ...; e_n] all well-formed in (i.e., indexed relative to) [G] (!). Then
[strengthen exp [e_1,...,e_n]] is the result of substituting away the
[x_i]'s, resulting in a term well-formed in [G].
In particular, [strengthen eBody [eArg]] is just [beta eBody eArg].
*)
val strengthen : term -> term list -> term
val strengthen_ty : ty -> term list -> ty
* If [ G |- exp ] then [ G ' |- weaken i exp ] , where [ G ' ] has
one extra ( unused ) variable inserted at former position [ i ] . The name of
that variable does n't matter , because we 're in de Bruijn notation .
E.g. , if [ x3 , x2 , x1 , t ] then
then [ x3 , x2 , z , x1 , ( weaken 2 e ) : ( weaken_ty 2 t ) ]
In particular , [ weaken 0 e ] is the same as [ shift 1 e ] .
one extra (unused) variable inserted at former position [i]. The name of
that variable doesn't matter, because we're in de Bruijn notation.
E.g., if [x3, x2, x1, x0 |- e : t] then
then [x3, x2, z, x1, x0 |- (weaken 2 e) : (weaken_ty 2 t)]
In particular, [weaken 0 e] is the same as [shift 1 e].
*)
val weaken : int -> term -> term
val weaken_ty : int -> ty -> ty
val occurs : Common.debruijn -> term -> bool
val occurs_ty : Common.debruijn -> ty -> bool
val simplify : term -> term
val simplify_ty : ty -> ty
val from_spine : ?loc:Position.t -> variable -> ty -> term list -> term
val fold_left_spine : Position.t ->
(name -> ty -> ty -> 'b -> term -> 'b) ->
'b -> ty -> term list -> 'b
val fold_left2_spine : Position.t ->
(name -> ty -> ty -> 'b -> 'a -> term -> 'b) ->
'b -> ty -> 'a list -> term list -> 'b
val whnf : ty -> term -> term
val whnf_ty : ty -> ty
|
03af9e1ee6306e5305a18199e9ec3762925e0319d55e2573e8107c4ac3c6914a | ftovagliari/ocamleditor | dialog_goto.ml | [@@@warning "-48"]
open GdkKeysyms
let show ~view () =
try begin
let w = GWindow.window
~title: "Go to..."
~resizable:false
~type_hint:`DIALOG
~allow_grow:false
~allow_shrink:false
~position:`CENTER_ALWAYS
~modal:true () in
Gmisclib.Window.GeometryMemo.add (!Otherwidgets_config.geometry_memo()) ~key:"dialog-goto-line" ~window:w;
let vbox = GPack.vbox ~border_width:8 ~spacing:8 ~packing:w#add () in
let eb = GPack.hbox ~spacing:3 ~packing:vbox#add () in
let _ = GMisc.label ~text:"Line Number: " ~xalign:0.0 ~width:120 ~packing:(eb#pack ~expand:false) () in
let line = GEdit.entry ~packing:eb#add () in
let eb = GPack.hbox ~spacing:3 ~packing:vbox#add () in
let _ = GMisc.label ~text:"Line(Buffer) Offset: " ~xalign:0.0 ~width:120 ~packing:(eb#pack ~expand:false) () in
let char = GEdit.entry ~packing:eb#add () in
let _ = GMisc.separator `HORIZONTAL ~packing:vbox#add () in
let bbox = GPack.button_box `HORIZONTAL ~layout:`END ~spacing:8 ~packing:vbox#add () in
let button_ok = GButton.button ~stock:`OK ~packing:bbox#add () in
let button_cancel = GButton.button ~stock:`CANCEL ~packing:bbox#add () in
let callback () =
try
let buf = view#buffer in
let char = try int_of_string char#text with _ -> 0 in
let where =
if String.trim line#text = "" then begin
let offset = max 0 (min char buf#end_iter#offset) in
buf#get_iter (`OFFSET offset)
end else begin
let line = (int_of_string line#text) - 1 in
let where = buf#get_iter (`LINE line) in
let char = max 0 (min (where#chars_in_line - 1) char) in
buf#get_iter (`LINECHAR (line, char))
end;
in
view#buffer#place_cursor ~where;
view#scroll_lazy where;
w#destroy();
with e -> Dialog.display_exn ~parent:view e
in
button_ok#connect#clicked ~callback:(fun () -> callback(); w#destroy()) |> ignore;
button_cancel#connect#clicked ~callback:w#destroy |> ignore;
w#event#connect#key_press ~callback:begin fun ev ->
let key = GdkEvent.Key.keyval ev in
if key = _Return then begin
callback();
true
end else if key = _Escape then begin
w#destroy();
true
end else false;
end |> ignore;
line#misc#grab_focus();
Gaux.may ~f:(fun x -> w#set_transient_for x#as_window) (GWindow.toplevel view);
w#present()
end with e -> Dialog.display_exn ~parent:view e;
| null | https://raw.githubusercontent.com/ftovagliari/ocamleditor/53284253cf7603b96051e7425e85a731f09abcd1/src/otherwidgets/dialog_goto.ml | ocaml | [@@@warning "-48"]
open GdkKeysyms
let show ~view () =
try begin
let w = GWindow.window
~title: "Go to..."
~resizable:false
~type_hint:`DIALOG
~allow_grow:false
~allow_shrink:false
~position:`CENTER_ALWAYS
~modal:true () in
Gmisclib.Window.GeometryMemo.add (!Otherwidgets_config.geometry_memo()) ~key:"dialog-goto-line" ~window:w;
let vbox = GPack.vbox ~border_width:8 ~spacing:8 ~packing:w#add () in
let eb = GPack.hbox ~spacing:3 ~packing:vbox#add () in
let _ = GMisc.label ~text:"Line Number: " ~xalign:0.0 ~width:120 ~packing:(eb#pack ~expand:false) () in
let line = GEdit.entry ~packing:eb#add () in
let eb = GPack.hbox ~spacing:3 ~packing:vbox#add () in
let _ = GMisc.label ~text:"Line(Buffer) Offset: " ~xalign:0.0 ~width:120 ~packing:(eb#pack ~expand:false) () in
let char = GEdit.entry ~packing:eb#add () in
let _ = GMisc.separator `HORIZONTAL ~packing:vbox#add () in
let bbox = GPack.button_box `HORIZONTAL ~layout:`END ~spacing:8 ~packing:vbox#add () in
let button_ok = GButton.button ~stock:`OK ~packing:bbox#add () in
let button_cancel = GButton.button ~stock:`CANCEL ~packing:bbox#add () in
let callback () =
try
let buf = view#buffer in
let char = try int_of_string char#text with _ -> 0 in
let where =
if String.trim line#text = "" then begin
let offset = max 0 (min char buf#end_iter#offset) in
buf#get_iter (`OFFSET offset)
end else begin
let line = (int_of_string line#text) - 1 in
let where = buf#get_iter (`LINE line) in
let char = max 0 (min (where#chars_in_line - 1) char) in
buf#get_iter (`LINECHAR (line, char))
end;
in
view#buffer#place_cursor ~where;
view#scroll_lazy where;
w#destroy();
with e -> Dialog.display_exn ~parent:view e
in
button_ok#connect#clicked ~callback:(fun () -> callback(); w#destroy()) |> ignore;
button_cancel#connect#clicked ~callback:w#destroy |> ignore;
w#event#connect#key_press ~callback:begin fun ev ->
let key = GdkEvent.Key.keyval ev in
if key = _Return then begin
callback();
true
end else if key = _Escape then begin
w#destroy();
true
end else false;
end |> ignore;
line#misc#grab_focus();
Gaux.may ~f:(fun x -> w#set_transient_for x#as_window) (GWindow.toplevel view);
w#present()
end with e -> Dialog.display_exn ~parent:view e;
|
|
0cbab18944d31c611802cffa85e42f4355efe9e0d70bdf5777df5f14d2332e9b | atomvm/atomvm_mqtt_client | mqtt_client_example.erl | %%
Copyright ( c ) 2021 dushin.net
%% All rights reserved.
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
-module(mqtt_client_example).
-export([start/0]).
start() ->
%%
%% Start the network
%%
ok = start_network(maps:get(sta, config:get())),
%%
Start the MQTT client .
%%
Config = #{
url => "mqtt",
connected_handler => fun handle_connected/1
},
{ok, _MQTT} = mqtt_client:start(Config),
io:format("MQTT started.~n"),
loop_forever().
loop_forever() ->
receive
halt -> halt
end.
%%
%% connected callback. This function will be called
%%
handle_connected(MQTT) ->
Config = mqtt_client:get_config(MQTT),
Topic = <<"atomvm/qos0">>,
io:format("Connected to ~p~n", [maps:get(url, Config)]),
io:format("Subscribing to ~p...~n", [Topic]),
ok = mqtt_client:subscribe(MQTT, Topic, #{
subscribed_handler => fun handle_subscribed/2,
data_handler => fun handle_data/3
}).
handle_subscribed(MQTT, Topic) ->
io:format("Subscribed to ~p.~n", [Topic]),
io:format("Spawning publish loop on topic ~p~n", [Topic]),
spawn(fun() -> publish_loop(MQTT, Topic, 1) end).
handle_data(_MQTT, Topic, Data) ->
io:format("Received data on topic ~p: ~p ~n", [Topic, Data]),
io : format("Pending publishes : ~p ~ n " , [ mqtt_client : ) ] ) ,
% io:format("Pending subscriptions: ~p~n", [mqtt_client:get_pending_subscriptions(MQTT)]),
% io:format("Pending unsubscriptions: ~p~n", [mqtt_client:get_pending_unsubscriptions(MQTT)]),
io:format("process count: ~p~n", [erlang:system_info(process_count)]),
io:format("Free heap on handle_data: ~p~n", [erlang:system_info(esp32_free_heap_size)]),
ok.
start_network(StaConfig) ->
case network_fsm:wait_for_sta(StaConfig) of
{ok, {Address, Netmask, Gateway}} ->
io:format(
"Acquired IP address: ~s Netmask: ~s Gateway: ~s~n",
[Address, Netmask, Gateway]
),
ok;
Error ->
throw({unable_to_start_network, Error})
end.
publish_loop(MQTT, Topic, Seq) ->
io:format("Publishing data on topic ~p~n", [Topic]),
_ = mqtt_client:publish(MQTT, Topic, list_to_binary("echo" ++ integer_to_list(Seq))),
timer:sleep(5000),
io:format("process count: ~p~n", [erlang:system_info(process_count)]),
io:format("Free heap after publish: ~p~n", [erlang:system_info(esp32_free_heap_size)]),
publish_loop(MQTT, Topic, Seq + 1).
| null | https://raw.githubusercontent.com/atomvm/atomvm_mqtt_client/b41c1cba1d8bb999edec9361dfe643c521a930cd/examples/mqtt_client_example/src/mqtt_client_example.erl | erlang |
All rights reserved.
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.
Start the network
connected callback. This function will be called
io:format("Pending subscriptions: ~p~n", [mqtt_client:get_pending_subscriptions(MQTT)]),
io:format("Pending unsubscriptions: ~p~n", [mqtt_client:get_pending_unsubscriptions(MQTT)]), | Copyright ( c ) 2021 dushin.net
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(mqtt_client_example).
-export([start/0]).
start() ->
ok = start_network(maps:get(sta, config:get())),
Start the MQTT client .
Config = #{
url => "mqtt",
connected_handler => fun handle_connected/1
},
{ok, _MQTT} = mqtt_client:start(Config),
io:format("MQTT started.~n"),
loop_forever().
loop_forever() ->
receive
halt -> halt
end.
handle_connected(MQTT) ->
Config = mqtt_client:get_config(MQTT),
Topic = <<"atomvm/qos0">>,
io:format("Connected to ~p~n", [maps:get(url, Config)]),
io:format("Subscribing to ~p...~n", [Topic]),
ok = mqtt_client:subscribe(MQTT, Topic, #{
subscribed_handler => fun handle_subscribed/2,
data_handler => fun handle_data/3
}).
handle_subscribed(MQTT, Topic) ->
io:format("Subscribed to ~p.~n", [Topic]),
io:format("Spawning publish loop on topic ~p~n", [Topic]),
spawn(fun() -> publish_loop(MQTT, Topic, 1) end).
handle_data(_MQTT, Topic, Data) ->
io:format("Received data on topic ~p: ~p ~n", [Topic, Data]),
io : format("Pending publishes : ~p ~ n " , [ mqtt_client : ) ] ) ,
io:format("process count: ~p~n", [erlang:system_info(process_count)]),
io:format("Free heap on handle_data: ~p~n", [erlang:system_info(esp32_free_heap_size)]),
ok.
start_network(StaConfig) ->
case network_fsm:wait_for_sta(StaConfig) of
{ok, {Address, Netmask, Gateway}} ->
io:format(
"Acquired IP address: ~s Netmask: ~s Gateway: ~s~n",
[Address, Netmask, Gateway]
),
ok;
Error ->
throw({unable_to_start_network, Error})
end.
publish_loop(MQTT, Topic, Seq) ->
io:format("Publishing data on topic ~p~n", [Topic]),
_ = mqtt_client:publish(MQTT, Topic, list_to_binary("echo" ++ integer_to_list(Seq))),
timer:sleep(5000),
io:format("process count: ~p~n", [erlang:system_info(process_count)]),
io:format("Free heap after publish: ~p~n", [erlang:system_info(esp32_free_heap_size)]),
publish_loop(MQTT, Topic, Seq + 1).
|
adacf9b4321cd6ae5e6b7b15f33820e92f43ef81c9d14bbbedabf64dd7535eb7 | emqx/mria | mria_lb.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
%% @doc This server runs on the replicant and periodically checks the
status of core nodes in case we need to RPC to one of them .
-module(mria_lb).
-behaviour(gen_server).
%% API
-export([ start_link/0
, probe/2
, core_nodes/0
, join_cluster/1
, leave_cluster/0
]).
%% gen_server callbacks
-export([ init/1
, terminate/2
, handle_call/3
, handle_cast/2
, handle_info/2
, code_change/3
]).
%% Internal exports
-export([ core_node_weight/1
, lb_callback/0
]).
-include_lib("snabbkaffe/include/trace.hrl").
-include("mria_rlog.hrl").
%%================================================================================
%% Type declarations
%%================================================================================
-type core_protocol_versions() :: #{node() => integer()}.
-record(s,
{ core_protocol_versions :: core_protocol_versions()
, core_nodes :: [node()]
}).
-type node_info() ::
#{ running := boolean()
, whoami := core | replicant | mnesia
, version := string() | undefined
, protocol_version := non_neg_integer()
, db_nodes => [node()]
, shard_badness => [{mria_rlog:shard(), float()}]
}.
-define(update, update).
-define(SERVER, ?MODULE).
-define(CORE_DISCOVERY_TIMEOUT, 30000).
%%================================================================================
%% API
%%================================================================================
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
-spec probe(node(), mria_rlog:shard()) -> boolean().
probe(Node, Shard) ->
gen_server:call(?SERVER, {probe, Node, Shard}).
-spec core_nodes() -> [node()].
core_nodes() ->
gen_server:call(?SERVER, core_nodes, ?CORE_DISCOVERY_TIMEOUT).
join_cluster(Node) ->
{ok, FD} = file:open(seed_file(), [write]),
ok = io:format(FD, "~p.", [Node]),
file:close(FD).
leave_cluster() ->
case file:delete(seed_file()) of
ok ->
ok;
{error, enoent} ->
ok;
{error, Err} ->
error(Err)
end.
%%================================================================================
%% gen_server callbacks
%%================================================================================
init(_) ->
process_flag(trap_exit, true),
logger:set_process_metadata(#{domain => [mria, rlog, lb]}),
start_timer(),
mria_membership:monitor(membership, self(), true),
State = #s{ core_protocol_versions = #{}
, core_nodes = []
},
{ok, State}.
handle_info(?update, St) ->
start_timer(),
{noreply, do_update(St)};
handle_info({membership, Event}, St) ->
case Event of
{mnesia, down, _Node} -> %% Trigger update immediately when core node goes down
{noreply, do_update(St)};
_ -> %% Everything else is handled via timer
{noreply, St}
end;
handle_info(Info, St) ->
?unexpected_event_tp(#{info => Info, state => St}),
{noreply, St}.
handle_cast(Cast, St) ->
?unexpected_event_tp(#{cast => Cast, state => St}),
{noreply, St}.
handle_call({probe, Node, Shard}, _From, St0 = #s{core_protocol_versions = ProtoVSNs}) ->
LastVSNChecked = maps:get(Node, ProtoVSNs, undefined),
MyVersion = mria_rlog:get_protocol_version(),
ProbeResult = mria_lib:rpc_call_nothrow({Node, Shard}, mria_rlog_server, do_probe, [Shard]),
{Reply, ServerVersion} =
case ProbeResult of
{true, MyVersion} ->
{true, MyVersion};
{true, CurrentVersion} when CurrentVersion =/= LastVSNChecked ->
?tp(warning, "Different Mria version on the core node",
#{ my_version => MyVersion
, server_version => CurrentVersion
, last_version => LastVSNChecked
, node => Node
}),
{false, CurrentVersion};
_ ->
{false, LastVSNChecked}
end,
St = St0#s{core_protocol_versions = ProtoVSNs#{Node => ServerVersion}},
{reply, Reply, St};
handle_call(core_nodes, _From, St = #s{core_nodes = CoreNodes}) ->
{reply, CoreNodes, St};
handle_call(Call, From, St) ->
?unexpected_event_tp(#{call => Call, from => From, state => St}),
{reply, {error, {unknown_call, Call}}, St}.
code_change(_OldVsn, St, _Extra) ->
{ok, St}.
terminate(_Reason, St) ->
{ok, St}.
%%================================================================================
Internal functions
%%================================================================================
do_update(State = #s{core_nodes = OldCoreNodes}) ->
DiscoveredNodes = discover_nodes(),
%% Get information about core nodes:
{NodeInfo0, _BadNodes} = rpc:multicall( DiscoveredNodes
, ?MODULE, lb_callback, []
, mria_config:lb_timeout()
),
NodeInfo1 = [I || I = {_, #{whoami := core, running := true}} <- NodeInfo0],
NodeInfo = maps:from_list(NodeInfo1),
%% Find partitions of the core cluster, and if the core cluster is
%% partitioned choose the best partition to connect to:
Clusters = find_clusters(NodeInfo),
maybe_report_netsplit(OldCoreNodes, Clusters),
{IsChanged, NewCoreNodes} = find_best_cluster(OldCoreNodes, Clusters),
%% Update shards:
ShardBadness = shard_badness(maps:with(NewCoreNodes, NodeInfo)),
maps:map(fun(Shard, {Node, _Badness}) ->
mria_status:notify_core_node_up(Shard, Node)
end,
ShardBadness),
[mria_status:notify_core_node_down(Shard)
|| Shard <- mria_schema:shards() -- maps:keys(ShardBadness)],
%% Notify changes
IsChanged andalso
?tp(info, mria_lb_core_discovery_new_nodes,
#{ previous_cores => OldCoreNodes
, returned_cores => NewCoreNodes
, ignored_nodes => DiscoveredNodes -- NewCoreNodes
, node => node()
}),
IsChanged andalso
ping_core_nodes(NewCoreNodes),
State#s{core_nodes = NewCoreNodes}.
%% Find fully connected clusters (i.e. cliques of nodes)
-spec find_clusters(#{node() => node_info()}) -> [[node()]].
find_clusters(NodeInfo) ->
find_clusters(maps:keys(NodeInfo), NodeInfo, []).
find_clusters([], _NodeInfo, Acc) ->
Acc;
find_clusters([Node|Rest], NodeInfo, Acc) ->
#{Node := #{db_nodes := Emanent}} = NodeInfo,
MutualConnections =
lists:filter(
fun(Peer) ->
case NodeInfo of
#{Peer := #{db_nodes := Incident}} ->
lists:member(Node, Incident);
_ ->
false
end
end,
Emanent),
Cluster = lists:usort([Node|MutualConnections]),
find_clusters(Rest -- MutualConnections, NodeInfo, [Cluster|Acc]).
%% Find the preferred core node for each shard:
-spec shard_badness(#{node() => node_info()}) -> #{mria_rlog:shard() => {node(), Badness}}
when Badness :: float().
shard_badness(NodeInfo) ->
maps:fold(
fun(Node, #{shard_badness := Shards}, Acc) ->
lists:foldl(
fun({Shard, Badness}, Acc1) ->
maps:update_with(Shard,
fun({_OldNode, OldBadness}) when OldBadness > Badness ->
{Node, Badness};
(Old) ->
Old
end,
{Node, Badness},
Acc1)
end,
Acc,
Shards)
end,
#{},
NodeInfo).
start_timer() ->
Interval = mria_config:lb_poll_interval(),
erlang:send_after(Interval + rand:uniform(Interval), self(), ?update).
-spec find_best_cluster([node()], [[node()]]) -> {_Changed :: boolean(), [node()]}.
find_best_cluster([], []) ->
{false, []};
find_best_cluster(_OldNodes, []) ->
Discovery failed :
{true, []};
find_best_cluster(OldNodes, Clusters) ->
%% Heuristic: pick the best cluster in case of a split brain:
[Cluster | _] = lists:sort(fun(Cluster1, Cluster2) ->
cluster_score(OldNodes, Cluster1) >=
cluster_score(OldNodes, Cluster2)
end,
Clusters),
IsChanged = OldNodes =/= Cluster,
{IsChanged, Cluster}.
-spec maybe_report_netsplit([node()], [[node()]]) -> ok.
maybe_report_netsplit(OldNodes, Clusters) ->
Alarm = mria_lb_divergent_alarm,
case Clusters of
[_,_|_] ->
case get(Alarm) of
undefined ->
put(Alarm, true),
?tp(error, mria_lb_split_brain,
#{ previous_cores => OldNodes
, clusters => Clusters
, node => node()
});
_ ->
ok
end;
_ ->
%% All discovered nodes belong to the same cluster (or no clusters found):
erase(Alarm)
end,
ok.
-spec ping_core_nodes([node()]) -> ok.
ping_core_nodes(NewCoreNodes) ->
%% Replicants do not have themselves as local members.
%% We make an entry on the fly.
LocalMember = mria_membership:make_new_local_member(),
lists:foreach(
fun(Core) ->
mria_membership:ping(Core, LocalMember)
end, NewCoreNodes).
%%================================================================================
%% Internal exports
%%================================================================================
%% This function runs on the core node. TODO: remove in the next release
core_node_weight(Shard) ->
case whereis(Shard) of
undefined ->
undefined;
_Pid ->
NAgents = length(mria_status:agents(Shard)),
%% TODO: Add OLP check
Load = 1.0 * NAgents,
%% The return values will be lexicographically sorted. Load will
%% be distributed evenly between the nodes with the same weight
%% due to the random term:
{ok, {Load, rand:uniform(), node()}}
end.
Return a bunch of information about the node . Called via RPC .
-spec lb_callback() -> {node(), node_info()}.
lb_callback() ->
IsRunning = is_pid(whereis(mria_rlog_sup)),
Whoami = mria_config:whoami(),
Version = case application:get_key(mria, vsn) of
{ok, Vsn} -> Vsn;
undefined -> undefined
end,
BasicInfo =
#{ running => IsRunning
, version => Version
, whoami => Whoami
, protocol_version => mria_rlog:get_protocol_version()
},
MoreInfo =
case Whoami of
core when IsRunning ->
Badness = [begin
Load = length(mria_status:agents(Shard)) + rand:uniform(),
{Shard, Load}
end || Shard <- mria_schema:shards()],
#{ db_nodes => mria_mnesia:db_nodes()
, shard_badness => Badness
};
_ ->
#{}
end,
{node(), maps:merge(BasicInfo, MoreInfo)}.
%%================================================================================
Internal functions
%%================================================================================
-spec discover_nodes() -> [node()].
discover_nodes() ->
DiscoveryFun = mria_config:core_node_discovery_callback(),
case manual_seed() of
[] ->
%% Run the discovery algorithm
DiscoveryFun();
[Seed] ->
discover_manually(Seed)
end.
%% Return the last node that has been explicitly specified via
%% "mria:join" command. It overrides other discovery mechanisms.
-spec manual_seed() -> [node()].
manual_seed() ->
case file:consult(seed_file()) of
{ok, [Node]} when is_atom(Node) ->
[Node];
{error, enoent} ->
[];
_ ->
logger:critical("~p is corrupt. Delete this file and re-join the node to the cluster. Stopping.",
[seed_file()]),
exit(corrupt_seed)
end.
%% Return the list of core nodes that belong to the same cluster as
%% the seed node.
-spec discover_manually(node()) -> [node()].
discover_manually(Seed) ->
try mria_lib:rpc_call(Seed, mria_mnesia, db_nodes, [])
catch _:_ ->
[Seed]
end.
seed_file() ->
filename:join(mnesia:system_info(directory), "mria_replicant_cluster_seed").
cluster_score(OldNodes, Cluster) ->
First we compare the clusters by the number of nodes that are
%% already in the cluster. In case of a tie, we choose a bigger
%% cluster:
{ lists:foldl(fun(Node, Acc) ->
case lists:member(Node, OldNodes) of
true -> Acc + 1;
false -> Acc
end
end,
0,
Cluster)
, length(Cluster)
}.
%%================================================================================
%% Unit tests
%%================================================================================
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
find_clusters_test_() ->
[ ?_assertMatch( [[1, 2, 3]]
, lists:sort(find_clusters(#{ 1 => #{db_nodes => [1, 2, 3]}
, 2 => #{db_nodes => [2, 1, 3]}
, 3 => #{db_nodes => [2, 3, 1]}
}))
)
, ?_assertMatch( [[1], [2, 3]]
, lists:sort(find_clusters(#{ 1 => #{db_nodes => [1, 2, 3]}
, 2 => #{db_nodes => [2, 3]}
, 3 => #{db_nodes => [3, 2]}
}))
)
, ?_assertMatch( [[1, 2, 3], [4, 5], [6]]
, lists:sort(find_clusters(#{ 1 => #{db_nodes => [1, 2, 3]}
, 2 => #{db_nodes => [1, 2, 3]}
, 3 => #{db_nodes => [3, 2, 1]}
, 4 => #{db_nodes => [4, 5]}
, 5 => #{db_nodes => [4, 5]}
, 6 => #{db_nodes => [6, 4, 5]}
}))
)
].
shard_badness_test_() ->
[ ?_assertMatch( #{foo := {n1, 1}, bar := {n2, 2}}
, shard_badness(#{ n1 => #{shard_badness => [{foo, 1}]}
, n2 => #{shard_badness => [{foo, 2}, {bar, 2}]}
})
)
].
cluster_score_test_() ->
[ ?_assertMatch({0, 0}, cluster_score([], []))
, ?_assertMatch({0, 2}, cluster_score([], [1, 2]))
, ?_assertMatch({2, 3}, cluster_score([1, 2, 4], [1, 2, 3]))
].
find_best_cluster_test_() ->
[ ?_assertMatch({false, []}, find_best_cluster([], []))
, ?_assertMatch({true, []}, find_best_cluster([1], []))
, ?_assertMatch({false, [1, 2]}, find_best_cluster([1, 2], [[1, 2]]))
, ?_assertMatch({true, [1, 2, 3]}, find_best_cluster([1, 2], [[1, 2, 3]]))
, ?_assertMatch({true, [1, 2]}, find_best_cluster([1, 2, 3], [[1, 2]]))
, ?_assertMatch({false, [1, 2]}, find_best_cluster([1, 2], [[1, 2], [3, 4, 5], [6, 7]]))
, ?_assertMatch({true, [6, 7]}, find_best_cluster([6, 7, 8], [[1, 2], [3, 4, 5], [6, 7]]))
, ?_assertMatch({true, [3, 4, 5]}, find_best_cluster([], [[1, 2], [3, 4, 5]]))
].
-endif.
| null | https://raw.githubusercontent.com/emqx/mria/80625f5654e4b3f434a9daf93a1f482c86b32ee4/src/mria_lb.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
@doc This server runs on the replicant and periodically checks the
API
gen_server callbacks
Internal exports
================================================================================
Type declarations
================================================================================
================================================================================
API
================================================================================
================================================================================
gen_server callbacks
================================================================================
Trigger update immediately when core node goes down
Everything else is handled via timer
================================================================================
================================================================================
Get information about core nodes:
Find partitions of the core cluster, and if the core cluster is
partitioned choose the best partition to connect to:
Update shards:
Notify changes
Find fully connected clusters (i.e. cliques of nodes)
Find the preferred core node for each shard:
Heuristic: pick the best cluster in case of a split brain:
All discovered nodes belong to the same cluster (or no clusters found):
Replicants do not have themselves as local members.
We make an entry on the fly.
================================================================================
Internal exports
================================================================================
This function runs on the core node. TODO: remove in the next release
TODO: Add OLP check
The return values will be lexicographically sorted. Load will
be distributed evenly between the nodes with the same weight
due to the random term:
================================================================================
================================================================================
Run the discovery algorithm
Return the last node that has been explicitly specified via
"mria:join" command. It overrides other discovery mechanisms.
Return the list of core nodes that belong to the same cluster as
the seed node.
already in the cluster. In case of a tie, we choose a bigger
cluster:
================================================================================
Unit tests
================================================================================ | Copyright ( c ) 2021 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
status of core nodes in case we need to RPC to one of them .
-module(mria_lb).
-behaviour(gen_server).
-export([ start_link/0
, probe/2
, core_nodes/0
, join_cluster/1
, leave_cluster/0
]).
-export([ init/1
, terminate/2
, handle_call/3
, handle_cast/2
, handle_info/2
, code_change/3
]).
-export([ core_node_weight/1
, lb_callback/0
]).
-include_lib("snabbkaffe/include/trace.hrl").
-include("mria_rlog.hrl").
-type core_protocol_versions() :: #{node() => integer()}.
-record(s,
{ core_protocol_versions :: core_protocol_versions()
, core_nodes :: [node()]
}).
-type node_info() ::
#{ running := boolean()
, whoami := core | replicant | mnesia
, version := string() | undefined
, protocol_version := non_neg_integer()
, db_nodes => [node()]
, shard_badness => [{mria_rlog:shard(), float()}]
}.
-define(update, update).
-define(SERVER, ?MODULE).
-define(CORE_DISCOVERY_TIMEOUT, 30000).
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
-spec probe(node(), mria_rlog:shard()) -> boolean().
probe(Node, Shard) ->
gen_server:call(?SERVER, {probe, Node, Shard}).
-spec core_nodes() -> [node()].
core_nodes() ->
gen_server:call(?SERVER, core_nodes, ?CORE_DISCOVERY_TIMEOUT).
join_cluster(Node) ->
{ok, FD} = file:open(seed_file(), [write]),
ok = io:format(FD, "~p.", [Node]),
file:close(FD).
leave_cluster() ->
case file:delete(seed_file()) of
ok ->
ok;
{error, enoent} ->
ok;
{error, Err} ->
error(Err)
end.
init(_) ->
process_flag(trap_exit, true),
logger:set_process_metadata(#{domain => [mria, rlog, lb]}),
start_timer(),
mria_membership:monitor(membership, self(), true),
State = #s{ core_protocol_versions = #{}
, core_nodes = []
},
{ok, State}.
handle_info(?update, St) ->
start_timer(),
{noreply, do_update(St)};
handle_info({membership, Event}, St) ->
case Event of
{noreply, do_update(St)};
{noreply, St}
end;
handle_info(Info, St) ->
?unexpected_event_tp(#{info => Info, state => St}),
{noreply, St}.
handle_cast(Cast, St) ->
?unexpected_event_tp(#{cast => Cast, state => St}),
{noreply, St}.
handle_call({probe, Node, Shard}, _From, St0 = #s{core_protocol_versions = ProtoVSNs}) ->
LastVSNChecked = maps:get(Node, ProtoVSNs, undefined),
MyVersion = mria_rlog:get_protocol_version(),
ProbeResult = mria_lib:rpc_call_nothrow({Node, Shard}, mria_rlog_server, do_probe, [Shard]),
{Reply, ServerVersion} =
case ProbeResult of
{true, MyVersion} ->
{true, MyVersion};
{true, CurrentVersion} when CurrentVersion =/= LastVSNChecked ->
?tp(warning, "Different Mria version on the core node",
#{ my_version => MyVersion
, server_version => CurrentVersion
, last_version => LastVSNChecked
, node => Node
}),
{false, CurrentVersion};
_ ->
{false, LastVSNChecked}
end,
St = St0#s{core_protocol_versions = ProtoVSNs#{Node => ServerVersion}},
{reply, Reply, St};
handle_call(core_nodes, _From, St = #s{core_nodes = CoreNodes}) ->
{reply, CoreNodes, St};
handle_call(Call, From, St) ->
?unexpected_event_tp(#{call => Call, from => From, state => St}),
{reply, {error, {unknown_call, Call}}, St}.
code_change(_OldVsn, St, _Extra) ->
{ok, St}.
terminate(_Reason, St) ->
{ok, St}.
Internal functions
do_update(State = #s{core_nodes = OldCoreNodes}) ->
DiscoveredNodes = discover_nodes(),
{NodeInfo0, _BadNodes} = rpc:multicall( DiscoveredNodes
, ?MODULE, lb_callback, []
, mria_config:lb_timeout()
),
NodeInfo1 = [I || I = {_, #{whoami := core, running := true}} <- NodeInfo0],
NodeInfo = maps:from_list(NodeInfo1),
Clusters = find_clusters(NodeInfo),
maybe_report_netsplit(OldCoreNodes, Clusters),
{IsChanged, NewCoreNodes} = find_best_cluster(OldCoreNodes, Clusters),
ShardBadness = shard_badness(maps:with(NewCoreNodes, NodeInfo)),
maps:map(fun(Shard, {Node, _Badness}) ->
mria_status:notify_core_node_up(Shard, Node)
end,
ShardBadness),
[mria_status:notify_core_node_down(Shard)
|| Shard <- mria_schema:shards() -- maps:keys(ShardBadness)],
IsChanged andalso
?tp(info, mria_lb_core_discovery_new_nodes,
#{ previous_cores => OldCoreNodes
, returned_cores => NewCoreNodes
, ignored_nodes => DiscoveredNodes -- NewCoreNodes
, node => node()
}),
IsChanged andalso
ping_core_nodes(NewCoreNodes),
State#s{core_nodes = NewCoreNodes}.
-spec find_clusters(#{node() => node_info()}) -> [[node()]].
find_clusters(NodeInfo) ->
find_clusters(maps:keys(NodeInfo), NodeInfo, []).
find_clusters([], _NodeInfo, Acc) ->
Acc;
find_clusters([Node|Rest], NodeInfo, Acc) ->
#{Node := #{db_nodes := Emanent}} = NodeInfo,
MutualConnections =
lists:filter(
fun(Peer) ->
case NodeInfo of
#{Peer := #{db_nodes := Incident}} ->
lists:member(Node, Incident);
_ ->
false
end
end,
Emanent),
Cluster = lists:usort([Node|MutualConnections]),
find_clusters(Rest -- MutualConnections, NodeInfo, [Cluster|Acc]).
-spec shard_badness(#{node() => node_info()}) -> #{mria_rlog:shard() => {node(), Badness}}
when Badness :: float().
shard_badness(NodeInfo) ->
maps:fold(
fun(Node, #{shard_badness := Shards}, Acc) ->
lists:foldl(
fun({Shard, Badness}, Acc1) ->
maps:update_with(Shard,
fun({_OldNode, OldBadness}) when OldBadness > Badness ->
{Node, Badness};
(Old) ->
Old
end,
{Node, Badness},
Acc1)
end,
Acc,
Shards)
end,
#{},
NodeInfo).
start_timer() ->
Interval = mria_config:lb_poll_interval(),
erlang:send_after(Interval + rand:uniform(Interval), self(), ?update).
-spec find_best_cluster([node()], [[node()]]) -> {_Changed :: boolean(), [node()]}.
find_best_cluster([], []) ->
{false, []};
find_best_cluster(_OldNodes, []) ->
Discovery failed :
{true, []};
find_best_cluster(OldNodes, Clusters) ->
[Cluster | _] = lists:sort(fun(Cluster1, Cluster2) ->
cluster_score(OldNodes, Cluster1) >=
cluster_score(OldNodes, Cluster2)
end,
Clusters),
IsChanged = OldNodes =/= Cluster,
{IsChanged, Cluster}.
-spec maybe_report_netsplit([node()], [[node()]]) -> ok.
maybe_report_netsplit(OldNodes, Clusters) ->
Alarm = mria_lb_divergent_alarm,
case Clusters of
[_,_|_] ->
case get(Alarm) of
undefined ->
put(Alarm, true),
?tp(error, mria_lb_split_brain,
#{ previous_cores => OldNodes
, clusters => Clusters
, node => node()
});
_ ->
ok
end;
_ ->
erase(Alarm)
end,
ok.
-spec ping_core_nodes([node()]) -> ok.
ping_core_nodes(NewCoreNodes) ->
LocalMember = mria_membership:make_new_local_member(),
lists:foreach(
fun(Core) ->
mria_membership:ping(Core, LocalMember)
end, NewCoreNodes).
core_node_weight(Shard) ->
case whereis(Shard) of
undefined ->
undefined;
_Pid ->
NAgents = length(mria_status:agents(Shard)),
Load = 1.0 * NAgents,
{ok, {Load, rand:uniform(), node()}}
end.
Return a bunch of information about the node . Called via RPC .
-spec lb_callback() -> {node(), node_info()}.
lb_callback() ->
IsRunning = is_pid(whereis(mria_rlog_sup)),
Whoami = mria_config:whoami(),
Version = case application:get_key(mria, vsn) of
{ok, Vsn} -> Vsn;
undefined -> undefined
end,
BasicInfo =
#{ running => IsRunning
, version => Version
, whoami => Whoami
, protocol_version => mria_rlog:get_protocol_version()
},
MoreInfo =
case Whoami of
core when IsRunning ->
Badness = [begin
Load = length(mria_status:agents(Shard)) + rand:uniform(),
{Shard, Load}
end || Shard <- mria_schema:shards()],
#{ db_nodes => mria_mnesia:db_nodes()
, shard_badness => Badness
};
_ ->
#{}
end,
{node(), maps:merge(BasicInfo, MoreInfo)}.
Internal functions
-spec discover_nodes() -> [node()].
discover_nodes() ->
DiscoveryFun = mria_config:core_node_discovery_callback(),
case manual_seed() of
[] ->
DiscoveryFun();
[Seed] ->
discover_manually(Seed)
end.
-spec manual_seed() -> [node()].
manual_seed() ->
case file:consult(seed_file()) of
{ok, [Node]} when is_atom(Node) ->
[Node];
{error, enoent} ->
[];
_ ->
logger:critical("~p is corrupt. Delete this file and re-join the node to the cluster. Stopping.",
[seed_file()]),
exit(corrupt_seed)
end.
-spec discover_manually(node()) -> [node()].
discover_manually(Seed) ->
try mria_lib:rpc_call(Seed, mria_mnesia, db_nodes, [])
catch _:_ ->
[Seed]
end.
seed_file() ->
filename:join(mnesia:system_info(directory), "mria_replicant_cluster_seed").
cluster_score(OldNodes, Cluster) ->
First we compare the clusters by the number of nodes that are
{ lists:foldl(fun(Node, Acc) ->
case lists:member(Node, OldNodes) of
true -> Acc + 1;
false -> Acc
end
end,
0,
Cluster)
, length(Cluster)
}.
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
find_clusters_test_() ->
[ ?_assertMatch( [[1, 2, 3]]
, lists:sort(find_clusters(#{ 1 => #{db_nodes => [1, 2, 3]}
, 2 => #{db_nodes => [2, 1, 3]}
, 3 => #{db_nodes => [2, 3, 1]}
}))
)
, ?_assertMatch( [[1], [2, 3]]
, lists:sort(find_clusters(#{ 1 => #{db_nodes => [1, 2, 3]}
, 2 => #{db_nodes => [2, 3]}
, 3 => #{db_nodes => [3, 2]}
}))
)
, ?_assertMatch( [[1, 2, 3], [4, 5], [6]]
, lists:sort(find_clusters(#{ 1 => #{db_nodes => [1, 2, 3]}
, 2 => #{db_nodes => [1, 2, 3]}
, 3 => #{db_nodes => [3, 2, 1]}
, 4 => #{db_nodes => [4, 5]}
, 5 => #{db_nodes => [4, 5]}
, 6 => #{db_nodes => [6, 4, 5]}
}))
)
].
shard_badness_test_() ->
[ ?_assertMatch( #{foo := {n1, 1}, bar := {n2, 2}}
, shard_badness(#{ n1 => #{shard_badness => [{foo, 1}]}
, n2 => #{shard_badness => [{foo, 2}, {bar, 2}]}
})
)
].
cluster_score_test_() ->
[ ?_assertMatch({0, 0}, cluster_score([], []))
, ?_assertMatch({0, 2}, cluster_score([], [1, 2]))
, ?_assertMatch({2, 3}, cluster_score([1, 2, 4], [1, 2, 3]))
].
find_best_cluster_test_() ->
[ ?_assertMatch({false, []}, find_best_cluster([], []))
, ?_assertMatch({true, []}, find_best_cluster([1], []))
, ?_assertMatch({false, [1, 2]}, find_best_cluster([1, 2], [[1, 2]]))
, ?_assertMatch({true, [1, 2, 3]}, find_best_cluster([1, 2], [[1, 2, 3]]))
, ?_assertMatch({true, [1, 2]}, find_best_cluster([1, 2, 3], [[1, 2]]))
, ?_assertMatch({false, [1, 2]}, find_best_cluster([1, 2], [[1, 2], [3, 4, 5], [6, 7]]))
, ?_assertMatch({true, [6, 7]}, find_best_cluster([6, 7, 8], [[1, 2], [3, 4, 5], [6, 7]]))
, ?_assertMatch({true, [3, 4, 5]}, find_best_cluster([], [[1, 2], [3, 4, 5]]))
].
-endif.
|
b466c1de69d9180419e9255b75f387f23b388a706a0190d08f7addc5c5e7cde1 | outergod/cl-heredoc | heredoc.lisp | ;;;; cl-heredoc - heredoc.lisp
Copyright ( C ) 2010 < >
;;;; This file is part of cl-heredoc.
;;;; cl-heredoc is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or
;;;; (at your option) any later version.
;;;;
;;;; cl-heredoc is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;;; GNU General Public License for more details.
;;;;
You should have received a copy of the GNU General Public License
;;;; along with this program. If not, see </>.
(in-package :cl-heredoc)
(defun read-until-match (stream terminal)
"read-until-match stream terminal => string
Read characters from STREAM until a sequence equal to string TERMINAL is read.
Return all characters read as string omitting TERMINAL itself. Signal error upon
EOF."
(with-output-to-string (out)
(do* ((match-length (length terminal))
(buffer (new-ring-buffer match-length))
(buffer-char nil)
(char (read-char stream t :eof t)
(or (setf buffer-char (ring-buffer-next buffer))
(read-char stream t :eof t)))
(match-pos 0))
((eql char :eof))
(cond ((char= char (char terminal match-pos))
(when (= (incf match-pos) match-length)
(return))
(unless buffer-char
(ring-buffer-insert buffer char)))
((zerop match-pos)
(write-char char out)
(when buffer-char
(ring-buffer-pop buffer)))
(t
(unless buffer-char
(ring-buffer-insert buffer char))
(write-char (ring-buffer-pop buffer) out)
(setf match-pos 0))))))
(defun read-heredoc (stream char arg)
"read-heredoc stream char arg => string
Return string from STREAM up to the point where the string read first until CHAR
is encountered. All evaluation is completely turned off so no quoting is
required at all.
Example:
CL-USER> (set-dispatch-macro-character #\# #\> #'cl-heredoc:read-heredoc)
CL-USER> #>eof>Write whatever (you) \"want\"!eof => Write whatever (you) \"want\"!"
(declare (ignore arg))
(read-until-match stream (read-until-match stream (string char))))
| null | https://raw.githubusercontent.com/outergod/cl-heredoc/a8c8a3557bb6b4854adff86f10182c22e6676ac8/src/heredoc.lisp | lisp | cl-heredoc - heredoc.lisp
This file is part of cl-heredoc.
cl-heredoc is free software; you can redistribute it and/or modify
either version 3 of the License , or
(at your option) any later version.
cl-heredoc is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>. | Copyright ( C ) 2010 < >
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
(in-package :cl-heredoc)
(defun read-until-match (stream terminal)
"read-until-match stream terminal => string
Read characters from STREAM until a sequence equal to string TERMINAL is read.
Return all characters read as string omitting TERMINAL itself. Signal error upon
EOF."
(with-output-to-string (out)
(do* ((match-length (length terminal))
(buffer (new-ring-buffer match-length))
(buffer-char nil)
(char (read-char stream t :eof t)
(or (setf buffer-char (ring-buffer-next buffer))
(read-char stream t :eof t)))
(match-pos 0))
((eql char :eof))
(cond ((char= char (char terminal match-pos))
(when (= (incf match-pos) match-length)
(return))
(unless buffer-char
(ring-buffer-insert buffer char)))
((zerop match-pos)
(write-char char out)
(when buffer-char
(ring-buffer-pop buffer)))
(t
(unless buffer-char
(ring-buffer-insert buffer char))
(write-char (ring-buffer-pop buffer) out)
(setf match-pos 0))))))
(defun read-heredoc (stream char arg)
"read-heredoc stream char arg => string
Return string from STREAM up to the point where the string read first until CHAR
is encountered. All evaluation is completely turned off so no quoting is
required at all.
Example:
CL-USER> (set-dispatch-macro-character #\# #\> #'cl-heredoc:read-heredoc)
CL-USER> #>eof>Write whatever (you) \"want\"!eof => Write whatever (you) \"want\"!"
(declare (ignore arg))
(read-until-match stream (read-until-match stream (string char))))
|
275e8539e18f59c5c0cbe9cf3d5296566368143b7759e923e8976f09459d7bce | grzm/awyeah-api | ec2.clj | Copyright ( c ) Cognitect , Inc.
;; All rights reserved.
(ns ^:skip-wiki com.grzm.awyeah.protocols.ec2
"Impl, don't call directly."
(:require
[com.grzm.awyeah.protocols :as aws.protocols]
[com.grzm.awyeah.protocols.query :as query]
[com.grzm.awyeah.shape :as shape]
[com.grzm.awyeah.util :as util]))
(set! *warn-on-reflection* true)
(defn serialized-name
[shape default]
(or (:queryName shape)
(when-let [name (:locationName shape)]
(apply str (Character/toUpperCase ^Character (first name)) (rest name)))
default))
(defmulti serialize
(fn [shape _args _serialized _prefix] (:type shape)))
(defmethod serialize :default
[shape args serialized prefix]
(query/serialize shape args serialized prefix))
(defmethod serialize "structure"
[shape args serialized prefix]
(let [args (util/with-defaults shape args)]
(reduce (fn [serialized k]
(let [member-shape (shape/member-shape shape k)
member-name (serialized-name member-shape (name k))]
(if (contains? args k)
(serialize member-shape (k args) serialized (conj prefix member-name))
serialized)))
serialized
(keys (:members shape)))))
(defmethod serialize "list"
[shape args serialized prefix]
(let [member-shape (shape/list-member-shape shape)]
(reduce (fn [serialized [i member]]
(serialize member-shape member serialized (conj prefix (str i))))
serialized
(map-indexed (fn [i member] [(inc i) member]) args))))
(defmethod aws.protocols/build-http-request "ec2"
[service op-map]
(query/build-query-http-request serialize service op-map))
(defmethod aws.protocols/parse-http-response "ec2"
[service op-map http-response]
(query/build-query-http-response service op-map http-response))
| null | https://raw.githubusercontent.com/grzm/awyeah-api/1810bf624da2be58c77813106a1d51e32db11690/src/com/grzm/awyeah/protocols/ec2.clj | clojure | All rights reserved. | Copyright ( c ) Cognitect , Inc.
(ns ^:skip-wiki com.grzm.awyeah.protocols.ec2
"Impl, don't call directly."
(:require
[com.grzm.awyeah.protocols :as aws.protocols]
[com.grzm.awyeah.protocols.query :as query]
[com.grzm.awyeah.shape :as shape]
[com.grzm.awyeah.util :as util]))
(set! *warn-on-reflection* true)
(defn serialized-name
[shape default]
(or (:queryName shape)
(when-let [name (:locationName shape)]
(apply str (Character/toUpperCase ^Character (first name)) (rest name)))
default))
(defmulti serialize
(fn [shape _args _serialized _prefix] (:type shape)))
(defmethod serialize :default
[shape args serialized prefix]
(query/serialize shape args serialized prefix))
(defmethod serialize "structure"
[shape args serialized prefix]
(let [args (util/with-defaults shape args)]
(reduce (fn [serialized k]
(let [member-shape (shape/member-shape shape k)
member-name (serialized-name member-shape (name k))]
(if (contains? args k)
(serialize member-shape (k args) serialized (conj prefix member-name))
serialized)))
serialized
(keys (:members shape)))))
(defmethod serialize "list"
[shape args serialized prefix]
(let [member-shape (shape/list-member-shape shape)]
(reduce (fn [serialized [i member]]
(serialize member-shape member serialized (conj prefix (str i))))
serialized
(map-indexed (fn [i member] [(inc i) member]) args))))
(defmethod aws.protocols/build-http-request "ec2"
[service op-map]
(query/build-query-http-request serialize service op-map))
(defmethod aws.protocols/parse-http-response "ec2"
[service op-map http-response]
(query/build-query-http-response service op-map http-response))
|
457abbebd9c50000819924e4b3b17c3730db1087bcce8ff272d2fcc488b91155 | tanakh/Peggy | Loc.hs | # LANGUAGE TemplateHaskell , QuasiQuotes , FlexibleContexts #
import Text.Peggy
data Number = Number SrcLoc Int deriving (Show)
[peggy|
nums :: [Number]
= num*
num ::: Number
= [0-9]+ { Number $p (read $1) }
|]
main :: IO ()
main =
case parseString nums "" "12 2434 \n 3 4 576" of
Left err -> print err
Right ns -> mapM_ print ns
| null | https://raw.githubusercontent.com/tanakh/Peggy/78280548d137c9ada703de0e4c9af1cd3cb8f728/example/Loc.hs | haskell | # LANGUAGE TemplateHaskell , QuasiQuotes , FlexibleContexts #
import Text.Peggy
data Number = Number SrcLoc Int deriving (Show)
[peggy|
nums :: [Number]
= num*
num ::: Number
= [0-9]+ { Number $p (read $1) }
|]
main :: IO ()
main =
case parseString nums "" "12 2434 \n 3 4 576" of
Left err -> print err
Right ns -> mapM_ print ns
|
|
30c542a833c4e6d307d5a700a452759b2a2a649b39e5f30fed58beedfe9a8e3d | janestreet/lwt-async | lwt_log_rules.mli | Lightweight thread library for
* Interface Lwt_log_rules
* Copyright ( C ) 2010 < >
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation , with linking exceptions ;
* either version 2.1 of the License , or ( at your option ) any later
* version . See COPYING file for details .
*
* This program is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA
* 02111 - 1307 , USA .
*
* Interface Lwt_log_rules
* Copyright (C) 2010 Jérémie Dimino <>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, with linking exceptions;
* either version 2.1 of the License, or (at your option) any later
* version. See COPYING file for details.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*)
(** Logging rules parsing *)
val rules : Lexing.lexbuf -> (string * string) list option
(** [parse lexbuf] returns the list of rules contained in
[lexbuf] or None in case of parsing error *)
| null | https://raw.githubusercontent.com/janestreet/lwt-async/c738e6202c1c7409e079e513c7bdf469f7f9984c/src/logger/lwt_log_rules.mli | ocaml | * Logging rules parsing
* [parse lexbuf] returns the list of rules contained in
[lexbuf] or None in case of parsing error | Lightweight thread library for
* Interface Lwt_log_rules
* Copyright ( C ) 2010 < >
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation , with linking exceptions ;
* either version 2.1 of the License , or ( at your option ) any later
* version . See COPYING file for details .
*
* This program is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA
* 02111 - 1307 , USA .
*
* Interface Lwt_log_rules
* Copyright (C) 2010 Jérémie Dimino <>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, with linking exceptions;
* either version 2.1 of the License, or (at your option) any later
* version. See COPYING file for details.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*)
val rules : Lexing.lexbuf -> (string * string) list option
|
447b9e9bb2086a33e1c01768d254f4627b5eaa2385c99ec42cb97e4ffe681e16 | RolfRolles/PandemicML | IDAHotKey.ml | (* IDAHotKey.ml *)
let int2fn = Hashtbl.create 16
let str2int = Hashtbl.create 16
let num = ref 0
let invoke i =
let fn = try Hashtbl.find int2fn i with Not_found -> (fun () -> ()) in
fn ()
let _ = Callback.register "HotkeyCallback" invoke
let register hk fn =
let b = IDA.add_ocaml_hotkey hk !num in
Hashtbl.replace int2fn !num fn;
Hashtbl.replace str2int hk !num;
incr num;
b
let unregister hk =
let i = try Hashtbl.find str2int hk with Not_found -> ~-1 in
Hashtbl.remove str2int hk;
Hashtbl.remove int2fn i;
ignore(IDA.del_ocaml_hotkey hk) | null | https://raw.githubusercontent.com/RolfRolles/PandemicML/9c31ecaf9c782dbbeb6cf502bc2a6730316d681e/IDA/IDAHotKey.ml | ocaml | IDAHotKey.ml | let int2fn = Hashtbl.create 16
let str2int = Hashtbl.create 16
let num = ref 0
let invoke i =
let fn = try Hashtbl.find int2fn i with Not_found -> (fun () -> ()) in
fn ()
let _ = Callback.register "HotkeyCallback" invoke
let register hk fn =
let b = IDA.add_ocaml_hotkey hk !num in
Hashtbl.replace int2fn !num fn;
Hashtbl.replace str2int hk !num;
incr num;
b
let unregister hk =
let i = try Hashtbl.find str2int hk with Not_found -> ~-1 in
Hashtbl.remove str2int hk;
Hashtbl.remove int2fn i;
ignore(IDA.del_ocaml_hotkey hk) |
52031f835dab62eb4abbbc735130f9e2629b8c5afcf6acc8cedd39cfcc837cb9 | Palmik/data-store | B01.hs | {-# LANGUAGE DeriveDataTypeable #-}
# OPTIONS_GHC -fno - warn - orphans #
module IS.B01
where
import Control.DeepSeq (NFData(rnf))
import Common
import Data.Data
import qualified Data.IxSet as I
import Data.IxSet ((@=), (@>=))
type IS = I.IxSet C01
newtype D1 = D1 Int deriving (Eq, Ord, Typeable)
newtype D2 = D2 Int deriving (Eq, Ord , Typeable)
newtype D3 = D3 Int deriving (Eq, Ord, Typeable)
instance NFData D1 where
rnf (D1 x) = rnf x
instance NFData D2 where
rnf (D2 x) = rnf x
instance NFData D3 where
rnf (D3 x) = rnf x
instance I.Indexable C01 where
empty = I.ixSet
[ I.ixFun $ \(C01 oo _ _) -> [D1 oo]
, I.ixFun $ \(C01 _ om _) -> [D2 om]
, I.ixFun $ \(C01 _ _ mm) -> map D3 mm
]
empty :: IS
empty = I.empty
size :: IS -> Int
size = I.size
insert :: C01 -> IS -> IS
insert = I.insert
insertLookup :: Int -> Int -> Int -> IS -> [C01]
insertLookup d1 d2 d3 s =
I.toList (new @= D1 d1) ++
I.toList (new @= D2 d2) ++
I.toList (new @= D3 d3)
where new = I.insert (C01 d1 d2 [d3]) s
lookupOOEQ :: Int -> IS -> [C01]
lookupOOEQ x s = I.toList (s @= D1 x)
lookupOOGE :: Int -> IS -> [C01]
lookupOOGE x s = I.toList (s @>= D1 x)
lookupOMEQ :: Int -> IS -> [C01]
lookupOMEQ x s = I.toList (s @= D2 x)
lookupOMGE :: Int -> IS -> [C01]
lookupOMGE x s = I.toList (s @>= D2 x)
lookupMMEQ :: Int -> IS -> [C01]
lookupMMEQ x s = I.toList (s @= D3 x)
force :: IS -> ()
force (I.IxSet ll) = seq (go ll) ()
where
go [] = ()
go (I.Ix m _:xs) = m `seq` go xs
| null | https://raw.githubusercontent.com/Palmik/data-store/20131a9d6d310c29b57fd9e3b508f0335e1113b4/benchmarks/src/IS/B01.hs | haskell | # LANGUAGE DeriveDataTypeable # | # OPTIONS_GHC -fno - warn - orphans #
module IS.B01
where
import Control.DeepSeq (NFData(rnf))
import Common
import Data.Data
import qualified Data.IxSet as I
import Data.IxSet ((@=), (@>=))
type IS = I.IxSet C01
newtype D1 = D1 Int deriving (Eq, Ord, Typeable)
newtype D2 = D2 Int deriving (Eq, Ord , Typeable)
newtype D3 = D3 Int deriving (Eq, Ord, Typeable)
instance NFData D1 where
rnf (D1 x) = rnf x
instance NFData D2 where
rnf (D2 x) = rnf x
instance NFData D3 where
rnf (D3 x) = rnf x
instance I.Indexable C01 where
empty = I.ixSet
[ I.ixFun $ \(C01 oo _ _) -> [D1 oo]
, I.ixFun $ \(C01 _ om _) -> [D2 om]
, I.ixFun $ \(C01 _ _ mm) -> map D3 mm
]
empty :: IS
empty = I.empty
size :: IS -> Int
size = I.size
insert :: C01 -> IS -> IS
insert = I.insert
insertLookup :: Int -> Int -> Int -> IS -> [C01]
insertLookup d1 d2 d3 s =
I.toList (new @= D1 d1) ++
I.toList (new @= D2 d2) ++
I.toList (new @= D3 d3)
where new = I.insert (C01 d1 d2 [d3]) s
lookupOOEQ :: Int -> IS -> [C01]
lookupOOEQ x s = I.toList (s @= D1 x)
lookupOOGE :: Int -> IS -> [C01]
lookupOOGE x s = I.toList (s @>= D1 x)
lookupOMEQ :: Int -> IS -> [C01]
lookupOMEQ x s = I.toList (s @= D2 x)
lookupOMGE :: Int -> IS -> [C01]
lookupOMGE x s = I.toList (s @>= D2 x)
lookupMMEQ :: Int -> IS -> [C01]
lookupMMEQ x s = I.toList (s @= D3 x)
force :: IS -> ()
force (I.IxSet ll) = seq (go ll) ()
where
go [] = ()
go (I.Ix m _:xs) = m `seq` go xs
|
cf76d255ae19bbd8af14cb0b1182587b7458bcf9174b1106d056cca51dc0916a | mpickering/apply-refact | Naming11.hs | case_foo = 1 | null | https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Naming11.hs | haskell | case_foo = 1 |
|
3fdd20821fd2fa3c8a0b2128636f314bee0857cb2096b93ced351c2bd9677293 | rongarret/ergolib | hashlib.lisp |
; Requires libssl-dev
(require :ergolib)
(require :rffi)
(require :cl+ssl)
(deftype u8 () '(unsigned-byte 8))
(define-method (hash (v vector) hashfn hashsize)
(bb
(for b in v do (assert (typep b 'u8)))
s (bytes-to-string v :latin1)
:mv (v p) (make-heap-ivector hashsize 'u8)
(funcall hashfn s (length s) p)
(prog1 (copy-seq v) (dispose-heap-ivector v))))
(define-method (hash (s string) hashfn hashsize)
(hash (string-to-bytes s :utf-8) hashfn hashsize))
(defmacro defhash (name size)
`(progn
(defff (,(symbol-name name) ,(symcat '_ name)) (:cstr :int :ptr) :ptr)
(define-method (,name (v vector)) (hash v ',(symcat '_ name) ,size))
(define-method (,name (s string)) (hash s ',(symcat '_ name) ,size))
',name))
; NOTE: only SHA1 is actually used at the moment
(defhash md5 16)
(defhash sha1 20)
(defhash sha256 32)
(defhash sha512 64)
| null | https://raw.githubusercontent.com/rongarret/ergolib/757e67471251ed1329e5c35c008fb69964567994/layer1/hashlib.lisp | lisp | Requires libssl-dev
NOTE: only SHA1 is actually used at the moment |
(require :ergolib)
(require :rffi)
(require :cl+ssl)
(deftype u8 () '(unsigned-byte 8))
(define-method (hash (v vector) hashfn hashsize)
(bb
(for b in v do (assert (typep b 'u8)))
s (bytes-to-string v :latin1)
:mv (v p) (make-heap-ivector hashsize 'u8)
(funcall hashfn s (length s) p)
(prog1 (copy-seq v) (dispose-heap-ivector v))))
(define-method (hash (s string) hashfn hashsize)
(hash (string-to-bytes s :utf-8) hashfn hashsize))
(defmacro defhash (name size)
`(progn
(defff (,(symbol-name name) ,(symcat '_ name)) (:cstr :int :ptr) :ptr)
(define-method (,name (v vector)) (hash v ',(symcat '_ name) ,size))
(define-method (,name (s string)) (hash s ',(symcat '_ name) ,size))
',name))
(defhash md5 16)
(defhash sha1 20)
(defhash sha256 32)
(defhash sha512 64)
|
dde1c6f74fa8cb968c0493b71e63c2bfcfcf509bc526b2d9cf2af404d727d636 | kumarshantanu/dime | service.clj | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file LICENSE 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 foo.service
(:require
[dime.core :as di]
[dime.util :as du]))
(defn find-items
"This has an implicit inject name, hence will be overridden by the explicit one in foo.db namespace."
[item-ids]
:mock-items)
(def recommend-products nil)
(defn ^{:expose- true
:post-inject (du/post-inject-alter #'recommend-products)}
recommend-products-impl
"Return item IDs for specified user ID."
[^:inject items-cache user-id]
(let [item-ids (get items-cache user-id)]
(find-items item-ids)))
(di/definj service-browse-items
[find-items]
[user-id]
(let [item-ids (recommend-products user-id)]
(find-items item-ids)))
(defn ^{:expose :svc/create-order} service-create-order
[^:inject [find-items db-create-order]
user-details order-details]
(let [item-ids (find-items (:item-ids order-details))
order-data {:order-data :dummy}] ; prepare order-data
(db-create-order order-data)))
| null | https://raw.githubusercontent.com/kumarshantanu/dime/5c3b8330ddab69ebefaa56dd9bfa2ff97b55c8a8/test/foo/service.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 LICENSE 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.
prepare order-data | Copyright ( c ) . All rights reserved .
(ns foo.service
(:require
[dime.core :as di]
[dime.util :as du]))
(defn find-items
"This has an implicit inject name, hence will be overridden by the explicit one in foo.db namespace."
[item-ids]
:mock-items)
(def recommend-products nil)
(defn ^{:expose- true
:post-inject (du/post-inject-alter #'recommend-products)}
recommend-products-impl
"Return item IDs for specified user ID."
[^:inject items-cache user-id]
(let [item-ids (get items-cache user-id)]
(find-items item-ids)))
(di/definj service-browse-items
[find-items]
[user-id]
(let [item-ids (recommend-products user-id)]
(find-items item-ids)))
(defn ^{:expose :svc/create-order} service-create-order
[^:inject [find-items db-create-order]
user-details order-details]
(let [item-ids (find-items (:item-ids order-details))
(db-create-order order-data)))
|
d46017d4028e054dc9cf930379aa18b4c3a7c30d6beb20c0e42869559aae4156 | input-output-hk/cardano-ledger | Slot.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
module Cardano.Ledger.Slot (
SlotNo (..),
Duration (..),
(-*),
(+*),
(*-),
EpochNo (..),
EpochSize (..),
EpochInfo,
-- Block number
BlockNo (..),
epochInfoEpoch,
epochInfoFirst,
epochInfoSize,
)
where
import Cardano.Ledger.BaseTypes (ShelleyBase)
import Cardano.Slotting.Block (BlockNo (..))
import Cardano.Slotting.EpochInfo (EpochInfo)
import qualified Cardano.Slotting.EpochInfo as EI
import Cardano.Slotting.Slot (EpochNo (..), EpochSize (..), SlotNo (..))
import Control.Monad.Trans (lift)
import Data.Functor.Identity (Identity)
import Data.Word (Word64)
import GHC.Generics (Generic)
import GHC.Stack (HasCallStack)
import NoThunks.Class (NoThunks (..))
import Quiet
newtype Duration = Duration {unDuration :: Word64}
deriving (Eq, Generic, Ord, NoThunks, Num, Integral, Real, Enum)
deriving (Show) via Quiet Duration
instance Semigroup Duration where
(Duration x) <> (Duration y) = Duration $ x + y
instance Monoid Duration where
mempty = Duration 0
mappend = (<>)
(-*) :: SlotNo -> SlotNo -> Duration
(SlotNo s) -* (SlotNo t) = Duration (if s > t then s - t else t - s)
(+*) :: SlotNo -> Duration -> SlotNo
(SlotNo s) +* (Duration d) = SlotNo (s + d)
-- | Subtract a duration from a slot
(*-) :: SlotNo -> Duration -> SlotNo
(SlotNo s) *- (Duration d) = SlotNo (if s > d then s - d else 0)
epochInfoEpoch ::
HasCallStack =>
EpochInfo Identity ->
SlotNo ->
ShelleyBase EpochNo
epochInfoEpoch ei = lift . EI.epochInfoEpoch ei
epochInfoFirst ::
HasCallStack =>
EpochInfo Identity ->
EpochNo ->
ShelleyBase SlotNo
epochInfoFirst ei = lift . EI.epochInfoFirst ei
epochInfoSize ::
HasCallStack =>
EpochInfo Identity ->
EpochNo ->
ShelleyBase EpochSize
epochInfoSize ei = lift . EI.epochInfoSize ei
| null | https://raw.githubusercontent.com/input-output-hk/cardano-ledger/31c0bb1f5e78e40b83adfd1a916e69f47fdc9835/libs/cardano-ledger-core/src/Cardano/Ledger/Slot.hs | haskell | Block number
| Subtract a duration from a slot | # LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
module Cardano.Ledger.Slot (
SlotNo (..),
Duration (..),
(-*),
(+*),
(*-),
EpochNo (..),
EpochSize (..),
EpochInfo,
BlockNo (..),
epochInfoEpoch,
epochInfoFirst,
epochInfoSize,
)
where
import Cardano.Ledger.BaseTypes (ShelleyBase)
import Cardano.Slotting.Block (BlockNo (..))
import Cardano.Slotting.EpochInfo (EpochInfo)
import qualified Cardano.Slotting.EpochInfo as EI
import Cardano.Slotting.Slot (EpochNo (..), EpochSize (..), SlotNo (..))
import Control.Monad.Trans (lift)
import Data.Functor.Identity (Identity)
import Data.Word (Word64)
import GHC.Generics (Generic)
import GHC.Stack (HasCallStack)
import NoThunks.Class (NoThunks (..))
import Quiet
newtype Duration = Duration {unDuration :: Word64}
deriving (Eq, Generic, Ord, NoThunks, Num, Integral, Real, Enum)
deriving (Show) via Quiet Duration
instance Semigroup Duration where
(Duration x) <> (Duration y) = Duration $ x + y
instance Monoid Duration where
mempty = Duration 0
mappend = (<>)
(-*) :: SlotNo -> SlotNo -> Duration
(SlotNo s) -* (SlotNo t) = Duration (if s > t then s - t else t - s)
(+*) :: SlotNo -> Duration -> SlotNo
(SlotNo s) +* (Duration d) = SlotNo (s + d)
(*-) :: SlotNo -> Duration -> SlotNo
(SlotNo s) *- (Duration d) = SlotNo (if s > d then s - d else 0)
epochInfoEpoch ::
HasCallStack =>
EpochInfo Identity ->
SlotNo ->
ShelleyBase EpochNo
epochInfoEpoch ei = lift . EI.epochInfoEpoch ei
epochInfoFirst ::
HasCallStack =>
EpochInfo Identity ->
EpochNo ->
ShelleyBase SlotNo
epochInfoFirst ei = lift . EI.epochInfoFirst ei
epochInfoSize ::
HasCallStack =>
EpochInfo Identity ->
EpochNo ->
ShelleyBase EpochSize
epochInfoSize ei = lift . EI.epochInfoSize ei
|
5a0d82e4d9cb9a0604c914bc42258a9185c81288a9ea0de83a1490896a180498 | tfausak/factory | Widget.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{- |
The core data type for this example application.
-}
module Factory.Types.Widget where
import Data.Aeson as Aeson
import qualified GHC.Generics as GHC
import qualified Data.Text as Text
{- |
A widget. Who knows what it does.
-}
data Widget = Widget
{ name :: Text.Text -- ^ The name of this widget.
} deriving (Aeson.FromJSON, Aeson.ToJSON, Eq, GHC.Generic, Read, Show)
| null | https://raw.githubusercontent.com/tfausak/factory/27025465dc0045d43d8db1769bcc665fb55ee62e/library/Factory/Types/Widget.hs | haskell | # LANGUAGE DeriveAnyClass #
|
The core data type for this example application.
|
A widget. Who knows what it does.
^ The name of this widget. | # LANGUAGE DeriveGeneric #
module Factory.Types.Widget where
import Data.Aeson as Aeson
import qualified GHC.Generics as GHC
import qualified Data.Text as Text
data Widget = Widget
} deriving (Aeson.FromJSON, Aeson.ToJSON, Eq, GHC.Generic, Read, Show)
|
88ce08914c6ef5cfebc1f91bf7eaaf1063f6963cf92d6ef631cdeeb1f56f8ffb | paurkedal/ocaml-mediawiki-api | mwapi_login.mli | Copyright ( C ) 2013 - -2016 Petter A. Urkedal < >
*
* 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 3 of the License , or ( at your
* option ) any later version , with the OCaml static compilation exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library . If not , see < / > .
*
* 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 3 of the License, or (at your
* option) any later version, with the OCaml static compilation exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see </>.
*)
open Mwapi
type login_status =
[ `Success
| `Illegal
| `Not_exists
| `Empty_pass
| `Wrong_pass
| `Wrong_plugin_pass
| `Created_blocked
| `Throttled
| `Blocked
| `Need_token of string ]
val string_of_login_status : login_status -> string
val login : name: string -> password: string -> ?domain: string ->
?token: string -> unit -> login_status request
val logout : unit request
| null | https://raw.githubusercontent.com/paurkedal/ocaml-mediawiki-api/6a1c1043a8ad578ea321a314fbe0a12a8d0933cf/lib/mwapi_login.mli | ocaml | Copyright ( C ) 2013 - -2016 Petter A. Urkedal < >
*
* 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 3 of the License , or ( at your
* option ) any later version , with the OCaml static compilation exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library . If not , see < / > .
*
* 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 3 of the License, or (at your
* option) any later version, with the OCaml static compilation exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see </>.
*)
open Mwapi
type login_status =
[ `Success
| `Illegal
| `Not_exists
| `Empty_pass
| `Wrong_pass
| `Wrong_plugin_pass
| `Created_blocked
| `Throttled
| `Blocked
| `Need_token of string ]
val string_of_login_status : login_status -> string
val login : name: string -> password: string -> ?domain: string ->
?token: string -> unit -> login_status request
val logout : unit request
|
|
74acf9b3061a7e0469344f8193187c71df6b19457d6bc60d6330b536212b5571 | na4zagin3/satyrographos | command_opam_install__library_recursive.ml | module StdList = List
open Satyrographos_testlib
open TestLib
open Shexp_process
let satyristes =
{|
(version "0.0.2")
(library
(name "grcnum")
(version "0.2")
(sources
((package "grcnum.satyh" "./grcnum.satyh")
(font "grcnum-font.ttf" "./font.ttf")
(hash "fonts.satysfi-hash" "./fonts.satysfi-hash")
(file "doc/grcnum.md" "README.md")
(fontDir "font")
(packageDir "src")
))
(opam "satysfi-grcnum.opam")
(dependencies ((fonts-theano ())))
(compatibility ((satyrographos 0.0.1))))
(libraryDoc
(name "grcnum-doc")
(version "0.2")
(build
((satysfi "doc-grcnum.saty" "-o" "doc-grcnum-ja.pdf")))
(sources
((doc "doc-grcnum-ja.pdf" "./doc-grcnum-ja.pdf")))
(opam "satysfi-grcnum-doc.opam")
(dependencies ((grcnum ())
(fonts-theano ()))))
|}
let fontHash =
{|{
"grcnum:grcnum-font":<"Single":{"src-dist":"grcnum/grcnum-font.ttf"}>
}|}
let env ~dest_dir:_ ~temp_dir : Satyrographos.Environment.t t =
let open Shexp_process.Infix in
let pkg_dir = FilePath.concat temp_dir "pkg" in
let prepare_pkg =
PrepareDist.empty pkg_dir
>> stdout_to (FilePath.concat pkg_dir "Satyristes") (echo satyristes)
>> stdout_to (FilePath.concat pkg_dir "README.md") (echo "@@README.md@@")
>> stdout_to (FilePath.concat pkg_dir "fonts.satysfi-hash") (echo fontHash)
>> stdout_to (FilePath.concat pkg_dir "grcnum.satyh") (echo "@@grcnum.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "font.ttf") (echo "@@font.ttf@@")
>> mkdir ~p:() (FilePath.concat pkg_dir "src/a/b-1/c-1")
>> mkdir ~p:() (FilePath.concat pkg_dir "src/a/b-1/c-2")
>> mkdir ~p:() (FilePath.concat pkg_dir "src/a/b-2")
>> stdout_to (FilePath.concat pkg_dir "src/a/b-1/c-1/file1.satyh") (echo "@@a/b-1/c-1/file1.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "src/a/b-1/c-1/file2.satyh") (echo "@@a/b-1/c-1/file2.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "src/a/b-1/c-2/file1.satyh") (echo "@@a/b-1/c-2/file1.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "src/a/b-1/file.satyh") (echo "@@a/b-1/file.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "src/a/file.satyh") (echo "@@a/file.satyh@@")
>> mkdir ~p:() (FilePath.concat pkg_dir "font/a/b-1/c-1")
>> mkdir ~p:() (FilePath.concat pkg_dir "font/a/b-1/c-2")
>> mkdir ~p:() (FilePath.concat pkg_dir "font/a/b-2")
>> stdout_to (FilePath.concat pkg_dir "font/a/b-1/c-1/file1.ttf") (echo "@@a/b-1/c-1/file1.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "font/a/b-1/c-1/file2.ttf") (echo "@@a/b-1/c-1/file2.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "font/a/b-1/c-2/file1.ttf") (echo "@@a/b-1/c-2/file1.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "font/a/b-1/file.ttf") (echo "@@a/b-1/file.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "font/a/file.ttf") (echo "@@a/file.ttf@@")
in
let empty_dist = FilePath.concat temp_dir "empty_dist" in
let prepare_dist = PrepareDist.empty empty_dist in
let opam_reg = FilePath.concat temp_dir "opam_reg" in
let prepare_opam_reg =
PrepareOpamReg.(prepare opam_reg theanoFiles)
>> PrepareOpamReg.(prepare opam_reg grcnumFiles)
>> PrepareOpamReg.(prepare opam_reg classGreekFiles)
>> PrepareOpamReg.(prepare opam_reg baseFiles)
in
prepare_pkg
>> prepare_dist
>> prepare_opam_reg
>>| read_env ~opam_reg ~dist_library_dir:empty_dist
let () =
let verbose = true in
let main env ~dest_dir ~temp_dir =
let name = Some "grcnum" in
let dest_dir = FilePath.concat dest_dir "dest" in
Satyrographos_command.Opam.(with_build_script install_opam ~verbose ~prefix:dest_dir ~buildscript_path:(FilePath.concat temp_dir "pkg/Satyristes") ~env ~name) () in
eval (test_install env main)
| null | https://raw.githubusercontent.com/na4zagin3/satyrographos/9dbccf05138510c977a67c859bbbb48755470c7f/test/testcases/command_opam_install__library_recursive.ml | ocaml | module StdList = List
open Satyrographos_testlib
open TestLib
open Shexp_process
let satyristes =
{|
(version "0.0.2")
(library
(name "grcnum")
(version "0.2")
(sources
((package "grcnum.satyh" "./grcnum.satyh")
(font "grcnum-font.ttf" "./font.ttf")
(hash "fonts.satysfi-hash" "./fonts.satysfi-hash")
(file "doc/grcnum.md" "README.md")
(fontDir "font")
(packageDir "src")
))
(opam "satysfi-grcnum.opam")
(dependencies ((fonts-theano ())))
(compatibility ((satyrographos 0.0.1))))
(libraryDoc
(name "grcnum-doc")
(version "0.2")
(build
((satysfi "doc-grcnum.saty" "-o" "doc-grcnum-ja.pdf")))
(sources
((doc "doc-grcnum-ja.pdf" "./doc-grcnum-ja.pdf")))
(opam "satysfi-grcnum-doc.opam")
(dependencies ((grcnum ())
(fonts-theano ()))))
|}
let fontHash =
{|{
"grcnum:grcnum-font":<"Single":{"src-dist":"grcnum/grcnum-font.ttf"}>
}|}
let env ~dest_dir:_ ~temp_dir : Satyrographos.Environment.t t =
let open Shexp_process.Infix in
let pkg_dir = FilePath.concat temp_dir "pkg" in
let prepare_pkg =
PrepareDist.empty pkg_dir
>> stdout_to (FilePath.concat pkg_dir "Satyristes") (echo satyristes)
>> stdout_to (FilePath.concat pkg_dir "README.md") (echo "@@README.md@@")
>> stdout_to (FilePath.concat pkg_dir "fonts.satysfi-hash") (echo fontHash)
>> stdout_to (FilePath.concat pkg_dir "grcnum.satyh") (echo "@@grcnum.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "font.ttf") (echo "@@font.ttf@@")
>> mkdir ~p:() (FilePath.concat pkg_dir "src/a/b-1/c-1")
>> mkdir ~p:() (FilePath.concat pkg_dir "src/a/b-1/c-2")
>> mkdir ~p:() (FilePath.concat pkg_dir "src/a/b-2")
>> stdout_to (FilePath.concat pkg_dir "src/a/b-1/c-1/file1.satyh") (echo "@@a/b-1/c-1/file1.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "src/a/b-1/c-1/file2.satyh") (echo "@@a/b-1/c-1/file2.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "src/a/b-1/c-2/file1.satyh") (echo "@@a/b-1/c-2/file1.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "src/a/b-1/file.satyh") (echo "@@a/b-1/file.satyh@@")
>> stdout_to (FilePath.concat pkg_dir "src/a/file.satyh") (echo "@@a/file.satyh@@")
>> mkdir ~p:() (FilePath.concat pkg_dir "font/a/b-1/c-1")
>> mkdir ~p:() (FilePath.concat pkg_dir "font/a/b-1/c-2")
>> mkdir ~p:() (FilePath.concat pkg_dir "font/a/b-2")
>> stdout_to (FilePath.concat pkg_dir "font/a/b-1/c-1/file1.ttf") (echo "@@a/b-1/c-1/file1.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "font/a/b-1/c-1/file2.ttf") (echo "@@a/b-1/c-1/file2.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "font/a/b-1/c-2/file1.ttf") (echo "@@a/b-1/c-2/file1.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "font/a/b-1/file.ttf") (echo "@@a/b-1/file.ttf@@")
>> stdout_to (FilePath.concat pkg_dir "font/a/file.ttf") (echo "@@a/file.ttf@@")
in
let empty_dist = FilePath.concat temp_dir "empty_dist" in
let prepare_dist = PrepareDist.empty empty_dist in
let opam_reg = FilePath.concat temp_dir "opam_reg" in
let prepare_opam_reg =
PrepareOpamReg.(prepare opam_reg theanoFiles)
>> PrepareOpamReg.(prepare opam_reg grcnumFiles)
>> PrepareOpamReg.(prepare opam_reg classGreekFiles)
>> PrepareOpamReg.(prepare opam_reg baseFiles)
in
prepare_pkg
>> prepare_dist
>> prepare_opam_reg
>>| read_env ~opam_reg ~dist_library_dir:empty_dist
let () =
let verbose = true in
let main env ~dest_dir ~temp_dir =
let name = Some "grcnum" in
let dest_dir = FilePath.concat dest_dir "dest" in
Satyrographos_command.Opam.(with_build_script install_opam ~verbose ~prefix:dest_dir ~buildscript_path:(FilePath.concat temp_dir "pkg/Satyristes") ~env ~name) () in
eval (test_install env main)
|
|
823677e396fa9e1681555cfcfd2f0ae084142af8343f3385cf56a6391cd59e77 | basho/riak_core | riak_core_new_claim.erl | %% -------------------------------------------------------------------
%%
%% riak_core: Core Riak Application
%%
Copyright ( c ) 2007 - 2011 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
%%
%% @doc This module is a pass-thru to `riak_core_claim' for backwards
%% compatability.
-module(riak_core_new_claim).
-export([new_wants_claim/2, new_choose_claim/2]).
%% @deprecated
%%
%% @doc This exists for the sole purpose of backwards compatability.
new_wants_claim(Ring, Node) ->
riak_core_claim:wants_claim_v2(Ring, Node).
%% @deprecated
%%
%% @doc This exists for the sole purpose of backwards compatability.
new_choose_claim(Ring, Node) ->
riak_core_claim:choose_claim_v2(Ring, Node).
| null | https://raw.githubusercontent.com/basho/riak_core/762ec81ae9af9a278e853f1feca418b9dcf748a3/src/riak_core_new_claim.erl | erlang | -------------------------------------------------------------------
riak_core: Core Riak Application
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
@doc This module is a pass-thru to `riak_core_claim' for backwards
compatability.
@deprecated
@doc This exists for the sole purpose of backwards compatability.
@deprecated
@doc This exists for the sole purpose of backwards compatability. | Copyright ( c ) 2007 - 2011 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(riak_core_new_claim).
-export([new_wants_claim/2, new_choose_claim/2]).
new_wants_claim(Ring, Node) ->
riak_core_claim:wants_claim_v2(Ring, Node).
new_choose_claim(Ring, Node) ->
riak_core_claim:choose_claim_v2(Ring, Node).
|
24c8345fe65469492de818de31301c8932e3193f58d609a52ddcb255128ffae3 | Decentralized-Pictures/T4L3NT | test_ssh_agent.ml | open Rresult
open Ledgerwallet_ssh_agent
let test_open_close () =
let h = Hidapi.open_id_exn ~vendor_id:0x2C97 ~product_id:0x1005 in
Hidapi.close h
let test_ping () =
let h = Hidapi.open_id_exn ~vendor_id:0x2C97 ~product_id:0x1005 in
match Ledgerwallet.Transport.ping h with
| Result.Ok () -> Hidapi.close h
| Result.Error e ->
let () = Hidapi.close h in
failwith
(Format.asprintf "Ledger error: %a" Ledgerwallet.Transport.pp_error e)
let hard x =
Int32.logor x 0x8000_0000l
let path = [
hard 44l ; hard 535348l
]
let test_get_public_key () =
let h = Hidapi.open_id_exn ~vendor_id:0x2C97 ~product_id:0x1005 in
let out =
get_public_key h ~curve:Prime256v1 ~path >>= fun pk_prime ->
get_public_key h ~curve:Curve25519 ~path >>| fun pk_curve ->
Format.printf "Uncompressed prime256v1 public key %a@." Hex.pp (Hex.of_cstruct pk_prime) ;
Format.printf "Uncompressed curve25519 public key %a@." Hex.pp (Hex.of_cstruct pk_curve) in
Hidapi.close h;
match out with
| Result.Ok () -> ()
| Result.Error e ->
failwith
(Format.asprintf "Ledger error: %a" Ledgerwallet.Transport.pp_error e)
let basic = [
"open_close", `Quick, test_open_close ;
"ping", `Quick, test_ping ;
"get_public_key", `Quick, test_get_public_key ;
]
let () =
Alcotest.run "ledgerwallet.ssh-agent" [
"basic", basic ;
]
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/vendors/ocaml-ledger-wallet/test/test_ssh_agent.ml | ocaml | open Rresult
open Ledgerwallet_ssh_agent
let test_open_close () =
let h = Hidapi.open_id_exn ~vendor_id:0x2C97 ~product_id:0x1005 in
Hidapi.close h
let test_ping () =
let h = Hidapi.open_id_exn ~vendor_id:0x2C97 ~product_id:0x1005 in
match Ledgerwallet.Transport.ping h with
| Result.Ok () -> Hidapi.close h
| Result.Error e ->
let () = Hidapi.close h in
failwith
(Format.asprintf "Ledger error: %a" Ledgerwallet.Transport.pp_error e)
let hard x =
Int32.logor x 0x8000_0000l
let path = [
hard 44l ; hard 535348l
]
let test_get_public_key () =
let h = Hidapi.open_id_exn ~vendor_id:0x2C97 ~product_id:0x1005 in
let out =
get_public_key h ~curve:Prime256v1 ~path >>= fun pk_prime ->
get_public_key h ~curve:Curve25519 ~path >>| fun pk_curve ->
Format.printf "Uncompressed prime256v1 public key %a@." Hex.pp (Hex.of_cstruct pk_prime) ;
Format.printf "Uncompressed curve25519 public key %a@." Hex.pp (Hex.of_cstruct pk_curve) in
Hidapi.close h;
match out with
| Result.Ok () -> ()
| Result.Error e ->
failwith
(Format.asprintf "Ledger error: %a" Ledgerwallet.Transport.pp_error e)
let basic = [
"open_close", `Quick, test_open_close ;
"ping", `Quick, test_ping ;
"get_public_key", `Quick, test_get_public_key ;
]
let () =
Alcotest.run "ledgerwallet.ssh-agent" [
"basic", basic ;
]
|
|
70aeb1c955357c2d1553a8b4e1f07e015bec0d3503deb4480ba087e4b8ecfbe4 | michalkonecny/aern2 | Statements.hs | module ERC.Statements where
import Prelude
import AERN2.Kleenean
import ERC.Monad
import ERC.Variables
import ERC.Logic
import ERC.Integer
return_ :: ERC s a -> ERC s a
return_ = id
while_ :: ERC s KLEENEAN -> ERC s a -> ERC s ()
while_ condERC doAction = aux
where
aux =
do
cond <- condERC
case cond of
CertainTrue -> do { _ <- doAction; aux }
CertainFalse -> pure ()
TrueOrFalse -> insufficientPrecision ()
ifThenElse_ :: ERC s KLEENEAN -> (ERC s (), ERC s ()) -> ERC s ()
ifThenElse_ condERC (thenAction, elseAction) =
do
cond <- condERC
case cond of
CertainTrue -> thenAction
CertainFalse -> elseAction
TrueOrFalse -> insufficientPrecision ()
else_ :: ERC s () -> ERC s () -> (ERC s (), ERC s ())
else_ = (,)
ifThen_ :: ERC s KLEENEAN -> ERC s () -> ERC s ()
ifThen_ condERC thenAction =
do
cond <- condERC
case cond of
CertainTrue -> thenAction
CertainFalse -> pure ()
TrueOrFalse -> insufficientPrecision ()
forNfromTo_ :: Var s INTEGER -> ERC s INTEGER -> ERC s INTEGER -> ERC s a -> ERC s ()
forNfromTo_ n k l c =
do
n .= k
while_ ((n?) <=# l) $ do
_ <- c
n .= (n?) + 1
| null | https://raw.githubusercontent.com/michalkonecny/aern2/e5a5c69a8f90cb4ede5fce023ca660fbafda08a9/aern2-erc/src/ERC/Statements.hs | haskell | module ERC.Statements where
import Prelude
import AERN2.Kleenean
import ERC.Monad
import ERC.Variables
import ERC.Logic
import ERC.Integer
return_ :: ERC s a -> ERC s a
return_ = id
while_ :: ERC s KLEENEAN -> ERC s a -> ERC s ()
while_ condERC doAction = aux
where
aux =
do
cond <- condERC
case cond of
CertainTrue -> do { _ <- doAction; aux }
CertainFalse -> pure ()
TrueOrFalse -> insufficientPrecision ()
ifThenElse_ :: ERC s KLEENEAN -> (ERC s (), ERC s ()) -> ERC s ()
ifThenElse_ condERC (thenAction, elseAction) =
do
cond <- condERC
case cond of
CertainTrue -> thenAction
CertainFalse -> elseAction
TrueOrFalse -> insufficientPrecision ()
else_ :: ERC s () -> ERC s () -> (ERC s (), ERC s ())
else_ = (,)
ifThen_ :: ERC s KLEENEAN -> ERC s () -> ERC s ()
ifThen_ condERC thenAction =
do
cond <- condERC
case cond of
CertainTrue -> thenAction
CertainFalse -> pure ()
TrueOrFalse -> insufficientPrecision ()
forNfromTo_ :: Var s INTEGER -> ERC s INTEGER -> ERC s INTEGER -> ERC s a -> ERC s ()
forNfromTo_ n k l c =
do
n .= k
while_ ((n?) <=# l) $ do
_ <- c
n .= (n?) + 1
|
|
c0f8226a312a8482e0afa01ecde3af1a3b69a5bcdd0c3d44f787119466d6eb5b | GaloisInc/HaLVM | Memory.hs | BANNERSTART
- Copyright 2006 - 2008 , Galois , Inc.
- This software is distributed under a standard , three - clause BSD license .
-- - Please see the file LICENSE, distributed with this software, for specific
-- - terms and conditions.
Author : < >
BANNEREND
|A low - level module for dealing with unprivileged Xen memory operations ,
-- including allocating pages, granting access to pages to other domains, and
-- mapping the grants of other domains.
module Hypervisor.Memory(
-- * Types and conversions for dealing with memory.
PFN, MFN
, VPtr, MPtr
, mfnToMPtr, mptrToMFN , mptrToPtr, toMFN, fromMFN, toPFN
, mfnToVPtr, vptrToMFN
, mptrToInteger
, pageSize
-- * Routines for creating, destroying, and modifying pages.
, allocPage
, AllocProt(..), defaultProt
, allocPageProt
, freePage
, withPage
, setPageWritable
, markAsPageTable
, markFrameAsPageTable
, mapFrames
-- * Routines for creating or destroying grant references
-- and grant handles.
, GrantRef(..)
, grantAccess
, endAccess
, GrantHandle(..)
, mapGrants
, unmapGrant
-- * Routines for transferring or copying pages to another domain.
, prepareTransfer
, transferFrame
, completeTransfer
, performFrameCopy
-- * Low-level routines for dealing with frames, address translation,
-- and similar grungy things.
, virtualToMachine
, machineToVirtual
, addressMapped
, systemWMB, systemRMB, systemMB
)
where
import Control.Exception (throwIO)
import Control.Monad
import Data.Binary
import Data.Bits
import Foreign.Ptr
import Foreign.Marshal.Alloc (alloca,allocaBytesAligned)
import Foreign.Marshal.Array (withArray,allocaArray,peekArray)
import Foreign.Storable
import GHC.Generics
import Numeric
#if __GLASGOW_HASKELL__ < 706
import Prelude hiding (catch)
#endif
import Hypervisor.DomainInfo
import Hypervisor.ErrorCodes
--
-- * Types and conversions for dealing with memory.
--
|Pseudo - physical frame numbers . These frame numbers have very little to
-- do with the machine address or the virtual address, but are used in some
Xen hypercalls .
newtype PFN = PFN Word
|Translate to a PFN
toPFN :: Integral a => a -> PFN
toPFN x = PFN (fromIntegral x)
|Machine frame numbers . These frame numbers identify a phyical 4096 - byte
-- frame on the underlying hardware.
newtype MFN = MFN Word
deriving (Eq, Ord, Num, Read, Generic, Storable, Bits)
instance Show MFN where
show (MFN x) = "MFN 0x" ++ showHex x ""
-- |A virtual address that, if you've mapped it, can be written to and read
-- from as per normal.
type VPtr a = Ptr a
-- |A machine address. These cannot be written to or read from directly, as
-- HaLVM's always run with paging enabled.
#if defined(CONFIG_X86_PAE) || defined(CONFIG_X86_64)
newtype MPtr a = MPtr Word64 deriving Storable
#else
newtype MPtr a = MPtr Word32 deriving Storable
#endif
mptrToInteger :: MPtr a -> Integer
mptrToInteger (MPtr x) = fromIntegral x
|Convert a 32 - bit word , from some other source , into an MFN . Manufacturing
-- your own MFNs is dangerous, so make sure you know what you're doing if
-- you use this function.
toMFN :: Word -> MFN
toMFN = MFN
-- | This is used when passing MFNs to some primitives.
-- Eventually, we should change the primitives to take MFNs directly.
fromMFN :: MFN -> Word
fromMFN (MFN x) = x
-- |Convert a machine frame number to the initial machine address within the
-- block.
mfnToMPtr :: MFN -> MPtr a
mfnToMPtr (MFN f) = MPtr (fromIntegral f `shiftL` 12)
-- |Convert a machine frame number to the address at which it is mapped in
-- the address space. Note that, obviously, if the page isn't currently
-- mapped, you'll get an error.
mfnToVPtr :: MFN -> IO (VPtr a)
mfnToVPtr = machineToVirtual . mfnToMPtr
-- |Convert a virtual address to the machine frame underlying its frame. This
-- function will perform the rounding for you. If the page is mapped (if
-- addressMapped) returns True, then this page is guaranteed to succeed.
vptrToMFN :: VPtr a -> IO MFN
vptrToMFN x = do
p <- virtualToMachine x
return (mptrToMFN p)
-- |Convert a machine pointer to its machine frame number. This operation
-- is necessarily lossy, so (x == mptrToMFN (mfnToMPtr x)) does not
-- necessarily hold.
mptrToMFN :: MPtr a -> MFN
mptrToMFN (MPtr p) = fromIntegral (p `shiftR` 12)
-- |Convert a machine pointer to a pointer. In order to use this, you should
-- really know what you're doing. Reading to or from the returned address
-- will probably cause a crash.
mptrToPtr :: MPtr a -> Ptr a
mptrToPtr (MPtr p) = intPtrToPtr (fromIntegral p)
-- |The size, in bytes, of a memory page.
pageSize :: Word32
pageSize = 4096
--
-- * Routines for creating, destroying, and modifying pages.
--
# DEPRECATED allocPage " Avoid use of this , can impact GC functionality . " #
-- |Allocate a page outside the garbage-collected heap. These pages
-- are almost always used with grants.
allocPage :: IO (VPtr a)
allocPage = allocPageProt defaultProt
data AllocProt = AllocProt
{ protRead :: Bool
, protWrite :: Bool
, protExec :: Bool
, protNoCache :: Bool
}
| These are the flags used by allocPage
defaultProt :: AllocProt
defaultProt = AllocProt
{ protRead = True
, protWrite = True
, protExec = True
, protNoCache = False
}
getProt :: AllocProt -> Int
getProt flags = flag (bit 0) protRead
.|. flag (bit 1) protWrite
.|. flag (bit 2) protExec
.|. flag (bit 3) protNoCache
where
flag b p | p flags = b
| otherwise = 0
# DEPRECATED allocPageProt " Avoid use of this , can impact GC functionality . " #
-- | Allocate with a set of protection flags.
allocPageProt :: AllocProt -> IO (VPtr a)
allocPageProt flags = do
va <- allocMemory nullPtr 4096 (getProt flags) 1
if va == nullPtr then throwIO ENOMEM else return $! va
-- |Free a page allocated with allocPage.
freePage :: VPtr a -> IO ()
freePage x
| x /= (x `alignPtr` 4096) = throwIO EINVAL
| otherwise = freeMemory x 4096
-- | Allocate a page, call a function with it, and free it.
withPage :: (VPtr a -> IO b) -> IO b
withPage = allocaBytesAligned 4096 4096
-- |Set a page writable (or not).
setPageWritable :: VPtr a -> Bool -> IO ()
setPageWritable x val = do
ent <- get_pt_entry x
set_pt_entry x (modify ent)
where
modify a | val = a `setBit` 1
| otherwise = a `clearBit` 1
-- |Mark the given page as one that will be used as a page table.
-- The given address is a virtual address. This is the analagous
version of the MMUEXT_PIN_L?_TABLE case of the MMUext hypercall ;
-- the argument specifying what level.
--
-- Note that changing your own page tables is a good way to crash,
-- unless you're very familiar with the HaLVM.
--
-- QUICK GUIDE:
-- Use level '1' for page tables
-- Use level '2' for page directories
Use level ' 3 ' for PAE base tables / directory pointer tables
Use level ' 4 ' for
markAsPageTable :: Int -> VPtr a -> DomId -> IO ()
markAsPageTable l addr dom = do
ent <- get_pt_entry addr
let mfn' = fromIntegral (ent `shiftR` 12)
markFrameAsPageTable l (MFN mfn') dom
markFrameAsPageTable :: Int -> MFN -> DomId -> IO ()
markFrameAsPageTable l mfn dom
| l `notElem` [1 .. 4] = throwIO EINVAL
| otherwise = do i <- pin_frame l (fromMFN mfn) (fromDomId dom)
standardUnitRes i
-- |Map the given list of frames into a contiguous chunk of memory.
mapFrames :: [MFN] -> IO (VPtr a)
mapFrames mfns = withArray (map fromMFN mfns) $ \p -> mapFrames' p (length mfns)
--
-- * Routines for creating or destroying grant references and grant handles.
--
newtype GrantRef = GrantRef { unGrantRef :: Word32 }
deriving (Eq, Ord, Generic, Storable)
instance Show GrantRef where
show (GrantRef x) = "grant:" ++ show x
instance Read GrantRef where
readsPrec d str =
case splitAt 6 str of
("grant:",x) -> map (\ (g,rest) -> (GrantRef g, rest)) (readsPrec d x)
_ -> []
instance Binary GrantRef where
put (GrantRef r) = put r
get = GrantRef `fmap` get
-- |Grant access to a given domain to a given region of memory (starting at
-- the pointer and extending for the given length). The boolean determines
-- if the given domain will be able to write to the memory (True) or not
-- (False).
grantAccess :: DomId -> Ptr a -> Word -> Bool -> IO [GrantRef]
grantAccess dom ptr len writable = ga ptr (fromIntegral len)
where
ga _ 0 = return []
ga p l = do
let pword = ptrToWordPtr ptr
offset = pword .&. 4095
clength = minimum [4096, (4096 - offset), l]
ro = if writable then 0 else 1
i <- alloca $ \ rptr -> do
res <- allocGrant (fromDomId dom) p (fromIntegral clength) ro rptr
if (res < 0)
then throwIO (toEnum (-res) :: ErrorCode)
else peek rptr
((GrantRef i):) `fmap` ga (p `plusPtr` fromIntegral clength) (l - clength)
-- |Stop any access grants associated with the given grant reference.
endAccess :: GrantRef -> IO ()
endAccess (GrantRef gr) = do
res <- endGrant gr
when (res < 0) $ throwIO (toEnum (-res) :: ErrorCode)
-- |The type of a grant handle, or (in other words), the handle to a
-- grant from another domain that we've mapped.
newtype GrantHandle = GrantHandle [Word32]
deriving (Eq, Ord, Show, Read)
-- |Map another domain's grants into our own address space. The return
-- values, if successful, are a pointer to the newly-mapped page in
-- memory and the grant handle. The boolean argument determines whether
HALVM should map the page read - only ( False ) or read\/write ( True ) .
mapGrants :: DomId -> [GrantRef] -> Bool -> IO (VPtr a, GrantHandle)
mapGrants dom refs writable =
withArray (map unGrantRef refs) $ \ ptr ->
alloca $ \ resptr ->
allocaArray count $ \ hndlptr -> do
res <- mapGrants' dom' readonly ptr count resptr hndlptr nullPtr
case compare res 0 of
EQ -> do retptr <- peek resptr
hnds <- GrantHandle `fmap` peekArray count hndlptr
return (retptr, hnds)
LT -> throwIO (toEnum (-res) :: ErrorCode)
GT -> throwIO (toEnum res :: GrantErrorCode)
where
readonly | writable = 0
| otherwise = 1
count = length refs
dom' = fromDomId dom
-- |Unmap the grant of another domain's page. This will make the shared
-- memory inaccessible.
unmapGrant :: GrantHandle -> IO ()
unmapGrant (GrantHandle gh) =
withArray gh $ \ ptr -> do
res <- unmapGrants ptr (length gh)
case compare res 0 of
EQ -> return ()
LT -> throwIO (toEnum (-res) :: ErrorCode)
GT -> throwIO (toEnum res :: GrantErrorCode)
--
-- * Routines for transferring or copying pages to another domain.
--
-- |Allow the given foreign domain to transfer a page to the running domain.
-- The resulting grant reference should be passed to the other domain, for
-- them to use in their transfer request. Usual protocol: Side A does
prepareTransfer , Side B does transferFrame , Side A does completeTransfer .
prepareTransfer :: DomId -> IO GrantRef
prepareTransfer dom = do
res <- prepTransfer (fromDomId dom)
when (res < 0) $ throwIO (toEnum (-res) :: ErrorCode)
return (GrantRef (fromIntegral res))
-- |Transfer the given frame to another domain, using the given grant
-- reference as the transfer mechanism.
transferFrame :: DomId -> GrantRef -> VPtr a -> IO ()
transferFrame dom (GrantRef ref) ptr = do
res <- transferGrant (fromDomId dom) ref ptr
case compare res 0 of
EQ -> return ()
LT -> throwIO (toEnum (-res) :: ErrorCode)
GT -> throwIO (toEnum res :: GrantErrorCode)
-- |Complete a grant transfer, returning the provided frame.
--
The first provided boolean determines the blocking behavior when the other
-- domain has not yet begun the transfer. If True, then the function will
-- block, under the assumption that the other side will begin the transfer
soon . If False , the function will not block , raising EAGAIN if the other
-- side has not yet begun the transfer. In all cases, if the other side has
-- begun the transfer, this routine will block until the transfer completes.
--
The second boolean determines if this grant reference should be recycled
-- and prepared for another grant transfer from the same domain upon completion
-- (True), or if the reference should be freed (False).
completeTransfer :: GrantRef -> Bool -> Bool -> IO MFN
completeTransfer gr@(GrantRef ref) block reset = do
res <- compTransfer ref reset
let ecode = toEnum (-res) :: ErrorCode
case compare res 0 of
LT | block && ecode == EAGAIN -> completeTransfer gr block reset
| otherwise -> throwIO ecode
_ -> return (MFN (fromIntegral res))
|Perform a copy of one frame to another frame . If two frame numbers are
-- used, they must be legitimate frame numbers for the calling domain. For
-- use between domains, the function can use grant references, which must
-- be set as read/write for the appropriate domains. The first mfn/ref and
domain is the source , the second set is the destination . Note that it is
an error to specify an MFN with any other identifier than domidSelf .
performFrameCopy :: (Either GrantRef MFN) -> DomId -> Word16 ->
(Either GrantRef MFN) -> DomId -> Word16 ->
Word16 ->
IO ()
performFrameCopy src sd soff dest dd doff len = do
let (snum,sisref) = argToVals src sd
(dnum,disref) = argToVals dest dd
ret <- perform_grant_copy snum sisref srcDom soff dnum disref destDom doff len
standardUnitRes ret
where
srcDom = fromDomId sd
destDom = fromDomId dd
argToVals :: (Either GrantRef MFN) -> DomId -> (Word, Bool)
argToVals (Left (GrantRef ref)) _ = (fromIntegral ref, True)
argToVals (Right (MFN _)) dom | dom /= domidSelf =
error "Called with an MFN and non-self domain!"
argToVals (Right (MFN mfn)) _ = (fromIntegral mfn, False)
--
-- * Low-level routines for dealing with frames, address translation,
-- and similar grungy things.
--
-- |Convert a virtual address into a machine-physical address.
virtualToMachine :: VPtr a -> IO (MPtr a)
virtualToMachine x = do
ent <- get_pt_entry x
if ent == 0 || not (ent `testBit` 0)
then throwIO EINVAL
else let inword = ptrToWordPtr x
inoff = fromIntegral (inword .&. 4095)
base = ent .&. (complement 4095)
in return (MPtr (fromIntegral (base + inoff)))
-- |Convert a machine-physical address into a virtual address. THIS IS VERY
-- SLOW.
machineToVirtual :: MPtr a -> IO (VPtr a)
machineToVirtual (MPtr x) = machine_to_virtual x >>= \ x' ->
if x' == nullPtr
then throwIO EINVAL
else return x'
-- |Determine if the given address is actually backed with some
-- physical page, thus determining whether or not someone can
-- read or write from the address.
addressMapped :: VPtr a -> IO Bool
addressMapped addr = do
ent <- get_pt_entry addr
return (ent `testBit` 0) -- lowest bit is the present bit
--
-- --------------------------------------------------------------------------
--
standardUnitRes :: Integral a => a -> IO ()
standardUnitRes 0 = return ()
standardUnitRes x = throwIO (toEnum (fromIntegral (-x)) :: ErrorCode)
#define C_PFN_T Word32
#if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
# define C_MADDR_T Word64
# define C_SIZE_T Word64
#else
# define C_MADDR_T Word32
# define C_SIZE_T Word32
#endif
#define C_PADDR_T Word32
#define C_VADDR_T (VPtr a)
-- Functions from vmm.h
foreign import ccall unsafe "vmm.h get_pt_entry"
get_pt_entry :: Ptr a -> IO Word64
foreign import ccall unsafe "vmm.h set_pt_entry"
set_pt_entry :: Ptr a -> Word64 -> IO ()
foreign import ccall unsafe "vmm.h machine_to_virtual"
machine_to_virtual :: C_MADDR_T -> IO (VPtr a)
-- Functions from memory.h
foreign import ccall unsafe "memory.h pin_frame"
pin_frame :: Int -> Word -> Word32 -> IO Int
foreign import ccall unsafe "memory.h map_frames"
mapFrames' :: VPtr Word -> Int -> IO (VPtr a)
foreign import ccall unsafe "memory.h system_wmb"
systemWMB :: IO ()
foreign import ccall unsafe "memory.h system_rmb"
systemRMB :: IO ()
foreign import ccall unsafe "memory.h system_mb"
systemMB :: IO ()
Functions from runtime_reqs.h
foreign import ccall unsafe "runtime_reqs.h runtime_alloc"
allocMemory :: VPtr a -> Word -> Int -> Int -> IO (VPtr a)
foreign import ccall unsafe "runtime_reqs.h runtime_free"
freeMemory :: VPtr a -> Word -> IO ()
-- functions from grants.h
foreign import ccall unsafe "grants.h alloc_grant"
allocGrant :: Word16 -> VPtr a -> Word16 -> Int -> VPtr Word32 -> IO Int
foreign import ccall unsafe "grants.h end_grant"
endGrant :: Word32 -> IO Int
foreign import ccall unsafe "grants.h map_grants"
mapGrants' :: Word16 -> Int -> VPtr Word32 -> Int ->
VPtr (VPtr a) -> VPtr Word32 -> VPtr Word64 ->
IO Int
foreign import ccall unsafe "grants.h unmap_grants"
unmapGrants :: VPtr Word32 -> Int -> IO Int
foreign import ccall unsafe "grants.h prepare_transfer"
prepTransfer :: Word16 -> IO Int
foreign import ccall unsafe "grants.h transfer_frame"
transferGrant :: Word16 -> Word32 -> VPtr a -> IO Int
foreign import ccall unsafe "grants.h complete_transfer"
compTransfer :: Word32 -> Bool -> IO Int
foreign import ccall unsafe "grants.h copy_frame"
perform_grant_copy :: Word -> Bool -> Word16 -> Word16 ->
Word -> Bool -> Word16 -> Word16 ->
Word16 -> IO Int
| null | https://raw.githubusercontent.com/GaloisInc/HaLVM/3ec1d7e4b6bcb91304ba2bfe8ee280cb1699f24d/src/HALVMCore/Hypervisor/Memory.hs | haskell | - Please see the file LICENSE, distributed with this software, for specific
- terms and conditions.
including allocating pages, granting access to pages to other domains, and
mapping the grants of other domains.
* Types and conversions for dealing with memory.
* Routines for creating, destroying, and modifying pages.
* Routines for creating or destroying grant references
and grant handles.
* Routines for transferring or copying pages to another domain.
* Low-level routines for dealing with frames, address translation,
and similar grungy things.
* Types and conversions for dealing with memory.
do with the machine address or the virtual address, but are used in some
frame on the underlying hardware.
|A virtual address that, if you've mapped it, can be written to and read
from as per normal.
|A machine address. These cannot be written to or read from directly, as
HaLVM's always run with paging enabled.
your own MFNs is dangerous, so make sure you know what you're doing if
you use this function.
| This is used when passing MFNs to some primitives.
Eventually, we should change the primitives to take MFNs directly.
|Convert a machine frame number to the initial machine address within the
block.
|Convert a machine frame number to the address at which it is mapped in
the address space. Note that, obviously, if the page isn't currently
mapped, you'll get an error.
|Convert a virtual address to the machine frame underlying its frame. This
function will perform the rounding for you. If the page is mapped (if
addressMapped) returns True, then this page is guaranteed to succeed.
|Convert a machine pointer to its machine frame number. This operation
is necessarily lossy, so (x == mptrToMFN (mfnToMPtr x)) does not
necessarily hold.
|Convert a machine pointer to a pointer. In order to use this, you should
really know what you're doing. Reading to or from the returned address
will probably cause a crash.
|The size, in bytes, of a memory page.
* Routines for creating, destroying, and modifying pages.
|Allocate a page outside the garbage-collected heap. These pages
are almost always used with grants.
| Allocate with a set of protection flags.
|Free a page allocated with allocPage.
| Allocate a page, call a function with it, and free it.
|Set a page writable (or not).
|Mark the given page as one that will be used as a page table.
The given address is a virtual address. This is the analagous
the argument specifying what level.
Note that changing your own page tables is a good way to crash,
unless you're very familiar with the HaLVM.
QUICK GUIDE:
Use level '1' for page tables
Use level '2' for page directories
|Map the given list of frames into a contiguous chunk of memory.
* Routines for creating or destroying grant references and grant handles.
|Grant access to a given domain to a given region of memory (starting at
the pointer and extending for the given length). The boolean determines
if the given domain will be able to write to the memory (True) or not
(False).
|Stop any access grants associated with the given grant reference.
|The type of a grant handle, or (in other words), the handle to a
grant from another domain that we've mapped.
|Map another domain's grants into our own address space. The return
values, if successful, are a pointer to the newly-mapped page in
memory and the grant handle. The boolean argument determines whether
|Unmap the grant of another domain's page. This will make the shared
memory inaccessible.
* Routines for transferring or copying pages to another domain.
|Allow the given foreign domain to transfer a page to the running domain.
The resulting grant reference should be passed to the other domain, for
them to use in their transfer request. Usual protocol: Side A does
|Transfer the given frame to another domain, using the given grant
reference as the transfer mechanism.
|Complete a grant transfer, returning the provided frame.
domain has not yet begun the transfer. If True, then the function will
block, under the assumption that the other side will begin the transfer
side has not yet begun the transfer. In all cases, if the other side has
begun the transfer, this routine will block until the transfer completes.
and prepared for another grant transfer from the same domain upon completion
(True), or if the reference should be freed (False).
used, they must be legitimate frame numbers for the calling domain. For
use between domains, the function can use grant references, which must
be set as read/write for the appropriate domains. The first mfn/ref and
* Low-level routines for dealing with frames, address translation,
and similar grungy things.
|Convert a virtual address into a machine-physical address.
|Convert a machine-physical address into a virtual address. THIS IS VERY
SLOW.
|Determine if the given address is actually backed with some
physical page, thus determining whether or not someone can
read or write from the address.
lowest bit is the present bit
--------------------------------------------------------------------------
Functions from vmm.h
Functions from memory.h
functions from grants.h | BANNERSTART
- Copyright 2006 - 2008 , Galois , Inc.
- This software is distributed under a standard , three - clause BSD license .
Author : < >
BANNEREND
|A low - level module for dealing with unprivileged Xen memory operations ,
module Hypervisor.Memory(
PFN, MFN
, VPtr, MPtr
, mfnToMPtr, mptrToMFN , mptrToPtr, toMFN, fromMFN, toPFN
, mfnToVPtr, vptrToMFN
, mptrToInteger
, pageSize
, allocPage
, AllocProt(..), defaultProt
, allocPageProt
, freePage
, withPage
, setPageWritable
, markAsPageTable
, markFrameAsPageTable
, mapFrames
, GrantRef(..)
, grantAccess
, endAccess
, GrantHandle(..)
, mapGrants
, unmapGrant
, prepareTransfer
, transferFrame
, completeTransfer
, performFrameCopy
, virtualToMachine
, machineToVirtual
, addressMapped
, systemWMB, systemRMB, systemMB
)
where
import Control.Exception (throwIO)
import Control.Monad
import Data.Binary
import Data.Bits
import Foreign.Ptr
import Foreign.Marshal.Alloc (alloca,allocaBytesAligned)
import Foreign.Marshal.Array (withArray,allocaArray,peekArray)
import Foreign.Storable
import GHC.Generics
import Numeric
#if __GLASGOW_HASKELL__ < 706
import Prelude hiding (catch)
#endif
import Hypervisor.DomainInfo
import Hypervisor.ErrorCodes
|Pseudo - physical frame numbers . These frame numbers have very little to
Xen hypercalls .
newtype PFN = PFN Word
|Translate to a PFN
toPFN :: Integral a => a -> PFN
toPFN x = PFN (fromIntegral x)
|Machine frame numbers . These frame numbers identify a phyical 4096 - byte
newtype MFN = MFN Word
deriving (Eq, Ord, Num, Read, Generic, Storable, Bits)
instance Show MFN where
show (MFN x) = "MFN 0x" ++ showHex x ""
type VPtr a = Ptr a
#if defined(CONFIG_X86_PAE) || defined(CONFIG_X86_64)
newtype MPtr a = MPtr Word64 deriving Storable
#else
newtype MPtr a = MPtr Word32 deriving Storable
#endif
mptrToInteger :: MPtr a -> Integer
mptrToInteger (MPtr x) = fromIntegral x
|Convert a 32 - bit word , from some other source , into an MFN . Manufacturing
toMFN :: Word -> MFN
toMFN = MFN
fromMFN :: MFN -> Word
fromMFN (MFN x) = x
mfnToMPtr :: MFN -> MPtr a
mfnToMPtr (MFN f) = MPtr (fromIntegral f `shiftL` 12)
mfnToVPtr :: MFN -> IO (VPtr a)
mfnToVPtr = machineToVirtual . mfnToMPtr
vptrToMFN :: VPtr a -> IO MFN
vptrToMFN x = do
p <- virtualToMachine x
return (mptrToMFN p)
mptrToMFN :: MPtr a -> MFN
mptrToMFN (MPtr p) = fromIntegral (p `shiftR` 12)
mptrToPtr :: MPtr a -> Ptr a
mptrToPtr (MPtr p) = intPtrToPtr (fromIntegral p)
pageSize :: Word32
pageSize = 4096
# DEPRECATED allocPage " Avoid use of this , can impact GC functionality . " #
allocPage :: IO (VPtr a)
allocPage = allocPageProt defaultProt
data AllocProt = AllocProt
{ protRead :: Bool
, protWrite :: Bool
, protExec :: Bool
, protNoCache :: Bool
}
| These are the flags used by allocPage
defaultProt :: AllocProt
defaultProt = AllocProt
{ protRead = True
, protWrite = True
, protExec = True
, protNoCache = False
}
getProt :: AllocProt -> Int
getProt flags = flag (bit 0) protRead
.|. flag (bit 1) protWrite
.|. flag (bit 2) protExec
.|. flag (bit 3) protNoCache
where
flag b p | p flags = b
| otherwise = 0
# DEPRECATED allocPageProt " Avoid use of this , can impact GC functionality . " #
allocPageProt :: AllocProt -> IO (VPtr a)
allocPageProt flags = do
va <- allocMemory nullPtr 4096 (getProt flags) 1
if va == nullPtr then throwIO ENOMEM else return $! va
freePage :: VPtr a -> IO ()
freePage x
| x /= (x `alignPtr` 4096) = throwIO EINVAL
| otherwise = freeMemory x 4096
withPage :: (VPtr a -> IO b) -> IO b
withPage = allocaBytesAligned 4096 4096
setPageWritable :: VPtr a -> Bool -> IO ()
setPageWritable x val = do
ent <- get_pt_entry x
set_pt_entry x (modify ent)
where
modify a | val = a `setBit` 1
| otherwise = a `clearBit` 1
version of the MMUEXT_PIN_L?_TABLE case of the MMUext hypercall ;
Use level ' 3 ' for PAE base tables / directory pointer tables
Use level ' 4 ' for
markAsPageTable :: Int -> VPtr a -> DomId -> IO ()
markAsPageTable l addr dom = do
ent <- get_pt_entry addr
let mfn' = fromIntegral (ent `shiftR` 12)
markFrameAsPageTable l (MFN mfn') dom
markFrameAsPageTable :: Int -> MFN -> DomId -> IO ()
markFrameAsPageTable l mfn dom
| l `notElem` [1 .. 4] = throwIO EINVAL
| otherwise = do i <- pin_frame l (fromMFN mfn) (fromDomId dom)
standardUnitRes i
mapFrames :: [MFN] -> IO (VPtr a)
mapFrames mfns = withArray (map fromMFN mfns) $ \p -> mapFrames' p (length mfns)
newtype GrantRef = GrantRef { unGrantRef :: Word32 }
deriving (Eq, Ord, Generic, Storable)
instance Show GrantRef where
show (GrantRef x) = "grant:" ++ show x
instance Read GrantRef where
readsPrec d str =
case splitAt 6 str of
("grant:",x) -> map (\ (g,rest) -> (GrantRef g, rest)) (readsPrec d x)
_ -> []
instance Binary GrantRef where
put (GrantRef r) = put r
get = GrantRef `fmap` get
grantAccess :: DomId -> Ptr a -> Word -> Bool -> IO [GrantRef]
grantAccess dom ptr len writable = ga ptr (fromIntegral len)
where
ga _ 0 = return []
ga p l = do
let pword = ptrToWordPtr ptr
offset = pword .&. 4095
clength = minimum [4096, (4096 - offset), l]
ro = if writable then 0 else 1
i <- alloca $ \ rptr -> do
res <- allocGrant (fromDomId dom) p (fromIntegral clength) ro rptr
if (res < 0)
then throwIO (toEnum (-res) :: ErrorCode)
else peek rptr
((GrantRef i):) `fmap` ga (p `plusPtr` fromIntegral clength) (l - clength)
endAccess :: GrantRef -> IO ()
endAccess (GrantRef gr) = do
res <- endGrant gr
when (res < 0) $ throwIO (toEnum (-res) :: ErrorCode)
newtype GrantHandle = GrantHandle [Word32]
deriving (Eq, Ord, Show, Read)
HALVM should map the page read - only ( False ) or read\/write ( True ) .
mapGrants :: DomId -> [GrantRef] -> Bool -> IO (VPtr a, GrantHandle)
mapGrants dom refs writable =
withArray (map unGrantRef refs) $ \ ptr ->
alloca $ \ resptr ->
allocaArray count $ \ hndlptr -> do
res <- mapGrants' dom' readonly ptr count resptr hndlptr nullPtr
case compare res 0 of
EQ -> do retptr <- peek resptr
hnds <- GrantHandle `fmap` peekArray count hndlptr
return (retptr, hnds)
LT -> throwIO (toEnum (-res) :: ErrorCode)
GT -> throwIO (toEnum res :: GrantErrorCode)
where
readonly | writable = 0
| otherwise = 1
count = length refs
dom' = fromDomId dom
unmapGrant :: GrantHandle -> IO ()
unmapGrant (GrantHandle gh) =
withArray gh $ \ ptr -> do
res <- unmapGrants ptr (length gh)
case compare res 0 of
EQ -> return ()
LT -> throwIO (toEnum (-res) :: ErrorCode)
GT -> throwIO (toEnum res :: GrantErrorCode)
prepareTransfer , Side B does transferFrame , Side A does completeTransfer .
prepareTransfer :: DomId -> IO GrantRef
prepareTransfer dom = do
res <- prepTransfer (fromDomId dom)
when (res < 0) $ throwIO (toEnum (-res) :: ErrorCode)
return (GrantRef (fromIntegral res))
transferFrame :: DomId -> GrantRef -> VPtr a -> IO ()
transferFrame dom (GrantRef ref) ptr = do
res <- transferGrant (fromDomId dom) ref ptr
case compare res 0 of
EQ -> return ()
LT -> throwIO (toEnum (-res) :: ErrorCode)
GT -> throwIO (toEnum res :: GrantErrorCode)
The first provided boolean determines the blocking behavior when the other
soon . If False , the function will not block , raising EAGAIN if the other
The second boolean determines if this grant reference should be recycled
completeTransfer :: GrantRef -> Bool -> Bool -> IO MFN
completeTransfer gr@(GrantRef ref) block reset = do
res <- compTransfer ref reset
let ecode = toEnum (-res) :: ErrorCode
case compare res 0 of
LT | block && ecode == EAGAIN -> completeTransfer gr block reset
| otherwise -> throwIO ecode
_ -> return (MFN (fromIntegral res))
|Perform a copy of one frame to another frame . If two frame numbers are
domain is the source , the second set is the destination . Note that it is
an error to specify an MFN with any other identifier than domidSelf .
performFrameCopy :: (Either GrantRef MFN) -> DomId -> Word16 ->
(Either GrantRef MFN) -> DomId -> Word16 ->
Word16 ->
IO ()
performFrameCopy src sd soff dest dd doff len = do
let (snum,sisref) = argToVals src sd
(dnum,disref) = argToVals dest dd
ret <- perform_grant_copy snum sisref srcDom soff dnum disref destDom doff len
standardUnitRes ret
where
srcDom = fromDomId sd
destDom = fromDomId dd
argToVals :: (Either GrantRef MFN) -> DomId -> (Word, Bool)
argToVals (Left (GrantRef ref)) _ = (fromIntegral ref, True)
argToVals (Right (MFN _)) dom | dom /= domidSelf =
error "Called with an MFN and non-self domain!"
argToVals (Right (MFN mfn)) _ = (fromIntegral mfn, False)
virtualToMachine :: VPtr a -> IO (MPtr a)
virtualToMachine x = do
ent <- get_pt_entry x
if ent == 0 || not (ent `testBit` 0)
then throwIO EINVAL
else let inword = ptrToWordPtr x
inoff = fromIntegral (inword .&. 4095)
base = ent .&. (complement 4095)
in return (MPtr (fromIntegral (base + inoff)))
machineToVirtual :: MPtr a -> IO (VPtr a)
machineToVirtual (MPtr x) = machine_to_virtual x >>= \ x' ->
if x' == nullPtr
then throwIO EINVAL
else return x'
addressMapped :: VPtr a -> IO Bool
addressMapped addr = do
ent <- get_pt_entry addr
standardUnitRes :: Integral a => a -> IO ()
standardUnitRes 0 = return ()
standardUnitRes x = throwIO (toEnum (fromIntegral (-x)) :: ErrorCode)
#define C_PFN_T Word32
#if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
# define C_MADDR_T Word64
# define C_SIZE_T Word64
#else
# define C_MADDR_T Word32
# define C_SIZE_T Word32
#endif
#define C_PADDR_T Word32
#define C_VADDR_T (VPtr a)
foreign import ccall unsafe "vmm.h get_pt_entry"
get_pt_entry :: Ptr a -> IO Word64
foreign import ccall unsafe "vmm.h set_pt_entry"
set_pt_entry :: Ptr a -> Word64 -> IO ()
foreign import ccall unsafe "vmm.h machine_to_virtual"
machine_to_virtual :: C_MADDR_T -> IO (VPtr a)
foreign import ccall unsafe "memory.h pin_frame"
pin_frame :: Int -> Word -> Word32 -> IO Int
foreign import ccall unsafe "memory.h map_frames"
mapFrames' :: VPtr Word -> Int -> IO (VPtr a)
foreign import ccall unsafe "memory.h system_wmb"
systemWMB :: IO ()
foreign import ccall unsafe "memory.h system_rmb"
systemRMB :: IO ()
foreign import ccall unsafe "memory.h system_mb"
systemMB :: IO ()
Functions from runtime_reqs.h
foreign import ccall unsafe "runtime_reqs.h runtime_alloc"
allocMemory :: VPtr a -> Word -> Int -> Int -> IO (VPtr a)
foreign import ccall unsafe "runtime_reqs.h runtime_free"
freeMemory :: VPtr a -> Word -> IO ()
foreign import ccall unsafe "grants.h alloc_grant"
allocGrant :: Word16 -> VPtr a -> Word16 -> Int -> VPtr Word32 -> IO Int
foreign import ccall unsafe "grants.h end_grant"
endGrant :: Word32 -> IO Int
foreign import ccall unsafe "grants.h map_grants"
mapGrants' :: Word16 -> Int -> VPtr Word32 -> Int ->
VPtr (VPtr a) -> VPtr Word32 -> VPtr Word64 ->
IO Int
foreign import ccall unsafe "grants.h unmap_grants"
unmapGrants :: VPtr Word32 -> Int -> IO Int
foreign import ccall unsafe "grants.h prepare_transfer"
prepTransfer :: Word16 -> IO Int
foreign import ccall unsafe "grants.h transfer_frame"
transferGrant :: Word16 -> Word32 -> VPtr a -> IO Int
foreign import ccall unsafe "grants.h complete_transfer"
compTransfer :: Word32 -> Bool -> IO Int
foreign import ccall unsafe "grants.h copy_frame"
perform_grant_copy :: Word -> Bool -> Word16 -> Word16 ->
Word -> Bool -> Word16 -> Word16 ->
Word16 -> IO Int
|
0a624528759e0ad4fa801c5a453722a0c9318d6b07954cfba7d0ecb324cf0fba | ucsd-progsys/liquidhaskell | RIO.hs | {-@ LIQUID "--expect-any-error" @-}
# LANGUAGE CPP #
module RIO where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
-- THE REST OF THIS FILE IS SAFE; just adding this to trigger an error to appease the "neg" gods.
@ : : @
silly_buggy_incr :: Int -> Int
silly_buggy_incr x = x - 1
@ data RIO a < p : : World - > Bool , q : : World - > a - > World - > Bool >
= RIO ( rs : : ( xxx : World < p > - > ( a , World)<\w - > { v : World < q xxx w > | true } > ) )
@
= RIO (rs :: (xxx:World<p> -> (a, World)<\w -> {v:World<q xxx w> | true}>))
@-}
data RIO a = RIO {runState :: World -> (a, World)}
@ runState : : forall < p : : World - > Bool , q : : World - > a - > World - > Bool > .
RIO < p , q > a - > xyy : World < p > - > ( a , World)<\w - > { v : World < q xyy w > | true } > @
RIO <p, q> a -> xyy:World<p> -> (a, World)<\w -> {v:World<q xyy w> | true}> @-}
data World = W
| RJ : Putting these in to get GHC 7.10 to not fuss
instance Functor RIO where
fmap = undefined
| RJ : Putting these in to get GHC 7.10 to not fuss
instance Applicative RIO where
pure = undefined
(<*>) = undefined
instance Monad RIO where
@ instance where
> > = : : forall < p : : World - > Bool
, p2 : : a - > World - > Bool
, r : : a - > Bool
, q1 : : World - > a - > World - > Bool
, q2 : : a - > World - > b - > World - > Bool
, q : : World - > b - > World - > Bool > .
{ x::a < r > , w::World < p>|- World < q1 w x > < : World < p2 x > }
{ y::a , w::World < p > , w2::World < p2 y > , x::b , y::a < r > |- World < q2 y w2 x > < : World < q w x > }
{ x::a , w::World , w2::World < q1 w x>|- { v : a | v = x } < : a < r > }
RIO < p , q1 > a
- > ( x : a < r > - > RIO < { v : World < p2 x > | true } , \w1 y - > { v : World < q2 x w1 y > | true } > b )
- > RIO < p , q > b ;
> > : : forall < p : : World - > Bool
, p2 : : World - > Bool
, q1 : : World - > a - > World - > Bool
, q2 : : World - > b - > World - > Bool
, q : : World - > b - > World - > Bool > .
{ x::a , w::World < p>|- World < q1 w x > < : World < p2 > }
{ w::World < p > , w2::World < p2 > , x::b , y::a |- World < q2 w2 x > < : World < q w x > }
RIO < p , q1 > a
- > RIO < p2 , q2 > b
- > RIO < p , q > b ;
return : : forall < p : : World - > Bool > .
x : a - > RIO < p , \w0 y - > { w1 : World | w0 = = w1 & & y = = x } > a
@
>>= :: forall < p :: World -> Bool
, p2 :: a -> World -> Bool
, r :: a -> Bool
, q1 :: World -> a -> World -> Bool
, q2 :: a -> World -> b -> World -> Bool
, q :: World -> b -> World -> Bool>.
{x::a<r>, w::World<p>|- World<q1 w x> <: World<p2 x>}
{y::a, w::World<p>, w2::World<p2 y>, x::b, y::a<r> |- World<q2 y w2 x> <: World<q w x>}
{x::a, w::World, w2::World<q1 w x>|- {v:a | v = x} <: a<r>}
RIO <p, q1> a
-> (x:a<r> -> RIO <{v:World<p2 x> | true}, \w1 y -> {v:World<q2 x w1 y> | true}> b)
-> RIO <p, q> b ;
>> :: forall < p :: World -> Bool
, p2 :: World -> Bool
, q1 :: World -> a -> World -> Bool
, q2 :: World -> b -> World -> Bool
, q :: World -> b -> World -> Bool>.
{x::a, w::World<p>|- World<q1 w x> <: World<p2>}
{w::World<p>, w2::World<p2>, x::b, y::a |- World<q2 w2 x> <: World<q w x>}
RIO <p, q1> a
-> RIO <p2, q2> b
-> RIO <p, q> b ;
return :: forall <p :: World -> Bool>.
x:a -> RIO <p, \w0 y -> {w1:World | w0 == w1 && y == x}> a
@-}
(RIO g) >>= f = RIO $ \x -> case g x of {(y, s) -> (runState (f y)) s}
(RIO g) >> f = RIO $ \x -> case g x of {(y, s) -> (runState f ) s}
return w = RIO $ \x -> (w, x)
{-@ qualif Papp4(v:a, x:b, y:c, z:d, p:Pred a b c d) : papp4(p, v, x, y, z) @-}
-- Test Cases:
-- * TestM (Basic)
-- * TwiceM
* IfM
-- * WhileM
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/benchmarks/icfp15/neg/RIO.hs | haskell | @ LIQUID "--expect-any-error" @
THE REST OF THIS FILE IS SAFE; just adding this to trigger an error to appease the "neg" gods.
@ qualif Papp4(v:a, x:b, y:c, z:d, p:Pred a b c d) : papp4(p, v, x, y, z) @
Test Cases:
* TestM (Basic)
* TwiceM
* WhileM | # LANGUAGE CPP #
module RIO where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
@ : : @
silly_buggy_incr :: Int -> Int
silly_buggy_incr x = x - 1
@ data RIO a < p : : World - > Bool , q : : World - > a - > World - > Bool >
= RIO ( rs : : ( xxx : World < p > - > ( a , World)<\w - > { v : World < q xxx w > | true } > ) )
@
= RIO (rs :: (xxx:World<p> -> (a, World)<\w -> {v:World<q xxx w> | true}>))
@-}
data RIO a = RIO {runState :: World -> (a, World)}
@ runState : : forall < p : : World - > Bool , q : : World - > a - > World - > Bool > .
RIO < p , q > a - > xyy : World < p > - > ( a , World)<\w - > { v : World < q xyy w > | true } > @
RIO <p, q> a -> xyy:World<p> -> (a, World)<\w -> {v:World<q xyy w> | true}> @-}
data World = W
| RJ : Putting these in to get GHC 7.10 to not fuss
instance Functor RIO where
fmap = undefined
| RJ : Putting these in to get GHC 7.10 to not fuss
instance Applicative RIO where
pure = undefined
(<*>) = undefined
instance Monad RIO where
@ instance where
> > = : : forall < p : : World - > Bool
, p2 : : a - > World - > Bool
, r : : a - > Bool
, q1 : : World - > a - > World - > Bool
, q2 : : a - > World - > b - > World - > Bool
, q : : World - > b - > World - > Bool > .
{ x::a < r > , w::World < p>|- World < q1 w x > < : World < p2 x > }
{ y::a , w::World < p > , w2::World < p2 y > , x::b , y::a < r > |- World < q2 y w2 x > < : World < q w x > }
{ x::a , w::World , w2::World < q1 w x>|- { v : a | v = x } < : a < r > }
RIO < p , q1 > a
- > ( x : a < r > - > RIO < { v : World < p2 x > | true } , \w1 y - > { v : World < q2 x w1 y > | true } > b )
- > RIO < p , q > b ;
> > : : forall < p : : World - > Bool
, p2 : : World - > Bool
, q1 : : World - > a - > World - > Bool
, q2 : : World - > b - > World - > Bool
, q : : World - > b - > World - > Bool > .
{ x::a , w::World < p>|- World < q1 w x > < : World < p2 > }
{ w::World < p > , w2::World < p2 > , x::b , y::a |- World < q2 w2 x > < : World < q w x > }
RIO < p , q1 > a
- > RIO < p2 , q2 > b
- > RIO < p , q > b ;
return : : forall < p : : World - > Bool > .
x : a - > RIO < p , \w0 y - > { w1 : World | w0 = = w1 & & y = = x } > a
@
>>= :: forall < p :: World -> Bool
, p2 :: a -> World -> Bool
, r :: a -> Bool
, q1 :: World -> a -> World -> Bool
, q2 :: a -> World -> b -> World -> Bool
, q :: World -> b -> World -> Bool>.
{x::a<r>, w::World<p>|- World<q1 w x> <: World<p2 x>}
{y::a, w::World<p>, w2::World<p2 y>, x::b, y::a<r> |- World<q2 y w2 x> <: World<q w x>}
{x::a, w::World, w2::World<q1 w x>|- {v:a | v = x} <: a<r>}
RIO <p, q1> a
-> (x:a<r> -> RIO <{v:World<p2 x> | true}, \w1 y -> {v:World<q2 x w1 y> | true}> b)
-> RIO <p, q> b ;
>> :: forall < p :: World -> Bool
, p2 :: World -> Bool
, q1 :: World -> a -> World -> Bool
, q2 :: World -> b -> World -> Bool
, q :: World -> b -> World -> Bool>.
{x::a, w::World<p>|- World<q1 w x> <: World<p2>}
{w::World<p>, w2::World<p2>, x::b, y::a |- World<q2 w2 x> <: World<q w x>}
RIO <p, q1> a
-> RIO <p2, q2> b
-> RIO <p, q> b ;
return :: forall <p :: World -> Bool>.
x:a -> RIO <p, \w0 y -> {w1:World | w0 == w1 && y == x}> a
@-}
(RIO g) >>= f = RIO $ \x -> case g x of {(y, s) -> (runState (f y)) s}
(RIO g) >> f = RIO $ \x -> case g x of {(y, s) -> (runState f ) s}
return w = RIO $ \x -> (w, x)
* IfM
|
58ba744343cfbc11f7c6c62d386c0e704c78de721cf8e3652f7b4cdd1d3c7b1f | amnh/PCG | Encodable.hs | -----------------------------------------------------------------------------
-- |
-- Module : Bio.Character.Encodable
Copyright : ( c ) 2015 - 2021 Ward Wheeler
-- License : BSD-style
--
-- Maintainer :
-- Stability : provisional
-- Portability : portable
--
-- Export of coded characters
--
-----------------------------------------------------------------------------
module Bio.Character.Encodable
( AmbiguityGroup()
, AlignmentContext(..)
, ContinuousCharacter()
, DecodableStream(..)
, DynamicCharacter(..)
, DynamicCharacterElement()
, StaticCharacter()
, StaticCharacterBlock()
, EncodedAmbiguityGroupContainer(..)
, EncodableContinuousCharacter(..)
, EncodableDynamicCharacter(..)
, EncodableDynamicCharacterElement(..)
, EncodableStaticCharacter(..)
, EncodableStaticCharacterStream(..)
, EncodableStreamElement(..)
, EncodableStream(..)
, PossiblyMissingCharacter(..)
, Subcomponent
, renderDynamicCharacter
, showStream
, showStreamElement
-- , selectDC
) where
import Bio.Character.Encodable.Continuous
import Bio.Character.Encodable.Dynamic
import Bio.Character.Encodable.Static
import Bio.Character.Encodable.Stream
| null | https://raw.githubusercontent.com/amnh/PCG/9341efe0ec2053302c22b4466157d0a24ed18154/lib/core/data-structures/src/Bio/Character/Encodable.hs | haskell | ---------------------------------------------------------------------------
|
Module : Bio.Character.Encodable
License : BSD-style
Maintainer :
Stability : provisional
Portability : portable
Export of coded characters
---------------------------------------------------------------------------
, selectDC | Copyright : ( c ) 2015 - 2021 Ward Wheeler
module Bio.Character.Encodable
( AmbiguityGroup()
, AlignmentContext(..)
, ContinuousCharacter()
, DecodableStream(..)
, DynamicCharacter(..)
, DynamicCharacterElement()
, StaticCharacter()
, StaticCharacterBlock()
, EncodedAmbiguityGroupContainer(..)
, EncodableContinuousCharacter(..)
, EncodableDynamicCharacter(..)
, EncodableDynamicCharacterElement(..)
, EncodableStaticCharacter(..)
, EncodableStaticCharacterStream(..)
, EncodableStreamElement(..)
, EncodableStream(..)
, PossiblyMissingCharacter(..)
, Subcomponent
, renderDynamicCharacter
, showStream
, showStreamElement
) where
import Bio.Character.Encodable.Continuous
import Bio.Character.Encodable.Dynamic
import Bio.Character.Encodable.Static
import Bio.Character.Encodable.Stream
|
fd90bc71f54c7c15cd64762759445a76900e5007688b6dacf3330a659a727c9c | kupl/LearnML | patch.ml | type formula =
| True
| False
| Not of formula
| AndAlso of (formula * formula)
| OrElse of (formula * formula)
| Imply of (formula * formula)
| Equal of (exp * exp)
and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp)
let rec eval_exp (e : exp) : int =
match e with
| Num x -> x
| Plus (x, y) -> eval_exp x + eval_exp y
| Minus (x, y) -> eval_exp x - eval_exp y
let rec eval (f : formula) : bool =
match f with
| True -> true
| False -> false
| Not a -> not (eval a)
| AndAlso (x, y) -> eval x && eval y
| OrElse (x, y) -> eval x || eval y
| Imply (x, y) -> if eval x = false || eval y = true then true else false
| Equal (x, y) -> if eval_exp x = eval_exp y then true else false
| null | https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/formula/sub24/patch.ml | ocaml | type formula =
| True
| False
| Not of formula
| AndAlso of (formula * formula)
| OrElse of (formula * formula)
| Imply of (formula * formula)
| Equal of (exp * exp)
and exp = Num of int | Plus of (exp * exp) | Minus of (exp * exp)
let rec eval_exp (e : exp) : int =
match e with
| Num x -> x
| Plus (x, y) -> eval_exp x + eval_exp y
| Minus (x, y) -> eval_exp x - eval_exp y
let rec eval (f : formula) : bool =
match f with
| True -> true
| False -> false
| Not a -> not (eval a)
| AndAlso (x, y) -> eval x && eval y
| OrElse (x, y) -> eval x || eval y
| Imply (x, y) -> if eval x = false || eval y = true then true else false
| Equal (x, y) -> if eval_exp x = eval_exp y then true else false
|
|
599d487d34d726a20e734bdc70d6604109686eb756aad618699054455c6e35ed | slyrus/abcl | gentemp.lisp | ;;; gentemp.lisp
;;;
Copyright ( C ) 2003 - 2005
$ Id$
;;;
;;; This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
of the License , or ( at your option ) any later version .
;;;
;;; This program is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
;;; along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
;;;
;;; As a special exception, the copyright holders of this library give you
;;; permission to link this library with independent modules to produce an
;;; executable, regardless of the license terms of these independent
;;; modules, and to copy and distribute the resulting executable under
;;; terms of your choice, provided that you also meet, for each linked
;;; independent module, the terms and conditions of the license of that
;;; module. An independent module is a module which is not derived from
;;; or based on this library. If you modify this library, you may extend
;;; this exception to your version of the library, but you are not
;;; obligated to do so. If you do not wish to do so, delete this
;;; exception statement from your version.
Adapted from CMUCL .
(in-package #:system)
(defvar *gentemp-counter* 0)
(defun gentemp (&optional (prefix "T") (package *package*))
(require-type prefix 'string)
(require-type package '(or package string symbol character))
(loop
(let ((name (format nil "~A~D" prefix (incf *gentemp-counter*))))
(multiple-value-bind (symbol exists-p) (find-symbol name package)
(unless exists-p
(return (values (intern name package))))))))
| null | https://raw.githubusercontent.com/slyrus/abcl/881f733fdbf4b722865318a7d2abe2ff8fdad96e/src/org/armedbear/lisp/gentemp.lisp | lisp | gentemp.lisp
This program is free software; you can redistribute it and/or
either version 2
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. | Copyright ( C ) 2003 - 2005
$ Id$
modify it under the terms of the GNU General Public License
of the License , or ( at your option ) any later version .
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
Adapted from CMUCL .
(in-package #:system)
(defvar *gentemp-counter* 0)
(defun gentemp (&optional (prefix "T") (package *package*))
(require-type prefix 'string)
(require-type package '(or package string symbol character))
(loop
(let ((name (format nil "~A~D" prefix (incf *gentemp-counter*))))
(multiple-value-bind (symbol exists-p) (find-symbol name package)
(unless exists-p
(return (values (intern name package))))))))
|
dbd41d5d98e3463d0fa9064dcb1c3464af54ae1953760919eb47e91a1d5cc254 | atlas-engineer/nyxt | mode.lisp | SPDX - FileCopyrightText : Atlas Engineer LLC
SPDX - License - Identifier : BSD-3 - Clause
(in-package :nyxt)
(defclass mode-class (user-class)
((toggler-command-p ; TODO: Rename to `togglable-p'?
:initform (list t)
:initarg :toggler-command-p
:type (cons boolean null)
:documentation "Whether to define a toggler command for the defined mode.")))
(export-always 'mode-class)
(defmethod closer-mop:validate-superclass ((class mode-class)
(superclass user-class))
t)
(defun define-or-undefine-command-for-mode (class)
(let ((name (class-name class)))
FIXME : SBCL ` slot - value ' returns a list , while CCL returns the boolean . Why ?
(if (alex:ensure-car (slot-value class 'toggler-command-p))
(sera:lret ((command (make-command
name
`(lambda (&rest args
&key (buffer (or (current-prompt-buffer) (current-buffer)))
(activate t explicit?)
&allow-other-keys)
,(let ((*print-case* :downcase))
(format nil "Toggle `~a'." name))
(declare (ignorable buffer activate explicit?))
(apply #'toggle-mode ',name args))
:global)))
(setf (fdefinition name) command))
(delete-command name))))
(defmethod initialize-instance :after ((class mode-class) &key)
(define-or-undefine-command-for-mode class))
(defmethod reinitialize-instance :after ((class mode-class) &key)
(define-or-undefine-command-for-mode class))
(define-class mode ()
((buffer
nil
:type (maybe null buffer))
(glyph
nil
:type (maybe string)
:accessor nil
:documentation "A glyph used to represent this mode.")
(visible-in-status-p
t
:documentation "Whether the mode is visible in the status line.")
(rememberable-p
t
:documentation "Whether this mode is visible to auto-rules.")
(enabled-p
nil
:accessor t
:documentation "Whether the mode is enabled in `buffer'.")
(enable-hook
(make-instance 'hook-mode)
:type hook-mode
:documentation "Hook run when enabling the mode, after the constructor.
The handlers take the mode as argument.")
(disable-hook
(make-instance 'hook-mode)
:type hook-mode
:documentation "Hook run when disabling the mode, before the destructor.
The handlers take the mode as argument.")
(keyscheme-map
(make-hash-table :size 0)
:type keymaps:keyscheme-map))
(:export-class-name-p t)
(:export-accessor-names-p t)
(:export-predicate-name-p t)
(:accessor-name-transformer (class*:make-name-transformer name))
(:toggler-command-p nil)
(:metaclass mode-class))
(defmethod initialize-instance :after ((mode mode) &key)
(when (eq 'mode (sera:class-name-of mode))
(error "Cannot initialize `mode', you must subclass it.")))
(defmethod name ((mode mode))
(sera:class-name-of mode))
(export-always 'enable)
(defgeneric enable (mode &key &allow-other-keys)
(:method-combination cascade)
(:method ((mode mode) &key &allow-other-keys)
mode)
(:documentation "Run when enabling a mode.
The pre-defined `:after' method handles further setup.
This method is meant to be specialized for every mode.
It is not meant to be called directly, see `enable-modes*' instead.
All the parent modes' `enable' methods run after the exact mode one, cascading
upwards to allow a more useful mode inheritance without duplicating the
functionality. A `cascade' method combination is used for that.
See also `disable'."))
(defmethod enable :before ((mode mode) &rest keys &key &allow-other-keys)
;; Using class-direct-slots here because `enable' will cascade to parent modes anyway.
;; FIXME: An easier way to initialize slots given initargs?
(loop with slot-defs = (closer-mop:class-direct-slots (class-of mode))
for (key value) on keys by #'cddr
do (alex:when-let ((slot-name (loop for slot-def in slot-defs
when (member key (c2mop:slot-definition-initargs slot-def))
do (return (c2cl:slot-definition-name slot-def)))))
;; TODO: Maybe use writer methods, if present? It implies a risk of
;; runtime actions on not-yet-fully-initialized mode instances
;; (because enable is a kind of initialization too).
(setf (slot-value mode slot-name) value))))
(defmethod enable :around ((mode mode) &key &allow-other-keys)
(let* ((buffer (buffer mode))
(existing-instance (find (sera:class-name-of mode)
(remove-if (sera:eqs mode) (slot-value buffer 'modes))
:key #'sera:class-name-of)))
(if existing-instance
(log:debug "Not enabling ~s since other ~s instance is already in buffer ~a" mode existing-instance buffer)
(call-next-method))
mode))
(defmethod enable :after ((mode mode) &key &allow-other-keys)
(setf (enabled-p mode) t)
(hooks:run-hook (enable-hook mode) mode)
(let ((buffer (buffer mode)))
;; TODO: Should we move mode to the front on re-enable?
(unless (find mode (slot-value buffer 'modes))
(setf (modes buffer)
(cons mode (slot-value buffer 'modes))))
(hooks:run-hook (enable-mode-hook buffer) mode)
(when (and (prompt-buffer-p buffer)
(eq (first (active-prompt-buffers (window buffer)))
buffer))
(prompt-render-prompt buffer))))
(export-always 'disable)
(defgeneric disable (mode &key &allow-other-keys)
(:method-combination cascade)
(:method ((mode mode) &key)
nil)
(:documentation "Run when disabling a mode.
The pre-defined `:after' method handles further cleanup.
This method is meant to be specialized for every mode.
It is not meant to be called directly, see `disable-modes' instead.
All the parent modes' `disable' methods run after the exact mode one, cascading
upwards to allow a more useful mode inheritance without duplicating the
functionality. A `cascade' method combination is used for that.
See also `enable'."))
(defmethod disable :around ((mode mode) &key &allow-other-keys)
(if (enabled-p mode)
(call-next-method)
(echo-warning "~a is not enabled, cannot disable it." mode)))
(defmethod disable :after ((mode mode) &key &allow-other-keys)
(setf (enabled-p mode) nil)
(hooks:run-hook (disable-hook mode) mode)
(let ((buffer (buffer mode)))
(hooks:run-hook (disable-mode-hook (buffer mode)) mode)
;; TODO: Remove from list or not?
( setf ( modes buffer ) ( delete , existing - instance ( modes buffer ) ) )
(when (and (prompt-buffer-p buffer)
(eq (first (active-prompt-buffers (window buffer)))
buffer))
(prompt-render-prompt buffer))))
(export-always 'define-mode)
(defmacro define-mode (name direct-superclasses &body body)
"Shorthand to define a mode. It has the same syntax as `define-class' but
optionally accepts a docstring after the superclass declaration.
The `mode' superclass is automatically added if not present."
(let* ((docstring (when (stringp (first body))
(first body)))
(body (if docstring
(rest body)
body))
(direct-slots (first body))
(options (rest body)))
`(sera:eval-always ; Important so that classes can be found from the same file at compile-time.
(define-class ,name (,@(append direct-superclasses
(unless (find 'mode direct-superclasses) '(mode))))
,direct-slots
,@(append options
(when docstring
`((:documentation ,docstring)))
`((:export-class-name-p t)
(:export-accessor-names-p t)
(:export-predicate-name-p t)
(:accessor-name-transformer (class*:make-name-transformer name))
(:metaclass mode-class)))))))
(hooks:define-hook-type mode (function (mode)))
(export-always 'glyph)
(defmethod glyph ((mode mode))
"Return the glyph for a mode.
When unset, it corresponds to the mode name."
(or (slot-value mode 'glyph)
(princ-to-string mode)))
(defmethod (setf glyph) (glyph (mode mode))
(setf (slot-value mode 'glyph) glyph))
(defmethod print-object ((mode mode) stream)
(if *print-escape*
(print-unreadable-object (mode stream :type t :identity t))
(let ((name (symbol-name (sera:class-name-of mode)))
(suffix "-MODE"))
(format stream "~(~a~)" (sera:string-replace
suffix name ""
:start (- (length name ) (length suffix)))))))
(sym:define-symbol-type mode (class)
(alex:when-let ((class (find-class sym:%symbol% nil)))
(mopu:subclassp class (find-class 'mode))))
(defun mode-class (symbol)
(when (sym:mode-symbol-p symbol)
(find-class symbol)))
(defun resolve-user-symbol (designator type &optional (packages (append (nyxt-packages)
(nyxt-user-packages)
(nyxt-extension-packages))))
"`nsymbols:resolve-symbol' wrapper, only resolving strings, keywords, and NYXT-USER symbols.
Useful for user configuration smarts, returns unaltered DESIGNATOR otherwise."
(etypecase designator
(string (sym:resolve-symbol designator type packages))
(keyword (sym:resolve-symbol designator type packages))
(symbol (if (eq (symbol-package designator) (find-package :nyxt-user))
(sym:resolve-symbol designator type packages)
designator))))
NOTE : We define it here so that it 's available in spinneret-tags.lisp .
(export-always 'resolve-backtick-quote-links)
(defun resolve-backtick-quote-links (string parent-package)
"Return the STRING documentation with symbols surrounded by the (` ') pair
turned into <a> links to their respective description page."
(labels ((resolve-as (symbol type)
(sym:resolve-symbol symbol type (list :nyxt :nyxt-user parent-package)))
(resolve-regex (target-string start end match-start match-end reg-starts reg-ends)
(declare (ignore start end reg-starts reg-ends))
Excluding backtick & quote .
(let* ((name (subseq target-string (1+ match-start) (1- match-end)))
(symbol (ignore-errors (uiop:safe-read-from-string
name :package parent-package :eof-error-p nil)))
(function (and symbol
(fboundp symbol)
(resolve-as symbol :function)))
(variable (when symbol
(resolve-as symbol :variable)))
(class (when symbol
(resolve-as symbol :class)))
;; TODO: No way to determine the class reliably based on the slot name?
;; (slot (resolve-symbol name :slot (list :nyxt :nyxt-user *package*)))
(url (cond
((and variable (not function) (not class))
(nyxt-url 'describe-variable :variable variable))
((and class (not function) (not variable))
(nyxt-url 'describe-class :class class))
((and function (not class) (not variable))
(nyxt-url 'describe-function :fn function))
(symbol
(nyxt-url 'describe-any :input symbol))
(t nil))))
(let ((*print-pretty* nil))
;; Disable pretty-printing to avoid spurious space insertion within links:
;; #issuecomment-884740046
(spinneret:with-html-string
(if url
(:a :href url (:code name))
(:code name)))))))
(if (not (uiop:emptyp string))
;; FIXME: Spaces are disallowed, but |one can use anything in a symbol|.
;; Maybe allow it? The problem then is that it increases the chances of
;; false-positives when the "`" character is used for other reasons.
(ppcre:regex-replace-all "`[^'\\s]+'" string #'resolve-regex)
"")))
(-> find-submode (sym:mode-symbol &optional buffer) (maybe mode))
(export-always 'find-submode)
(defun find-submode (mode-symbol &optional (buffer (current-buffer)))
"Return the first submode instance of MODE-SYMBOL in BUFFER.
As a second value, return all matching submode instances.
Return nil if mode is not found."
(when (modable-buffer-p buffer)
(alex:if-let ((class (mode-class mode-symbol)))
(let ((results (sera:filter
(rcurry #'closer-mop:subclassp class)
(modes buffer)
:key #'class-of)))
(when (< 1 (length results))
;; TODO: What's the best action on multiple mode match?
(log:debug "Found multiple matching modes: ~a" results))
(values (first results)
results))
CCL catches the error at compile time but not all implementations do ,
;; hence the redundant error report here.
(error "Mode ~a does not exist" mode-symbol))))
(-> current-mode ((or keyword string) &optional buffer) (maybe mode))
(export-always 'current-mode)
(defun current-mode (mode-designator &optional (buffer (current-buffer)))
"Return mode instance of MODE-DESIGNATOR in BUFFER.
Return NIL if none.
The \"-mode\" suffix is automatically appended to MODE-KEYWORD if missing.
This is convenience function for interactive use.
For production code, see `find-submode' instead."
(let ((mode-designator (sera:ensure-suffix (string mode-designator) "-MODE")))
(find-submode (resolve-user-symbol mode-designator :mode)
buffer)))
(defun all-mode-symbols ()
"Return the list of mode symbols."
(mapcar #'class-name (mopu:subclasses 'mode)))
(defun make-mode-suggestion (mode &optional source input)
"Return a `suggestion' wrapping around MODE. "
(declare (ignore source input))
(make-instance 'prompter:suggestion
:value mode
:attributes `(("Mode" ,(string-downcase (symbol-name mode)))
("Documentation" ,(or (first (sera:lines (documentation mode 'type)))
""))
("Package" ,(string-downcase (package-name (symbol-package mode)))))))
(define-class mode-source (prompter:source)
((prompter:name "Modes")
(prompter:enable-marks-p t)
(prompter:constructor (sort (all-mode-symbols) #'string< :key #'symbol-name))
(prompter:suggestion-maker 'make-mode-suggestion))
(:export-class-name-p t)
(:metaclass user-class))
(defmethod prompter:object-attributes ((mode mode) (source prompter:source))
(declare (ignore source))
`(("Name" ,mode)))
(define-class active-mode-source (mode-source)
((prompter:name "Active modes")
(buffers '())
(prompter:enable-marks-p t)
(prompter:constructor (lambda (source)
(delete-duplicates
(mapcar
#'name
(mappend
#'modes
(uiop:ensure-list (buffers source))))))))
(:export-class-name-p t)
(:export-accessor-names-p t)
(:accessor-name-transformer (class*:make-name-transformer name))
(:metaclass user-class))
(define-class inactive-mode-source (mode-source)
((prompter:name "Inactive modes")
(buffers '())
(prompter:enable-marks-p t)
(prompter:constructor (lambda (source)
(let ((common-modes
(reduce #'intersection
(mappend (compose #'name #'modes)
(uiop:ensure-list (buffers source))))))
(set-difference (all-mode-symbols) common-modes)))))
(:export-class-name-p t)
(:export-accessor-names-p t)
(:accessor-name-transformer (class*:make-name-transformer name))
(:metaclass user-class))
(export-always 'enable-modes*)
(defgeneric enable-modes* (modes buffers &rest args &key remember-p &allow-other-keys)
;; FIXME: Better type dispatching? The types used to be:
( - > enable - modes * ( ( or sym : mode - symbol ( list - of sym : mode - symbol ) )
;; (or buffer (list-of buffer))
;; &key &allow-other-keys) *)
(:method (modes buffers &rest args &key &allow-other-keys)
(let ((modes (uiop:ensure-list modes))
(buffers (uiop:ensure-list buffers)))
(dolist (mode modes)
(check-type mode sym:mode-symbol))
(dolist (buffer buffers)
(check-type buffer buffer))
(mapcar (lambda (buffer)
(mapcar (lambda (mode-sym)
(apply #'enable (or (find mode-sym (slot-value buffer 'modes) :key #'name)
(make-instance mode-sym :buffer buffer))
args))
modes)
buffer)
(sera:filter #'modable-buffer-p buffers))))
(:documentation "Enable MODES in BUFFERS.
ARGS are the keyword arguments for `make-instance' on MODES.
If REMEMBER-P is true, save active modes so that auto-rules don't override those."))
(define-command enable-modes (&key
(modes nil explicit-modes-p)
(buffers (current-buffer) explicit-buffers-p))
"Enable MODES for BUFFERS prompting for either or both.
MODES should be a list of mode symbols or a mode symbol.
BUFFERS and MODES are automatically coerced into a list.
If BUFFERS is a list, return it.
If it's a single buffer, return it directly (not as a list)."
;; We allow NIL values for MODES and BUFFERS in case they are forms, in which
;; case it's handy that this function does not error, it simply does nothing.
;; REVIEW: But we wrap commands into `with-protect' for this, don't we?
(let* ((buffers (or buffers
(unless explicit-buffers-p
(prompt
:prompt "Enable mode(s) for buffer(s)"
:sources (make-instance 'buffer-source
:enable-marks-p t
:actions-on-return '())))))
(modes (or modes
(unless explicit-modes-p
(prompt
:prompt "Enable mode(s)"
:sources (make-instance 'inactive-mode-source
:buffers buffers))))))
(enable-modes* modes buffers)
(remember-on-mode-toggle modes buffers :enabled-p t))
buffers)
(export-always 'disable-modes*)
(defgeneric disable-modes* (modes buffers &rest args &key remember-p &allow-other-keys)
;; FIXME: Better type dispatching?
(:method (modes buffers &rest args &key &allow-other-keys)
(declare (ignorable args))
(let ((modes (uiop:ensure-list modes))
(buffers (uiop:ensure-list buffers)))
(dolist (mode modes)
(check-type mode sym:mode-symbol))
(dolist (buffer buffers)
(check-type buffer buffer))
(mapcar (lambda (buffer)
(mapcar #'disable
(delete nil (mapcar (lambda (mode) (find mode (modes buffer) :key #'name))
modes))))
buffers)))
(:documentation "Disable MODES in BUFFERS.
If REMEMBER-P is true, save active modes so that auto-rules don't override those."))
(define-command disable-modes (&key (modes nil explicit-modes-p)
(buffers (current-buffer) explicit-buffers-p))
"Disable MODES for BUFFERS.
MODES should be a list of mode symbols.
BUFFERS and MODES are automatically coerced into a list.
If BUFFERS is a list, return it.
If it's a single buffer, return it directly (not as a list)."
(let* ((buffers (or buffers
(unless explicit-buffers-p
(prompt
:prompt "Enable mode(s) for buffer(s)"
:sources (make-instance 'buffer-source
:enable-marks-p t
:actions-on-return '())))))
(modes (or modes
(unless explicit-modes-p
(prompt
:prompt "Disable mode(s)"
:sources (make-instance 'active-mode-source
:buffers buffers))))))
(disable-modes* modes buffers)
(remember-on-mode-toggle modes buffers :enabled-p nil))
buffers)
(define-command toggle-modes (&key (buffer (current-buffer)))
"Enable marked modes, disable unmarked modes for BUFFER."
(let* ((modes-to-enable
(prompt
:prompt "Mark modes to enable, unmark to disable"
:sources (make-instance
'mode-source
:marks (mapcar #'sera:class-name-of (modes buffer)))))
(modes-to-disable (set-difference (all-mode-symbols) modes-to-enable
:test #'string=)))
(disable-modes* modes-to-disable buffer)
(remember-on-mode-toggle modes-to-disable buffer :enabled-p nil)
(enable-modes* modes-to-enable buffer)
(remember-on-mode-toggle modes-to-enable buffer :enabled-p t))
buffer)
;; TODO: Factor `toggle-mode' and `toggle-modes' somehow?
;; TODO: Shall we have a function that returns the focused buffer?
;; `focused-buffer'? `current-buffer*'? Rename `current-buffer' to
;; `current-view-buffer' and add `current-buffer' for this task?
(defun toggle-mode (mode-sym
&rest args
&key (buffer (or (current-prompt-buffer) (current-buffer)))
(activate t explicit?)
&allow-other-keys)
"Enable MODE-SYM if not already enabled, disable it otherwise."
(when (modable-buffer-p buffer)
(let ((existing-instance (find mode-sym (slot-value buffer 'modes) :key #'sera:class-name-of)))
(unless explicit?
(setf activate (or (not existing-instance)
(not (enabled-p existing-instance)))))
(if activate
;; TODO: Shall we pass args to `make-instance' or `enable'?
Have 2 args parameters ?
(let ((mode (or existing-instance
(apply #'make-instance mode-sym
:buffer buffer
args))))
(enable mode)
(echo "~@(~a~) mode enabled." mode))
(when existing-instance
(disable existing-instance)
(echo "~@(~a~) mode disabled." existing-instance)))
(remember-on-mode-toggle mode-sym buffer :enabled-p activate))))
(define-command-global reload-with-modes (&optional (buffer (current-buffer)))
"Reload the BUFFER with the queried modes.
This bypasses auto-rules.
Auto-rules are re-applied once the page is reloaded once again."
(let* ((modes-to-enable (prompt
:prompt "Mark modes to enable, unmark to disable"
:sources (make-instance 'mode-source
:marks (mapcar #'sera:class-name-of (modes (current-buffer))))))
(modes-to-disable (set-difference (all-mode-symbols) modes-to-enable
:test #'string=)))
(hooks:once-on (request-resource-hook buffer)
(request-data)
(when modes-to-enable
(disable-modes* modes-to-disable buffer))
(when modes-to-disable
(enable-modes* modes-to-enable buffer))
request-data)
(reload-buffer buffer)))
(export-always 'find-buffer)
(defun find-buffer (mode-symbol)
"Return first buffer matching MODE-SYMBOL."
(find-if (lambda (b)
(find-submode mode-symbol b))
(buffer-list)))
(export-always 'keymap)
(defmethod keymap ((mode mode))
"Return the keymap of MODE according to its buffer `keyscheme-map'.
If there is no corresponding keymap, return nil."
(keymaps:get-keymap (if (buffer mode)
(keyscheme (buffer mode))
keyscheme:cua)
(keyscheme-map mode)))
(defmethod on-signal-notify-uri ((mode mode) url)
url)
(defmethod on-signal-notify-title ((mode mode) title)
(on-signal-notify-uri mode (url (buffer mode)))
title)
(defmethod on-signal-load-started ((mode mode) url)
url)
(defmethod on-signal-load-redirected ((mode mode) url)
url)
(defmethod on-signal-load-canceled ((mode mode) url)
url)
(defmethod on-signal-load-committed ((mode mode) url)
url)
(defmethod on-signal-load-finished ((mode mode) url)
url)
(defmethod on-signal-load-failed ((mode mode) url)
url)
(defmethod on-signal-button-press ((mode mode) button-key)
(declare (ignorable button-key))
nil)
(defmethod on-signal-key-press ((mode mode) key)
(declare (ignorable key))
nil)
(defmethod url-sources ((mode mode) actions-on-return)
(declare (ignore actions-on-return))
nil)
(defmethod url-sources :around ((mode mode) actions-on-return)
(declare (ignore actions-on-return))
(alex:ensure-list (call-next-method)))
(defmethod s-serialization:serializable-slots ((object mode))
"Discard keymaps which can be quite verbose."
(delete 'keyscheme-map
(mapcar #'closer-mop:slot-definition-name
(closer-mop:class-slots (class-of object)))))
| null | https://raw.githubusercontent.com/atlas-engineer/nyxt/fa3b0e7f977427ff2e2dabb1fab1cff15e2e5ad1/source/mode.lisp | lisp | TODO: Rename to `togglable-p'?
Using class-direct-slots here because `enable' will cascade to parent modes anyway.
FIXME: An easier way to initialize slots given initargs?
TODO: Maybe use writer methods, if present? It implies a risk of
runtime actions on not-yet-fully-initialized mode instances
(because enable is a kind of initialization too).
TODO: Should we move mode to the front on re-enable?
TODO: Remove from list or not?
Important so that classes can be found from the same file at compile-time.
TODO: No way to determine the class reliably based on the slot name?
(slot (resolve-symbol name :slot (list :nyxt :nyxt-user *package*)))
Disable pretty-printing to avoid spurious space insertion within links:
#issuecomment-884740046
FIXME: Spaces are disallowed, but |one can use anything in a symbol|.
Maybe allow it? The problem then is that it increases the chances of
false-positives when the "`" character is used for other reasons.
TODO: What's the best action on multiple mode match?
hence the redundant error report here.
FIXME: Better type dispatching? The types used to be:
(or buffer (list-of buffer))
&key &allow-other-keys) *)
We allow NIL values for MODES and BUFFERS in case they are forms, in which
case it's handy that this function does not error, it simply does nothing.
REVIEW: But we wrap commands into `with-protect' for this, don't we?
FIXME: Better type dispatching?
TODO: Factor `toggle-mode' and `toggle-modes' somehow?
TODO: Shall we have a function that returns the focused buffer?
`focused-buffer'? `current-buffer*'? Rename `current-buffer' to
`current-view-buffer' and add `current-buffer' for this task?
TODO: Shall we pass args to `make-instance' or `enable'? | SPDX - FileCopyrightText : Atlas Engineer LLC
SPDX - License - Identifier : BSD-3 - Clause
(in-package :nyxt)
(defclass mode-class (user-class)
:initform (list t)
:initarg :toggler-command-p
:type (cons boolean null)
:documentation "Whether to define a toggler command for the defined mode.")))
(export-always 'mode-class)
(defmethod closer-mop:validate-superclass ((class mode-class)
(superclass user-class))
t)
(defun define-or-undefine-command-for-mode (class)
(let ((name (class-name class)))
FIXME : SBCL ` slot - value ' returns a list , while CCL returns the boolean . Why ?
(if (alex:ensure-car (slot-value class 'toggler-command-p))
(sera:lret ((command (make-command
name
`(lambda (&rest args
&key (buffer (or (current-prompt-buffer) (current-buffer)))
(activate t explicit?)
&allow-other-keys)
,(let ((*print-case* :downcase))
(format nil "Toggle `~a'." name))
(declare (ignorable buffer activate explicit?))
(apply #'toggle-mode ',name args))
:global)))
(setf (fdefinition name) command))
(delete-command name))))
(defmethod initialize-instance :after ((class mode-class) &key)
(define-or-undefine-command-for-mode class))
(defmethod reinitialize-instance :after ((class mode-class) &key)
(define-or-undefine-command-for-mode class))
(define-class mode ()
((buffer
nil
:type (maybe null buffer))
(glyph
nil
:type (maybe string)
:accessor nil
:documentation "A glyph used to represent this mode.")
(visible-in-status-p
t
:documentation "Whether the mode is visible in the status line.")
(rememberable-p
t
:documentation "Whether this mode is visible to auto-rules.")
(enabled-p
nil
:accessor t
:documentation "Whether the mode is enabled in `buffer'.")
(enable-hook
(make-instance 'hook-mode)
:type hook-mode
:documentation "Hook run when enabling the mode, after the constructor.
The handlers take the mode as argument.")
(disable-hook
(make-instance 'hook-mode)
:type hook-mode
:documentation "Hook run when disabling the mode, before the destructor.
The handlers take the mode as argument.")
(keyscheme-map
(make-hash-table :size 0)
:type keymaps:keyscheme-map))
(:export-class-name-p t)
(:export-accessor-names-p t)
(:export-predicate-name-p t)
(:accessor-name-transformer (class*:make-name-transformer name))
(:toggler-command-p nil)
(:metaclass mode-class))
(defmethod initialize-instance :after ((mode mode) &key)
(when (eq 'mode (sera:class-name-of mode))
(error "Cannot initialize `mode', you must subclass it.")))
(defmethod name ((mode mode))
(sera:class-name-of mode))
(export-always 'enable)
(defgeneric enable (mode &key &allow-other-keys)
(:method-combination cascade)
(:method ((mode mode) &key &allow-other-keys)
mode)
(:documentation "Run when enabling a mode.
The pre-defined `:after' method handles further setup.
This method is meant to be specialized for every mode.
It is not meant to be called directly, see `enable-modes*' instead.
All the parent modes' `enable' methods run after the exact mode one, cascading
upwards to allow a more useful mode inheritance without duplicating the
functionality. A `cascade' method combination is used for that.
See also `disable'."))
(defmethod enable :before ((mode mode) &rest keys &key &allow-other-keys)
(loop with slot-defs = (closer-mop:class-direct-slots (class-of mode))
for (key value) on keys by #'cddr
do (alex:when-let ((slot-name (loop for slot-def in slot-defs
when (member key (c2mop:slot-definition-initargs slot-def))
do (return (c2cl:slot-definition-name slot-def)))))
(setf (slot-value mode slot-name) value))))
(defmethod enable :around ((mode mode) &key &allow-other-keys)
(let* ((buffer (buffer mode))
(existing-instance (find (sera:class-name-of mode)
(remove-if (sera:eqs mode) (slot-value buffer 'modes))
:key #'sera:class-name-of)))
(if existing-instance
(log:debug "Not enabling ~s since other ~s instance is already in buffer ~a" mode existing-instance buffer)
(call-next-method))
mode))
(defmethod enable :after ((mode mode) &key &allow-other-keys)
(setf (enabled-p mode) t)
(hooks:run-hook (enable-hook mode) mode)
(let ((buffer (buffer mode)))
(unless (find mode (slot-value buffer 'modes))
(setf (modes buffer)
(cons mode (slot-value buffer 'modes))))
(hooks:run-hook (enable-mode-hook buffer) mode)
(when (and (prompt-buffer-p buffer)
(eq (first (active-prompt-buffers (window buffer)))
buffer))
(prompt-render-prompt buffer))))
(export-always 'disable)
(defgeneric disable (mode &key &allow-other-keys)
(:method-combination cascade)
(:method ((mode mode) &key)
nil)
(:documentation "Run when disabling a mode.
The pre-defined `:after' method handles further cleanup.
This method is meant to be specialized for every mode.
It is not meant to be called directly, see `disable-modes' instead.
All the parent modes' `disable' methods run after the exact mode one, cascading
upwards to allow a more useful mode inheritance without duplicating the
functionality. A `cascade' method combination is used for that.
See also `enable'."))
(defmethod disable :around ((mode mode) &key &allow-other-keys)
(if (enabled-p mode)
(call-next-method)
(echo-warning "~a is not enabled, cannot disable it." mode)))
(defmethod disable :after ((mode mode) &key &allow-other-keys)
(setf (enabled-p mode) nil)
(hooks:run-hook (disable-hook mode) mode)
(let ((buffer (buffer mode)))
(hooks:run-hook (disable-mode-hook (buffer mode)) mode)
( setf ( modes buffer ) ( delete , existing - instance ( modes buffer ) ) )
(when (and (prompt-buffer-p buffer)
(eq (first (active-prompt-buffers (window buffer)))
buffer))
(prompt-render-prompt buffer))))
(export-always 'define-mode)
(defmacro define-mode (name direct-superclasses &body body)
"Shorthand to define a mode. It has the same syntax as `define-class' but
optionally accepts a docstring after the superclass declaration.
The `mode' superclass is automatically added if not present."
(let* ((docstring (when (stringp (first body))
(first body)))
(body (if docstring
(rest body)
body))
(direct-slots (first body))
(options (rest body)))
(define-class ,name (,@(append direct-superclasses
(unless (find 'mode direct-superclasses) '(mode))))
,direct-slots
,@(append options
(when docstring
`((:documentation ,docstring)))
`((:export-class-name-p t)
(:export-accessor-names-p t)
(:export-predicate-name-p t)
(:accessor-name-transformer (class*:make-name-transformer name))
(:metaclass mode-class)))))))
(hooks:define-hook-type mode (function (mode)))
(export-always 'glyph)
(defmethod glyph ((mode mode))
"Return the glyph for a mode.
When unset, it corresponds to the mode name."
(or (slot-value mode 'glyph)
(princ-to-string mode)))
(defmethod (setf glyph) (glyph (mode mode))
(setf (slot-value mode 'glyph) glyph))
(defmethod print-object ((mode mode) stream)
(if *print-escape*
(print-unreadable-object (mode stream :type t :identity t))
(let ((name (symbol-name (sera:class-name-of mode)))
(suffix "-MODE"))
(format stream "~(~a~)" (sera:string-replace
suffix name ""
:start (- (length name ) (length suffix)))))))
(sym:define-symbol-type mode (class)
(alex:when-let ((class (find-class sym:%symbol% nil)))
(mopu:subclassp class (find-class 'mode))))
(defun mode-class (symbol)
(when (sym:mode-symbol-p symbol)
(find-class symbol)))
(defun resolve-user-symbol (designator type &optional (packages (append (nyxt-packages)
(nyxt-user-packages)
(nyxt-extension-packages))))
"`nsymbols:resolve-symbol' wrapper, only resolving strings, keywords, and NYXT-USER symbols.
Useful for user configuration smarts, returns unaltered DESIGNATOR otherwise."
(etypecase designator
(string (sym:resolve-symbol designator type packages))
(keyword (sym:resolve-symbol designator type packages))
(symbol (if (eq (symbol-package designator) (find-package :nyxt-user))
(sym:resolve-symbol designator type packages)
designator))))
NOTE : We define it here so that it 's available in spinneret-tags.lisp .
(export-always 'resolve-backtick-quote-links)
(defun resolve-backtick-quote-links (string parent-package)
"Return the STRING documentation with symbols surrounded by the (` ') pair
turned into <a> links to their respective description page."
(labels ((resolve-as (symbol type)
(sym:resolve-symbol symbol type (list :nyxt :nyxt-user parent-package)))
(resolve-regex (target-string start end match-start match-end reg-starts reg-ends)
(declare (ignore start end reg-starts reg-ends))
Excluding backtick & quote .
(let* ((name (subseq target-string (1+ match-start) (1- match-end)))
(symbol (ignore-errors (uiop:safe-read-from-string
name :package parent-package :eof-error-p nil)))
(function (and symbol
(fboundp symbol)
(resolve-as symbol :function)))
(variable (when symbol
(resolve-as symbol :variable)))
(class (when symbol
(resolve-as symbol :class)))
(url (cond
((and variable (not function) (not class))
(nyxt-url 'describe-variable :variable variable))
((and class (not function) (not variable))
(nyxt-url 'describe-class :class class))
((and function (not class) (not variable))
(nyxt-url 'describe-function :fn function))
(symbol
(nyxt-url 'describe-any :input symbol))
(t nil))))
(let ((*print-pretty* nil))
(spinneret:with-html-string
(if url
(:a :href url (:code name))
(:code name)))))))
(if (not (uiop:emptyp string))
(ppcre:regex-replace-all "`[^'\\s]+'" string #'resolve-regex)
"")))
(-> find-submode (sym:mode-symbol &optional buffer) (maybe mode))
(export-always 'find-submode)
(defun find-submode (mode-symbol &optional (buffer (current-buffer)))
"Return the first submode instance of MODE-SYMBOL in BUFFER.
As a second value, return all matching submode instances.
Return nil if mode is not found."
(when (modable-buffer-p buffer)
(alex:if-let ((class (mode-class mode-symbol)))
(let ((results (sera:filter
(rcurry #'closer-mop:subclassp class)
(modes buffer)
:key #'class-of)))
(when (< 1 (length results))
(log:debug "Found multiple matching modes: ~a" results))
(values (first results)
results))
CCL catches the error at compile time but not all implementations do ,
(error "Mode ~a does not exist" mode-symbol))))
(-> current-mode ((or keyword string) &optional buffer) (maybe mode))
(export-always 'current-mode)
(defun current-mode (mode-designator &optional (buffer (current-buffer)))
"Return mode instance of MODE-DESIGNATOR in BUFFER.
Return NIL if none.
The \"-mode\" suffix is automatically appended to MODE-KEYWORD if missing.
This is convenience function for interactive use.
For production code, see `find-submode' instead."
(let ((mode-designator (sera:ensure-suffix (string mode-designator) "-MODE")))
(find-submode (resolve-user-symbol mode-designator :mode)
buffer)))
(defun all-mode-symbols ()
"Return the list of mode symbols."
(mapcar #'class-name (mopu:subclasses 'mode)))
(defun make-mode-suggestion (mode &optional source input)
"Return a `suggestion' wrapping around MODE. "
(declare (ignore source input))
(make-instance 'prompter:suggestion
:value mode
:attributes `(("Mode" ,(string-downcase (symbol-name mode)))
("Documentation" ,(or (first (sera:lines (documentation mode 'type)))
""))
("Package" ,(string-downcase (package-name (symbol-package mode)))))))
(define-class mode-source (prompter:source)
((prompter:name "Modes")
(prompter:enable-marks-p t)
(prompter:constructor (sort (all-mode-symbols) #'string< :key #'symbol-name))
(prompter:suggestion-maker 'make-mode-suggestion))
(:export-class-name-p t)
(:metaclass user-class))
(defmethod prompter:object-attributes ((mode mode) (source prompter:source))
(declare (ignore source))
`(("Name" ,mode)))
(define-class active-mode-source (mode-source)
((prompter:name "Active modes")
(buffers '())
(prompter:enable-marks-p t)
(prompter:constructor (lambda (source)
(delete-duplicates
(mapcar
#'name
(mappend
#'modes
(uiop:ensure-list (buffers source))))))))
(:export-class-name-p t)
(:export-accessor-names-p t)
(:accessor-name-transformer (class*:make-name-transformer name))
(:metaclass user-class))
(define-class inactive-mode-source (mode-source)
((prompter:name "Inactive modes")
(buffers '())
(prompter:enable-marks-p t)
(prompter:constructor (lambda (source)
(let ((common-modes
(reduce #'intersection
(mappend (compose #'name #'modes)
(uiop:ensure-list (buffers source))))))
(set-difference (all-mode-symbols) common-modes)))))
(:export-class-name-p t)
(:export-accessor-names-p t)
(:accessor-name-transformer (class*:make-name-transformer name))
(:metaclass user-class))
(export-always 'enable-modes*)
(defgeneric enable-modes* (modes buffers &rest args &key remember-p &allow-other-keys)
( - > enable - modes * ( ( or sym : mode - symbol ( list - of sym : mode - symbol ) )
(:method (modes buffers &rest args &key &allow-other-keys)
(let ((modes (uiop:ensure-list modes))
(buffers (uiop:ensure-list buffers)))
(dolist (mode modes)
(check-type mode sym:mode-symbol))
(dolist (buffer buffers)
(check-type buffer buffer))
(mapcar (lambda (buffer)
(mapcar (lambda (mode-sym)
(apply #'enable (or (find mode-sym (slot-value buffer 'modes) :key #'name)
(make-instance mode-sym :buffer buffer))
args))
modes)
buffer)
(sera:filter #'modable-buffer-p buffers))))
(:documentation "Enable MODES in BUFFERS.
ARGS are the keyword arguments for `make-instance' on MODES.
If REMEMBER-P is true, save active modes so that auto-rules don't override those."))
(define-command enable-modes (&key
(modes nil explicit-modes-p)
(buffers (current-buffer) explicit-buffers-p))
"Enable MODES for BUFFERS prompting for either or both.
MODES should be a list of mode symbols or a mode symbol.
BUFFERS and MODES are automatically coerced into a list.
If BUFFERS is a list, return it.
If it's a single buffer, return it directly (not as a list)."
(let* ((buffers (or buffers
(unless explicit-buffers-p
(prompt
:prompt "Enable mode(s) for buffer(s)"
:sources (make-instance 'buffer-source
:enable-marks-p t
:actions-on-return '())))))
(modes (or modes
(unless explicit-modes-p
(prompt
:prompt "Enable mode(s)"
:sources (make-instance 'inactive-mode-source
:buffers buffers))))))
(enable-modes* modes buffers)
(remember-on-mode-toggle modes buffers :enabled-p t))
buffers)
(export-always 'disable-modes*)
(defgeneric disable-modes* (modes buffers &rest args &key remember-p &allow-other-keys)
(:method (modes buffers &rest args &key &allow-other-keys)
(declare (ignorable args))
(let ((modes (uiop:ensure-list modes))
(buffers (uiop:ensure-list buffers)))
(dolist (mode modes)
(check-type mode sym:mode-symbol))
(dolist (buffer buffers)
(check-type buffer buffer))
(mapcar (lambda (buffer)
(mapcar #'disable
(delete nil (mapcar (lambda (mode) (find mode (modes buffer) :key #'name))
modes))))
buffers)))
(:documentation "Disable MODES in BUFFERS.
If REMEMBER-P is true, save active modes so that auto-rules don't override those."))
(define-command disable-modes (&key (modes nil explicit-modes-p)
(buffers (current-buffer) explicit-buffers-p))
"Disable MODES for BUFFERS.
MODES should be a list of mode symbols.
BUFFERS and MODES are automatically coerced into a list.
If BUFFERS is a list, return it.
If it's a single buffer, return it directly (not as a list)."
(let* ((buffers (or buffers
(unless explicit-buffers-p
(prompt
:prompt "Enable mode(s) for buffer(s)"
:sources (make-instance 'buffer-source
:enable-marks-p t
:actions-on-return '())))))
(modes (or modes
(unless explicit-modes-p
(prompt
:prompt "Disable mode(s)"
:sources (make-instance 'active-mode-source
:buffers buffers))))))
(disable-modes* modes buffers)
(remember-on-mode-toggle modes buffers :enabled-p nil))
buffers)
(define-command toggle-modes (&key (buffer (current-buffer)))
"Enable marked modes, disable unmarked modes for BUFFER."
(let* ((modes-to-enable
(prompt
:prompt "Mark modes to enable, unmark to disable"
:sources (make-instance
'mode-source
:marks (mapcar #'sera:class-name-of (modes buffer)))))
(modes-to-disable (set-difference (all-mode-symbols) modes-to-enable
:test #'string=)))
(disable-modes* modes-to-disable buffer)
(remember-on-mode-toggle modes-to-disable buffer :enabled-p nil)
(enable-modes* modes-to-enable buffer)
(remember-on-mode-toggle modes-to-enable buffer :enabled-p t))
buffer)
(defun toggle-mode (mode-sym
&rest args
&key (buffer (or (current-prompt-buffer) (current-buffer)))
(activate t explicit?)
&allow-other-keys)
"Enable MODE-SYM if not already enabled, disable it otherwise."
(when (modable-buffer-p buffer)
(let ((existing-instance (find mode-sym (slot-value buffer 'modes) :key #'sera:class-name-of)))
(unless explicit?
(setf activate (or (not existing-instance)
(not (enabled-p existing-instance)))))
(if activate
Have 2 args parameters ?
(let ((mode (or existing-instance
(apply #'make-instance mode-sym
:buffer buffer
args))))
(enable mode)
(echo "~@(~a~) mode enabled." mode))
(when existing-instance
(disable existing-instance)
(echo "~@(~a~) mode disabled." existing-instance)))
(remember-on-mode-toggle mode-sym buffer :enabled-p activate))))
(define-command-global reload-with-modes (&optional (buffer (current-buffer)))
"Reload the BUFFER with the queried modes.
This bypasses auto-rules.
Auto-rules are re-applied once the page is reloaded once again."
(let* ((modes-to-enable (prompt
:prompt "Mark modes to enable, unmark to disable"
:sources (make-instance 'mode-source
:marks (mapcar #'sera:class-name-of (modes (current-buffer))))))
(modes-to-disable (set-difference (all-mode-symbols) modes-to-enable
:test #'string=)))
(hooks:once-on (request-resource-hook buffer)
(request-data)
(when modes-to-enable
(disable-modes* modes-to-disable buffer))
(when modes-to-disable
(enable-modes* modes-to-enable buffer))
request-data)
(reload-buffer buffer)))
(export-always 'find-buffer)
(defun find-buffer (mode-symbol)
"Return first buffer matching MODE-SYMBOL."
(find-if (lambda (b)
(find-submode mode-symbol b))
(buffer-list)))
(export-always 'keymap)
(defmethod keymap ((mode mode))
"Return the keymap of MODE according to its buffer `keyscheme-map'.
If there is no corresponding keymap, return nil."
(keymaps:get-keymap (if (buffer mode)
(keyscheme (buffer mode))
keyscheme:cua)
(keyscheme-map mode)))
(defmethod on-signal-notify-uri ((mode mode) url)
url)
(defmethod on-signal-notify-title ((mode mode) title)
(on-signal-notify-uri mode (url (buffer mode)))
title)
(defmethod on-signal-load-started ((mode mode) url)
url)
(defmethod on-signal-load-redirected ((mode mode) url)
url)
(defmethod on-signal-load-canceled ((mode mode) url)
url)
(defmethod on-signal-load-committed ((mode mode) url)
url)
(defmethod on-signal-load-finished ((mode mode) url)
url)
(defmethod on-signal-load-failed ((mode mode) url)
url)
(defmethod on-signal-button-press ((mode mode) button-key)
(declare (ignorable button-key))
nil)
(defmethod on-signal-key-press ((mode mode) key)
(declare (ignorable key))
nil)
(defmethod url-sources ((mode mode) actions-on-return)
(declare (ignore actions-on-return))
nil)
(defmethod url-sources :around ((mode mode) actions-on-return)
(declare (ignore actions-on-return))
(alex:ensure-list (call-next-method)))
(defmethod s-serialization:serializable-slots ((object mode))
"Discard keymaps which can be quite verbose."
(delete 'keyscheme-map
(mapcar #'closer-mop:slot-definition-name
(closer-mop:class-slots (class-of object)))))
|
aa4880dbe69eaf5fc4184d317f5ff60e62bba43f978f31a5107863c72536c79e | omcljs/om | tempid.cljc | (ns om.tempid
#?(:clj (:import [java.io Writer])))
;; =============================================================================
;; ClojureScript
#?(:cljs
(deftype TempId [^:mutable id ^:mutable __hash]
Object
(toString [this]
(pr-str this))
IEquiv
(-equiv [this other]
(and (instance? TempId other)
(= (. this -id) (. other -id))))
IHash
(-hash [this]
(when (nil? __hash)
(set! __hash (hash id)))
__hash)
IPrintWithWriter
(-pr-writer [_ writer _]
(write-all writer "#om/id[\"" id "\"]"))))
#?(:cljs
(defn tempid
([]
(tempid (random-uuid)))
([id]
(TempId. id nil))))
;; =============================================================================
Clojure
#?(:clj
(defrecord TempId [id]
Object
(toString [this]
(pr-str this))))
#?(:clj
(defmethod print-method TempId [^TempId x ^Writer writer]
(.write writer (str "#om/id[\"" (.id x) "\"]"))))
#?(:clj
(defn tempid
([]
(tempid (java.util.UUID/randomUUID)))
([uuid]
(TempId. uuid))))
(defn tempid?
#?(:cljs {:tag boolean})
[x]
(instance? TempId x))
| null | https://raw.githubusercontent.com/omcljs/om/3a1fbe9c0e282646fc58550139b491ff9869f96d/src/main/om/tempid.cljc | clojure | =============================================================================
ClojureScript
============================================================================= | (ns om.tempid
#?(:clj (:import [java.io Writer])))
#?(:cljs
(deftype TempId [^:mutable id ^:mutable __hash]
Object
(toString [this]
(pr-str this))
IEquiv
(-equiv [this other]
(and (instance? TempId other)
(= (. this -id) (. other -id))))
IHash
(-hash [this]
(when (nil? __hash)
(set! __hash (hash id)))
__hash)
IPrintWithWriter
(-pr-writer [_ writer _]
(write-all writer "#om/id[\"" id "\"]"))))
#?(:cljs
(defn tempid
([]
(tempid (random-uuid)))
([id]
(TempId. id nil))))
Clojure
#?(:clj
(defrecord TempId [id]
Object
(toString [this]
(pr-str this))))
#?(:clj
(defmethod print-method TempId [^TempId x ^Writer writer]
(.write writer (str "#om/id[\"" (.id x) "\"]"))))
#?(:clj
(defn tempid
([]
(tempid (java.util.UUID/randomUUID)))
([uuid]
(TempId. uuid))))
(defn tempid?
#?(:cljs {:tag boolean})
[x]
(instance? TempId x))
|
ce6e4cef790b845fc3c51fbe2a475d6e82ca845e719eac5c2133d40bd35a7591 | calyau/maxima | sinint.lisp | -*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The data in this file contains enhancments. ;;;;;
;;; ;;;;;
Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ;
;;; All rights reserved ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
( c ) Copyright 1982 Massachusetts Institute of Technology ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :maxima)
(macsyma-module sinint)
(load-macsyma-macros ratmac)
(declare-top (special genvar checkfactors
exp var $factorflag $logabs $expop $expon
$keepfloat ratform rootfactor pardenom $algebraic
wholepart parnumer varlist logptdx switch1))
(defun rootfac (q)
(prog (nthdq nthdq1 simproots ans)
(setq nthdq (pgcd q (pderivative q var)))
(setq simproots (pquotient q nthdq))
(setq ans (list (pquotient simproots (pgcd nthdq simproots))))
amen (if (or (pcoefp nthdq) (pointergp var (car nthdq)))
(return (reverse ans)))
(setq nthdq1 (pgcd (pderivative nthdq var) nthdq))
(push (pquotient (pgcd nthdq simproots) (pgcd nthdq1 simproots)) ans)
(setq nthdq nthdq1)
(go amen)))
(defun aprog (q)
(setq q (oldcontent q))
(setq rootfactor (rootfac (cadr q)))
(setq rootfactor
(cons (ptimes (car q) (car rootfactor)) (cdr rootfactor)))
(do ((pd (list (car rootfactor)))
(rf (cdr rootfactor) (cdr rf))
(n 2 (1+ n)))
((null rf) (setq pardenom (reverse pd)))
(push (pexpt (car rf) n) pd))
rootfactor)
(defun cprog (top bottom)
(prog (frpart pardenomc ppdenom thebpg)
(setq frpart (pdivide top bottom))
(setq wholepart (car frpart))
(setq frpart (cadr frpart))
(if (= (length pardenom) 1)
(return (setq parnumer (list frpart))))
(setq pardenomc (cdr pardenom))
(setq ppdenom (list (car pardenom)))
dseq (if (= (length pardenomc) 1) (go ok))
(setq ppdenom (cons (ptimes (car ppdenom) (car pardenomc)) ppdenom))
(setq pardenomc (cdr pardenomc))
(go dseq)
ok (setq pardenomc (reverse pardenom))
numc (setq thebpg (bprog (car pardenomc) (car ppdenom)))
(setq parnumer
(cons (cdr (ratdivide (ratti frpart (cdr thebpg) t)
(car pardenomc)))
parnumer))
(setq frpart
(cdr (ratdivide (ratti frpart (car thebpg) t)
(car ppdenom))))
(setq pardenomc (cdr pardenomc))
(setq ppdenom (cdr ppdenom))
(if (null ppdenom)
(return (setq parnumer (cons frpart parnumer))))
(go numc)))
(defun polyint (p) (ratqu (polyint1 (ratnumerator p)) (ratdenominator p)))
(defun polyint1 (p)
(cond ((or (null p) (equal p 0)) (cons 0 1))
((atom p) (list var 1 p))
((not (numberp (car p)))
(if (pointergp var (car p)) (list var 1 p) (polyint1 (cdr p))))
(t (ratplus (polyint2 p) (polyint1 (cddr p))))))
(defun polyint2 (p) (cons (list var (1+ (car p)) (cadr p)) (1+ (car p))))
(defun dprog (ratarg)
(prog (klth kx arootf deriv thebpg thetop thebot prod1 prod2 ans)
(setq ans (cons 0 1))
(if (or (pcoefp (cdr ratarg)) (pointergp var (cadr ratarg)))
(return (disrep (polyint ratarg))))
(aprog (ratdenominator ratarg))
(cprog (ratnumerator ratarg) (ratdenominator ratarg))
(setq rootfactor (reverse rootfactor))
(setq parnumer (reverse parnumer))
(setq klth (length rootfactor))
intg (if (= klth 1) (go simp))
(setq arootf (car rootfactor))
(if (zerop (pdegree arootf var)) (go reset))
(setq deriv (pderivative arootf var))
(setq thebpg (bprog arootf deriv))
(setq kx (1- klth))
(setq thetop (car parnumer))
iter (setq prod1 (ratti thetop (car thebpg) t))
(setq prod2 (ratti thetop (cdr thebpg) t))
(setq thebot (pexpt arootf kx))
(setq ans
(ratplus ans (ratqu (ratminus prod2) (ratti kx thebot t))))
(setq thetop
(ratplus prod1
(ratqu (ratreduce (pderivative (car prod2) var)
(cdr prod2))
kx)))
(setq thetop (cdr (ratdivide thetop thebot)))
(cond ((= kx 1) (setq logptdx (cons (ratqu thetop arootf) logptdx))
(go reset)))
(setq kx (1- kx))
(go iter)
reset(setq rootfactor (cdr rootfactor))
(setq parnumer (cdr parnumer))
(decf klth)
(go intg)
simp (push (ratqu (car parnumer) (car rootfactor)) logptdx)
(if (equal ans 0) (return (disrep (polyint wholepart))))
(setq thetop
(cadr (pdivide (ratnumerator ans) (ratdenominator ans))))
(return (list '(mplus)
(disrep (polyint wholepart))
(disrep (ratqu thetop (ratdenominator ans)))))))
(defun logmabs (x)
(list '(%log) (if $logabs (simplify (list '(mabs) x)) x)))
(defun npask (exp)
(cond ((freeof '$%i exp)
(learn `((mnotequal) ,exp 0) t) (asksign exp))
(t '$positive)))
(defvar $integrate_use_rootsof nil "Use the rootsof form for integrals when denominator does not factor")
(defun integrate-use-rootsof (f q variable)
(let ((dummy (make-param))
(qprime (disrep (pderivative q (p-var q))))
(ff (disrep f))
(qq (disrep q)))
;; This basically does a partial fraction expansion and integrates
;; the result. Let r be one (simple) root of the denominator
;; polynomial q. Then the partial fraction expansion is
;;
;; f(x)/q(x) = A/(x-r) + similar terms.
;;
;; Then
;;
;; f(x) = A*q(x)/(x-r) + others
;;
;; Take the limit as x -> r.
;;
;; f(r) = A*limit(q(x)/(x-r),x,r) + others
;; = A*at(diff(q(x),r), [x=r])
;;
;; Hence, A = f(r)/at(diff(q(x),x),[x=r])
;;
;; Then it follows that the integral is
;;
A*log(x - r )
;;
;; Note that we don't express the polynomial in terms of the
;; variable of integration, but in our dummy variable instead.
;; Using the variable of integration results in a wrong answer
;; when a substitution was done previously, since when the
;; substitution is finally undone, that modifies the polynomial.
`((%lsum) ((mtimes)
,(div* (subst dummy variable ff)
(subst dummy variable qprime))
((%log) ,(sub* variable dummy)))
,dummy
(($rootsof) ,(subst dummy variable qq) ,dummy))))
(defun eprog (p)
(prog (p1e p2e a1e a2e a3e discrim repart sign ncc dcc allcc xx deg)
(if (or (equal p 0) (equal (car p) 0)) (return 0))
(setq p1e (ratnumerator p) p2e (ratdenominator p))
(cond ((or switch1
(and (not (atom p2e))
(eq (car (setq xx (cadr (oldcontent p2e)))) var)
(member (setq deg (pdegree xx var)) '(5 6) :test #'equal)
(zerocoefl xx deg)
(or (equal deg 5) (not (pminusp (car (last xx)))))))
(go efac)))
(setq a1e (intfactor p2e))
(if (> (length a1e) 1) (go e40))
efac (setq ncc (oldcontent p1e))
(setq p1e (cadr ncc))
(setq dcc (oldcontent p2e))
(setq p2e (cadr dcc))
(setq allcc (ratqu (car ncc) (car dcc)))
(setq deg (pdegree p2e var))
(setq a1e (pderivative p2e var))
(setq a2e (ratqu (polcoef p1e (pdegree p1e var))
(polcoef a1e (pdegree a1e var))))
(cond ((equal (ratti a2e a1e t) (cons p1e 1))
(return (list '(mtimes)
(disrep (ratti allcc a2e t))
(logmabs (disrep p2e))))))
(cond ((equal deg 1) (go e10))
((equal deg 2) (go e20))
((and (equal deg 3) (equal (polcoef p2e 2) 0)
(equal (polcoef p2e 1) 0))
(return (e3prog p1e p2e allcc)))
((and (member deg '(4 5 6) :test #'equal) (zerocoefl p2e deg))
(return (enprog p1e p2e allcc deg))))
(cond ((and $integrate_use_rootsof (equal (car (psqfr p2e)) p2e))
(return (list '(mtimes) (disrep allcc)
(integrate-use-rootsof p1e p2e
(car (last varlist)))))))
(return (list '(mtimes)
(disrep allcc)
(list '(%integrate)
(list '(mquotient) (disrep p1e) (disrep p2e))
(car (last varlist)))))
e10 (return (list '(mtimes)
(disrep (ratti allcc
(ratqu (polcoef p1e (pdegree p1e var))
(polcoef p2e 1))
t))
(logmabs (disrep p2e))))
e20 (setq discrim
(ratdifference (cons (pexpt (polcoef p2e 1) 2) 1)
(ratti 4 (ratti (polcoef p2e 2) (polcoef p2e 0) t) t)))
(setq a2e (ratti (polcoef p2e (pdegree p2e var)) 2 t))
(setq xx (simplify (disrep discrim)))
(when (equal ($imagpart xx) 0)
(setq sign (npask xx))
(cond ((eq sign '$negative) (go e30))
((eq sign '$zero) (go zip))))
(setq a1e (ratsqrt discrim))
(setq a3e (logmabs
(list '(mquotient)
(list '(mplus)
(list '(mtimes)
(disrep a2e) (disrep (list var 1 1)))
(disrep (polcoef p2e 1))
(list '(mminus) a1e))
(list '(mplus)
(list '(mtimes)
(disrep a2e) (disrep (list var 1 1)))
(disrep (polcoef p2e 1))
a1e))))
(cond ((zerop (pdegree p1e var))
(return (list '(mtimes)
(disrep allcc)
(list '(mquotient) (disrep (polcoef p1e 0)) a1e)
a3e))))
(return
(list
'(mplus)
(list '(mtimes)
(disrep (ratti allcc (ratqu (polcoef p1e (pdegree p1e var)) a2e) t))
(logmabs (disrep p2e)))
(list
'(mtimes)
(list
'(mquotient)
(disrep (ratti allcc (ratqu (eprogratd a2e p1e p2e) a2e) t))
a1e)
a3e)))
e30 (setq a1e (ratsqrt (ratminus discrim)))
(setq
repart
(ratqu (cond ((zerop (pdegree p1e var)) (ratti a2e (polcoef p1e 0) t))
(t (eprogratd a2e p1e p2e)))
(polcoef p2e (pdegree p2e var))))
(setq a3e (cond ((equal 0 (car repart)) 0)
(t `((mtimes) ((mquotient)
,(disrep (ratti allcc repart t))
,a1e)
((%atan)
((mquotient)
,(disrep (pderivative p2e var))
,a1e))))))
(if (zerop (pdegree p1e var)) (return a3e))
(return (list '(mplus)
(list '(mtimes)
(disrep (ratti allcc
(ratqu (polcoef p1e (pdegree p1e var)) a2e)
t))
(logmabs (disrep p2e)))
a3e))
zip (setq
p2e
(ratqu
(psimp
(p-var p2e)
(pcoefadd 2
(pexpt (ptimes 2 (polcoef p2e 2)) 2)
(pcoefadd 1 (ptimes 4 (ptimes (polcoef p2e 2)
(polcoef p2e 1)))
(pcoefadd 0 (pexpt (polcoef p2e 1) 2) ()))))
(ptimes 4 (polcoef p2e 2))))
(return (fprog (ratti allcc (ratqu p1e p2e) t)))
e40 (setq parnumer nil pardenom a1e switch1 t)
(cprog p1e p2e)
(setq a2e
(mapcar #'(lambda (j k) (eprog (ratqu j k))) parnumer pardenom))
(setq switch1 nil)
(return (cons '(mplus) a2e))))
(defun e3prog (num denom cont)
(prog (a b c d e r ratr var* x)
(setq a (polcoef num 2) b (polcoef num 1) c (polcoef num 0)
d (polcoef denom 3) e (polcoef denom 0))
(setq r (cond ((eq (npask (simplify (disrep (ratqu e d)))) '$negative)
(simpnrt (disrep (ratqu (ratti -1 e t) d)) 3))
(t (neg (simpnrt (disrep (ratqu e d)) 3)))))
(setq var* (list var 1 1))
(newvar r)
(orderpointer varlist)
(setq x (ratf r))
(setq ratform (car x) ratr (cdr x))
(return
(simplify
(list '(mplus)
(list '(mtimes)
(disrep (ratqu (r* cont (r+ (r* a ratr ratr) (r* b ratr) c))
(r* ratr ratr 3 d)))
(logmabs (disrep (ratpl (ratti -1 ratr t) var*))))
(eprog (r* cont (ratqu (r+ (r* (r+ (r* 2 a ratr ratr)
(r* -1 b ratr)
(r* -1 c))
var*)
(r+ (ratqu (r* -1 a e) d)
(r* b ratr ratr)
(r* -1 2 c ratr)))
(r* 3 d ratr ratr
(r+ (ratti var* var* t)
(ratti ratr var* t)
(ratti ratr ratr t))))))
)))))
(defun eprogratd (a2e p1e p2e)
(ratdifference (ratti a2e (polcoef p1e (1- (pdegree p1e var))) t)
(ratti (polcoef p2e (1- (pdegree p2e var)))
(polcoef p1e (pdegree p1e var))
t)))
(defun enprog (num denom cont deg)
;; Denominator is (A*VAR^4+B) =
;; if B<0 then (SQRT(A)*VAR^2 - SQRT(-B)) (SQRT(A)*VAR^2 + SQRT(-B))
;; else
;; (SQRT(A)*VAR^2 - SQRT(2)*A^(1/4)*B^(1/4)*VAR + SQRT(B)) *
;; (SQRT(A)*VAR^2 + SQRT(2)*A^(1/4)*B^(1/4)*VAR + SQRT(B))
or ( A*VAR^5+B ) =
( 1/4 ) * ( A^(1/5)*VAR + B^(1/5 ) ) *
;; (2*A^(2/5)*VAR^2 + (-SQRT(5)-1)*A^(1/5)*B^(1/5)*VAR + 2*B^(2/5)) *
;; (2*A^(2/5)*VAR^2 + (+SQRT(5)-1)*A^(1/5)*B^(1/5)*VAR + 2*B^(2/5))
;; or (A*VAR^6+B) =
;; if B<0 then (SQRT(A)*VAR^3 - SQRT(-B)) (SQRT(A)*VAR^3 + SQRT(-B))
;; else
;; (A^(1/3)*VAR^2 + B^(1/3)) *
;; (A^(1/3)*VAR^2 - SQRT(3)*A^(1/6)*B^(1/6)*VAR + B^(1/3)) *
;; (A^(1/3)*VAR^2 + SQRT(3)*A^(1/6)*B^(1/6)*VAR + B^(1/3))
(prog ($expop $expon a b term disvar $algebraic)
(setq $expop 0 $expon 0)
(setq a (simplify (disrep (polcoef denom deg)))
b (simplify (disrep (polcoef denom 0)))
disvar (simplify (get var 'disrep))
num (simplify (disrep num))
cont (simplify (disrep cont)))
(cond ((= deg 4)
(if (eq '$neg ($asksign b))
(setq denom
(mul2 (add2 (mul2 (power a '((rat simp) 1 2)) (power disvar 2))
(power (mul -1 b) '((rat simp) 1 2)))
(add2 (mul2 (power a '((rat simp) 1 2)) (power disvar 2))
(mul -1 (power (mul -1 b) '((rat simp) 1 2))))))
(progn
(setq denom (add2 (mul2 (power a '((rat simp) 1 2)) (power disvar 2))
(power b '((rat simp) 1 2)))
term (muln (list (power 2 '((rat simp) 1 2))
(power a '((rat simp) 1 4))
(power b '((rat simp) 1 4))
disvar)
t))
(setq denom (mul2 (add2 denom term) (sub denom term))))))
((= deg 5)
(setq term (mul3 (power a '((rat simp) 1 5))
(power b '((rat simp) 1 5))
disvar))
(setq denom (add2 (mul3 2 (power a '((rat simp) 2 5))
(power disvar 2))
(sub (mul2 2 (power b '((rat simp) 2 5))) term)))
(setq term (mul2 (power 5 '((rat simp) 1 2)) term))
(setq denom (muln (list '((rat simp) 1 4)
(add2 (mul2 (power a '((rat simp) 1 5)) disvar)
(power b '((rat simp) 1 5)))
(add2 denom term) (sub denom term))
t)))
(t
(if (eq '$neg ($asksign b))
(setq denom
(mul2 (add2 (mul2 (power a '((rat simp) 1 2)) (power disvar 3))
(power (mul -1 b) '((rat simp) 1 2)))
(add2 (mul2 (power a '((rat simp) 1 2)) (power disvar 3))
(mul -1 (power (mul -1 b) '((rat simp) 1 2))))))
(progn
(setq denom (add2 (mul2 (power a '((rat simp) 1 3)) (power disvar 2))
(power b '((rat simp) 1 3)))
term (muln (list (power 3 '((rat simp) 1 2))
(power a '((rat simp) 1 6))
(power b '((rat simp) 1 6))
disvar)
t))
(setq denom (mul3 denom (add2 denom term) (sub denom term))))
)))
Needs $ ALGEBRAIC NIL so next call to RATF will preserve factorization .
(return (mul2 cont (ratint (div num denom) disvar)))))
(defun zerocoefl (e n)
(do ((i 1 (1+ i))) ((= i n) t)
(if (not (equal (polcoef e i) 0)) (return nil))))
(defun ratsqrt (a) (let (varlist) (simpnrt (disrep a) 2)))
(defun fprog (rat*)
(prog (rootfactor pardenom parnumer logptdx wholepart switch1)
(return (addn (cons (dprog rat*) (mapcar #'eprog logptdx)) nil))))
(defun ratint (exp var)
(prog (genvar checkfactors varlist ratarg ratform $keepfloat)
(setq varlist (list var))
(setq ratarg (ratf exp))
(setq ratform (car ratarg))
(setq var (caadr (ratf var)))
(return (fprog (cdr ratarg)))))
(defun intfactor (l)
(prog ($factorflag a b)
(setq a (oldcontent l) b (everysecond (pfactor (cadr a))))
(return (if (equal (car a) 1) b (cons (car a) b)))))
(defun everysecond (a)
(if a (cons (if (numberp (car a))
(pexpt (car a) (cadr a))
(car a))
(everysecond (cddr a)))))
| null | https://raw.githubusercontent.com/calyau/maxima/9352a3f5c22b9b5d0b367fddeb0185c53d7f4d02/src/sinint.lisp | lisp | Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
The data in this file contains enhancments. ;;;;;
;;;;;
; ; ; ;
All rights reserved ;;;;;
; ;
This basically does a partial fraction expansion and integrates
the result. Let r be one (simple) root of the denominator
polynomial q. Then the partial fraction expansion is
f(x)/q(x) = A/(x-r) + similar terms.
Then
f(x) = A*q(x)/(x-r) + others
Take the limit as x -> r.
f(r) = A*limit(q(x)/(x-r),x,r) + others
= A*at(diff(q(x),r), [x=r])
Hence, A = f(r)/at(diff(q(x),x),[x=r])
Then it follows that the integral is
Note that we don't express the polynomial in terms of the
variable of integration, but in our dummy variable instead.
Using the variable of integration results in a wrong answer
when a substitution was done previously, since when the
substitution is finally undone, that modifies the polynomial.
Denominator is (A*VAR^4+B) =
if B<0 then (SQRT(A)*VAR^2 - SQRT(-B)) (SQRT(A)*VAR^2 + SQRT(-B))
else
(SQRT(A)*VAR^2 - SQRT(2)*A^(1/4)*B^(1/4)*VAR + SQRT(B)) *
(SQRT(A)*VAR^2 + SQRT(2)*A^(1/4)*B^(1/4)*VAR + SQRT(B))
(2*A^(2/5)*VAR^2 + (-SQRT(5)-1)*A^(1/5)*B^(1/5)*VAR + 2*B^(2/5)) *
(2*A^(2/5)*VAR^2 + (+SQRT(5)-1)*A^(1/5)*B^(1/5)*VAR + 2*B^(2/5))
or (A*VAR^6+B) =
if B<0 then (SQRT(A)*VAR^3 - SQRT(-B)) (SQRT(A)*VAR^3 + SQRT(-B))
else
(A^(1/3)*VAR^2 + B^(1/3)) *
(A^(1/3)*VAR^2 - SQRT(3)*A^(1/6)*B^(1/6)*VAR + B^(1/3)) *
(A^(1/3)*VAR^2 + SQRT(3)*A^(1/6)*B^(1/6)*VAR + B^(1/3)) |
(in-package :maxima)
(macsyma-module sinint)
(load-macsyma-macros ratmac)
(declare-top (special genvar checkfactors
exp var $factorflag $logabs $expop $expon
$keepfloat ratform rootfactor pardenom $algebraic
wholepart parnumer varlist logptdx switch1))
(defun rootfac (q)
(prog (nthdq nthdq1 simproots ans)
(setq nthdq (pgcd q (pderivative q var)))
(setq simproots (pquotient q nthdq))
(setq ans (list (pquotient simproots (pgcd nthdq simproots))))
amen (if (or (pcoefp nthdq) (pointergp var (car nthdq)))
(return (reverse ans)))
(setq nthdq1 (pgcd (pderivative nthdq var) nthdq))
(push (pquotient (pgcd nthdq simproots) (pgcd nthdq1 simproots)) ans)
(setq nthdq nthdq1)
(go amen)))
(defun aprog (q)
(setq q (oldcontent q))
(setq rootfactor (rootfac (cadr q)))
(setq rootfactor
(cons (ptimes (car q) (car rootfactor)) (cdr rootfactor)))
(do ((pd (list (car rootfactor)))
(rf (cdr rootfactor) (cdr rf))
(n 2 (1+ n)))
((null rf) (setq pardenom (reverse pd)))
(push (pexpt (car rf) n) pd))
rootfactor)
(defun cprog (top bottom)
(prog (frpart pardenomc ppdenom thebpg)
(setq frpart (pdivide top bottom))
(setq wholepart (car frpart))
(setq frpart (cadr frpart))
(if (= (length pardenom) 1)
(return (setq parnumer (list frpart))))
(setq pardenomc (cdr pardenom))
(setq ppdenom (list (car pardenom)))
dseq (if (= (length pardenomc) 1) (go ok))
(setq ppdenom (cons (ptimes (car ppdenom) (car pardenomc)) ppdenom))
(setq pardenomc (cdr pardenomc))
(go dseq)
ok (setq pardenomc (reverse pardenom))
numc (setq thebpg (bprog (car pardenomc) (car ppdenom)))
(setq parnumer
(cons (cdr (ratdivide (ratti frpart (cdr thebpg) t)
(car pardenomc)))
parnumer))
(setq frpart
(cdr (ratdivide (ratti frpart (car thebpg) t)
(car ppdenom))))
(setq pardenomc (cdr pardenomc))
(setq ppdenom (cdr ppdenom))
(if (null ppdenom)
(return (setq parnumer (cons frpart parnumer))))
(go numc)))
(defun polyint (p) (ratqu (polyint1 (ratnumerator p)) (ratdenominator p)))
(defun polyint1 (p)
(cond ((or (null p) (equal p 0)) (cons 0 1))
((atom p) (list var 1 p))
((not (numberp (car p)))
(if (pointergp var (car p)) (list var 1 p) (polyint1 (cdr p))))
(t (ratplus (polyint2 p) (polyint1 (cddr p))))))
(defun polyint2 (p) (cons (list var (1+ (car p)) (cadr p)) (1+ (car p))))
(defun dprog (ratarg)
(prog (klth kx arootf deriv thebpg thetop thebot prod1 prod2 ans)
(setq ans (cons 0 1))
(if (or (pcoefp (cdr ratarg)) (pointergp var (cadr ratarg)))
(return (disrep (polyint ratarg))))
(aprog (ratdenominator ratarg))
(cprog (ratnumerator ratarg) (ratdenominator ratarg))
(setq rootfactor (reverse rootfactor))
(setq parnumer (reverse parnumer))
(setq klth (length rootfactor))
intg (if (= klth 1) (go simp))
(setq arootf (car rootfactor))
(if (zerop (pdegree arootf var)) (go reset))
(setq deriv (pderivative arootf var))
(setq thebpg (bprog arootf deriv))
(setq kx (1- klth))
(setq thetop (car parnumer))
iter (setq prod1 (ratti thetop (car thebpg) t))
(setq prod2 (ratti thetop (cdr thebpg) t))
(setq thebot (pexpt arootf kx))
(setq ans
(ratplus ans (ratqu (ratminus prod2) (ratti kx thebot t))))
(setq thetop
(ratplus prod1
(ratqu (ratreduce (pderivative (car prod2) var)
(cdr prod2))
kx)))
(setq thetop (cdr (ratdivide thetop thebot)))
(cond ((= kx 1) (setq logptdx (cons (ratqu thetop arootf) logptdx))
(go reset)))
(setq kx (1- kx))
(go iter)
reset(setq rootfactor (cdr rootfactor))
(setq parnumer (cdr parnumer))
(decf klth)
(go intg)
simp (push (ratqu (car parnumer) (car rootfactor)) logptdx)
(if (equal ans 0) (return (disrep (polyint wholepart))))
(setq thetop
(cadr (pdivide (ratnumerator ans) (ratdenominator ans))))
(return (list '(mplus)
(disrep (polyint wholepart))
(disrep (ratqu thetop (ratdenominator ans)))))))
(defun logmabs (x)
(list '(%log) (if $logabs (simplify (list '(mabs) x)) x)))
(defun npask (exp)
(cond ((freeof '$%i exp)
(learn `((mnotequal) ,exp 0) t) (asksign exp))
(t '$positive)))
(defvar $integrate_use_rootsof nil "Use the rootsof form for integrals when denominator does not factor")
(defun integrate-use-rootsof (f q variable)
(let ((dummy (make-param))
(qprime (disrep (pderivative q (p-var q))))
(ff (disrep f))
(qq (disrep q)))
A*log(x - r )
`((%lsum) ((mtimes)
,(div* (subst dummy variable ff)
(subst dummy variable qprime))
((%log) ,(sub* variable dummy)))
,dummy
(($rootsof) ,(subst dummy variable qq) ,dummy))))
(defun eprog (p)
(prog (p1e p2e a1e a2e a3e discrim repart sign ncc dcc allcc xx deg)
(if (or (equal p 0) (equal (car p) 0)) (return 0))
(setq p1e (ratnumerator p) p2e (ratdenominator p))
(cond ((or switch1
(and (not (atom p2e))
(eq (car (setq xx (cadr (oldcontent p2e)))) var)
(member (setq deg (pdegree xx var)) '(5 6) :test #'equal)
(zerocoefl xx deg)
(or (equal deg 5) (not (pminusp (car (last xx)))))))
(go efac)))
(setq a1e (intfactor p2e))
(if (> (length a1e) 1) (go e40))
efac (setq ncc (oldcontent p1e))
(setq p1e (cadr ncc))
(setq dcc (oldcontent p2e))
(setq p2e (cadr dcc))
(setq allcc (ratqu (car ncc) (car dcc)))
(setq deg (pdegree p2e var))
(setq a1e (pderivative p2e var))
(setq a2e (ratqu (polcoef p1e (pdegree p1e var))
(polcoef a1e (pdegree a1e var))))
(cond ((equal (ratti a2e a1e t) (cons p1e 1))
(return (list '(mtimes)
(disrep (ratti allcc a2e t))
(logmabs (disrep p2e))))))
(cond ((equal deg 1) (go e10))
((equal deg 2) (go e20))
((and (equal deg 3) (equal (polcoef p2e 2) 0)
(equal (polcoef p2e 1) 0))
(return (e3prog p1e p2e allcc)))
((and (member deg '(4 5 6) :test #'equal) (zerocoefl p2e deg))
(return (enprog p1e p2e allcc deg))))
(cond ((and $integrate_use_rootsof (equal (car (psqfr p2e)) p2e))
(return (list '(mtimes) (disrep allcc)
(integrate-use-rootsof p1e p2e
(car (last varlist)))))))
(return (list '(mtimes)
(disrep allcc)
(list '(%integrate)
(list '(mquotient) (disrep p1e) (disrep p2e))
(car (last varlist)))))
e10 (return (list '(mtimes)
(disrep (ratti allcc
(ratqu (polcoef p1e (pdegree p1e var))
(polcoef p2e 1))
t))
(logmabs (disrep p2e))))
e20 (setq discrim
(ratdifference (cons (pexpt (polcoef p2e 1) 2) 1)
(ratti 4 (ratti (polcoef p2e 2) (polcoef p2e 0) t) t)))
(setq a2e (ratti (polcoef p2e (pdegree p2e var)) 2 t))
(setq xx (simplify (disrep discrim)))
(when (equal ($imagpart xx) 0)
(setq sign (npask xx))
(cond ((eq sign '$negative) (go e30))
((eq sign '$zero) (go zip))))
(setq a1e (ratsqrt discrim))
(setq a3e (logmabs
(list '(mquotient)
(list '(mplus)
(list '(mtimes)
(disrep a2e) (disrep (list var 1 1)))
(disrep (polcoef p2e 1))
(list '(mminus) a1e))
(list '(mplus)
(list '(mtimes)
(disrep a2e) (disrep (list var 1 1)))
(disrep (polcoef p2e 1))
a1e))))
(cond ((zerop (pdegree p1e var))
(return (list '(mtimes)
(disrep allcc)
(list '(mquotient) (disrep (polcoef p1e 0)) a1e)
a3e))))
(return
(list
'(mplus)
(list '(mtimes)
(disrep (ratti allcc (ratqu (polcoef p1e (pdegree p1e var)) a2e) t))
(logmabs (disrep p2e)))
(list
'(mtimes)
(list
'(mquotient)
(disrep (ratti allcc (ratqu (eprogratd a2e p1e p2e) a2e) t))
a1e)
a3e)))
e30 (setq a1e (ratsqrt (ratminus discrim)))
(setq
repart
(ratqu (cond ((zerop (pdegree p1e var)) (ratti a2e (polcoef p1e 0) t))
(t (eprogratd a2e p1e p2e)))
(polcoef p2e (pdegree p2e var))))
(setq a3e (cond ((equal 0 (car repart)) 0)
(t `((mtimes) ((mquotient)
,(disrep (ratti allcc repart t))
,a1e)
((%atan)
((mquotient)
,(disrep (pderivative p2e var))
,a1e))))))
(if (zerop (pdegree p1e var)) (return a3e))
(return (list '(mplus)
(list '(mtimes)
(disrep (ratti allcc
(ratqu (polcoef p1e (pdegree p1e var)) a2e)
t))
(logmabs (disrep p2e)))
a3e))
zip (setq
p2e
(ratqu
(psimp
(p-var p2e)
(pcoefadd 2
(pexpt (ptimes 2 (polcoef p2e 2)) 2)
(pcoefadd 1 (ptimes 4 (ptimes (polcoef p2e 2)
(polcoef p2e 1)))
(pcoefadd 0 (pexpt (polcoef p2e 1) 2) ()))))
(ptimes 4 (polcoef p2e 2))))
(return (fprog (ratti allcc (ratqu p1e p2e) t)))
e40 (setq parnumer nil pardenom a1e switch1 t)
(cprog p1e p2e)
(setq a2e
(mapcar #'(lambda (j k) (eprog (ratqu j k))) parnumer pardenom))
(setq switch1 nil)
(return (cons '(mplus) a2e))))
(defun e3prog (num denom cont)
(prog (a b c d e r ratr var* x)
(setq a (polcoef num 2) b (polcoef num 1) c (polcoef num 0)
d (polcoef denom 3) e (polcoef denom 0))
(setq r (cond ((eq (npask (simplify (disrep (ratqu e d)))) '$negative)
(simpnrt (disrep (ratqu (ratti -1 e t) d)) 3))
(t (neg (simpnrt (disrep (ratqu e d)) 3)))))
(setq var* (list var 1 1))
(newvar r)
(orderpointer varlist)
(setq x (ratf r))
(setq ratform (car x) ratr (cdr x))
(return
(simplify
(list '(mplus)
(list '(mtimes)
(disrep (ratqu (r* cont (r+ (r* a ratr ratr) (r* b ratr) c))
(r* ratr ratr 3 d)))
(logmabs (disrep (ratpl (ratti -1 ratr t) var*))))
(eprog (r* cont (ratqu (r+ (r* (r+ (r* 2 a ratr ratr)
(r* -1 b ratr)
(r* -1 c))
var*)
(r+ (ratqu (r* -1 a e) d)
(r* b ratr ratr)
(r* -1 2 c ratr)))
(r* 3 d ratr ratr
(r+ (ratti var* var* t)
(ratti ratr var* t)
(ratti ratr ratr t))))))
)))))
(defun eprogratd (a2e p1e p2e)
(ratdifference (ratti a2e (polcoef p1e (1- (pdegree p1e var))) t)
(ratti (polcoef p2e (1- (pdegree p2e var)))
(polcoef p1e (pdegree p1e var))
t)))
(defun enprog (num denom cont deg)
or ( A*VAR^5+B ) =
( 1/4 ) * ( A^(1/5)*VAR + B^(1/5 ) ) *
(prog ($expop $expon a b term disvar $algebraic)
(setq $expop 0 $expon 0)
(setq a (simplify (disrep (polcoef denom deg)))
b (simplify (disrep (polcoef denom 0)))
disvar (simplify (get var 'disrep))
num (simplify (disrep num))
cont (simplify (disrep cont)))
(cond ((= deg 4)
(if (eq '$neg ($asksign b))
(setq denom
(mul2 (add2 (mul2 (power a '((rat simp) 1 2)) (power disvar 2))
(power (mul -1 b) '((rat simp) 1 2)))
(add2 (mul2 (power a '((rat simp) 1 2)) (power disvar 2))
(mul -1 (power (mul -1 b) '((rat simp) 1 2))))))
(progn
(setq denom (add2 (mul2 (power a '((rat simp) 1 2)) (power disvar 2))
(power b '((rat simp) 1 2)))
term (muln (list (power 2 '((rat simp) 1 2))
(power a '((rat simp) 1 4))
(power b '((rat simp) 1 4))
disvar)
t))
(setq denom (mul2 (add2 denom term) (sub denom term))))))
((= deg 5)
(setq term (mul3 (power a '((rat simp) 1 5))
(power b '((rat simp) 1 5))
disvar))
(setq denom (add2 (mul3 2 (power a '((rat simp) 2 5))
(power disvar 2))
(sub (mul2 2 (power b '((rat simp) 2 5))) term)))
(setq term (mul2 (power 5 '((rat simp) 1 2)) term))
(setq denom (muln (list '((rat simp) 1 4)
(add2 (mul2 (power a '((rat simp) 1 5)) disvar)
(power b '((rat simp) 1 5)))
(add2 denom term) (sub denom term))
t)))
(t
(if (eq '$neg ($asksign b))
(setq denom
(mul2 (add2 (mul2 (power a '((rat simp) 1 2)) (power disvar 3))
(power (mul -1 b) '((rat simp) 1 2)))
(add2 (mul2 (power a '((rat simp) 1 2)) (power disvar 3))
(mul -1 (power (mul -1 b) '((rat simp) 1 2))))))
(progn
(setq denom (add2 (mul2 (power a '((rat simp) 1 3)) (power disvar 2))
(power b '((rat simp) 1 3)))
term (muln (list (power 3 '((rat simp) 1 2))
(power a '((rat simp) 1 6))
(power b '((rat simp) 1 6))
disvar)
t))
(setq denom (mul3 denom (add2 denom term) (sub denom term))))
)))
Needs $ ALGEBRAIC NIL so next call to RATF will preserve factorization .
(return (mul2 cont (ratint (div num denom) disvar)))))
(defun zerocoefl (e n)
(do ((i 1 (1+ i))) ((= i n) t)
(if (not (equal (polcoef e i) 0)) (return nil))))
(defun ratsqrt (a) (let (varlist) (simpnrt (disrep a) 2)))
(defun fprog (rat*)
(prog (rootfactor pardenom parnumer logptdx wholepart switch1)
(return (addn (cons (dprog rat*) (mapcar #'eprog logptdx)) nil))))
(defun ratint (exp var)
(prog (genvar checkfactors varlist ratarg ratform $keepfloat)
(setq varlist (list var))
(setq ratarg (ratf exp))
(setq ratform (car ratarg))
(setq var (caadr (ratf var)))
(return (fprog (cdr ratarg)))))
(defun intfactor (l)
(prog ($factorflag a b)
(setq a (oldcontent l) b (everysecond (pfactor (cadr a))))
(return (if (equal (car a) 1) b (cons (car a) b)))))
(defun everysecond (a)
(if a (cons (if (numberp (car a))
(pexpt (car a) (cadr a))
(car a))
(everysecond (cddr a)))))
|
70581a4898e7830360f1c7597ba70216dd9858668453b20ed1cb2fcbd3dd2312 | tezos-commons/baseDAO | LambdaTreasuryDAO.hs | SPDX - FileCopyrightText : 2021 Tezos Commons
SPDX - License - Identifier : LicenseRef - MIT - TC
# OPTIONS_GHC -Wno - orphans #
module Test.Ligo.LambdaTreasuryDAO
( test_LambdaTreasuryDAO
) where
import Prelude
import Data.Map qualified as Map
import Data.Set qualified as S
import Test.Tasty (TestTree)
import Lorentz as L hiding (assert, div)
import Morley.Tezos.Address
import Test.Cleveland
import Ligo.BaseDAO.Contract
import Ligo.BaseDAO.LambdaDAO.Types
import Ligo.BaseDAO.Types
import Test.Ligo.Common
import Test.Ligo.TreasuryDAO
import Test.Ligo.TreasuryDAO.Types
instance TestableVariant 'LambdaTreasury where
getInitialStorage admin = initialStorageWithExplictLambdaDAOConfig admin
getContract = baseDAOLambdaTreasuryLigo
getVariantStorageRPC addr = getStorage @(StorageSkeleton (VariantToExtra 'LambdaTreasury)) addr
instance IsProposalArgument 'LambdaTreasury TransferProposal where
toMetadata a = lPackValueRaw @LambdaDaoProposalMetadata $ Execute_handler $ ExecuteHandlerParam "transfer_proposal" $ lPackValueRaw a
instance IsProposalArgument 'LambdaTreasury Address where
toMetadata a = lPackValueRaw @LambdaDaoProposalMetadata $ Execute_handler $ ExecuteHandlerParam "update_guardian_proposal" $ lPackValueRaw a
instance IsProposalArgument 'LambdaTreasury (Maybe KeyHash) where
toMetadata a = lPackValueRaw @LambdaDaoProposalMetadata $ Execute_handler $ ExecuteHandlerParam "update_contract_delegate_proposal" $ lPackValueRaw a
instance VariantExtraHasField 'LambdaTreasury "ProposalReceivers" (Set Address) where
setVariantExtra a = setExtra (setInHandlerStorage [mt|proposal_receivers|] a)
getVariantExtra = getInHandlerStorage [mt|proposal_receivers|]
instance VariantExtraHasField 'LambdaTreasury "MinXtzAmount" Mutez where
setVariantExtra a = setExtra (setInHandlerStorage [mt|min_xtz_amount|] a)
getVariantExtra = getInHandlerStorage [mt|min_xtz_amount|]
instance VariantExtraHasField 'LambdaTreasury "FrozenExtraValue" Natural where
setVariantExtra a = setExtra (setInHandlerStorage [mt|frozen_extra_value|] a)
getVariantExtra = getInHandlerStorage [mt|frozen_extra_value|]
instance VariantExtraHasField 'LambdaTreasury "FrozenScaleValue" Natural where
setVariantExtra a = setExtra (setInHandlerStorage [mt|frozen_scale_value|] a)
getVariantExtra = getInHandlerStorage [mt|frozen_scale_value|]
instance VariantExtraHasField 'LambdaTreasury "SlashScaleValue" Natural where
setVariantExtra a = setExtra (setInHandlerStorage [mt|slash_scale_value|] a)
getVariantExtra = getInHandlerStorage [mt|slash_scale_value|]
instance VariantExtraHasField 'LambdaTreasury "SlashDivisionValue" Natural where
setVariantExtra a = setExtra (setInHandlerStorage [mt|slash_division_value|] a)
getVariantExtra = getInHandlerStorage [mt|slash_division_value|]
instance VariantExtraHasField 'LambdaTreasury "MaxProposalSize" Natural where
setVariantExtra a = setExtra (setInHandlerStorage [mt|max_proposal_size|] a)
getVariantExtra = getInHandlerStorage [mt|max_proposal_size|]
| We test non - token entrypoints of the BaseDAO contract here
test_LambdaTreasuryDAO :: TestTree
test_LambdaTreasuryDAO = treasuryDAOTests @'LambdaTreasury
initialStorage :: ImplicitAddress -> LambdaStorage
initialStorage admin = let
fs = baseDAOLambdatreasuryStorageLigo
in fs { sAdmin = toAddress admin, sConfig = (sConfig fs)
{ cPeriod = 11
, cProposalFlushLevel = 22
, cProposalExpiredLevel = 33
, cGovernanceTotalSupply = 100
}}
initialStorageWithExplictLambdaDAOConfig :: ImplicitAddress -> LambdaStorage
initialStorageWithExplictLambdaDAOConfig admin = (initialStorage admin)
& setExtra (setInHandlerStorage [mt|proposal_receivers|] (mempty :: S.Set Address))
& setExtra (setInHandlerStorage [mt|frozen_scale_value|] (1 :: Natural))
& setExtra (setInHandlerStorage [mt|frozen_extra_value|] (0 :: Natural))
& setExtra (setInHandlerStorage [mt|slash_scale_value|] (1 :: Natural))
& setExtra (setInHandlerStorage [mt|slash_division_value|] (1 :: Natural))
& setExtra (setInHandlerStorage [mt|min_xtz_amount|] [tz|2u|])
& setExtra (setInHandlerStorage [mt|max_xtz_amount|] [tz|5u|])
& setExtra (setInHandlerStorage [mt|max_proposal_size|] (1000 :: Natural))
setInHandlerStorage :: NicePackedValue v => MText -> v -> LambdaExtra -> LambdaExtra
setInHandlerStorage k v e = e { leHandlerStorage = Map.insert k (lPackValueRaw v) (leHandlerStorage e) }
getInHandlerStorage :: NiceUnpackedValue v => MText -> LambdaExtraRPC -> v
getInHandlerStorage k e = fromRight (error "Unpacking failed") $ lUnpackValueRaw $ fromMaybe (error "Key not found in Handler storage") $ Map.lookup k (leHandlerStorageRPC e)
| null | https://raw.githubusercontent.com/tezos-commons/baseDAO/c8cc03362b64e8f27432ec70cdb4c0df82abff35/haskell/test/Test/Ligo/LambdaTreasuryDAO.hs | haskell | SPDX - FileCopyrightText : 2021 Tezos Commons
SPDX - License - Identifier : LicenseRef - MIT - TC
# OPTIONS_GHC -Wno - orphans #
module Test.Ligo.LambdaTreasuryDAO
( test_LambdaTreasuryDAO
) where
import Prelude
import Data.Map qualified as Map
import Data.Set qualified as S
import Test.Tasty (TestTree)
import Lorentz as L hiding (assert, div)
import Morley.Tezos.Address
import Test.Cleveland
import Ligo.BaseDAO.Contract
import Ligo.BaseDAO.LambdaDAO.Types
import Ligo.BaseDAO.Types
import Test.Ligo.Common
import Test.Ligo.TreasuryDAO
import Test.Ligo.TreasuryDAO.Types
instance TestableVariant 'LambdaTreasury where
getInitialStorage admin = initialStorageWithExplictLambdaDAOConfig admin
getContract = baseDAOLambdaTreasuryLigo
getVariantStorageRPC addr = getStorage @(StorageSkeleton (VariantToExtra 'LambdaTreasury)) addr
instance IsProposalArgument 'LambdaTreasury TransferProposal where
toMetadata a = lPackValueRaw @LambdaDaoProposalMetadata $ Execute_handler $ ExecuteHandlerParam "transfer_proposal" $ lPackValueRaw a
instance IsProposalArgument 'LambdaTreasury Address where
toMetadata a = lPackValueRaw @LambdaDaoProposalMetadata $ Execute_handler $ ExecuteHandlerParam "update_guardian_proposal" $ lPackValueRaw a
instance IsProposalArgument 'LambdaTreasury (Maybe KeyHash) where
toMetadata a = lPackValueRaw @LambdaDaoProposalMetadata $ Execute_handler $ ExecuteHandlerParam "update_contract_delegate_proposal" $ lPackValueRaw a
instance VariantExtraHasField 'LambdaTreasury "ProposalReceivers" (Set Address) where
setVariantExtra a = setExtra (setInHandlerStorage [mt|proposal_receivers|] a)
getVariantExtra = getInHandlerStorage [mt|proposal_receivers|]
instance VariantExtraHasField 'LambdaTreasury "MinXtzAmount" Mutez where
setVariantExtra a = setExtra (setInHandlerStorage [mt|min_xtz_amount|] a)
getVariantExtra = getInHandlerStorage [mt|min_xtz_amount|]
instance VariantExtraHasField 'LambdaTreasury "FrozenExtraValue" Natural where
setVariantExtra a = setExtra (setInHandlerStorage [mt|frozen_extra_value|] a)
getVariantExtra = getInHandlerStorage [mt|frozen_extra_value|]
instance VariantExtraHasField 'LambdaTreasury "FrozenScaleValue" Natural where
setVariantExtra a = setExtra (setInHandlerStorage [mt|frozen_scale_value|] a)
getVariantExtra = getInHandlerStorage [mt|frozen_scale_value|]
instance VariantExtraHasField 'LambdaTreasury "SlashScaleValue" Natural where
setVariantExtra a = setExtra (setInHandlerStorage [mt|slash_scale_value|] a)
getVariantExtra = getInHandlerStorage [mt|slash_scale_value|]
instance VariantExtraHasField 'LambdaTreasury "SlashDivisionValue" Natural where
setVariantExtra a = setExtra (setInHandlerStorage [mt|slash_division_value|] a)
getVariantExtra = getInHandlerStorage [mt|slash_division_value|]
instance VariantExtraHasField 'LambdaTreasury "MaxProposalSize" Natural where
setVariantExtra a = setExtra (setInHandlerStorage [mt|max_proposal_size|] a)
getVariantExtra = getInHandlerStorage [mt|max_proposal_size|]
| We test non - token entrypoints of the BaseDAO contract here
test_LambdaTreasuryDAO :: TestTree
test_LambdaTreasuryDAO = treasuryDAOTests @'LambdaTreasury
initialStorage :: ImplicitAddress -> LambdaStorage
initialStorage admin = let
fs = baseDAOLambdatreasuryStorageLigo
in fs { sAdmin = toAddress admin, sConfig = (sConfig fs)
{ cPeriod = 11
, cProposalFlushLevel = 22
, cProposalExpiredLevel = 33
, cGovernanceTotalSupply = 100
}}
initialStorageWithExplictLambdaDAOConfig :: ImplicitAddress -> LambdaStorage
initialStorageWithExplictLambdaDAOConfig admin = (initialStorage admin)
& setExtra (setInHandlerStorage [mt|proposal_receivers|] (mempty :: S.Set Address))
& setExtra (setInHandlerStorage [mt|frozen_scale_value|] (1 :: Natural))
& setExtra (setInHandlerStorage [mt|frozen_extra_value|] (0 :: Natural))
& setExtra (setInHandlerStorage [mt|slash_scale_value|] (1 :: Natural))
& setExtra (setInHandlerStorage [mt|slash_division_value|] (1 :: Natural))
& setExtra (setInHandlerStorage [mt|min_xtz_amount|] [tz|2u|])
& setExtra (setInHandlerStorage [mt|max_xtz_amount|] [tz|5u|])
& setExtra (setInHandlerStorage [mt|max_proposal_size|] (1000 :: Natural))
setInHandlerStorage :: NicePackedValue v => MText -> v -> LambdaExtra -> LambdaExtra
setInHandlerStorage k v e = e { leHandlerStorage = Map.insert k (lPackValueRaw v) (leHandlerStorage e) }
getInHandlerStorage :: NiceUnpackedValue v => MText -> LambdaExtraRPC -> v
getInHandlerStorage k e = fromRight (error "Unpacking failed") $ lUnpackValueRaw $ fromMaybe (error "Key not found in Handler storage") $ Map.lookup k (leHandlerStorageRPC e)
|
|
dbbccb91758a03a659850ee6d8026d0e5da7976e2b6f8a4f3ade270261da36d7 | facebook/flow | comment_test.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open OUnit2
open Ast_builder
open Layout_test_utils
open Layout_generator_test_utils
module L = Layout_builder
let tests =
[
( "block" >:: fun ctxt ->
let comment = Ast_builder.Comments.block "test" in
let layout = Js_layout_generator.comment comment in
assert_layout ~ctxt L.(loc (fused [atom "/*"; atom "test"; atom "*/"])) layout;
assert_output ~ctxt "/*test*/" layout;
assert_output ~ctxt ~pretty:true "/*test*/" layout
);
( "line" >:: fun ctxt ->
let comment = Ast_builder.Comments.line "test" in
let layout = Js_layout_generator.comment comment in
assert_layout ~ctxt L.(loc (fused [atom "//"; atom "test"; Layout.Newline])) layout;
assert_output ~ctxt "//test\n" layout;
assert_output ~ctxt ~pretty:true "//test\n" layout
);
( "leading" >:: fun ctxt ->
(* Line with single newline *)
let ast = expression_of_string "//L\nA" in
assert_expression ~ctxt "//L\nA" ast;
assert_expression ~ctxt ~pretty:true "//L\nA" ast;
Line with two newlines
let ast = expression_of_string "//L\n\nA" in
assert_expression ~ctxt "//L\nA" ast;
assert_expression ~ctxt ~pretty:true "//L\n\nA" ast;
Line with more than two newlines
let ast = expression_of_string "//L\n\n\nA" in
assert_expression ~ctxt "//L\nA" ast;
assert_expression ~ctxt ~pretty:true "//L\n\nA" ast;
(* Block with no newline *)
let ast = expression_of_string "/*L*/A" in
assert_expression ~ctxt "/*L*/A" ast;
assert_expression ~ctxt ~pretty:true "/*L*/ A" ast;
(* Block with single newline *)
let ast = expression_of_string "/*L*/\nA" in
assert_expression ~ctxt "/*L*/A" ast;
assert_expression ~ctxt ~pretty:true "/*L*/\nA" ast;
Block with two newlines
let ast = expression_of_string "/*L*/\n\nA" in
assert_expression ~ctxt "/*L*/A" ast;
assert_expression ~ctxt ~pretty:true "/*L*/\n\nA" ast;
Block with more than two newlines
let ast = expression_of_string "/*L*/\n\n\nA" in
assert_expression ~ctxt "/*L*/A" ast;
assert_expression ~ctxt ~pretty:true "/*L*/\n\nA" ast;
(* Multiple leading comments *)
let ast = expression_of_string "//L1\n//L2\nA" in
assert_expression ~ctxt "//L1\n//L2\nA" ast;
assert_expression ~ctxt ~pretty:true "//L1\n//L2\nA" ast
);
( "trailing" >:: fun ctxt ->
(* After node with no newline *)
let ast = expression_of_string "A//T\n" in
assert_expression ~ctxt "A//T\n" ast;
assert_expression ~ctxt ~pretty:true "A //T\n" ast;
(* After node with single newline *)
let ast = expression_of_string "A\n//T\n" in
assert_expression ~ctxt "A//T\n" ast;
assert_expression ~ctxt ~pretty:true "A\n//T\n" ast;
After node with two newlines
let ast = expression_of_string "A\n\n//T\n" in
assert_expression ~ctxt "A//T\n" ast;
assert_expression ~ctxt ~pretty:true "A\n\n//T\n" ast;
After node with more than two newlines
let ast = expression_of_string "A\n\n\n//T\n" in
assert_expression ~ctxt "A//T\n" ast;
assert_expression ~ctxt ~pretty:true "A\n\n//T\n" ast;
(* After line with single newline *)
let ast = expression_of_string "A\n//T1\n//T2\n" in
assert_expression ~ctxt "A//T1\n//T2\n" ast;
assert_expression ~ctxt ~pretty:true "A\n//T1\n//T2\n" ast;
After line with two newlines
let ast = expression_of_string "A\n//T1\n\n//T2\n" in
assert_expression ~ctxt "A//T1\n//T2\n" ast;
assert_expression ~ctxt ~pretty:true "A\n//T1\n\n//T2\n" ast;
After line with more than two newlines
let ast = expression_of_string "A\n//T1\n\n\n//T2\n" in
assert_expression ~ctxt "A//T1\n//T2\n" ast;
assert_expression ~ctxt ~pretty:true "A\n//T1\n\n//T2\n" ast;
(* After block with no newline *)
let ast = expression_of_string "A\n/*T1*//*T2*/" in
assert_expression ~ctxt "A/*T1*//*T2*/" ast;
assert_expression ~ctxt ~pretty:true "A\n/*T1*/ /*T2*/" ast;
(* After block with single newline *)
let ast = expression_of_string "A\n/*T1*/\n/*T2*/" in
assert_expression ~ctxt "A/*T1*//*T2*/" ast;
assert_expression ~ctxt ~pretty:true "A\n/*T1*/\n/*T2*/" ast;
After block with two newlines
let ast = expression_of_string "A\n/*T1*/\n\n/*T2*/" in
assert_expression ~ctxt "A/*T1*//*T2*/" ast;
assert_expression ~ctxt ~pretty:true "A\n/*T1*/\n\n/*T2*/" ast;
After block with more than two newlines
let ast = expression_of_string "A\n/*T1*/\n\n\n/*T2*/" in
assert_expression ~ctxt "A/*T1*//*T2*/" ast;
assert_expression ~ctxt ~pretty:true "A\n/*T1*/\n\n/*T2*/" ast
);
( "statements_separated_by_comments" >:: fun ctxt ->
assert_program_string ~ctxt ~pretty:true "A;\n//L\nB;";
assert_program_string ~ctxt ~pretty:true "A;\n/*L1*/\n/*L2*/\nB;";
assert_program_string ~ctxt ~pretty:true "A; //L\nB;";
assert_program_string ~ctxt ~pretty:true "A; /*T1\nT2*/\nB;"
);
( "assignment_expression" >:: fun ctxt ->
assert_expression_string ~ctxt ~pretty:true "A = //L\nB";
assert_expression_string ~ctxt ~pretty:true "A =\n//L\nB"
);
( "array" >:: fun ctxt ->
assert_expression_string ~ctxt "[/*I*/]";
assert_expression_string ~ctxt ~pretty:true "[\n a,\n /*I*/\n]";
assert_expression_string ~ctxt ~pretty:true "[\n a,\n \n /*I*/\n]";
assert_expression_string ~ctxt ~pretty:true "[\n a //T\n ,\n \n //L\n b,\n]"
);
( "array_pattern" >:: fun ctxt ->
assert_statement_string ~ctxt "var[/*I*/];";
assert_statement_string ~ctxt ~pretty:true "var [\n a\n /*I*/\n];";
assert_statement_string ~ctxt ~pretty:true "var [\n a\n \n /*I*/\n];"
);
( "arrow_function_body" >:: fun ctxt ->
(* Body without leading comment separated by space *)
assert_expression_string ~ctxt ~pretty:true "() => <A />";
(* Body with leading comment separated by newline *)
assert_expression_string ~ctxt ~pretty:true "() =>\n//L\n<A />"
);
( "arrow_function_params" >:: fun ctxt ->
assert_expression_string ~ctxt "/*L*/()/*T*/=>{}";
assert_expression ~ctxt "/*L*/A/*T*/=>{}" (expression_of_string "/*L*/(A)/*T*/=>{}");
assert_expression_string ~ctxt "(/*L*/A/*T*/)=>{}";
assert_expression_string ~ctxt "//L\nA=>{}"
);
("block" >:: fun ctxt -> assert_statement_string ~ctxt "{/*I*/}");
("break" >:: fun ctxt -> assert_statement_string ~ctxt "break;/*T*/");
( "binary_expression" >:: fun ctxt ->
assert_expression_string ~ctxt ~pretty:true "a + //L\nb";
assert_expression_string ~ctxt ~pretty:true "a + //L\n+b";
assert_expression_string ~ctxt ~pretty:true "a + \n//L\nb";
assert_expression_string ~ctxt ~pretty:true "a + \n//L\n+b"
);
( "call" >:: fun ctxt ->
let a80 = String.make 80 'a' in
assert_expression_string ~ctxt "foo(/*I*/)";
assert_expression_string ~ctxt ~pretty:true ("foo(\n " ^ a80 ^ ",\n /*I*/\n)");
assert_expression_string ~ctxt ~pretty:true "foo(\n a,\n \n /*I*/\n)"
);
( "call_type_args" >:: fun ctxt ->
let a80 = String.make 80 'a' in
assert_expression_string ~ctxt "foo</*I*/>()";
assert_expression_string ~ctxt ~pretty:true ("foo<\n " ^ a80 ^ ",\n /*I*/\n>()");
assert_expression_string ~ctxt ~pretty:true "foo<\n a,\n \n /*I*/\n>()"
);
("class_private_field" >:: fun ctxt -> assert_expression_string ~ctxt "class C{/*L*/#A/*T*/;}");
("continue" >:: fun ctxt -> assert_statement_string ~ctxt "continue;/*T*/");
("debugger" >:: fun ctxt -> assert_statement_string ~ctxt "debugger;/*T*/");
("declare_module" >:: fun ctxt -> assert_statement_string ~ctxt "declare module A{/*I*/}");
("do_while" >:: fun ctxt -> assert_statement_string ~ctxt "do{}while(A);/*T*/");
( "enum" >:: fun ctxt ->
assert_statement_string ~ctxt "enum E of boolean{A=/*L*/true/*T*/,}";
assert_statement_string ~ctxt "enum E of number{A=/*L*/1/*T*/,}";
assert_statement_string ~ctxt {|enum E of string{A=/*L*/"A"/*T*/,}|}
);
("function_body" >:: fun ctxt -> assert_statement_string ~ctxt "function foo(){/*I*/}");
( "function_params" >:: fun ctxt ->
let ast = expression_of_string "function foo/*L*/()/*T*/\n{}" in
assert_expression ~ctxt "function foo/*L*/()/*T*/{}" ast;
assert_expression_string ~ctxt "(/*I*/)=>{}";
assert_expression_string ~ctxt ~pretty:true "(\n a,\n /*I*/\n) => {}";
assert_expression_string ~ctxt ~pretty:true "(\n a,\n \n /*I*/\n) => {}"
);
( "function_type_params" >:: fun ctxt ->
assert_statement_string ~ctxt "type T=(/*I*/)=>a;";
assert_statement_string ~ctxt ~pretty:true "type T = (\n a\n /*I*/\n) => b;";
assert_statement_string ~ctxt ~pretty:true "type T = (\n a\n \n /*I*/\n) => b;"
);
( "if_statement" >:: fun ctxt ->
assert_statement_string ~ctxt ~pretty:true "if (true) {} //L\n else {}";
assert_statement_string ~ctxt ~pretty:true "if (true) {}\n//L\nelse {}"
);
("jsx_expression_container" >:: fun ctxt -> assert_expression_string ~ctxt "<A>{/*I*/}</A>");
("literal" >:: fun ctxt -> assert_expression_string ~ctxt "//L\n1//T\n");
( "logical_expression" >:: fun ctxt ->
assert_expression_string ~ctxt ~pretty:true "a && //L\n b";
assert_expression_string ~ctxt ~pretty:true "a &&\n //L\n b";
assert_expression_string ~ctxt ~pretty:true "(\n //L\n a &&\n b\n) ??\n c"
);
("tagged_template" >:: fun ctxt -> assert_expression_string ~ctxt "/*L1*/A/*L2*/`B`/*T*/");
( "member_expression" >:: fun ctxt ->
assert_expression_string ~ctxt "A./*L*/B/*T*/";
assert_expression_string ~ctxt "A./*L*/#B/*T*/";
assert_expression_string ~ctxt ~pretty:true "foo //C\n.bar";
assert_expression_string ~ctxt ~pretty:true "foo /*C*/\n.bar";
assert_expression_string ~ctxt ~pretty:true "foo /*C*/.bar";
assert_expression_string ~ctxt ~pretty:true "foo\n//C\n.bar";
assert_expression_string ~ctxt ~pretty:true "foo\n/*C*/\n.bar";
assert_expression_string ~ctxt ~pretty:true "foo\n/*C*/.bar";
assert_expression_string ~ctxt ~pretty:true "foo[\n //L\n a\n]"
);
( "new" >:: fun ctxt ->
let a80 = String.make 80 'a' in
assert_expression_string ~ctxt "new Foo(/*I*/)";
assert_expression_string ~ctxt ~pretty:true ("new Foo(\n " ^ a80 ^ ",\n /*I*/\n)");
assert_expression_string ~ctxt ~pretty:true "new Foo(\n a,\n \n /*I*/\n)";
assert_expression_string ~ctxt ~pretty:true "new (\n //L\n A ||\n B\n)"
);
( "object" >:: fun ctxt ->
assert_expression_string ~ctxt "{/*I*/}";
assert_expression_string ~ctxt ~pretty:true "{\n a,\n /*I*/\n}";
assert_expression_string ~ctxt ~pretty:true "{\n a,\n \n /*I*/\n}";
assert_expression_string ~ctxt ~pretty:true "{\n a: //L\n b,\n}";
assert_expression_string ~ctxt ~pretty:true "{\n a:\n //L\n b,\n}"
);
( "object_pattern" >:: fun ctxt ->
let b80 = String.make 80 'b' in
assert_statement_string ~ctxt "var{/*I*/};";
assert_statement_string ~ctxt ~pretty:true ("var {\n a,\n " ^ b80 ^ "\n /*I*/\n};");
assert_statement_string ~ctxt ~pretty:true ("var {\n a,\n " ^ b80 ^ "\n \n /*I*/\n};")
);
( "object_type" >:: fun ctxt ->
assert_statement_string ~ctxt "type T={/*I*/};";
assert_statement_string ~ctxt "type T={a:any,/*I*/};";
assert_statement_string
~ctxt
~pretty:true
"type T = {\n a: any,\n /*I1*/\n /*I2*/\n ...\n};";
assert_statement
~ctxt
~pretty:true
"type T = {\n a: any,\n \n /*I1*/\n /*I2*/\n ...\n};"
(statement_of_string "type T = {\n a: any,\n ...\n /*I1*/\n /*I2*/\n};");
assert_statement_string
~ctxt
~pretty:true
"type T = {\n a: any,\n /*I1*/\n \n /*I2*/\n ...\n};";
(* Leading comments on variance nodes are included in comment bounds of property *)
assert_statement_string ~ctxt ~pretty:true "type T = {\n +a: any,\n //L\n +b: any,\n};"
);
( "parenthesized_expression" >:: fun ctxt ->
assert_expression_string ~ctxt ~pretty:true "(\n //L\n a + b\n) * c"
);
( "return" >:: fun ctxt ->
assert_statement_string ~ctxt "return;/*T*/";
assert_statement_string ~ctxt ~pretty:true "return (\n //L\n x\n);";
assert_statement_string ~ctxt ~pretty:true "return /*L*/ x;"
);
( "switch_case" >:: fun ctxt ->
assert_statement_string ~ctxt ~pretty:true "switch (x) {\n case 1: /*T*/\n break;\n}"
);
( "throw" >:: fun ctxt ->
assert_statement_string ~ctxt "throw A;/*T*/";
assert_statement_string ~ctxt ~pretty:true "throw (\n //L\n x\n);";
assert_statement_string ~ctxt ~pretty:true "throw /*L*/ x;"
);
( "type_alias" >:: fun ctxt ->
assert_statement_string ~ctxt ~pretty:true "type A = //L\nB;";
assert_statement_string ~ctxt ~pretty:true "type A =\n//L\nB;"
);
( "type_args" >:: fun ctxt ->
let a80 = String.make 80 'a' in
assert_statement_string ~ctxt "type Foo=Bar</*I*/>;";
assert_statement_string ~ctxt ~pretty:true ("type Foo = Bar<\n " ^ a80 ^ ",\n /*I*/\n>;");
assert_statement_string ~ctxt ~pretty:true "type Foo = Bar<\n a,\n \n /*I*/\n>;"
);
( "type_params" >:: fun ctxt ->
let a80 = String.make 80 'a' in
assert_expression_string ~ctxt ~pretty:true ("<\n " ^ a80 ^ ",\n /*I*/\n>() => {}");
assert_expression_string ~ctxt ~pretty:true ("<\n " ^ a80 ^ ",\n \n /*I*/\n>() => {}")
);
( "union_type" >:: fun ctxt ->
let b80 = String.make 80 'b' in
assert_statement_string ~ctxt ~pretty:true ("type Foo =\n//L\n| a\n | " ^ b80 ^ ";");
assert_statement_string ~ctxt ~pretty:true ("type Foo = \n | a\n | //L\n " ^ b80 ^ ";");
assert_statement_string ~ctxt ~pretty:true ("type Foo = \n | a\n |\n //L\n " ^ b80 ^ ";")
);
( "variable_declaration" >:: fun ctxt ->
assert_statement_string ~ctxt "let A=B;/*T*/";
assert_statement_string ~ctxt ~pretty:true "let A = //L\nB;";
assert_statement_string ~ctxt ~pretty:true "let A =\n//L\nB;"
);
]
| null | https://raw.githubusercontent.com/facebook/flow/741104e69c43057ebd32804dd6bcc1b5e97548ea/src/parser_utils/output/__tests__/js_layout_generator/comment_test.ml | ocaml | Line with single newline
Block with no newline
Block with single newline
Multiple leading comments
After node with no newline
After node with single newline
After line with single newline
After block with no newline
After block with single newline
Body without leading comment separated by space
Body with leading comment separated by newline
Leading comments on variance nodes are included in comment bounds of property |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open OUnit2
open Ast_builder
open Layout_test_utils
open Layout_generator_test_utils
module L = Layout_builder
let tests =
[
( "block" >:: fun ctxt ->
let comment = Ast_builder.Comments.block "test" in
let layout = Js_layout_generator.comment comment in
assert_layout ~ctxt L.(loc (fused [atom "/*"; atom "test"; atom "*/"])) layout;
assert_output ~ctxt "/*test*/" layout;
assert_output ~ctxt ~pretty:true "/*test*/" layout
);
( "line" >:: fun ctxt ->
let comment = Ast_builder.Comments.line "test" in
let layout = Js_layout_generator.comment comment in
assert_layout ~ctxt L.(loc (fused [atom "//"; atom "test"; Layout.Newline])) layout;
assert_output ~ctxt "//test\n" layout;
assert_output ~ctxt ~pretty:true "//test\n" layout
);
( "leading" >:: fun ctxt ->
let ast = expression_of_string "//L\nA" in
assert_expression ~ctxt "//L\nA" ast;
assert_expression ~ctxt ~pretty:true "//L\nA" ast;
Line with two newlines
let ast = expression_of_string "//L\n\nA" in
assert_expression ~ctxt "//L\nA" ast;
assert_expression ~ctxt ~pretty:true "//L\n\nA" ast;
Line with more than two newlines
let ast = expression_of_string "//L\n\n\nA" in
assert_expression ~ctxt "//L\nA" ast;
assert_expression ~ctxt ~pretty:true "//L\n\nA" ast;
let ast = expression_of_string "/*L*/A" in
assert_expression ~ctxt "/*L*/A" ast;
assert_expression ~ctxt ~pretty:true "/*L*/ A" ast;
let ast = expression_of_string "/*L*/\nA" in
assert_expression ~ctxt "/*L*/A" ast;
assert_expression ~ctxt ~pretty:true "/*L*/\nA" ast;
Block with two newlines
let ast = expression_of_string "/*L*/\n\nA" in
assert_expression ~ctxt "/*L*/A" ast;
assert_expression ~ctxt ~pretty:true "/*L*/\n\nA" ast;
Block with more than two newlines
let ast = expression_of_string "/*L*/\n\n\nA" in
assert_expression ~ctxt "/*L*/A" ast;
assert_expression ~ctxt ~pretty:true "/*L*/\n\nA" ast;
let ast = expression_of_string "//L1\n//L2\nA" in
assert_expression ~ctxt "//L1\n//L2\nA" ast;
assert_expression ~ctxt ~pretty:true "//L1\n//L2\nA" ast
);
( "trailing" >:: fun ctxt ->
let ast = expression_of_string "A//T\n" in
assert_expression ~ctxt "A//T\n" ast;
assert_expression ~ctxt ~pretty:true "A //T\n" ast;
let ast = expression_of_string "A\n//T\n" in
assert_expression ~ctxt "A//T\n" ast;
assert_expression ~ctxt ~pretty:true "A\n//T\n" ast;
After node with two newlines
let ast = expression_of_string "A\n\n//T\n" in
assert_expression ~ctxt "A//T\n" ast;
assert_expression ~ctxt ~pretty:true "A\n\n//T\n" ast;
After node with more than two newlines
let ast = expression_of_string "A\n\n\n//T\n" in
assert_expression ~ctxt "A//T\n" ast;
assert_expression ~ctxt ~pretty:true "A\n\n//T\n" ast;
let ast = expression_of_string "A\n//T1\n//T2\n" in
assert_expression ~ctxt "A//T1\n//T2\n" ast;
assert_expression ~ctxt ~pretty:true "A\n//T1\n//T2\n" ast;
After line with two newlines
let ast = expression_of_string "A\n//T1\n\n//T2\n" in
assert_expression ~ctxt "A//T1\n//T2\n" ast;
assert_expression ~ctxt ~pretty:true "A\n//T1\n\n//T2\n" ast;
After line with more than two newlines
let ast = expression_of_string "A\n//T1\n\n\n//T2\n" in
assert_expression ~ctxt "A//T1\n//T2\n" ast;
assert_expression ~ctxt ~pretty:true "A\n//T1\n\n//T2\n" ast;
let ast = expression_of_string "A\n/*T1*//*T2*/" in
assert_expression ~ctxt "A/*T1*//*T2*/" ast;
assert_expression ~ctxt ~pretty:true "A\n/*T1*/ /*T2*/" ast;
let ast = expression_of_string "A\n/*T1*/\n/*T2*/" in
assert_expression ~ctxt "A/*T1*//*T2*/" ast;
assert_expression ~ctxt ~pretty:true "A\n/*T1*/\n/*T2*/" ast;
After block with two newlines
let ast = expression_of_string "A\n/*T1*/\n\n/*T2*/" in
assert_expression ~ctxt "A/*T1*//*T2*/" ast;
assert_expression ~ctxt ~pretty:true "A\n/*T1*/\n\n/*T2*/" ast;
After block with more than two newlines
let ast = expression_of_string "A\n/*T1*/\n\n\n/*T2*/" in
assert_expression ~ctxt "A/*T1*//*T2*/" ast;
assert_expression ~ctxt ~pretty:true "A\n/*T1*/\n\n/*T2*/" ast
);
( "statements_separated_by_comments" >:: fun ctxt ->
assert_program_string ~ctxt ~pretty:true "A;\n//L\nB;";
assert_program_string ~ctxt ~pretty:true "A;\n/*L1*/\n/*L2*/\nB;";
assert_program_string ~ctxt ~pretty:true "A; //L\nB;";
assert_program_string ~ctxt ~pretty:true "A; /*T1\nT2*/\nB;"
);
( "assignment_expression" >:: fun ctxt ->
assert_expression_string ~ctxt ~pretty:true "A = //L\nB";
assert_expression_string ~ctxt ~pretty:true "A =\n//L\nB"
);
( "array" >:: fun ctxt ->
assert_expression_string ~ctxt "[/*I*/]";
assert_expression_string ~ctxt ~pretty:true "[\n a,\n /*I*/\n]";
assert_expression_string ~ctxt ~pretty:true "[\n a,\n \n /*I*/\n]";
assert_expression_string ~ctxt ~pretty:true "[\n a //T\n ,\n \n //L\n b,\n]"
);
( "array_pattern" >:: fun ctxt ->
assert_statement_string ~ctxt "var[/*I*/];";
assert_statement_string ~ctxt ~pretty:true "var [\n a\n /*I*/\n];";
assert_statement_string ~ctxt ~pretty:true "var [\n a\n \n /*I*/\n];"
);
( "arrow_function_body" >:: fun ctxt ->
assert_expression_string ~ctxt ~pretty:true "() => <A />";
assert_expression_string ~ctxt ~pretty:true "() =>\n//L\n<A />"
);
( "arrow_function_params" >:: fun ctxt ->
assert_expression_string ~ctxt "/*L*/()/*T*/=>{}";
assert_expression ~ctxt "/*L*/A/*T*/=>{}" (expression_of_string "/*L*/(A)/*T*/=>{}");
assert_expression_string ~ctxt "(/*L*/A/*T*/)=>{}";
assert_expression_string ~ctxt "//L\nA=>{}"
);
("block" >:: fun ctxt -> assert_statement_string ~ctxt "{/*I*/}");
("break" >:: fun ctxt -> assert_statement_string ~ctxt "break;/*T*/");
( "binary_expression" >:: fun ctxt ->
assert_expression_string ~ctxt ~pretty:true "a + //L\nb";
assert_expression_string ~ctxt ~pretty:true "a + //L\n+b";
assert_expression_string ~ctxt ~pretty:true "a + \n//L\nb";
assert_expression_string ~ctxt ~pretty:true "a + \n//L\n+b"
);
( "call" >:: fun ctxt ->
let a80 = String.make 80 'a' in
assert_expression_string ~ctxt "foo(/*I*/)";
assert_expression_string ~ctxt ~pretty:true ("foo(\n " ^ a80 ^ ",\n /*I*/\n)");
assert_expression_string ~ctxt ~pretty:true "foo(\n a,\n \n /*I*/\n)"
);
( "call_type_args" >:: fun ctxt ->
let a80 = String.make 80 'a' in
assert_expression_string ~ctxt "foo</*I*/>()";
assert_expression_string ~ctxt ~pretty:true ("foo<\n " ^ a80 ^ ",\n /*I*/\n>()");
assert_expression_string ~ctxt ~pretty:true "foo<\n a,\n \n /*I*/\n>()"
);
("class_private_field" >:: fun ctxt -> assert_expression_string ~ctxt "class C{/*L*/#A/*T*/;}");
("continue" >:: fun ctxt -> assert_statement_string ~ctxt "continue;/*T*/");
("debugger" >:: fun ctxt -> assert_statement_string ~ctxt "debugger;/*T*/");
("declare_module" >:: fun ctxt -> assert_statement_string ~ctxt "declare module A{/*I*/}");
("do_while" >:: fun ctxt -> assert_statement_string ~ctxt "do{}while(A);/*T*/");
( "enum" >:: fun ctxt ->
assert_statement_string ~ctxt "enum E of boolean{A=/*L*/true/*T*/,}";
assert_statement_string ~ctxt "enum E of number{A=/*L*/1/*T*/,}";
assert_statement_string ~ctxt {|enum E of string{A=/*L*/"A"/*T*/,}|}
);
("function_body" >:: fun ctxt -> assert_statement_string ~ctxt "function foo(){/*I*/}");
( "function_params" >:: fun ctxt ->
let ast = expression_of_string "function foo/*L*/()/*T*/\n{}" in
assert_expression ~ctxt "function foo/*L*/()/*T*/{}" ast;
assert_expression_string ~ctxt "(/*I*/)=>{}";
assert_expression_string ~ctxt ~pretty:true "(\n a,\n /*I*/\n) => {}";
assert_expression_string ~ctxt ~pretty:true "(\n a,\n \n /*I*/\n) => {}"
);
( "function_type_params" >:: fun ctxt ->
assert_statement_string ~ctxt "type T=(/*I*/)=>a;";
assert_statement_string ~ctxt ~pretty:true "type T = (\n a\n /*I*/\n) => b;";
assert_statement_string ~ctxt ~pretty:true "type T = (\n a\n \n /*I*/\n) => b;"
);
( "if_statement" >:: fun ctxt ->
assert_statement_string ~ctxt ~pretty:true "if (true) {} //L\n else {}";
assert_statement_string ~ctxt ~pretty:true "if (true) {}\n//L\nelse {}"
);
("jsx_expression_container" >:: fun ctxt -> assert_expression_string ~ctxt "<A>{/*I*/}</A>");
("literal" >:: fun ctxt -> assert_expression_string ~ctxt "//L\n1//T\n");
( "logical_expression" >:: fun ctxt ->
assert_expression_string ~ctxt ~pretty:true "a && //L\n b";
assert_expression_string ~ctxt ~pretty:true "a &&\n //L\n b";
assert_expression_string ~ctxt ~pretty:true "(\n //L\n a &&\n b\n) ??\n c"
);
("tagged_template" >:: fun ctxt -> assert_expression_string ~ctxt "/*L1*/A/*L2*/`B`/*T*/");
( "member_expression" >:: fun ctxt ->
assert_expression_string ~ctxt "A./*L*/B/*T*/";
assert_expression_string ~ctxt "A./*L*/#B/*T*/";
assert_expression_string ~ctxt ~pretty:true "foo //C\n.bar";
assert_expression_string ~ctxt ~pretty:true "foo /*C*/\n.bar";
assert_expression_string ~ctxt ~pretty:true "foo /*C*/.bar";
assert_expression_string ~ctxt ~pretty:true "foo\n//C\n.bar";
assert_expression_string ~ctxt ~pretty:true "foo\n/*C*/\n.bar";
assert_expression_string ~ctxt ~pretty:true "foo\n/*C*/.bar";
assert_expression_string ~ctxt ~pretty:true "foo[\n //L\n a\n]"
);
( "new" >:: fun ctxt ->
let a80 = String.make 80 'a' in
assert_expression_string ~ctxt "new Foo(/*I*/)";
assert_expression_string ~ctxt ~pretty:true ("new Foo(\n " ^ a80 ^ ",\n /*I*/\n)");
assert_expression_string ~ctxt ~pretty:true "new Foo(\n a,\n \n /*I*/\n)";
assert_expression_string ~ctxt ~pretty:true "new (\n //L\n A ||\n B\n)"
);
( "object" >:: fun ctxt ->
assert_expression_string ~ctxt "{/*I*/}";
assert_expression_string ~ctxt ~pretty:true "{\n a,\n /*I*/\n}";
assert_expression_string ~ctxt ~pretty:true "{\n a,\n \n /*I*/\n}";
assert_expression_string ~ctxt ~pretty:true "{\n a: //L\n b,\n}";
assert_expression_string ~ctxt ~pretty:true "{\n a:\n //L\n b,\n}"
);
( "object_pattern" >:: fun ctxt ->
let b80 = String.make 80 'b' in
assert_statement_string ~ctxt "var{/*I*/};";
assert_statement_string ~ctxt ~pretty:true ("var {\n a,\n " ^ b80 ^ "\n /*I*/\n};");
assert_statement_string ~ctxt ~pretty:true ("var {\n a,\n " ^ b80 ^ "\n \n /*I*/\n};")
);
( "object_type" >:: fun ctxt ->
assert_statement_string ~ctxt "type T={/*I*/};";
assert_statement_string ~ctxt "type T={a:any,/*I*/};";
assert_statement_string
~ctxt
~pretty:true
"type T = {\n a: any,\n /*I1*/\n /*I2*/\n ...\n};";
assert_statement
~ctxt
~pretty:true
"type T = {\n a: any,\n \n /*I1*/\n /*I2*/\n ...\n};"
(statement_of_string "type T = {\n a: any,\n ...\n /*I1*/\n /*I2*/\n};");
assert_statement_string
~ctxt
~pretty:true
"type T = {\n a: any,\n /*I1*/\n \n /*I2*/\n ...\n};";
assert_statement_string ~ctxt ~pretty:true "type T = {\n +a: any,\n //L\n +b: any,\n};"
);
( "parenthesized_expression" >:: fun ctxt ->
assert_expression_string ~ctxt ~pretty:true "(\n //L\n a + b\n) * c"
);
( "return" >:: fun ctxt ->
assert_statement_string ~ctxt "return;/*T*/";
assert_statement_string ~ctxt ~pretty:true "return (\n //L\n x\n);";
assert_statement_string ~ctxt ~pretty:true "return /*L*/ x;"
);
( "switch_case" >:: fun ctxt ->
assert_statement_string ~ctxt ~pretty:true "switch (x) {\n case 1: /*T*/\n break;\n}"
);
( "throw" >:: fun ctxt ->
assert_statement_string ~ctxt "throw A;/*T*/";
assert_statement_string ~ctxt ~pretty:true "throw (\n //L\n x\n);";
assert_statement_string ~ctxt ~pretty:true "throw /*L*/ x;"
);
( "type_alias" >:: fun ctxt ->
assert_statement_string ~ctxt ~pretty:true "type A = //L\nB;";
assert_statement_string ~ctxt ~pretty:true "type A =\n//L\nB;"
);
( "type_args" >:: fun ctxt ->
let a80 = String.make 80 'a' in
assert_statement_string ~ctxt "type Foo=Bar</*I*/>;";
assert_statement_string ~ctxt ~pretty:true ("type Foo = Bar<\n " ^ a80 ^ ",\n /*I*/\n>;");
assert_statement_string ~ctxt ~pretty:true "type Foo = Bar<\n a,\n \n /*I*/\n>;"
);
( "type_params" >:: fun ctxt ->
let a80 = String.make 80 'a' in
assert_expression_string ~ctxt ~pretty:true ("<\n " ^ a80 ^ ",\n /*I*/\n>() => {}");
assert_expression_string ~ctxt ~pretty:true ("<\n " ^ a80 ^ ",\n \n /*I*/\n>() => {}")
);
( "union_type" >:: fun ctxt ->
let b80 = String.make 80 'b' in
assert_statement_string ~ctxt ~pretty:true ("type Foo =\n//L\n| a\n | " ^ b80 ^ ";");
assert_statement_string ~ctxt ~pretty:true ("type Foo = \n | a\n | //L\n " ^ b80 ^ ";");
assert_statement_string ~ctxt ~pretty:true ("type Foo = \n | a\n |\n //L\n " ^ b80 ^ ";")
);
( "variable_declaration" >:: fun ctxt ->
assert_statement_string ~ctxt "let A=B;/*T*/";
assert_statement_string ~ctxt ~pretty:true "let A = //L\nB;";
assert_statement_string ~ctxt ~pretty:true "let A =\n//L\nB;"
);
]
|
7227c66b0f4cdd1db3beb706295b4b72edbb88ebc8153606d1e0aeec3f3a0c60 | pirapira/coq2rust | program.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Pp
open Errors
open Util
open Names
open Term
let make_dir l = DirPath.make (List.rev_map Id.of_string l)
let find_reference locstr dir s =
let sp = Libnames.make_path (make_dir dir) (Id.of_string s) in
try Nametab.global_of_path sp
with Not_found ->
anomaly ~label:locstr (Pp.str "cannot find" ++ spc () ++ Libnames.pr_path sp)
let coq_reference locstr dir s = find_reference locstr ("Coq"::dir) s
let coq_constant locstr dir s = Universes.constr_of_global (coq_reference locstr dir s)
let init_constant dir s () = coq_constant "Program" dir s
let init_reference dir s () = coq_reference "Program" dir s
let papp evdref r args =
let gr = delayed_force r in
mkApp (Evarutil.e_new_global evdref gr, args)
let sig_typ = init_reference ["Init"; "Specif"] "sig"
let sig_intro = init_reference ["Init"; "Specif"] "exist"
let sig_proj1 = init_reference ["Init"; "Specif"] "proj1_sig"
let sigT_typ = init_reference ["Init"; "Specif"] "sigT"
let sigT_intro = init_reference ["Init"; "Specif"] "existT"
let sigT_proj1 = init_reference ["Init"; "Specif"] "projT1"
let sigT_proj2 = init_reference ["Init"; "Specif"] "projT2"
let prod_typ = init_reference ["Init"; "Datatypes"] "prod"
let prod_intro = init_reference ["Init"; "Datatypes"] "pair"
let prod_proj1 = init_reference ["Init"; "Datatypes"] "fst"
let prod_proj2 = init_reference ["Init"; "Datatypes"] "snd"
let coq_eq_ind = init_reference ["Init"; "Logic"] "eq"
let coq_eq_refl = init_reference ["Init"; "Logic"] "eq_refl"
let coq_eq_refl_ref = init_reference ["Init"; "Logic"] "eq_refl"
let coq_eq_rect = init_reference ["Init"; "Logic"] "eq_rect"
let coq_JMeq_ind = init_reference ["Logic";"JMeq"] "JMeq"
let coq_JMeq_refl = init_reference ["Logic";"JMeq"] "JMeq_refl"
let coq_not = init_constant ["Init";"Logic"] "not"
let coq_and = init_constant ["Init";"Logic"] "and"
let mk_coq_not x = mkApp (delayed_force coq_not, [| x |])
let unsafe_fold_right f = function
hd :: tl -> List.fold_right f tl hd
| [] -> invalid_arg "unsafe_fold_right"
let mk_coq_and l =
let and_typ = delayed_force coq_and in
unsafe_fold_right
(fun c conj ->
mkApp (and_typ, [| c ; conj |]))
l
| null | https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/pretyping/program.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
********************************************************************** | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Pp
open Errors
open Util
open Names
open Term
let make_dir l = DirPath.make (List.rev_map Id.of_string l)
let find_reference locstr dir s =
let sp = Libnames.make_path (make_dir dir) (Id.of_string s) in
try Nametab.global_of_path sp
with Not_found ->
anomaly ~label:locstr (Pp.str "cannot find" ++ spc () ++ Libnames.pr_path sp)
let coq_reference locstr dir s = find_reference locstr ("Coq"::dir) s
let coq_constant locstr dir s = Universes.constr_of_global (coq_reference locstr dir s)
let init_constant dir s () = coq_constant "Program" dir s
let init_reference dir s () = coq_reference "Program" dir s
let papp evdref r args =
let gr = delayed_force r in
mkApp (Evarutil.e_new_global evdref gr, args)
let sig_typ = init_reference ["Init"; "Specif"] "sig"
let sig_intro = init_reference ["Init"; "Specif"] "exist"
let sig_proj1 = init_reference ["Init"; "Specif"] "proj1_sig"
let sigT_typ = init_reference ["Init"; "Specif"] "sigT"
let sigT_intro = init_reference ["Init"; "Specif"] "existT"
let sigT_proj1 = init_reference ["Init"; "Specif"] "projT1"
let sigT_proj2 = init_reference ["Init"; "Specif"] "projT2"
let prod_typ = init_reference ["Init"; "Datatypes"] "prod"
let prod_intro = init_reference ["Init"; "Datatypes"] "pair"
let prod_proj1 = init_reference ["Init"; "Datatypes"] "fst"
let prod_proj2 = init_reference ["Init"; "Datatypes"] "snd"
let coq_eq_ind = init_reference ["Init"; "Logic"] "eq"
let coq_eq_refl = init_reference ["Init"; "Logic"] "eq_refl"
let coq_eq_refl_ref = init_reference ["Init"; "Logic"] "eq_refl"
let coq_eq_rect = init_reference ["Init"; "Logic"] "eq_rect"
let coq_JMeq_ind = init_reference ["Logic";"JMeq"] "JMeq"
let coq_JMeq_refl = init_reference ["Logic";"JMeq"] "JMeq_refl"
let coq_not = init_constant ["Init";"Logic"] "not"
let coq_and = init_constant ["Init";"Logic"] "and"
let mk_coq_not x = mkApp (delayed_force coq_not, [| x |])
let unsafe_fold_right f = function
hd :: tl -> List.fold_right f tl hd
| [] -> invalid_arg "unsafe_fold_right"
let mk_coq_and l =
let and_typ = delayed_force coq_and in
unsafe_fold_right
(fun c conj ->
mkApp (and_typ, [| c ; conj |]))
l
|
f004e9712887b3928f2cadb0a43a52c7e0243fb676803f98b11ae5524560b39f | Dasudian/DSDIN | dsdc_db_backends.erl |
-module(dsdc_db_backends).
-export([ accounts_backend/0
, calls_backend/0
, channels_backend/0
, contracts_backend/0
, ns_backend/0
, ns_cache_backend/0
, oracles_backend/0
, oracles_cache_backend/0
]).
%% Callbacks for dsdu_mp_trees_db
-export([ db_commit/2
, db_get/2
, db_put/3
]).
%%%===================================================================
%%% API
%%%===================================================================
-spec accounts_backend() -> dsdu_mp_trees_db:db().
accounts_backend() ->
dsdu_mp_trees_db:new(db_spec(accounts)).
-spec calls_backend() -> dsdu_mp_trees_db:db().
calls_backend() ->
dsdu_mp_trees_db:new(db_spec(calls)).
-spec channels_backend() -> dsdu_mp_trees_db:db().
channels_backend() ->
dsdu_mp_trees_db:new(db_spec(channels)).
-spec contracts_backend() -> dsdu_mp_trees_db:db().
contracts_backend() ->
dsdu_mp_trees_db:new(db_spec(contracts)).
-spec ns_backend() -> dsdu_mp_trees_db:db().
ns_backend() ->
dsdu_mp_trees_db:new(db_spec(ns)).
-spec ns_cache_backend() -> dsdu_mp_trees_db:db().
ns_cache_backend() ->
dsdu_mp_trees_db:new(db_spec(ns_cache)).
-spec oracles_backend() -> dsdu_mp_trees_db:db().
oracles_backend() ->
dsdu_mp_trees_db:new(db_spec(oracles)).
-spec oracles_cache_backend() -> dsdu_mp_trees_db:db().
oracles_cache_backend() ->
dsdu_mp_trees_db:new(db_spec(oracles_cache)).
%%%===================================================================
Internal functions
%%%===================================================================
db_spec(Type) ->
#{ handle => Type
, cache => {gb_trees, gb_trees:empty()}
, get => {?MODULE, db_get}
, put => {?MODULE, db_put}
, commit => {?MODULE, db_commit}
}.
db_get(Key, {gb_trees, Tree}) ->
gb_trees:lookup(Key, Tree);
db_get(Key, accounts) ->
dsdc_db:find_accounts_node(Key);
db_get(Key, calls) ->
dsdc_db:find_calls_node(Key);
db_get(Key, channels) ->
dsdc_db:find_channels_node(Key);
db_get(Key, contracts) ->
dsdc_db:find_contracts_node(Key);
db_get(Key, ns) ->
dsdc_db:find_ns_node(Key);
db_get(Key, ns_cache) ->
dsdc_db:find_ns_cache_node(Key);
db_get(Key, oracles) ->
dsdc_db:find_oracles_node(Key);
db_get(Key, oracles_cache) ->
dsdc_db:find_oracles_cache_node(Key).
db_put(Key, Val, {gb_trees, Tree}) ->
{gb_trees, gb_trees:enter(Key, Val, Tree)};
db_put(Key, Val, accounts = Handle) ->
ok = dsdc_db:write_accounts_node(Key, Val),
{ok, Handle};
db_put(Key, Val, channels = Handle) ->
ok = dsdc_db:write_channels_node(Key, Val),
{ok, Handle};
db_put(Key, Val, ns = Handle) ->
ok = dsdc_db:write_ns_node(Key, Val),
{ok, Handle};
db_put(Key, Val, ns_cache = Handle) ->
ok = dsdc_db:write_ns_cache_node(Key, Val),
{ok, Handle};
db_put(Key, Val, calls = Handle) ->
ok = dsdc_db:write_calls_node(Key, Val),
{ok, Handle};
db_put(Key, Val, contracts = Handle) ->
ok = dsdc_db:write_contracts_node(Key, Val),
{ok, Handle};
db_put(Key, Val, oracles = Handle) ->
ok = dsdc_db:write_oracles_node(Key, Val),
{ok, Handle};
db_put(Key, Val, oracles_cache = Handle) ->
ok = dsdc_db:write_oracles_cache_node(Key, Val),
{ok, Handle}.
db_commit(Handle, {gb_trees, Cache}) ->
Iter = gb_trees:iterator(Cache),
db_commit_1(Handle, gb_trees:next(Iter)).
db_commit_1(Handle, none) -> {ok, Handle, {gb_trees, gb_trees:empty()}};
db_commit_1(Handle, {Key, Val, Iter}) ->
{ok, Handle} = db_put(Key, Val, Handle),
db_commit_1(Handle, gb_trees:next(Iter)).
| null | https://raw.githubusercontent.com/Dasudian/DSDIN/b27a437d8deecae68613604fffcbb9804a6f1729/apps/dsdcore/src/dsdc_db_backends.erl | erlang | Callbacks for dsdu_mp_trees_db
===================================================================
API
===================================================================
===================================================================
=================================================================== |
-module(dsdc_db_backends).
-export([ accounts_backend/0
, calls_backend/0
, channels_backend/0
, contracts_backend/0
, ns_backend/0
, ns_cache_backend/0
, oracles_backend/0
, oracles_cache_backend/0
]).
-export([ db_commit/2
, db_get/2
, db_put/3
]).
-spec accounts_backend() -> dsdu_mp_trees_db:db().
accounts_backend() ->
dsdu_mp_trees_db:new(db_spec(accounts)).
-spec calls_backend() -> dsdu_mp_trees_db:db().
calls_backend() ->
dsdu_mp_trees_db:new(db_spec(calls)).
-spec channels_backend() -> dsdu_mp_trees_db:db().
channels_backend() ->
dsdu_mp_trees_db:new(db_spec(channels)).
-spec contracts_backend() -> dsdu_mp_trees_db:db().
contracts_backend() ->
dsdu_mp_trees_db:new(db_spec(contracts)).
-spec ns_backend() -> dsdu_mp_trees_db:db().
ns_backend() ->
dsdu_mp_trees_db:new(db_spec(ns)).
-spec ns_cache_backend() -> dsdu_mp_trees_db:db().
ns_cache_backend() ->
dsdu_mp_trees_db:new(db_spec(ns_cache)).
-spec oracles_backend() -> dsdu_mp_trees_db:db().
oracles_backend() ->
dsdu_mp_trees_db:new(db_spec(oracles)).
-spec oracles_cache_backend() -> dsdu_mp_trees_db:db().
oracles_cache_backend() ->
dsdu_mp_trees_db:new(db_spec(oracles_cache)).
Internal functions
db_spec(Type) ->
#{ handle => Type
, cache => {gb_trees, gb_trees:empty()}
, get => {?MODULE, db_get}
, put => {?MODULE, db_put}
, commit => {?MODULE, db_commit}
}.
db_get(Key, {gb_trees, Tree}) ->
gb_trees:lookup(Key, Tree);
db_get(Key, accounts) ->
dsdc_db:find_accounts_node(Key);
db_get(Key, calls) ->
dsdc_db:find_calls_node(Key);
db_get(Key, channels) ->
dsdc_db:find_channels_node(Key);
db_get(Key, contracts) ->
dsdc_db:find_contracts_node(Key);
db_get(Key, ns) ->
dsdc_db:find_ns_node(Key);
db_get(Key, ns_cache) ->
dsdc_db:find_ns_cache_node(Key);
db_get(Key, oracles) ->
dsdc_db:find_oracles_node(Key);
db_get(Key, oracles_cache) ->
dsdc_db:find_oracles_cache_node(Key).
db_put(Key, Val, {gb_trees, Tree}) ->
{gb_trees, gb_trees:enter(Key, Val, Tree)};
db_put(Key, Val, accounts = Handle) ->
ok = dsdc_db:write_accounts_node(Key, Val),
{ok, Handle};
db_put(Key, Val, channels = Handle) ->
ok = dsdc_db:write_channels_node(Key, Val),
{ok, Handle};
db_put(Key, Val, ns = Handle) ->
ok = dsdc_db:write_ns_node(Key, Val),
{ok, Handle};
db_put(Key, Val, ns_cache = Handle) ->
ok = dsdc_db:write_ns_cache_node(Key, Val),
{ok, Handle};
db_put(Key, Val, calls = Handle) ->
ok = dsdc_db:write_calls_node(Key, Val),
{ok, Handle};
db_put(Key, Val, contracts = Handle) ->
ok = dsdc_db:write_contracts_node(Key, Val),
{ok, Handle};
db_put(Key, Val, oracles = Handle) ->
ok = dsdc_db:write_oracles_node(Key, Val),
{ok, Handle};
db_put(Key, Val, oracles_cache = Handle) ->
ok = dsdc_db:write_oracles_cache_node(Key, Val),
{ok, Handle}.
db_commit(Handle, {gb_trees, Cache}) ->
Iter = gb_trees:iterator(Cache),
db_commit_1(Handle, gb_trees:next(Iter)).
db_commit_1(Handle, none) -> {ok, Handle, {gb_trees, gb_trees:empty()}};
db_commit_1(Handle, {Key, Val, Iter}) ->
{ok, Handle} = db_put(Key, Val, Handle),
db_commit_1(Handle, gb_trees:next(Iter)).
|
93f7ea3463c37eb19e43c88de16534a7e8032a9f67b4b80674551856d36d7328 | zotonic/zotonic | m_mqtt_ticket.erl | @author < >
2020
%% @doc Handle tickets for out of band MQTT actions via controller_mqtt_transport.
Copyright 2020
%%
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(m_mqtt_ticket).
-behaviour(zotonic_model).
-export([
m_get/3,
m_post/3,
m_delete/3,
new_ticket/1,
exchange_ticket/2
]).
%% @doc Fetch the value for the key from a model source
-spec m_get( list(), zotonic_model:opt_msg(), z:context() ) -> zotonic_model:return().
m_get(_Path, _Msg, _Context) ->
{error, unknown_path}.
%% @doc Create a new ticket for the current context, must be called via a MQTT connection.
-spec m_post( list( binary() ), zotonic_model:opt_msg(), z:context() ) -> {ok, term()} | ok | {error, term()}.
m_post([ <<"new">> ], _Msg, Context) ->
new_ticket(Context);
m_post(_Path, _Msg, _Context) ->
{error, unknown_path}.
%% @doc Delete ticket.
-spec m_delete( list( binary() ), zotonic_model:opt_msg(), z:context() ) -> {ok, term()} | ok | {error, term()}.
m_delete([ Ticket ], _Msg, Context) when is_binary(Ticket) ->
delete_ticket(Ticket, Context);
m_delete(_Path, _Msg, _Context) ->
{error, unknown_path}.
%% @doc Create a new ticket. This store the context and returns an unique ticket-id. This ticket can later
%% be exchanged for the stored context. The stored context MUST contain the MQTT client-id.
-spec new_ticket( z:context() ) -> {ok, binary()} | {error, term()}.
new_ticket(Context) ->
case z_context:client_id(Context) of
{error, _} = Error ->
Error;
{ok, _ClientId} ->
z_mqtt_ticket:new_ticket(Context)
end.
%% @doc Delete a ticket.
-spec delete_ticket( binary(), z:context() ) -> ok | {error, term()}.
delete_ticket(Ticket, Context) ->
z_mqtt_ticket:delete_ticket(Ticket, Context).
%% @doc Exchange a ticket for a previously saved MQTT connection context.
-spec exchange_ticket( binary(), z:context() ) -> {ok, z:context()} | {error, term()}.
exchange_ticket(Ticket, Context) ->
z_mqtt_ticket:exchange_ticket(Ticket, Context).
| null | https://raw.githubusercontent.com/zotonic/zotonic/852f627c28adf6e5212e8ad5383d4af3a2f25e3f/apps/zotonic_mod_base/src/models/m_mqtt_ticket.erl | erlang | @doc Handle tickets for out of band MQTT actions via controller_mqtt_transport.
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@doc Fetch the value for the key from a model source
@doc Create a new ticket for the current context, must be called via a MQTT connection.
@doc Delete ticket.
@doc Create a new ticket. This store the context and returns an unique ticket-id. This ticket can later
be exchanged for the stored context. The stored context MUST contain the MQTT client-id.
@doc Delete a ticket.
@doc Exchange a ticket for a previously saved MQTT connection context. | @author < >
2020
Copyright 2020
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(m_mqtt_ticket).
-behaviour(zotonic_model).
-export([
m_get/3,
m_post/3,
m_delete/3,
new_ticket/1,
exchange_ticket/2
]).
-spec m_get( list(), zotonic_model:opt_msg(), z:context() ) -> zotonic_model:return().
m_get(_Path, _Msg, _Context) ->
{error, unknown_path}.
-spec m_post( list( binary() ), zotonic_model:opt_msg(), z:context() ) -> {ok, term()} | ok | {error, term()}.
m_post([ <<"new">> ], _Msg, Context) ->
new_ticket(Context);
m_post(_Path, _Msg, _Context) ->
{error, unknown_path}.
-spec m_delete( list( binary() ), zotonic_model:opt_msg(), z:context() ) -> {ok, term()} | ok | {error, term()}.
m_delete([ Ticket ], _Msg, Context) when is_binary(Ticket) ->
delete_ticket(Ticket, Context);
m_delete(_Path, _Msg, _Context) ->
{error, unknown_path}.
-spec new_ticket( z:context() ) -> {ok, binary()} | {error, term()}.
new_ticket(Context) ->
case z_context:client_id(Context) of
{error, _} = Error ->
Error;
{ok, _ClientId} ->
z_mqtt_ticket:new_ticket(Context)
end.
-spec delete_ticket( binary(), z:context() ) -> ok | {error, term()}.
delete_ticket(Ticket, Context) ->
z_mqtt_ticket:delete_ticket(Ticket, Context).
-spec exchange_ticket( binary(), z:context() ) -> {ok, z:context()} | {error, term()}.
exchange_ticket(Ticket, Context) ->
z_mqtt_ticket:exchange_ticket(Ticket, Context).
|
230059964371844968cff4d2a4770c42493c8b098ac1337db938681408d50d9f | glondu/belenios | languages.ml | (**************************************************************************)
(* BELENIOS *)
(* *)
Copyright © 2012 - 2022
(* *)
(* 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, with the additional *)
exemption that compiling , linking , and/or using OpenSSL is allowed .
(* *)
(* 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 *)
(* </>. *)
(**************************************************************************)
let available =
[
"ar", "العربية";
"cs", "Čeština";
"de", "Deutsch";
"el", "Ελληνικά";
"en", "English";
"es", "Español";
"es_419", "Español (Latinoamérica)";
"fi", "Suomi";
"fr", "Français";
"it", "Italiano";
"lt", "Lietuvių";
"ms", "Bahasa Melayu";
"nb", "Norsk (Bokmål)";
"nl", "Nederlands";
"oc", "Occitan";
"pl", "Polski";
"pt_BR", "Português (Brasil)";
"ro", "Română";
"sk", "Slovenčina";
"uk", "Українська";
]
| null | https://raw.githubusercontent.com/glondu/belenios/d00a6d82506ad539f384f6dd5658c13c191a257c/src/web/common/languages.ml | ocaml | ************************************************************************
BELENIOS
This program is free software: you can redistribute it and/or modify
License, or (at your option) any later version, with the additional
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.
License along with this program. If not, see
</>.
************************************************************************ | Copyright © 2012 - 2022
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation , either version 3 of the
exemption that compiling , linking , and/or using OpenSSL is allowed .
You should have received a copy of the GNU Affero General Public
let available =
[
"ar", "العربية";
"cs", "Čeština";
"de", "Deutsch";
"el", "Ελληνικά";
"en", "English";
"es", "Español";
"es_419", "Español (Latinoamérica)";
"fi", "Suomi";
"fr", "Français";
"it", "Italiano";
"lt", "Lietuvių";
"ms", "Bahasa Melayu";
"nb", "Norsk (Bokmål)";
"nl", "Nederlands";
"oc", "Occitan";
"pl", "Polski";
"pt_BR", "Português (Brasil)";
"ro", "Română";
"sk", "Slovenčina";
"uk", "Українська";
]
|
9c704f8d26cd889cac9bbed24b86558dd63d8b82325b390c33d9d47111f12fd5 | mathiasbourgoin/SPOC | Kirc.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
- * , et ( 2012 )
*
*
*
* This software is a computer program whose purpose is to allow
* GPU programming with the OCaml language .
*
* This software is governed by the CeCILL - B license under French law and
* abiding by the rules of distribution of free software . You can use ,
* modify and/ or redistribute the software under the terms of the CeCILL - B
* license as circulated by CEA , CNRS and INRIA at the following URL
* " " .
*
* As a counterpart to the access to the source code and rights to copy ,
* modify and redistribute granted by the license , users are provided only
* with a limited warranty and the software 's author , the holder of the
* economic rights , and the successive licensors have only limited
* liability .
*
* In this respect , the user 's attention is drawn to the risks associated
* with loading , using , modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software ,
* that may mean that it is complicated to manipulate , and that also
* therefore means that it is reserved for developers and experienced
* professionals having in - depth computer knowledge . Users are therefore
* encouraged to load and test the software 's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and , more generally , to use and operate it in the
* same conditions as regards security .
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL - B license and that you accept its terms .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
- * Mathias Bourgoin, Université Pierre et Marie Curie (2012)
*
*
*
* This software is a computer program whose purpose is to allow
* GPU programming with the OCaml language.
*
* This software is governed by the CeCILL-B license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-B
* license as circulated by CEA, CNRS and INRIA at the following URL
* "".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*******************************************************************************)
open Spoc
open Kernel
let debug = true
let idkern = ref 0
open Kirc_Ast
module Kirc_OpenCL = Gen.Generator (Kirc_OpenCL)
module Kirc_Cuda = Gen.Generator (Kirc_Cuda)
module Kirc_Profile = Gen.Generator (Profile)
type float64 = float
type float32 = float
type extension = ExFloat32 | ExFloat64
type ('a, 'b, 'c) kirc_kernel =
{ ml_kern: 'a
; body: Kirc_Ast.k_ext
; ret_val: Kirc_Ast.k_ext * ('b, 'c) Vector.kind
; extensions: extension array }
type ('a, 'b, 'c, 'd) kirc_function =
{ fun_name: string
; ml_fun: 'a
; funbody: Kirc_Ast.k_ext
; fun_ret: Kirc_Ast.k_ext * ('b, 'c) Vector.kind
; fastflow_acc: 'd
; fun_extensions: extension array }
type ('a, 'b, 'c, 'd, 'e) sarek_kernel =
('a, 'b) spoc_kernel * ('c, 'd, 'e) kirc_kernel
let constructors = ref []
let opencl_head =
"#define SAREK_VEC_LENGTH(A) sarek_## A ##_length\n"
^ "float spoc_fadd ( float a, float b );\n"
^ "float spoc_fminus ( float a, float b );\n"
^ "float spoc_fmul ( float a, float b );\n"
^ "float spoc_fdiv ( float a, float b );\n" ^ "int logical_and (int, int);\n"
^ "int spoc_powint (int, int);\n" ^ "int spoc_xor (int, int);\n"
^ "float spoc_fadd ( float a, float b ) { return (a + b);}\n"
^ "float spoc_fminus ( float a, float b ) { return (a - b);}\n"
^ "float spoc_fmul ( float a, float b ) { return (a * b);}\n"
^ "float spoc_fdiv ( float a, float b ) { return (a / b);}\n"
^ "int logical_and (int a, int b ) { return (a & b);}\n"
^ "int spoc_powint (int a, int b ) { return ((int) pow (((float) a), \
((float) b)));}\n" ^ "int spoc_xor (int a, int b ) { return (a^b);}\n"
^ "void spoc_barrier ( ) { barrier(CLK_LOCAL_MEM_FENCE);}\n"
let opencl_common_profile =
"\n/*********** PROFILER FUNCTIONS **************/\n"
^ "#pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable\n"
^ "void spoc_atomic_add(__global ulong *a, ulong b){ atom_add(a, (ulong)b);}\n"
^ "\n\
\ void* memory_analysis(__global ulong *profile_counters, __global \
void* mp, int store, int load){\n\
\ if (store) spoc_atomic_add(profile_counters+0, 1ULL);\n\
\ if (load) spoc_atomic_add(profile_counters+1, 1ULL);\n\
\ return mp;\n\
}" ^ "\n"
let opencl_profile_head =
opencl_common_profile
^ "\n\
void branch_analysis(__global ulong *profile_counters, int eval, int \
counters){\n\
\ \n\
\ unsigned int threadIdxInGroup = \n\
\ get_local_id(2)*get_local_size(0)*get_local_size(1) + \n\
\ get_local_id(1)*get_local_size(0) + get_local_id(0);\n\
\ \n\
\ \n\
\ //Get count of 1) active work items in this workgroup\n\
\ //2) work items that will take the branch\n\
\ //3) work items that do not take the branch.\n\
\ __local ulong numActive[1]; numActive[0] = 0;\n\
\ __local ulong numTaken[1]; numTaken[0] = 0;\n\
\ __local ulong numNotTaken[1]; numNotTaken[0] = 0;\n\
\ __local unsigned int lig[1]; lig[0] = 0;\n\
\ barrier(CLK_LOCAL_MEM_FENCE);\n\n\
\ atomic_inc(numActive);\n\
\ atom_max(lig, threadIdxInGroup);\n\
\ \n\
\ if (eval) atomic_inc(numTaken);\n\
\ if (!eval) atomic_inc(numNotTaken);\n\
\ \n\
\ barrier(CLK_LOCAL_MEM_FENCE);\n\
\ \n\
\ // The last active work item in each group gets to write results.\n\
\ if (lig[0] == threadIdxInGroup) {\n\
\ spoc_atomic_add(profile_counters+4, (ulong)1); //\n\
\ spoc_atomic_add(profile_counters+counters+1, numActive[0]);\n\
\ spoc_atomic_add(profile_counters+counters+2, numTaken[0]);\n\
\ spoc_atomic_add(profile_counters+counters+3, numNotTaken[0]);\n\
\ if (numTaken[0] != numActive[0] && numNotTaken[0] != numActive[0]) {\n\
\ // If threads go different ways, note it.\n\
\ spoc_atomic_add(profile_counters+5, (ulong)1);\n\
\ }\n\
\ }\n\
}\n"
^ "void while_analysis(__global ulong *profile_counters, int eval){\n\
\ /* unsigned int threadIdxInGroup = \n\
\ get_local_id(2)*get_local_size(0)*get_local_size(1) + \n\
\ get_local_id(1)*get_local_size(0) + get_local_id(0);\n\n\
\ //Get count of 1) active work items in this workgroup\n\
\ //2) work items that will take the branch\n\
\ //3) work items that do not take the branch.\n\
\ __local ulong numActive[1]; numActive[0] = 0;\n\
\ __local unsigned int numTaken; numTaken = 0;\n\
\ __local unsigned int numNotTaken; numNotTaken = 0;\n\
\ __local unsigned int lig; lig = 0;\n\
\ barrier(CLK_LOCAL_MEM_FENCE);\n\n\
\ atomic_inc(numActive);\n\
\ atom_max(&lig, threadIdxInGroup);\n\
\ \n\
\ if (eval) atom_inc(&numTaken);\n\
\ if (!eval) atom_inc(&numNotTaken);\n\
\ \n\
\ barrier(CLK_LOCAL_MEM_FENCE);\n\
\ \n\
\ // The last active work item in each group gets to write results.\n\
\ if (lig == threadIdxInGroup) {\n\
\ spoc_atomic_add(profile_counters+4, (ulong)1); //\n\
\ if (numTaken != numActive[0] && numNotTaken != numActive[0]) {\n\
\ // If threads go different ways, note it.\n\
\ spoc_atomic_add(profile_counters+5, (ulong)1);\n\
\ }\n\
\ } */ \n\
}\n\n"
let opencl_profile_head_cpu =
opencl_common_profile
^ "\n\
void branch_analysis(__global ulong *profile_counters, int eval, int \
counters){\n\
\ \n\
\ unsigned int threadIdxInGroup = \n\
\ get_local_id(2)*get_local_size(0)*get_local_size(1) + \n\
\ get_local_id(1)*get_local_size(0) + get_local_id(0);\n\
\ \n\
\ spoc_atomic_add(profile_counters+4, (ul;ong)1); //\n\
\ spoc_atomic_add(profile_counters+counters+1, 1);\n\
\ if (eval) \n\
\ spoc_atomic_add(profile_counters+counters+2, 1);\n\
\ if (!eval)\n\
\ spoc_atomic_add(profile_counters+counters+3, 1);\n\
\ }\n"
^ "void while_analysis(__global ulong *profile_counters, int eval){\n}\n\n"
let opencl_float64 =
"#ifndef __FLOAT64_EXTENSION__ \n" ^ "#define __FLOAT64_EXTENSION__ \n"
^ "#if defined(cl_khr_fp64) // Khronos extension available?\n"
^ "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
^ "#elif defined(cl_amd_fp64) // AMD extension available?\n"
^ "#pragma OPENCL EXTENSION cl_amd_fp64 : enable\n" ^ "#endif\n"
^ "double spoc_dadd ( double a, double b );\n"
^ "double spoc_dminus ( double a, double b );\n"
^ "double spoc_dmul ( double a, double b );\n"
^ "double spoc_ddiv ( double a, double b );\n"
^ "double spoc_dadd ( double a, double b ) { return (a + b);}\n"
^ "double spoc_dminus ( double a, double b ) { return (a - b);}\n"
^ "double spoc_dmul ( double a, double b ) { return (a * b);}\n"
^ "double spoc_ddiv ( double a, double b ) { return (a / b);}\n" ^ "#endif\n"
let cuda_float64 =
"#ifndef __FLOAT64_EXTENSION__ \n" ^ "#define __FLOAT64_EXTENSION__ \n"
^ "__device__ double spoc_dadd ( double a, double b ) { return (a + b);}\n"
^ "__device__ double spoc_dminus ( double a, double b ) { return (a - b);}\n"
^ "__device__ double spoc_dmul ( double a, double b ) { return (a * b);}\n"
^ "__device__ double spoc_ddiv ( double a, double b ) { return (a / b);}\n"
^ "#endif\n"
let cuda_head =
"#define SAREK_VEC_LENGTH(a) sarek_ ## a ## _length\n"
^ "#define FULL_MASK 0xffffffff\n"
^ "__device__ float spoc_fadd ( float a, float b ) { return (a + b);}\n"
^ "__device__ float spoc_fminus ( float a, float b ) { return (a - b);}\n"
^ "__device__ float spoc_fmul ( float a, float b ) { return (a * b);}\n"
^ "__device__ float spoc_fdiv ( float a, float b ) { return (a / b);}\n"
^ "__device__ int logical_and (int a, int b ) { return (a & b);}\n"
^ "__device__ int spoc_powint (int a, int b ) { return ((int) pow \
(((double) a), ((double) b)));}\n"
^ "__device__ int spoc_xor (int a, int b ) { return (a^b);}\n"
let cuda_profile_head =
"\n/*********** PROFILER FUNCTIONS **************/\n"
^ "__device__ void spoc_atomic_add(unsigned long long int *a, unsigned int \
b){ atomicAdd(a, b);}\n"
^ "__device__ __forceinline__ unsigned int get_laneid(void) {\n\
\ unsigned int laneid;\n\
\ asm volatile (\"mov.u32 %0, %laneid;\" : \"=r\"(laneid));\n\
\ return laneid;\n\
\ }\n"
^ "__device__ void branch_analysis(unsigned long long int \
*profile_counters, int eval, int counters){\n\
\ \n\
\ int threadIdxInWarp = get_laneid();//threadIdx.x & (warpSize-1);\n\
\ \n\
\ //Get count of 1) active threads in this warp\n\
\ //2) threads that will take the branch\n\
\ //3) threads that do not take the branch.\n\
\ unsigned int active = __ballot(1);\n\
\ int taken = __ballot(eval);\n\
\ int ntaken = __ballot(!eval);\n\
\ int numActive = __popc(active);\n\
\ int numTaken = __popc(taken), numNotTaken = __popc(ntaken);\n\n\
\ // The first active thread in each warp gets to write results.\n\
\ if ((__ffs(active)-1) == threadIdxInWarp) {\n\
\ atomicAdd(profile_counters+4, 1ULL); //\n\
\ atomicAdd(profile_counters+counters+1, numActive);\n\
\ atomicAdd(profile_counters+counters+2, numTaken);\n\
\ atomicAdd(profile_counters+counters+3, numNotTaken);\n\
\ if (numTaken != numActive && numNotTaken != numActive) {\n\
\ // If threads go different ways, note it.\n\
\ atomicAdd(profile_counters+5, 1ULL);\n\
\ }\n\
\ }\n\
}\n"
^ "__device__ void while_analysis(unsigned long long int *profile_counters, \
int eval){\n\n\
\ int threadIdxInWarp = get_laneid();//threadIdx.x & (warpSize-1);\n\n\
\ //Get count of 1) active threads in this \
warp //2) threads that will take the \
branch //3) threads that do not \
take the \
branch. \n\
\ int active = __ballot(1);\n\
\ int taken = __ballot(eval);\n\
\ int ntaken = __ballot(!eval);\n\
\ int numActive = __popc(active);\n\
\ int numTaken = __popc(taken), numNotTaken = __popc(ntaken);\n\n\
\ // The first active thread in each warp gets to write \
results. \n\
\ if ((__ffs(active)-1) == threadIdxInWarp) {\n\
\ atomicAdd(profile_counters+4, 1ULL); \
// \n\
\ if (numTaken != numActive && numNotTaken != numActive) {\n\
\ // If threads go different ways, note \
it. \n\
\ atomicAdd(profile_counters+5, 1ULL);\n\
\ }\n\
\ }\n\
}\n\n"
^ "\n\
#include<cuda.h>\n\
template <typename T>\n\
__device__ T __broadcast(T t, int fromWhom)\n\
{\n\
\ union {\n\
\ int32_t shflVals[sizeof(T)];\n\
\ T t;\n\
\ } p;\n\
\ \n\
\ p.t = t;\n\
\ #pragma unroll\n\
\ for (int i = 0; i < sizeof(T); i++) {\n\
\ int32_t shfl = (int32_t)p.shflVals[i];\n\
\ p.shflVals[i] = __shfl(shfl, fromWhom);\n\
\ }\n\
\ return p.t;\n\
}\n\n\
/// The number of bits we need to shift off to get the cache line address.\n\
#define LINE_BITS 5\n\n\
template<typename T>\n\
__device__ T* memory_analysis(unsigned long long int *profile_counters, \
T* mp, int store, int load){\n\n\
\ int threadIdxInWarp = get_laneid();//threadIdx.x & (warpSize-1);\n\
\ intptr_t addrAsInt = (intptr_t) mp;\n\n\
\ if (__isGlobal(mp)){\n\
\ if (store) atomicAdd(profile_counters+0, 1ULL);\n\
\ if (load) atomicAdd(profile_counters+1, 1ULL);\n\n\
\ unsigned unique = 0; // Num unique lines per warp.\n\n\
\ // Shift off the offset bits into the cache line.\n\
\ intptr_t lineAddr = addrAsInt >> LINE_BITS;\n\n\
\ int workset = __ballot(1);\n\
\ int firstActive = __ffs(workset)-1;\n\
\ int numActive = __popc(workset);\n\
\ while (workset) {\n\
\ // Elect a leader, get its cache line, see who matches it.\n\
\ int leader = __ffs(workset) - 1;\n\
\ intptr_t leadersAddr = __broadcast(lineAddr, leader);\n\
\ int notMatchesLeader = __ballot(leadersAddr != lineAddr);\n\n\
\ // We have accounted for all values that match the leader’s.\n\
\ // Let’s remove them all from the workset.\n\
\ workset = workset & notMatchesLeader;\n\
\ unique++;\n\
\ }\n\n\
\ if (firstActive == threadIdxInWarp && unique ) {\n\
\ atomicAdd(profile_counters+6, 1ULL);\n\
\ }\n\
\ \n\
\ }\n\
\ return mp;\n\n\
}\n" ^ "\n"
let eint32 = EInt32
let eint64 = EInt64
let efloat32 = EFloat32
let efloat64 = EFloat64
let global = Global
let local = LocalSpace
let shared = Shared
let new_var i = IdName ("spoc_var" ^ string_of_int i)
let new_array n l t m = Arr (n, l, t, m)
let var i s = IntId (s, i)
( " spoc_var"^(string_of_int i ) ) , i )
let spoc_gen_kernel args body = Kern (args, body)
let spoc_fun_kernel _a _b = ()
let global_fun a =
GlobalFun
( a.funbody
, ( match snd a.fun_ret with
| Vector.Int32 _ -> "int"
| Vector.Float32 _ -> "float"
| Vector.Custom _ -> (
match fst a.fun_ret with
| CustomVar (s, _, _) -> "struct " ^ s ^ "_sarek"
| _ -> assert false )
| _ -> "void" )
, a.fun_name )
let seq a b = Seq (a, b)
let app a b = App (a, b)
let spoc_unit () = Unit
let spoc_int a = Int a
let global_int_var a = GInt a
let global_float_var a = GFloat a
let global_float64_var a = GFloat64 a
let spoc_int32 a = Int (Int32.to_int a)
let spoc_float f = Float f
let spoc_double d = Double d
let spoc_int_id a = Int a
IntId ( a,-1 )
let spoc_float_id a = Float a
let spoc_plus a b = Plus (a, b)
let spoc_plus_float a b = Plusf (a, b)
let spoc_min a b = Min (a, b)
let spoc_min_float a b = Minf (a, b)
let spoc_mul a b = Mul (a, b)
let spoc_mul_float a b = Mulf (a, b)
let spoc_div a b = Div (a, b)
let spoc_div_float a b = Divf (a, b)
let spoc_mod a b = Mod (a, b)
let spoc_ife a b c = Ife (a, b, c)
let spoc_if a b = If (a, b)
let spoc_match s e l = Match (s, e, l)
let spoc_case i o e : case = (i, o, e)
let spoc_do a b c d = DoLoop (a, b, c, d)
let spoc_while a b = While (a, b)
let params l = Params l
let spoc_id _i = Id ""
let spoc_constr t c params = Constr (t, c, params)
let spoc_record t params = Record (t, params)
let spoc_return k = Return k
let concat a b = Concat (a, b)
let empty_arg () = Empty
let new_int_var i s = IntVar (i, s)
let new_float_var i s = FloatVar (i, s)
let new_float64_var i s = DoubleVar (i, s)
let new_double_var i s = DoubleVar (i, s)
let new_unit_var i s = UnitVar (i, s)
let new_custom_var n v s = Custom (n, v, s)
(* <--- *)
let new_int_vec_var v s = VecVar (Int 0, v, s)
let new_float_vec_var v s = VecVar (Float 0., v, s)
let new_double_vec_var v s = VecVar (Double 0., v, s)
let new_custom_vec_var n v s = VecVar (Custom (n, 0, s), v, s)
(* <--- *)
let int_vect i = IntVect i
let spoc_rec_get r id = RecGet (r, id)
let spoc_rec_set r v = RecSet (r, v)
let set_vect_var vecacc value = SetV (vecacc, value)
let set_arr_var arracc value = SetV (arracc, value)
let intrinsics a b = Intrinsics (a, b)
let spoc_local_env local_var b = Local (local_var, b)
let spoc_set name value = Set (name, value)
let spoc_declare name = Decl name
let spoc_local_var a = a
let spoc_acc a b = Acc (a, b)
let int_var i = i
let int32_var i = i
let float_var f = f
let double_var d = CastDoubleVar (d, "")
let equals a b = EqBool (a, b)
let equals_custom s v1 v2 = EqCustom (s, v1, v2)
let equals32 a b = EqBool (a, b)
let equals64 a b = EqBool (a, b)
let equalsF a b = EqBool (a, b)
let equalsF64 a b = EqBool (a, b)
let b_or a b = Or (a, b)
let b_and a b = And (a, b)
let b_not a = Not a
let lt a b = LtBool (a, b)
let lt32 a b = LtBool (a, b)
let lt64 a b = LtBool (a, b)
let ltF a b = LtBool (a, b)
let ltF64 a b = LtBool (a, b)
let gt a b = GtBool (a, b)
let gt32 a b = GtBool (a, b)
let gt64 a b = GtBool (a, b)
let gtF a b = GtBool (a, b)
let gtF64 a b = GtBool (a, b)
let lte a b = LtEBool (a, b)
let lte32 a b = LtEBool (a, b)
let lte64 a b = LtEBool (a, b)
let lteF a b = LtEBool (a, b)
let lteF64 a b = LtEBool (a, b)
let gte a b = GtEBool (a, b)
let gte32 a b = GtEBool (a, b)
let gte64 a b = GtEBool (a, b)
let gteF a b = GtEBool (a, b)
let gteF64 a b = GtEBool (a, b)
let get_vec a b = IntVecAcc (a, b)
let get_arr a b = IntVecAcc (a, b)
let return_unit () = Unit
let return_int i s = IntVar (i, s)
let return_float f s = FloatVar (f, s)
let return_double d s = DoubleVar (d, s)
let return_bool b s = BoolVar (b, s)
let return_custom n sn s = CustomVar (n, sn, s)
let spoc_native f = Native f
let pragma l e = Pragma (l, e)
let map f a b = Map (f, a, b)
let print_ast = Kirc_Ast.print_ast
let debug_print (ker : ('a, 'b, 'c, 'd, 'e) sarek_kernel) =
let _, k = ker in
let _k1, k2, _k3 = (k.ml_kern, k.body, k.ret_val) in
print_ast k2
let rewrite ker =
let b = ref false in
let rec aux kern =
match kern with
| Native _ -> kern
| Pragma (opts, k) -> Pragma (opts, aux k)
| Block b -> Block (aux b)
| Kern (k1, k2) -> Kern (aux k1, aux k2)
| Params k -> Params (aux k)
| Plus (k1, k2) -> Plus (aux k1, aux k2)
| Plusf (k1, k2) -> (
match (k1, k2) with
| Float f1, Float f2 ->
b := true ;
Float (f1 +. f2)
| _ -> Plusf (aux k1, aux k2) )
| Min (k1, k2) -> Min (aux k1, aux k2)
| Minf (k1, k2) -> (
match (k1, k2) with
| Float f1, Float f2 ->
b := true ;
Float (f1 +. f2)
| _ -> Minf (aux k1, aux k2) )
| Mul (k1, k2) -> Mul (aux k1, aux k2)
| Mulf (k1, k2) -> (
match (k1, k2) with
| Float f1, Float f2 ->
b := true ;
Float (f1 +. f2)
| _ -> Mulf (aux k1, aux k2) )
| Div (k1, k2) -> Div (aux k1, aux k2)
| Divf (k1, k2) -> (
match (k1, k2) with
| Float f1, Float f2 ->
b := true ;
Float (f1 +. f2)
| _ -> Divf (aux k1, aux k2) )
| Mod (k1, k2) -> Mod (aux k1, aux k2)
| Id _ -> kern
| IdName _ -> kern
| IntVar _ -> kern
| FloatVar _ -> kern
| UnitVar _ -> Seq (kern, kern)
| CastDoubleVar _ -> kern
| DoubleVar _ -> kern
| BoolVar _ -> kern
| VecVar (k, idx, s) -> VecVar (aux k, idx, s)
| Concat (k1, k2) -> Concat (aux k1, aux k2)
| Constr (t, c, l) -> Constr (t, c, List.map aux l)
| Record (t, l) -> Record (t, List.map aux l)
| RecGet (r, s) -> RecGet (aux r, s)
| RecSet (r, v) -> RecSet (aux r, aux v)
| Empty -> kern
| Seq (k1, Unit) -> aux k1
| Seq (k1, k2) -> Seq (aux k1, aux k2)
| Return k -> (
match k with
| Return k ->
b := true ;
aux (Return k)
| Acc _ | Set _ -> aux k
| Ife (k1, k2, k3) ->
b := true ;
Ife (aux k1, aux (Return k2), aux (Return k3))
| If (k1, k2) ->
b := true ;
If (aux k1, aux (Return k2))
| DoLoop (k1, k2, k3, k4) ->
b := true ;
DoLoop (aux k1, aux k2, aux k3, aux (Return k4))
| While (k1, k2) ->
b := true ;
While (aux k1, aux (Return k2))
| Seq (k1, k2) ->
b := true ;
Seq (aux k1, aux (Return k2))
| Match (s, a, bb) ->
b := true ;
Match
( s
, aux a
, Array.map (fun (i, ofid, e) -> (i, ofid, aux (Return e))) bb )
| _ -> Return (aux k) )
| Acc (k1, k2) -> (
match k2 with
| Ife (k1', k2', k3') ->
b := true ;
Ife (aux k1', aux (Acc (k1, k2')), aux (Acc (k1, k3')))
| If (k1', k2') ->
b := true ;
If (aux k1', aux (Acc (k1, k2')))
| DoLoop (k1', k2', k3', k4') ->
b := true ;
DoLoop (aux k1', aux k2', aux k3', aux (Acc (k1, k4')))
| While (k1', k2') ->
b := true ;
While (aux k1', aux (Acc (k1, k2')))
| Seq (k1', k2') ->
b := true ;
Seq (aux k1', aux (Acc (k1, k2')))
| Match (s, a, bb) ->
b := true ;
Match
( s
, aux a
, Array.map (fun (i, ofid, e) -> (i, ofid, aux (Acc (k1, e)))) bb
)
| Return _ -> assert false
| _ -> Acc (aux k1, aux k2) )
| Set (k1, k2) -> aux (Acc (k1, k2))
| Decl k1 -> aux k1
| SetV (k1, k2) -> (
match k2 with
| Seq (k3, k4) -> Seq (k3, SetV (aux k1, aux k4))
| Ife (k3, k4, k5) ->
b := true ;
Ife (aux k3, SetV (aux k1, aux k4), SetV (aux k1, k5))
| Match (s, a, bb) ->
b := true ;
Match
( s
, aux a
, Array.map
(fun (i, ofid, e) -> (i, ofid, SetV (aux k1, aux e)))
bb )
| _ -> SetV (aux k1, aux k2) )
| SetLocalVar (k1, k2, k3) -> SetLocalVar (aux k1, aux k2, aux k3)
| Intrinsics _ -> kern
| IntId _ -> kern
| Int _ -> kern
| GInt _ -> kern
| GFloat _ -> kern
| GFloat64 _ -> kern
| Float _ -> kern
| Double _ -> kern
| Custom _ -> kern
| IntVecAcc (k1, k2) -> (
match k2 with
| Seq (k3, k4) -> Seq (k3, IntVecAcc (aux k1, aux k4))
| _ -> IntVecAcc (aux k1, aux k2) )
| Local (k1, k2) -> Local (aux k1, aux k2)
| Ife (k1, k2, k3) -> Ife (aux k1, aux k2, aux k3)
| If (k1, k2) -> If (aux k1, aux k2)
| Not k -> Not (aux k)
| Or (k1, k2) -> Or (aux k1, aux k2)
| And (k1, k2) -> And (aux k1, aux k2)
| EqBool (k1, k2) -> EqBool (aux k1, aux k2)
| EqCustom (n, k1, k2) -> EqCustom (n, aux k1, aux k2)
| LtBool (k1, k2) -> LtBool (aux k1, aux k2)
| GtBool (k1, k2) -> GtBool (aux k1, aux k2)
| LtEBool (k1, k2) -> LtEBool (aux k1, aux k2)
| GtEBool (k1, k2) -> GtEBool (aux k1, aux k2)
| DoLoop (k1, k2, k3, k4) -> DoLoop (aux k1, aux k2, aux k3, aux k4)
| Arr (l, t, s, m) -> Arr (l, t, s, m)
| While (k1, k2) -> While (aux k1, aux k2)
| App (a, b) -> App (aux a, Array.map aux b)
| GlobalFun (a, b, n) -> GlobalFun (aux a, b, n)
| Unit -> kern
| Match (s, a, b) ->
Match (s, aux a, Array.map (fun (i, ofid, e) -> (i, ofid, aux e)) b)
| CustomVar _ -> kern
| Map (a, b, c) -> Map (aux a, aux b, aux c)
in
let kern = ref (aux ker) in
while !b do
b := false ;
kern := aux !kern
done ;
!kern
let return_v = ref ("", "")
let save file string =
ignore (Sys.command ("rm -f " ^ file)) ;
let channel = open_out file in
output_string channel string ;
close_out channel
let load_file f =
let ic = open_in f in
let n = in_channel_length ic in
let s = Bytes.make n ' ' in
really_input ic s 0 n ; close_in ic ; s
external print_source : string - > unit = " "
let gen_profile ker dev =
let _kir, k = ker in
let _k1, _k2, _k3 = (k.ml_kern, k.body, k.ret_val) in
return_v := ("", "") ;
let k ' =
* ( 0 ( fst k3 ) dev
* , match fst k3 with
* ( i , s ) | FloatVar ( i , s ) | DoubleVar ( i , s ) - >
* s ( \*"sspoc_var"^(string_of_int i)^*\ ) ^ " = "
* | Unit - > " "
* | SetV _ - > " "
* | IntVecAcc _ - > " "
* | VecVar _ - > " "
* | _ - >
* debug_print
* ( kir
* , { ml_kern= k1
* ; k3
* ; ret_val= k3
* ; extensions= k.extensions } ) ;
* Stdlib.flush stdout ;
* assert false )
* ( Kirc_Profile.parse 0 (fst k3) dev
* , match fst k3 with
* | IntVar (i, s) | FloatVar (i, s) | DoubleVar (i, s) ->
* s (\*"sspoc_var"^(string_of_int i)^*\) ^ " = "
* | Unit -> ""
* | SetV _ -> ""
* | IntVecAcc _ -> ""
* | VecVar _ -> ""
* | _ ->
* debug_print
* ( kir
* , { ml_kern= k1
* ; body= fst k3
* ; ret_val= k3
* ; extensions= k.extensions } ) ;
* Stdlib.flush stdout ;
* assert false ) *)
(* in *)
let profile_source = Kirc_Profile.parse 0 _k2 dev in
Printf.printf "%s" profile_source
(* external from SPOC*)
external nvrtc_ptx : string -> string array -> string = "spoc_nvrtc_ptx"
let gen ?keep_temp:(kt=false) ?profile:(prof = false) ?return:(r = false) ?only:o
?nvrtc_options:(nvopt = [||]) (ker : ('a, 'b, 'c, 'd, 'e) sarek_kernel) dev
=
let kir, k = ker in
let k1, k2, k3 = (k.ml_kern, k.body, k.ret_val) in
return_v := ("", "") ;
let k' =
( Kirc_Cuda.parse ~profile:prof 0 (fst k3) dev
, match fst k3 with
| IntVar (_i, s) | FloatVar (_i, s) | DoubleVar (_i, s) ->
s (*"sspoc_var"^(string_of_int i)^*) ^ " = "
| Unit -> ""
| SetV _ -> ""
| IntVecAcc _ -> ""
| VecVar _ -> ""
| _ ->
debug_print
( kir
, { ml_kern= k1
; body= fst k3
; ret_val= k3
; extensions= k.extensions } ) ;
Stdlib.flush stdout ;
assert false )
in
if r then (
Kirc_Cuda.return_v := k' ;
Kirc_OpenCL.return_v := k' ) ;
let gen_cuda ?opts:(_s = "") () =
let cuda_head =
Array.fold_left
(fun header extension ->
match extension with
| ExFloat32 -> header
| ExFloat64 -> cuda_float64 ^ header )
cuda_head k.extensions
in
let src = Kirc_Cuda.parse ~profile:prof 0 (rewrite k2) dev in
let global_funs = ref "" in
Hashtbl.iter
(fun _ a -> global_funs := !global_funs ^ fst a ^ "\n")
Kirc_Cuda.global_funs ;
let i = ref 0 in
let constructors =
List.fold_left
(fun a b ->
incr i ;
(if !i mod 3 = 0 then " " else "__device__ ") ^ b ^ a )
"\n\n" !constructors
in
let protos =
"/************* FUNCTION PROTOTYPES ******************/\n"
^ List.fold_left (fun a b -> b ^ ";\n" ^ a) "" !Kirc_Cuda.protos
in
if debug then
save
("kirc_kernel" ^ string_of_int !idkern ^ ".cu")
( cuda_head
^ (if prof then cuda_profile_head else "")
^ constructors ^ protos ^ !global_funs ^ src ) ;
ignore(Sys.command ( " nvcc -g -G " ^ s ^ " " ^"-arch = sm_30 -ptx kirc_kernel.cu -o kirc_kernel.ptx " ) ) ;
let genopt =
match dev.Devices.specific_info with
| Devices.CudaInfo cu ->
let computecap = (cu.Devices.major * 10) + cu.Devices.minor in
[| ( if computecap < 35 then
failwith "CUDA device too old for this XXX"
else if computecap < 35 then "--gpu-architecture=compute_30"
else if computecap < 50 then "--gpu-architecture=compute_35"
else if computecap < 52 then "--gpu-architecture=compute_50"
else if computecap < 53 then "--gpu-architecture=compute_52"
else if computecap < 60 then "--gpu-architecture=compute_53"
else if computecap < 61 then "--gpu-architecture=compute_60"
else if computecap < 62 then "--gpu-architecture=compute_61"
else if computecap < 70 then "--gpu-architecture=compute_30"
else if computecap < 72 then "--gpu-architecture=compute_70"
else if computecap < 75 then "--gpu-architecture=compute_72"
else if computecap = 75 then "--gpu-architecture=compute_75"
else if computecap = 80 then "--gpu-architecture=compute_80"
else if computecap = 86 then "--gpu-architecture=compute_86"
else "--gpu-architecture=compute_35" ) |]
| _ -> [||]
in
let nvrtc_options = Array.append nvopt genopt in
let s =
nvrtc_ptx
( cuda_head
^ (if prof then cuda_profile_head else "")
^ constructors ^ !global_funs ^ src )
nvrtc_options
in
save ("kirc_kernel" ^ string_of_int !idkern ^ ".ptx") s ;
(*let s = (load_file "kirc_kernel.ptx") in*)
kir#set_cuda_sources s ;
if not kt then ignore
(Sys.command
( "rm kirc_kernel" ^ string_of_int !idkern ^ ".cu kirc_kernel"
^ string_of_int !idkern ^ ".ptx" )) ;
incr idkern
and gen_opencl () =
let opencl_head =
Array.fold_left
(fun header extension ->
match extension with
| ExFloat32 -> header
| ExFloat64 -> opencl_float64 ^ header )
opencl_head k.extensions
in
let src = Kirc_OpenCL.parse ~profile:prof 0 (rewrite k2) dev in
let global_funs =
ref "/************* FUNCTION DEFINITIONS ******************/\n"
in
Hashtbl.iter
(fun _ a -> global_funs := !global_funs ^ "\n" ^ fst a ^ "\n")
Kirc_OpenCL.global_funs ;
let constructors =
"/************* CUSTOM TYPES ******************/\n"
^ List.fold_left (fun a b -> b ^ a) "\n\n" !constructors
in
let protos =
"/************* FUNCTION PROTOTYPES ******************/\n"
^ List.fold_left (fun a b -> b ^ ";\n" ^ a) "" !Kirc_OpenCL.protos
in
let clkernel =
( if prof then
"#pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable\n"
else "" )
^ opencl_head
^ ( if prof then
match dev.Devices.specific_info with
| Devices.OpenCLInfo
{Devices.device_type= Devices.CL_DEVICE_TYPE_CPU ; _} ->
opencl_profile_head_cpu
| _ -> opencl_profile_head
else "" )
^ constructors ^ protos ^ !global_funs ^ src
in
save ("kirc_kernel" ^ string_of_int !idkern ^ ".cl") clkernel ;
kir#set_opencl_sources clkernel;
if not kt then ignore
(Sys.command
( "rm kirc_kernel" ^ string_of_int !idkern ^ ".cl" )) ;
in
( match o with
| None -> (
match dev.Devices.specific_info with
| Devices.OpenCLInfo _ ->
ignore (Kirc_OpenCL.get_profile_counter ()) ;
gen_opencl ()
| _ ->
ignore (Kirc_OpenCL.get_profile_counter ()) ;
gen_cuda () )
| Some d -> (
match d with
| Devices.Both ->
ignore (Kirc_Cuda.get_profile_counter ()) ;
gen_cuda () ;
ignore (Kirc_OpenCL.get_profile_counter ()) ;
gen_opencl ()
| Devices.Cuda ->
ignore (Kirc_Cuda.get_profile_counter ()) ;
gen_cuda ()
| Devices.OpenCL ->
ignore (Kirc_OpenCL.get_profile_counter ()) ;
gen_opencl () ) ) ;
kir#reset_binaries () ;
ignore (kir#compile dev) ;
(kir, k)
let arg_of_vec v =
match Vector.kind v with
| Vector.Int32 _ -> Kernel.VInt32 v
| Vector.Float32 _ -> Kernel.VFloat32 v
| Vector.Int64 _ -> Kernel.VInt64 v
| _ -> assert false
let run ?recompile:(r = false) (ker : ('a, 'b, 'c, 'd, 'e) sarek_kernel) a
(block, grid) _q dev =
let kir, k = ker in
( match dev.Devices.specific_info with
| Devices.CudaInfo _ -> (
if r then ignore (gen ~only:Devices.Cuda (kir, k) dev)
else
match kir#get_cuda_sources () with
| [] -> ignore (gen ~only:Devices.Cuda (kir, k) dev)
| _ -> () )
| Devices.OpenCLInfo _ -> (
if r then ignore (gen ~only:Devices.OpenCL (kir, k) dev)
else
match kir#get_opencl_sources () with
| [] -> ignore (gen ~only:Devices.OpenCL (kir, k) dev)
| _ -> () ) ) ;
let args = kir#args_to_list a in
let offset = ref 0 in
kir#compile ~debug:true dev ;
let bin = Hashtbl.find (kir#get_binaries ()) dev in
let nvec = ref 0 in
Array.iter
(fun a ->
match a with
| VChar _v
|VFloat32 _v
|VFloat64 _v
|VInt32 _v
|VInt64 _v
|VComplex32 _v
|VCustom _v ->
incr nvec
| _ -> () )
args ;
match dev.Devices.specific_info with
| Devices.CudaInfo _cI ->
let extra = Kernel.Cuda.cuda_create_extra (Array.length args + !nvec) in
. Cuda.cuda_load_arg offset extra dev ( arg_of_vec profiler_counters ) ;
let idx = ref 0 in
Array.iter
(fun a ->
match a with
| VChar v
|VFloat32 v
|VFloat64 v
|VInt32 v
|VInt64 v
|VComplex32 v
|VCustom v ->
Kernel.Cuda.cuda_load_arg offset extra dev bin !idx a ;
Kernel.Cuda.cuda_load_arg offset extra dev bin (!idx + 1)
(Kernel.Int32 (Vector.length v)) ;
idx := !idx + 2
| _ ->
Kernel.Cuda.cuda_load_arg offset extra dev bin idx a ;
incr idx )
args ;
Kernel.Cuda.cuda_launch_grid offset bin grid block extra
dev.Devices.general_info 0
| Devices.OpenCLInfo _ ->
. OpenCL.opencl_load_arg offset dev ( arg_of_vec profiler_counters ) ;
let idx = ref 0 in
Array.iter
(fun a ->
match a with
| VChar v
|VFloat32 v
|VFloat64 v
|VInt32 v
|VInt64 v
|VComplex32 v
|VCustom v ->
Kernel.OpenCL.opencl_load_arg offset dev bin !idx a ;
Kernel.OpenCL.opencl_load_arg offset dev bin (!idx + 1)
(Kernel.Int32 (Vector.length v)) ;
idx := !idx + 2
| _ ->
Kernel.OpenCL.opencl_load_arg offset dev bin !idx a ;
incr idx )
args ;
Array.iteri ( fun i a - > Kernel . OpenCL.opencl_load_arg offset dev ( i ) a ) args ;
Kernel.OpenCL.opencl_launch_grid bin grid block dev.Devices.general_info
0
let profile_run ?recompile:(r = true) (ker : ('a, 'b, 'c, 'd, 'e) sarek_kernel)
a b _q dev =
let kir, k = ker in
( match dev.Devices.specific_info with
| Devices.CudaInfo _ -> (
if r then ignore (gen ~profile:true ~only:Devices.Cuda (kir, k) dev)
else
match kir#get_cuda_sources () with
| [] -> ignore (gen ~profile:true ~only:Devices.Cuda (kir, k) dev)
| _ -> () )
| Devices.OpenCLInfo _ -> (
if r then ignore (gen ~profile:true ~only:Devices.OpenCL (kir, k) dev)
else
match kir#get_opencl_sources () with
| [] -> ignore (gen ~profile:true ~only:Devices.OpenCL (kir, k) dev)
| _ -> () ) ) ;
(*kir#run a b q dev;*)
let nCounter =
!( match dev.Devices.specific_info with
| Devices.CudaInfo _ -> Kirc_Cuda.profiler_counter
| Devices.OpenCLInfo _ -> Kirc_OpenCL.profiler_counter )
in
Printf.printf " Number of counters : % d\n% ! " nCounter ;
let profiler_counters = Vector.create Vector.int64 nCounter in
for i = 0 to nCounter - 1 do
Mem.set profiler_counters i 0L
done ;
(let args = kir#args_to_list a in
let offset = ref 0 in
kir#compile ~debug:true dev ;
let block, grid = b in
let bin = Hashtbl.find (kir#get_binaries ()) dev in
match dev.Devices.specific_info with
| Devices.CudaInfo _cI ->
let extra = Kernel.Cuda.cuda_create_extra (Array.length args + 1) in
Kernel.Cuda.cuda_load_arg offset extra dev bin 0
(arg_of_vec profiler_counters) ;
Array.iteri
(fun i a ->
match a with
| VChar _ | VFloat32 _ | VFloat64 _ | VInt32 _ | VInt64 _
|VComplex32 _ | VCustom _ ->
Kernel.Cuda.cuda_load_arg offset extra dev bin i a
| _ -> Kernel.Cuda.cuda_load_arg offset extra dev bin i a )
args ;
Kernel.Cuda.cuda_launch_grid offset bin grid block extra
dev.Devices.general_info 0
| Devices.OpenCLInfo _ ->
Kernel.OpenCL.opencl_load_arg offset dev bin 0
(arg_of_vec profiler_counters) ;
Array.iteri
(fun i a -> Kernel.OpenCL.opencl_load_arg offset dev bin i a)
args ;
Kernel.OpenCL.opencl_launch_grid bin grid block dev.Devices.general_info
0) ;
Devices.flush dev () ;
if not !Mem.auto then Mem.to_cpu profiler_counters () ;
Spoc.Tools.iter ( fun a - > Printf.printf " % Ld " a ) profiler_counters ;
Gen.profile_vect := profiler_counters ;
gen_profile ker dev
let compile_kernel_to_files s (ker : ('a, 'b, 'c, 'd, 'e) sarek_kernel) dev =
let kir, k = ker in
let k1, k2, k3 = (k.ml_kern, k.body, k.ret_val) in
return_v := ("", "") ;
let k' =
( (Kirc_Cuda.parse 0 (fst k3)) dev
, match fst k3 with
| IntVar (_i, s) | FloatVar (_i, s) | DoubleVar (_i, s) ->
s ^ (*"spoc_var"^(string_of_int i)^*) " = "
| Unit -> ""
| SetV _ -> ""
| IntVecAcc _ -> ""
| VecVar _ -> ""
| _ ->
debug_print
( kir
, { ml_kern= k1
; body= fst k3
; ret_val= k3
; extensions= k.extensions } ) ;
Stdlib.flush stdout ;
assert false )
in
Kirc_Cuda.return_v := k' ;
Kirc_OpenCL.return_v := k' ;
let cuda_head =
Array.fold_left
(fun header extension ->
match extension with
| ExFloat32 -> header
| ExFloat64 -> cuda_float64 ^ header )
cuda_head k.extensions
in
let opencl_head =
Array.fold_left
(fun header extension ->
match extension with
| ExFloat32 -> header
| ExFloat64 -> opencl_float64 ^ header )
opencl_head k.extensions
in
save (s ^ ".cu") (cuda_head ^ Kirc_Cuda.parse 0 (rewrite k2) dev) ;
save (s ^ ".cl") (opencl_head ^ Kirc_OpenCL.parse 0 (rewrite k2) dev)
module Std = struct
let thread_idx_x = 1l
let thread_idx_y = 1l
let thread_idx_z = 1l
let block_idx_x = 1l
let block_idx_y = 1l
let block_idx_z = 1l
let block_dim_x = 1l
let block_dim_y = 1l
let block_dim_z = 1l
let grid_dim_x = 1l
let grid_dim_y = 1l
let grid_dim_z = 1l
let global_thread_id = 0l
let return () = ()
let float64 i = float (Int32.to_int i)
let float i = float (Int32.to_int i)
let int_of_float64 f = Int32.of_int (int_of_float f)
let int_of_float f = Int32.of_int (int_of_float f)
let block_barrier () = ()
let make_shared i = Array.make (Int32.to_int i) 0l
let make_local i = Array.make (Int32.to_int i) 0l
let map f a b =
assert (Vector.length a = Vector.length b) ;
for i = 0 to Vector.length a do
Mem.set b i (f (Mem.get a i))
done
let reduce f a b =
let rec aux acc i =
if Vector.length a < i then aux (f acc (Mem.get a i)) (i + 1) else acc
in
Mem.set b 0 (aux (Mem.get a 0) 1)
end
module Sarek_vector = struct
let length v = Int32.of_int (Vector.length v)
end
module Math = struct
let pow a b =
Int32.of_float (Float.pow (Int32.to_float a) (Int32.to_float b))
let logical_and a b = Int32.logand a b
let xor a b = Int32.logxor a b
module Float32 = struct
let add = ( +. )
let minus = ( -. )
let mul = ( *. )
let div = ( /. )
let pow = ( ** )
let sqrt = sqrt
let rsqrt = sqrt
(* todo*)
let exp = exp
let log = log
let log10 = log10
let expm1 = expm1
let log1p = log1p
let acos = acos
let cos = cos
let cosh = cosh
let asin = asin
let sin = sin
let sinh = sinh
let tan = tan
let tanh = tanh
let atan = atan
let atan2 = atan2
let hypot = hypot
let ceil = ceil
let floor = floor
let abs_float = abs_float
let copysign = copysign
let modf = modf
let zero = 0.
let one = 1.
let make_shared i = Array.make (Int32.to_int i) 0.
let make_local i = Array.make (Int32.to_int i) 0.
end
module Float64 = struct
let add = ( +. )
let minus = ( -. )
let mul = ( *. )
let div = ( /. )
let pow = ( ** )
let sqrt = sqrt
let rsqrt = sqrt
(* todo*)
let exp = exp
let log = log
let log10 = log10
let expm1 = expm1
let log1p = log1p
let acos = acos
let cos = cos
let cosh = cosh
let asin = asin
let sin = sin
let sinh = sinh
let tan = tan
let tanh = tanh
let atan = atan
let atan2 = atan2
let hypot = hypot
let ceil = ceil
let floor = floor
let abs_float = abs_float
let copysign = copysign
let modf = modf
let zero = 0.
let one = 1.
let of_float32 f = f
let of_float f = f
let to_float32 f = f
let make_shared i = Array.make (Int32.to_int i) 0.
let make_local i = Array.make (Int32.to_int i) 0.
end
end
| null | https://raw.githubusercontent.com/mathiasbourgoin/SPOC/ddfde5bdb089f519457c7bb0a2cb1469d71d00fb/SpocLibs/Sarek/Kirc.ml | ocaml | <---
<---
in
external from SPOC
"sspoc_var"^(string_of_int i)^
let s = (load_file "kirc_kernel.ptx") in
kir#run a b q dev;
"spoc_var"^(string_of_int i)^
todo
todo | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
- * , et ( 2012 )
*
*
*
* This software is a computer program whose purpose is to allow
* GPU programming with the OCaml language .
*
* This software is governed by the CeCILL - B license under French law and
* abiding by the rules of distribution of free software . You can use ,
* modify and/ or redistribute the software under the terms of the CeCILL - B
* license as circulated by CEA , CNRS and INRIA at the following URL
* " " .
*
* As a counterpart to the access to the source code and rights to copy ,
* modify and redistribute granted by the license , users are provided only
* with a limited warranty and the software 's author , the holder of the
* economic rights , and the successive licensors have only limited
* liability .
*
* In this respect , the user 's attention is drawn to the risks associated
* with loading , using , modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software ,
* that may mean that it is complicated to manipulate , and that also
* therefore means that it is reserved for developers and experienced
* professionals having in - depth computer knowledge . Users are therefore
* encouraged to load and test the software 's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and , more generally , to use and operate it in the
* same conditions as regards security .
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL - B license and that you accept its terms .
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
- * Mathias Bourgoin, Université Pierre et Marie Curie (2012)
*
*
*
* This software is a computer program whose purpose is to allow
* GPU programming with the OCaml language.
*
* This software is governed by the CeCILL-B license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-B
* license as circulated by CEA, CNRS and INRIA at the following URL
* "".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*******************************************************************************)
open Spoc
open Kernel
let debug = true
let idkern = ref 0
open Kirc_Ast
module Kirc_OpenCL = Gen.Generator (Kirc_OpenCL)
module Kirc_Cuda = Gen.Generator (Kirc_Cuda)
module Kirc_Profile = Gen.Generator (Profile)
type float64 = float
type float32 = float
type extension = ExFloat32 | ExFloat64
type ('a, 'b, 'c) kirc_kernel =
{ ml_kern: 'a
; body: Kirc_Ast.k_ext
; ret_val: Kirc_Ast.k_ext * ('b, 'c) Vector.kind
; extensions: extension array }
type ('a, 'b, 'c, 'd) kirc_function =
{ fun_name: string
; ml_fun: 'a
; funbody: Kirc_Ast.k_ext
; fun_ret: Kirc_Ast.k_ext * ('b, 'c) Vector.kind
; fastflow_acc: 'd
; fun_extensions: extension array }
type ('a, 'b, 'c, 'd, 'e) sarek_kernel =
('a, 'b) spoc_kernel * ('c, 'd, 'e) kirc_kernel
let constructors = ref []
let opencl_head =
"#define SAREK_VEC_LENGTH(A) sarek_## A ##_length\n"
^ "float spoc_fadd ( float a, float b );\n"
^ "float spoc_fminus ( float a, float b );\n"
^ "float spoc_fmul ( float a, float b );\n"
^ "float spoc_fdiv ( float a, float b );\n" ^ "int logical_and (int, int);\n"
^ "int spoc_powint (int, int);\n" ^ "int spoc_xor (int, int);\n"
^ "float spoc_fadd ( float a, float b ) { return (a + b);}\n"
^ "float spoc_fminus ( float a, float b ) { return (a - b);}\n"
^ "float spoc_fmul ( float a, float b ) { return (a * b);}\n"
^ "float spoc_fdiv ( float a, float b ) { return (a / b);}\n"
^ "int logical_and (int a, int b ) { return (a & b);}\n"
^ "int spoc_powint (int a, int b ) { return ((int) pow (((float) a), \
((float) b)));}\n" ^ "int spoc_xor (int a, int b ) { return (a^b);}\n"
^ "void spoc_barrier ( ) { barrier(CLK_LOCAL_MEM_FENCE);}\n"
let opencl_common_profile =
"\n/*********** PROFILER FUNCTIONS **************/\n"
^ "#pragma OPENCL EXTENSION cl_khr_int64_extended_atomics : enable\n"
^ "void spoc_atomic_add(__global ulong *a, ulong b){ atom_add(a, (ulong)b);}\n"
^ "\n\
\ void* memory_analysis(__global ulong *profile_counters, __global \
void* mp, int store, int load){\n\
\ if (store) spoc_atomic_add(profile_counters+0, 1ULL);\n\
\ if (load) spoc_atomic_add(profile_counters+1, 1ULL);\n\
\ return mp;\n\
}" ^ "\n"
let opencl_profile_head =
opencl_common_profile
^ "\n\
void branch_analysis(__global ulong *profile_counters, int eval, int \
counters){\n\
\ \n\
\ unsigned int threadIdxInGroup = \n\
\ get_local_id(2)*get_local_size(0)*get_local_size(1) + \n\
\ get_local_id(1)*get_local_size(0) + get_local_id(0);\n\
\ \n\
\ \n\
\ //Get count of 1) active work items in this workgroup\n\
\ //2) work items that will take the branch\n\
\ //3) work items that do not take the branch.\n\
\ __local ulong numActive[1]; numActive[0] = 0;\n\
\ __local ulong numTaken[1]; numTaken[0] = 0;\n\
\ __local ulong numNotTaken[1]; numNotTaken[0] = 0;\n\
\ __local unsigned int lig[1]; lig[0] = 0;\n\
\ barrier(CLK_LOCAL_MEM_FENCE);\n\n\
\ atomic_inc(numActive);\n\
\ atom_max(lig, threadIdxInGroup);\n\
\ \n\
\ if (eval) atomic_inc(numTaken);\n\
\ if (!eval) atomic_inc(numNotTaken);\n\
\ \n\
\ barrier(CLK_LOCAL_MEM_FENCE);\n\
\ \n\
\ // The last active work item in each group gets to write results.\n\
\ if (lig[0] == threadIdxInGroup) {\n\
\ spoc_atomic_add(profile_counters+4, (ulong)1); //\n\
\ spoc_atomic_add(profile_counters+counters+1, numActive[0]);\n\
\ spoc_atomic_add(profile_counters+counters+2, numTaken[0]);\n\
\ spoc_atomic_add(profile_counters+counters+3, numNotTaken[0]);\n\
\ if (numTaken[0] != numActive[0] && numNotTaken[0] != numActive[0]) {\n\
\ // If threads go different ways, note it.\n\
\ spoc_atomic_add(profile_counters+5, (ulong)1);\n\
\ }\n\
\ }\n\
}\n"
^ "void while_analysis(__global ulong *profile_counters, int eval){\n\
\ /* unsigned int threadIdxInGroup = \n\
\ get_local_id(2)*get_local_size(0)*get_local_size(1) + \n\
\ get_local_id(1)*get_local_size(0) + get_local_id(0);\n\n\
\ //Get count of 1) active work items in this workgroup\n\
\ //2) work items that will take the branch\n\
\ //3) work items that do not take the branch.\n\
\ __local ulong numActive[1]; numActive[0] = 0;\n\
\ __local unsigned int numTaken; numTaken = 0;\n\
\ __local unsigned int numNotTaken; numNotTaken = 0;\n\
\ __local unsigned int lig; lig = 0;\n\
\ barrier(CLK_LOCAL_MEM_FENCE);\n\n\
\ atomic_inc(numActive);\n\
\ atom_max(&lig, threadIdxInGroup);\n\
\ \n\
\ if (eval) atom_inc(&numTaken);\n\
\ if (!eval) atom_inc(&numNotTaken);\n\
\ \n\
\ barrier(CLK_LOCAL_MEM_FENCE);\n\
\ \n\
\ // The last active work item in each group gets to write results.\n\
\ if (lig == threadIdxInGroup) {\n\
\ spoc_atomic_add(profile_counters+4, (ulong)1); //\n\
\ if (numTaken != numActive[0] && numNotTaken != numActive[0]) {\n\
\ // If threads go different ways, note it.\n\
\ spoc_atomic_add(profile_counters+5, (ulong)1);\n\
\ }\n\
\ } */ \n\
}\n\n"
let opencl_profile_head_cpu =
opencl_common_profile
^ "\n\
void branch_analysis(__global ulong *profile_counters, int eval, int \
counters){\n\
\ \n\
\ unsigned int threadIdxInGroup = \n\
\ get_local_id(2)*get_local_size(0)*get_local_size(1) + \n\
\ get_local_id(1)*get_local_size(0) + get_local_id(0);\n\
\ \n\
\ spoc_atomic_add(profile_counters+4, (ul;ong)1); //\n\
\ spoc_atomic_add(profile_counters+counters+1, 1);\n\
\ if (eval) \n\
\ spoc_atomic_add(profile_counters+counters+2, 1);\n\
\ if (!eval)\n\
\ spoc_atomic_add(profile_counters+counters+3, 1);\n\
\ }\n"
^ "void while_analysis(__global ulong *profile_counters, int eval){\n}\n\n"
let opencl_float64 =
"#ifndef __FLOAT64_EXTENSION__ \n" ^ "#define __FLOAT64_EXTENSION__ \n"
^ "#if defined(cl_khr_fp64) // Khronos extension available?\n"
^ "#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
^ "#elif defined(cl_amd_fp64) // AMD extension available?\n"
^ "#pragma OPENCL EXTENSION cl_amd_fp64 : enable\n" ^ "#endif\n"
^ "double spoc_dadd ( double a, double b );\n"
^ "double spoc_dminus ( double a, double b );\n"
^ "double spoc_dmul ( double a, double b );\n"
^ "double spoc_ddiv ( double a, double b );\n"
^ "double spoc_dadd ( double a, double b ) { return (a + b);}\n"
^ "double spoc_dminus ( double a, double b ) { return (a - b);}\n"
^ "double spoc_dmul ( double a, double b ) { return (a * b);}\n"
^ "double spoc_ddiv ( double a, double b ) { return (a / b);}\n" ^ "#endif\n"
let cuda_float64 =
"#ifndef __FLOAT64_EXTENSION__ \n" ^ "#define __FLOAT64_EXTENSION__ \n"
^ "__device__ double spoc_dadd ( double a, double b ) { return (a + b);}\n"
^ "__device__ double spoc_dminus ( double a, double b ) { return (a - b);}\n"
^ "__device__ double spoc_dmul ( double a, double b ) { return (a * b);}\n"
^ "__device__ double spoc_ddiv ( double a, double b ) { return (a / b);}\n"
^ "#endif\n"
let cuda_head =
"#define SAREK_VEC_LENGTH(a) sarek_ ## a ## _length\n"
^ "#define FULL_MASK 0xffffffff\n"
^ "__device__ float spoc_fadd ( float a, float b ) { return (a + b);}\n"
^ "__device__ float spoc_fminus ( float a, float b ) { return (a - b);}\n"
^ "__device__ float spoc_fmul ( float a, float b ) { return (a * b);}\n"
^ "__device__ float spoc_fdiv ( float a, float b ) { return (a / b);}\n"
^ "__device__ int logical_and (int a, int b ) { return (a & b);}\n"
^ "__device__ int spoc_powint (int a, int b ) { return ((int) pow \
(((double) a), ((double) b)));}\n"
^ "__device__ int spoc_xor (int a, int b ) { return (a^b);}\n"
let cuda_profile_head =
"\n/*********** PROFILER FUNCTIONS **************/\n"
^ "__device__ void spoc_atomic_add(unsigned long long int *a, unsigned int \
b){ atomicAdd(a, b);}\n"
^ "__device__ __forceinline__ unsigned int get_laneid(void) {\n\
\ unsigned int laneid;\n\
\ asm volatile (\"mov.u32 %0, %laneid;\" : \"=r\"(laneid));\n\
\ return laneid;\n\
\ }\n"
^ "__device__ void branch_analysis(unsigned long long int \
*profile_counters, int eval, int counters){\n\
\ \n\
\ int threadIdxInWarp = get_laneid();//threadIdx.x & (warpSize-1);\n\
\ \n\
\ //Get count of 1) active threads in this warp\n\
\ //2) threads that will take the branch\n\
\ //3) threads that do not take the branch.\n\
\ unsigned int active = __ballot(1);\n\
\ int taken = __ballot(eval);\n\
\ int ntaken = __ballot(!eval);\n\
\ int numActive = __popc(active);\n\
\ int numTaken = __popc(taken), numNotTaken = __popc(ntaken);\n\n\
\ // The first active thread in each warp gets to write results.\n\
\ if ((__ffs(active)-1) == threadIdxInWarp) {\n\
\ atomicAdd(profile_counters+4, 1ULL); //\n\
\ atomicAdd(profile_counters+counters+1, numActive);\n\
\ atomicAdd(profile_counters+counters+2, numTaken);\n\
\ atomicAdd(profile_counters+counters+3, numNotTaken);\n\
\ if (numTaken != numActive && numNotTaken != numActive) {\n\
\ // If threads go different ways, note it.\n\
\ atomicAdd(profile_counters+5, 1ULL);\n\
\ }\n\
\ }\n\
}\n"
^ "__device__ void while_analysis(unsigned long long int *profile_counters, \
int eval){\n\n\
\ int threadIdxInWarp = get_laneid();//threadIdx.x & (warpSize-1);\n\n\
\ //Get count of 1) active threads in this \
warp //2) threads that will take the \
branch //3) threads that do not \
take the \
branch. \n\
\ int active = __ballot(1);\n\
\ int taken = __ballot(eval);\n\
\ int ntaken = __ballot(!eval);\n\
\ int numActive = __popc(active);\n\
\ int numTaken = __popc(taken), numNotTaken = __popc(ntaken);\n\n\
\ // The first active thread in each warp gets to write \
results. \n\
\ if ((__ffs(active)-1) == threadIdxInWarp) {\n\
\ atomicAdd(profile_counters+4, 1ULL); \
// \n\
\ if (numTaken != numActive && numNotTaken != numActive) {\n\
\ // If threads go different ways, note \
it. \n\
\ atomicAdd(profile_counters+5, 1ULL);\n\
\ }\n\
\ }\n\
}\n\n"
^ "\n\
#include<cuda.h>\n\
template <typename T>\n\
__device__ T __broadcast(T t, int fromWhom)\n\
{\n\
\ union {\n\
\ int32_t shflVals[sizeof(T)];\n\
\ T t;\n\
\ } p;\n\
\ \n\
\ p.t = t;\n\
\ #pragma unroll\n\
\ for (int i = 0; i < sizeof(T); i++) {\n\
\ int32_t shfl = (int32_t)p.shflVals[i];\n\
\ p.shflVals[i] = __shfl(shfl, fromWhom);\n\
\ }\n\
\ return p.t;\n\
}\n\n\
/// The number of bits we need to shift off to get the cache line address.\n\
#define LINE_BITS 5\n\n\
template<typename T>\n\
__device__ T* memory_analysis(unsigned long long int *profile_counters, \
T* mp, int store, int load){\n\n\
\ int threadIdxInWarp = get_laneid();//threadIdx.x & (warpSize-1);\n\
\ intptr_t addrAsInt = (intptr_t) mp;\n\n\
\ if (__isGlobal(mp)){\n\
\ if (store) atomicAdd(profile_counters+0, 1ULL);\n\
\ if (load) atomicAdd(profile_counters+1, 1ULL);\n\n\
\ unsigned unique = 0; // Num unique lines per warp.\n\n\
\ // Shift off the offset bits into the cache line.\n\
\ intptr_t lineAddr = addrAsInt >> LINE_BITS;\n\n\
\ int workset = __ballot(1);\n\
\ int firstActive = __ffs(workset)-1;\n\
\ int numActive = __popc(workset);\n\
\ while (workset) {\n\
\ // Elect a leader, get its cache line, see who matches it.\n\
\ int leader = __ffs(workset) - 1;\n\
\ intptr_t leadersAddr = __broadcast(lineAddr, leader);\n\
\ int notMatchesLeader = __ballot(leadersAddr != lineAddr);\n\n\
\ // We have accounted for all values that match the leader’s.\n\
\ // Let’s remove them all from the workset.\n\
\ workset = workset & notMatchesLeader;\n\
\ unique++;\n\
\ }\n\n\
\ if (firstActive == threadIdxInWarp && unique ) {\n\
\ atomicAdd(profile_counters+6, 1ULL);\n\
\ }\n\
\ \n\
\ }\n\
\ return mp;\n\n\
}\n" ^ "\n"
let eint32 = EInt32
let eint64 = EInt64
let efloat32 = EFloat32
let efloat64 = EFloat64
let global = Global
let local = LocalSpace
let shared = Shared
let new_var i = IdName ("spoc_var" ^ string_of_int i)
let new_array n l t m = Arr (n, l, t, m)
let var i s = IntId (s, i)
( " spoc_var"^(string_of_int i ) ) , i )
let spoc_gen_kernel args body = Kern (args, body)
let spoc_fun_kernel _a _b = ()
let global_fun a =
GlobalFun
( a.funbody
, ( match snd a.fun_ret with
| Vector.Int32 _ -> "int"
| Vector.Float32 _ -> "float"
| Vector.Custom _ -> (
match fst a.fun_ret with
| CustomVar (s, _, _) -> "struct " ^ s ^ "_sarek"
| _ -> assert false )
| _ -> "void" )
, a.fun_name )
let seq a b = Seq (a, b)
let app a b = App (a, b)
let spoc_unit () = Unit
let spoc_int a = Int a
let global_int_var a = GInt a
let global_float_var a = GFloat a
let global_float64_var a = GFloat64 a
let spoc_int32 a = Int (Int32.to_int a)
let spoc_float f = Float f
let spoc_double d = Double d
let spoc_int_id a = Int a
IntId ( a,-1 )
let spoc_float_id a = Float a
let spoc_plus a b = Plus (a, b)
let spoc_plus_float a b = Plusf (a, b)
let spoc_min a b = Min (a, b)
let spoc_min_float a b = Minf (a, b)
let spoc_mul a b = Mul (a, b)
let spoc_mul_float a b = Mulf (a, b)
let spoc_div a b = Div (a, b)
let spoc_div_float a b = Divf (a, b)
let spoc_mod a b = Mod (a, b)
let spoc_ife a b c = Ife (a, b, c)
let spoc_if a b = If (a, b)
let spoc_match s e l = Match (s, e, l)
let spoc_case i o e : case = (i, o, e)
let spoc_do a b c d = DoLoop (a, b, c, d)
let spoc_while a b = While (a, b)
let params l = Params l
let spoc_id _i = Id ""
let spoc_constr t c params = Constr (t, c, params)
let spoc_record t params = Record (t, params)
let spoc_return k = Return k
let concat a b = Concat (a, b)
let empty_arg () = Empty
let new_int_var i s = IntVar (i, s)
let new_float_var i s = FloatVar (i, s)
let new_float64_var i s = DoubleVar (i, s)
let new_double_var i s = DoubleVar (i, s)
let new_unit_var i s = UnitVar (i, s)
let new_custom_var n v s = Custom (n, v, s)
let new_int_vec_var v s = VecVar (Int 0, v, s)
let new_float_vec_var v s = VecVar (Float 0., v, s)
let new_double_vec_var v s = VecVar (Double 0., v, s)
let new_custom_vec_var n v s = VecVar (Custom (n, 0, s), v, s)
let int_vect i = IntVect i
let spoc_rec_get r id = RecGet (r, id)
let spoc_rec_set r v = RecSet (r, v)
let set_vect_var vecacc value = SetV (vecacc, value)
let set_arr_var arracc value = SetV (arracc, value)
let intrinsics a b = Intrinsics (a, b)
let spoc_local_env local_var b = Local (local_var, b)
let spoc_set name value = Set (name, value)
let spoc_declare name = Decl name
let spoc_local_var a = a
let spoc_acc a b = Acc (a, b)
let int_var i = i
let int32_var i = i
let float_var f = f
let double_var d = CastDoubleVar (d, "")
let equals a b = EqBool (a, b)
let equals_custom s v1 v2 = EqCustom (s, v1, v2)
let equals32 a b = EqBool (a, b)
let equals64 a b = EqBool (a, b)
let equalsF a b = EqBool (a, b)
let equalsF64 a b = EqBool (a, b)
let b_or a b = Or (a, b)
let b_and a b = And (a, b)
let b_not a = Not a
let lt a b = LtBool (a, b)
let lt32 a b = LtBool (a, b)
let lt64 a b = LtBool (a, b)
let ltF a b = LtBool (a, b)
let ltF64 a b = LtBool (a, b)
let gt a b = GtBool (a, b)
let gt32 a b = GtBool (a, b)
let gt64 a b = GtBool (a, b)
let gtF a b = GtBool (a, b)
let gtF64 a b = GtBool (a, b)
let lte a b = LtEBool (a, b)
let lte32 a b = LtEBool (a, b)
let lte64 a b = LtEBool (a, b)
let lteF a b = LtEBool (a, b)
let lteF64 a b = LtEBool (a, b)
let gte a b = GtEBool (a, b)
let gte32 a b = GtEBool (a, b)
let gte64 a b = GtEBool (a, b)
let gteF a b = GtEBool (a, b)
let gteF64 a b = GtEBool (a, b)
let get_vec a b = IntVecAcc (a, b)
let get_arr a b = IntVecAcc (a, b)
let return_unit () = Unit
let return_int i s = IntVar (i, s)
let return_float f s = FloatVar (f, s)
let return_double d s = DoubleVar (d, s)
let return_bool b s = BoolVar (b, s)
let return_custom n sn s = CustomVar (n, sn, s)
let spoc_native f = Native f
let pragma l e = Pragma (l, e)
let map f a b = Map (f, a, b)
let print_ast = Kirc_Ast.print_ast
let debug_print (ker : ('a, 'b, 'c, 'd, 'e) sarek_kernel) =
let _, k = ker in
let _k1, k2, _k3 = (k.ml_kern, k.body, k.ret_val) in
print_ast k2
let rewrite ker =
let b = ref false in
let rec aux kern =
match kern with
| Native _ -> kern
| Pragma (opts, k) -> Pragma (opts, aux k)
| Block b -> Block (aux b)
| Kern (k1, k2) -> Kern (aux k1, aux k2)
| Params k -> Params (aux k)
| Plus (k1, k2) -> Plus (aux k1, aux k2)
| Plusf (k1, k2) -> (
match (k1, k2) with
| Float f1, Float f2 ->
b := true ;
Float (f1 +. f2)
| _ -> Plusf (aux k1, aux k2) )
| Min (k1, k2) -> Min (aux k1, aux k2)
| Minf (k1, k2) -> (
match (k1, k2) with
| Float f1, Float f2 ->
b := true ;
Float (f1 +. f2)
| _ -> Minf (aux k1, aux k2) )
| Mul (k1, k2) -> Mul (aux k1, aux k2)
| Mulf (k1, k2) -> (
match (k1, k2) with
| Float f1, Float f2 ->
b := true ;
Float (f1 +. f2)
| _ -> Mulf (aux k1, aux k2) )
| Div (k1, k2) -> Div (aux k1, aux k2)
| Divf (k1, k2) -> (
match (k1, k2) with
| Float f1, Float f2 ->
b := true ;
Float (f1 +. f2)
| _ -> Divf (aux k1, aux k2) )
| Mod (k1, k2) -> Mod (aux k1, aux k2)
| Id _ -> kern
| IdName _ -> kern
| IntVar _ -> kern
| FloatVar _ -> kern
| UnitVar _ -> Seq (kern, kern)
| CastDoubleVar _ -> kern
| DoubleVar _ -> kern
| BoolVar _ -> kern
| VecVar (k, idx, s) -> VecVar (aux k, idx, s)
| Concat (k1, k2) -> Concat (aux k1, aux k2)
| Constr (t, c, l) -> Constr (t, c, List.map aux l)
| Record (t, l) -> Record (t, List.map aux l)
| RecGet (r, s) -> RecGet (aux r, s)
| RecSet (r, v) -> RecSet (aux r, aux v)
| Empty -> kern
| Seq (k1, Unit) -> aux k1
| Seq (k1, k2) -> Seq (aux k1, aux k2)
| Return k -> (
match k with
| Return k ->
b := true ;
aux (Return k)
| Acc _ | Set _ -> aux k
| Ife (k1, k2, k3) ->
b := true ;
Ife (aux k1, aux (Return k2), aux (Return k3))
| If (k1, k2) ->
b := true ;
If (aux k1, aux (Return k2))
| DoLoop (k1, k2, k3, k4) ->
b := true ;
DoLoop (aux k1, aux k2, aux k3, aux (Return k4))
| While (k1, k2) ->
b := true ;
While (aux k1, aux (Return k2))
| Seq (k1, k2) ->
b := true ;
Seq (aux k1, aux (Return k2))
| Match (s, a, bb) ->
b := true ;
Match
( s
, aux a
, Array.map (fun (i, ofid, e) -> (i, ofid, aux (Return e))) bb )
| _ -> Return (aux k) )
| Acc (k1, k2) -> (
match k2 with
| Ife (k1', k2', k3') ->
b := true ;
Ife (aux k1', aux (Acc (k1, k2')), aux (Acc (k1, k3')))
| If (k1', k2') ->
b := true ;
If (aux k1', aux (Acc (k1, k2')))
| DoLoop (k1', k2', k3', k4') ->
b := true ;
DoLoop (aux k1', aux k2', aux k3', aux (Acc (k1, k4')))
| While (k1', k2') ->
b := true ;
While (aux k1', aux (Acc (k1, k2')))
| Seq (k1', k2') ->
b := true ;
Seq (aux k1', aux (Acc (k1, k2')))
| Match (s, a, bb) ->
b := true ;
Match
( s
, aux a
, Array.map (fun (i, ofid, e) -> (i, ofid, aux (Acc (k1, e)))) bb
)
| Return _ -> assert false
| _ -> Acc (aux k1, aux k2) )
| Set (k1, k2) -> aux (Acc (k1, k2))
| Decl k1 -> aux k1
| SetV (k1, k2) -> (
match k2 with
| Seq (k3, k4) -> Seq (k3, SetV (aux k1, aux k4))
| Ife (k3, k4, k5) ->
b := true ;
Ife (aux k3, SetV (aux k1, aux k4), SetV (aux k1, k5))
| Match (s, a, bb) ->
b := true ;
Match
( s
, aux a
, Array.map
(fun (i, ofid, e) -> (i, ofid, SetV (aux k1, aux e)))
bb )
| _ -> SetV (aux k1, aux k2) )
| SetLocalVar (k1, k2, k3) -> SetLocalVar (aux k1, aux k2, aux k3)
| Intrinsics _ -> kern
| IntId _ -> kern
| Int _ -> kern
| GInt _ -> kern
| GFloat _ -> kern
| GFloat64 _ -> kern
| Float _ -> kern
| Double _ -> kern
| Custom _ -> kern
| IntVecAcc (k1, k2) -> (
match k2 with
| Seq (k3, k4) -> Seq (k3, IntVecAcc (aux k1, aux k4))
| _ -> IntVecAcc (aux k1, aux k2) )
| Local (k1, k2) -> Local (aux k1, aux k2)
| Ife (k1, k2, k3) -> Ife (aux k1, aux k2, aux k3)
| If (k1, k2) -> If (aux k1, aux k2)
| Not k -> Not (aux k)
| Or (k1, k2) -> Or (aux k1, aux k2)
| And (k1, k2) -> And (aux k1, aux k2)
| EqBool (k1, k2) -> EqBool (aux k1, aux k2)
| EqCustom (n, k1, k2) -> EqCustom (n, aux k1, aux k2)
| LtBool (k1, k2) -> LtBool (aux k1, aux k2)
| GtBool (k1, k2) -> GtBool (aux k1, aux k2)
| LtEBool (k1, k2) -> LtEBool (aux k1, aux k2)
| GtEBool (k1, k2) -> GtEBool (aux k1, aux k2)
| DoLoop (k1, k2, k3, k4) -> DoLoop (aux k1, aux k2, aux k3, aux k4)
| Arr (l, t, s, m) -> Arr (l, t, s, m)
| While (k1, k2) -> While (aux k1, aux k2)
| App (a, b) -> App (aux a, Array.map aux b)
| GlobalFun (a, b, n) -> GlobalFun (aux a, b, n)
| Unit -> kern
| Match (s, a, b) ->
Match (s, aux a, Array.map (fun (i, ofid, e) -> (i, ofid, aux e)) b)
| CustomVar _ -> kern
| Map (a, b, c) -> Map (aux a, aux b, aux c)
in
let kern = ref (aux ker) in
while !b do
b := false ;
kern := aux !kern
done ;
!kern
let return_v = ref ("", "")
let save file string =
ignore (Sys.command ("rm -f " ^ file)) ;
let channel = open_out file in
output_string channel string ;
close_out channel
let load_file f =
let ic = open_in f in
let n = in_channel_length ic in
let s = Bytes.make n ' ' in
really_input ic s 0 n ; close_in ic ; s
external print_source : string - > unit = " "
let gen_profile ker dev =
let _kir, k = ker in
let _k1, _k2, _k3 = (k.ml_kern, k.body, k.ret_val) in
return_v := ("", "") ;
let k ' =
* ( 0 ( fst k3 ) dev
* , match fst k3 with
* ( i , s ) | FloatVar ( i , s ) | DoubleVar ( i , s ) - >
* s ( \*"sspoc_var"^(string_of_int i)^*\ ) ^ " = "
* | Unit - > " "
* | SetV _ - > " "
* | IntVecAcc _ - > " "
* | VecVar _ - > " "
* | _ - >
* debug_print
* ( kir
* , { ml_kern= k1
* ; k3
* ; ret_val= k3
* ; extensions= k.extensions } ) ;
* Stdlib.flush stdout ;
* assert false )
* ( Kirc_Profile.parse 0 (fst k3) dev
* , match fst k3 with
* | IntVar (i, s) | FloatVar (i, s) | DoubleVar (i, s) ->
* s (\*"sspoc_var"^(string_of_int i)^*\) ^ " = "
* | Unit -> ""
* | SetV _ -> ""
* | IntVecAcc _ -> ""
* | VecVar _ -> ""
* | _ ->
* debug_print
* ( kir
* , { ml_kern= k1
* ; body= fst k3
* ; ret_val= k3
* ; extensions= k.extensions } ) ;
* Stdlib.flush stdout ;
* assert false ) *)
let profile_source = Kirc_Profile.parse 0 _k2 dev in
Printf.printf "%s" profile_source
external nvrtc_ptx : string -> string array -> string = "spoc_nvrtc_ptx"
let gen ?keep_temp:(kt=false) ?profile:(prof = false) ?return:(r = false) ?only:o
?nvrtc_options:(nvopt = [||]) (ker : ('a, 'b, 'c, 'd, 'e) sarek_kernel) dev
=
let kir, k = ker in
let k1, k2, k3 = (k.ml_kern, k.body, k.ret_val) in
return_v := ("", "") ;
let k' =
( Kirc_Cuda.parse ~profile:prof 0 (fst k3) dev
, match fst k3 with
| IntVar (_i, s) | FloatVar (_i, s) | DoubleVar (_i, s) ->
| Unit -> ""
| SetV _ -> ""
| IntVecAcc _ -> ""
| VecVar _ -> ""
| _ ->
debug_print
( kir
, { ml_kern= k1
; body= fst k3
; ret_val= k3
; extensions= k.extensions } ) ;
Stdlib.flush stdout ;
assert false )
in
if r then (
Kirc_Cuda.return_v := k' ;
Kirc_OpenCL.return_v := k' ) ;
let gen_cuda ?opts:(_s = "") () =
let cuda_head =
Array.fold_left
(fun header extension ->
match extension with
| ExFloat32 -> header
| ExFloat64 -> cuda_float64 ^ header )
cuda_head k.extensions
in
let src = Kirc_Cuda.parse ~profile:prof 0 (rewrite k2) dev in
let global_funs = ref "" in
Hashtbl.iter
(fun _ a -> global_funs := !global_funs ^ fst a ^ "\n")
Kirc_Cuda.global_funs ;
let i = ref 0 in
let constructors =
List.fold_left
(fun a b ->
incr i ;
(if !i mod 3 = 0 then " " else "__device__ ") ^ b ^ a )
"\n\n" !constructors
in
let protos =
"/************* FUNCTION PROTOTYPES ******************/\n"
^ List.fold_left (fun a b -> b ^ ";\n" ^ a) "" !Kirc_Cuda.protos
in
if debug then
save
("kirc_kernel" ^ string_of_int !idkern ^ ".cu")
( cuda_head
^ (if prof then cuda_profile_head else "")
^ constructors ^ protos ^ !global_funs ^ src ) ;
ignore(Sys.command ( " nvcc -g -G " ^ s ^ " " ^"-arch = sm_30 -ptx kirc_kernel.cu -o kirc_kernel.ptx " ) ) ;
let genopt =
match dev.Devices.specific_info with
| Devices.CudaInfo cu ->
let computecap = (cu.Devices.major * 10) + cu.Devices.minor in
[| ( if computecap < 35 then
failwith "CUDA device too old for this XXX"
else if computecap < 35 then "--gpu-architecture=compute_30"
else if computecap < 50 then "--gpu-architecture=compute_35"
else if computecap < 52 then "--gpu-architecture=compute_50"
else if computecap < 53 then "--gpu-architecture=compute_52"
else if computecap < 60 then "--gpu-architecture=compute_53"
else if computecap < 61 then "--gpu-architecture=compute_60"
else if computecap < 62 then "--gpu-architecture=compute_61"
else if computecap < 70 then "--gpu-architecture=compute_30"
else if computecap < 72 then "--gpu-architecture=compute_70"
else if computecap < 75 then "--gpu-architecture=compute_72"
else if computecap = 75 then "--gpu-architecture=compute_75"
else if computecap = 80 then "--gpu-architecture=compute_80"
else if computecap = 86 then "--gpu-architecture=compute_86"
else "--gpu-architecture=compute_35" ) |]
| _ -> [||]
in
let nvrtc_options = Array.append nvopt genopt in
let s =
nvrtc_ptx
( cuda_head
^ (if prof then cuda_profile_head else "")
^ constructors ^ !global_funs ^ src )
nvrtc_options
in
save ("kirc_kernel" ^ string_of_int !idkern ^ ".ptx") s ;
kir#set_cuda_sources s ;
if not kt then ignore
(Sys.command
( "rm kirc_kernel" ^ string_of_int !idkern ^ ".cu kirc_kernel"
^ string_of_int !idkern ^ ".ptx" )) ;
incr idkern
and gen_opencl () =
let opencl_head =
Array.fold_left
(fun header extension ->
match extension with
| ExFloat32 -> header
| ExFloat64 -> opencl_float64 ^ header )
opencl_head k.extensions
in
let src = Kirc_OpenCL.parse ~profile:prof 0 (rewrite k2) dev in
let global_funs =
ref "/************* FUNCTION DEFINITIONS ******************/\n"
in
Hashtbl.iter
(fun _ a -> global_funs := !global_funs ^ "\n" ^ fst a ^ "\n")
Kirc_OpenCL.global_funs ;
let constructors =
"/************* CUSTOM TYPES ******************/\n"
^ List.fold_left (fun a b -> b ^ a) "\n\n" !constructors
in
let protos =
"/************* FUNCTION PROTOTYPES ******************/\n"
^ List.fold_left (fun a b -> b ^ ";\n" ^ a) "" !Kirc_OpenCL.protos
in
let clkernel =
( if prof then
"#pragma OPENCL EXTENSION cl_khr_int64_base_atomics : enable\n"
else "" )
^ opencl_head
^ ( if prof then
match dev.Devices.specific_info with
| Devices.OpenCLInfo
{Devices.device_type= Devices.CL_DEVICE_TYPE_CPU ; _} ->
opencl_profile_head_cpu
| _ -> opencl_profile_head
else "" )
^ constructors ^ protos ^ !global_funs ^ src
in
save ("kirc_kernel" ^ string_of_int !idkern ^ ".cl") clkernel ;
kir#set_opencl_sources clkernel;
if not kt then ignore
(Sys.command
( "rm kirc_kernel" ^ string_of_int !idkern ^ ".cl" )) ;
in
( match o with
| None -> (
match dev.Devices.specific_info with
| Devices.OpenCLInfo _ ->
ignore (Kirc_OpenCL.get_profile_counter ()) ;
gen_opencl ()
| _ ->
ignore (Kirc_OpenCL.get_profile_counter ()) ;
gen_cuda () )
| Some d -> (
match d with
| Devices.Both ->
ignore (Kirc_Cuda.get_profile_counter ()) ;
gen_cuda () ;
ignore (Kirc_OpenCL.get_profile_counter ()) ;
gen_opencl ()
| Devices.Cuda ->
ignore (Kirc_Cuda.get_profile_counter ()) ;
gen_cuda ()
| Devices.OpenCL ->
ignore (Kirc_OpenCL.get_profile_counter ()) ;
gen_opencl () ) ) ;
kir#reset_binaries () ;
ignore (kir#compile dev) ;
(kir, k)
let arg_of_vec v =
match Vector.kind v with
| Vector.Int32 _ -> Kernel.VInt32 v
| Vector.Float32 _ -> Kernel.VFloat32 v
| Vector.Int64 _ -> Kernel.VInt64 v
| _ -> assert false
let run ?recompile:(r = false) (ker : ('a, 'b, 'c, 'd, 'e) sarek_kernel) a
(block, grid) _q dev =
let kir, k = ker in
( match dev.Devices.specific_info with
| Devices.CudaInfo _ -> (
if r then ignore (gen ~only:Devices.Cuda (kir, k) dev)
else
match kir#get_cuda_sources () with
| [] -> ignore (gen ~only:Devices.Cuda (kir, k) dev)
| _ -> () )
| Devices.OpenCLInfo _ -> (
if r then ignore (gen ~only:Devices.OpenCL (kir, k) dev)
else
match kir#get_opencl_sources () with
| [] -> ignore (gen ~only:Devices.OpenCL (kir, k) dev)
| _ -> () ) ) ;
let args = kir#args_to_list a in
let offset = ref 0 in
kir#compile ~debug:true dev ;
let bin = Hashtbl.find (kir#get_binaries ()) dev in
let nvec = ref 0 in
Array.iter
(fun a ->
match a with
| VChar _v
|VFloat32 _v
|VFloat64 _v
|VInt32 _v
|VInt64 _v
|VComplex32 _v
|VCustom _v ->
incr nvec
| _ -> () )
args ;
match dev.Devices.specific_info with
| Devices.CudaInfo _cI ->
let extra = Kernel.Cuda.cuda_create_extra (Array.length args + !nvec) in
. Cuda.cuda_load_arg offset extra dev ( arg_of_vec profiler_counters ) ;
let idx = ref 0 in
Array.iter
(fun a ->
match a with
| VChar v
|VFloat32 v
|VFloat64 v
|VInt32 v
|VInt64 v
|VComplex32 v
|VCustom v ->
Kernel.Cuda.cuda_load_arg offset extra dev bin !idx a ;
Kernel.Cuda.cuda_load_arg offset extra dev bin (!idx + 1)
(Kernel.Int32 (Vector.length v)) ;
idx := !idx + 2
| _ ->
Kernel.Cuda.cuda_load_arg offset extra dev bin idx a ;
incr idx )
args ;
Kernel.Cuda.cuda_launch_grid offset bin grid block extra
dev.Devices.general_info 0
| Devices.OpenCLInfo _ ->
. OpenCL.opencl_load_arg offset dev ( arg_of_vec profiler_counters ) ;
let idx = ref 0 in
Array.iter
(fun a ->
match a with
| VChar v
|VFloat32 v
|VFloat64 v
|VInt32 v
|VInt64 v
|VComplex32 v
|VCustom v ->
Kernel.OpenCL.opencl_load_arg offset dev bin !idx a ;
Kernel.OpenCL.opencl_load_arg offset dev bin (!idx + 1)
(Kernel.Int32 (Vector.length v)) ;
idx := !idx + 2
| _ ->
Kernel.OpenCL.opencl_load_arg offset dev bin !idx a ;
incr idx )
args ;
Array.iteri ( fun i a - > Kernel . OpenCL.opencl_load_arg offset dev ( i ) a ) args ;
Kernel.OpenCL.opencl_launch_grid bin grid block dev.Devices.general_info
0
let profile_run ?recompile:(r = true) (ker : ('a, 'b, 'c, 'd, 'e) sarek_kernel)
a b _q dev =
let kir, k = ker in
( match dev.Devices.specific_info with
| Devices.CudaInfo _ -> (
if r then ignore (gen ~profile:true ~only:Devices.Cuda (kir, k) dev)
else
match kir#get_cuda_sources () with
| [] -> ignore (gen ~profile:true ~only:Devices.Cuda (kir, k) dev)
| _ -> () )
| Devices.OpenCLInfo _ -> (
if r then ignore (gen ~profile:true ~only:Devices.OpenCL (kir, k) dev)
else
match kir#get_opencl_sources () with
| [] -> ignore (gen ~profile:true ~only:Devices.OpenCL (kir, k) dev)
| _ -> () ) ) ;
let nCounter =
!( match dev.Devices.specific_info with
| Devices.CudaInfo _ -> Kirc_Cuda.profiler_counter
| Devices.OpenCLInfo _ -> Kirc_OpenCL.profiler_counter )
in
Printf.printf " Number of counters : % d\n% ! " nCounter ;
let profiler_counters = Vector.create Vector.int64 nCounter in
for i = 0 to nCounter - 1 do
Mem.set profiler_counters i 0L
done ;
(let args = kir#args_to_list a in
let offset = ref 0 in
kir#compile ~debug:true dev ;
let block, grid = b in
let bin = Hashtbl.find (kir#get_binaries ()) dev in
match dev.Devices.specific_info with
| Devices.CudaInfo _cI ->
let extra = Kernel.Cuda.cuda_create_extra (Array.length args + 1) in
Kernel.Cuda.cuda_load_arg offset extra dev bin 0
(arg_of_vec profiler_counters) ;
Array.iteri
(fun i a ->
match a with
| VChar _ | VFloat32 _ | VFloat64 _ | VInt32 _ | VInt64 _
|VComplex32 _ | VCustom _ ->
Kernel.Cuda.cuda_load_arg offset extra dev bin i a
| _ -> Kernel.Cuda.cuda_load_arg offset extra dev bin i a )
args ;
Kernel.Cuda.cuda_launch_grid offset bin grid block extra
dev.Devices.general_info 0
| Devices.OpenCLInfo _ ->
Kernel.OpenCL.opencl_load_arg offset dev bin 0
(arg_of_vec profiler_counters) ;
Array.iteri
(fun i a -> Kernel.OpenCL.opencl_load_arg offset dev bin i a)
args ;
Kernel.OpenCL.opencl_launch_grid bin grid block dev.Devices.general_info
0) ;
Devices.flush dev () ;
if not !Mem.auto then Mem.to_cpu profiler_counters () ;
Spoc.Tools.iter ( fun a - > Printf.printf " % Ld " a ) profiler_counters ;
Gen.profile_vect := profiler_counters ;
gen_profile ker dev
let compile_kernel_to_files s (ker : ('a, 'b, 'c, 'd, 'e) sarek_kernel) dev =
let kir, k = ker in
let k1, k2, k3 = (k.ml_kern, k.body, k.ret_val) in
return_v := ("", "") ;
let k' =
( (Kirc_Cuda.parse 0 (fst k3)) dev
, match fst k3 with
| IntVar (_i, s) | FloatVar (_i, s) | DoubleVar (_i, s) ->
| Unit -> ""
| SetV _ -> ""
| IntVecAcc _ -> ""
| VecVar _ -> ""
| _ ->
debug_print
( kir
, { ml_kern= k1
; body= fst k3
; ret_val= k3
; extensions= k.extensions } ) ;
Stdlib.flush stdout ;
assert false )
in
Kirc_Cuda.return_v := k' ;
Kirc_OpenCL.return_v := k' ;
let cuda_head =
Array.fold_left
(fun header extension ->
match extension with
| ExFloat32 -> header
| ExFloat64 -> cuda_float64 ^ header )
cuda_head k.extensions
in
let opencl_head =
Array.fold_left
(fun header extension ->
match extension with
| ExFloat32 -> header
| ExFloat64 -> opencl_float64 ^ header )
opencl_head k.extensions
in
save (s ^ ".cu") (cuda_head ^ Kirc_Cuda.parse 0 (rewrite k2) dev) ;
save (s ^ ".cl") (opencl_head ^ Kirc_OpenCL.parse 0 (rewrite k2) dev)
module Std = struct
let thread_idx_x = 1l
let thread_idx_y = 1l
let thread_idx_z = 1l
let block_idx_x = 1l
let block_idx_y = 1l
let block_idx_z = 1l
let block_dim_x = 1l
let block_dim_y = 1l
let block_dim_z = 1l
let grid_dim_x = 1l
let grid_dim_y = 1l
let grid_dim_z = 1l
let global_thread_id = 0l
let return () = ()
let float64 i = float (Int32.to_int i)
let float i = float (Int32.to_int i)
let int_of_float64 f = Int32.of_int (int_of_float f)
let int_of_float f = Int32.of_int (int_of_float f)
let block_barrier () = ()
let make_shared i = Array.make (Int32.to_int i) 0l
let make_local i = Array.make (Int32.to_int i) 0l
let map f a b =
assert (Vector.length a = Vector.length b) ;
for i = 0 to Vector.length a do
Mem.set b i (f (Mem.get a i))
done
let reduce f a b =
let rec aux acc i =
if Vector.length a < i then aux (f acc (Mem.get a i)) (i + 1) else acc
in
Mem.set b 0 (aux (Mem.get a 0) 1)
end
module Sarek_vector = struct
let length v = Int32.of_int (Vector.length v)
end
module Math = struct
let pow a b =
Int32.of_float (Float.pow (Int32.to_float a) (Int32.to_float b))
let logical_and a b = Int32.logand a b
let xor a b = Int32.logxor a b
module Float32 = struct
let add = ( +. )
let minus = ( -. )
let mul = ( *. )
let div = ( /. )
let pow = ( ** )
let sqrt = sqrt
let rsqrt = sqrt
let exp = exp
let log = log
let log10 = log10
let expm1 = expm1
let log1p = log1p
let acos = acos
let cos = cos
let cosh = cosh
let asin = asin
let sin = sin
let sinh = sinh
let tan = tan
let tanh = tanh
let atan = atan
let atan2 = atan2
let hypot = hypot
let ceil = ceil
let floor = floor
let abs_float = abs_float
let copysign = copysign
let modf = modf
let zero = 0.
let one = 1.
let make_shared i = Array.make (Int32.to_int i) 0.
let make_local i = Array.make (Int32.to_int i) 0.
end
module Float64 = struct
let add = ( +. )
let minus = ( -. )
let mul = ( *. )
let div = ( /. )
let pow = ( ** )
let sqrt = sqrt
let rsqrt = sqrt
let exp = exp
let log = log
let log10 = log10
let expm1 = expm1
let log1p = log1p
let acos = acos
let cos = cos
let cosh = cosh
let asin = asin
let sin = sin
let sinh = sinh
let tan = tan
let tanh = tanh
let atan = atan
let atan2 = atan2
let hypot = hypot
let ceil = ceil
let floor = floor
let abs_float = abs_float
let copysign = copysign
let modf = modf
let zero = 0.
let one = 1.
let of_float32 f = f
let of_float f = f
let to_float32 f = f
let make_shared i = Array.make (Int32.to_int i) 0.
let make_local i = Array.make (Int32.to_int i) 0.
end
end
|
439c8557876b493e6ccfbd78ca97a229fc44031ded2a06e3e9f874f6f78103d4 | niconaus/pcode-interpreter | WordString.hs | |
Module : WordString
Description : Word8 string helper functions
Copyright : ( c ) , 2022
Maintainer :
Stability : experimental
This module defines several helper functions to perform operations on strings
Module : WordString
Description : Word8 string helper functions
Copyright : (c) Nico Naus, 2022
Maintainer :
Stability : experimental
This module defines several helper functions to perform operations on word8 strings
-}
module WordString where
import Data.Binary ( Word8, Word16, Word32, Word64 )
import Data.ByteString.Builder
( toLazyByteString, word16BE, word32BE, word64BE )
import qualified Data.ByteString.Lazy as BS
import Data.Binary.Get
( getWord16be, getWord32be, getWord64be, runGet )
import Data.Bits ( Bits(testBit) )
-- Unsigned addition
uAdd :: [Word8] -> [Word8] -> [Word8]
uAdd w1 w2 | length w1 == 1 = encodeWord8 $ decodeWord8 w1 + decodeWord8 w2
| length w1 == 2 = encodeWord16 $ decodeWord16 w1 + decodeWord16 w2
| length w1 == 4 = encodeWord32 $ decodeWord32 w1 + decodeWord32 w2
| length w1 == 8 = encodeWord64 $ decodeWord64 w1 + decodeWord64 w2
uAdd _ _ = error "addition not defined for this length"
--Sign extension
signExtend :: Word8 -> [Word8] -> [Word8]
signExtend i wx | length wx > fromEnum i = error "sign extend cannot shorten word"
| otherwise = concat $ replicate (fromEnum i-length wx) (if getSign wx then [255] else [0]) ++ [wx]
zeroExtend :: Word8 -> [Word8] -> [Word8]
zeroExtend i wx | length wx > fromEnum i = error "unsigned extend cannot shorten word"
| otherwise = replicate (fromEnum i-length wx) 0 ++ wx
getSign :: [Word8] -> Bool
getSign xs = testBit (last xs) 7
-- From and to Word
encodeWord8 :: Word8 -> [Word8]
encodeWord8 x = [x]
decodeWord8 :: [Word8] -> Word8
decodeWord8 [x] = x
decodeWord8 xs = error $ "Bytestring too long or short to be a word8: " ++ show xs
encodeWord16 :: Word16 -> [Word8]
encodeWord16 = BS.unpack . toLazyByteString . word16BE
decodeWord16 :: [Word8] -> Word16
decodeWord16 xs = runGet getWord16be (BS.pack xs)
encodeWord32 :: Word32 -> [Word8]
encodeWord32 = BS.unpack . toLazyByteString . word32BE
decodeWord32 :: [Word8] -> Word32
decodeWord32 xs = runGet getWord32be (BS.pack xs)
encodeWord64 :: Word64 -> [Word8]
encodeWord64 = BS.unpack . toLazyByteString . word64BE
decodeWord64 :: [Word8] -> Word64
decodeWord64 x = runGet getWord64be (BS.pack x)
| null | https://raw.githubusercontent.com/niconaus/pcode-interpreter/1e8053226e658b4c609470836b867c231f8c756d/WordString.hs | haskell | Unsigned addition
Sign extension
From and to Word | |
Module : WordString
Description : Word8 string helper functions
Copyright : ( c ) , 2022
Maintainer :
Stability : experimental
This module defines several helper functions to perform operations on strings
Module : WordString
Description : Word8 string helper functions
Copyright : (c) Nico Naus, 2022
Maintainer :
Stability : experimental
This module defines several helper functions to perform operations on word8 strings
-}
module WordString where
import Data.Binary ( Word8, Word16, Word32, Word64 )
import Data.ByteString.Builder
( toLazyByteString, word16BE, word32BE, word64BE )
import qualified Data.ByteString.Lazy as BS
import Data.Binary.Get
( getWord16be, getWord32be, getWord64be, runGet )
import Data.Bits ( Bits(testBit) )
uAdd :: [Word8] -> [Word8] -> [Word8]
uAdd w1 w2 | length w1 == 1 = encodeWord8 $ decodeWord8 w1 + decodeWord8 w2
| length w1 == 2 = encodeWord16 $ decodeWord16 w1 + decodeWord16 w2
| length w1 == 4 = encodeWord32 $ decodeWord32 w1 + decodeWord32 w2
| length w1 == 8 = encodeWord64 $ decodeWord64 w1 + decodeWord64 w2
uAdd _ _ = error "addition not defined for this length"
signExtend :: Word8 -> [Word8] -> [Word8]
signExtend i wx | length wx > fromEnum i = error "sign extend cannot shorten word"
| otherwise = concat $ replicate (fromEnum i-length wx) (if getSign wx then [255] else [0]) ++ [wx]
zeroExtend :: Word8 -> [Word8] -> [Word8]
zeroExtend i wx | length wx > fromEnum i = error "unsigned extend cannot shorten word"
| otherwise = replicate (fromEnum i-length wx) 0 ++ wx
getSign :: [Word8] -> Bool
getSign xs = testBit (last xs) 7
encodeWord8 :: Word8 -> [Word8]
encodeWord8 x = [x]
decodeWord8 :: [Word8] -> Word8
decodeWord8 [x] = x
decodeWord8 xs = error $ "Bytestring too long or short to be a word8: " ++ show xs
encodeWord16 :: Word16 -> [Word8]
encodeWord16 = BS.unpack . toLazyByteString . word16BE
decodeWord16 :: [Word8] -> Word16
decodeWord16 xs = runGet getWord16be (BS.pack xs)
encodeWord32 :: Word32 -> [Word8]
encodeWord32 = BS.unpack . toLazyByteString . word32BE
decodeWord32 :: [Word8] -> Word32
decodeWord32 xs = runGet getWord32be (BS.pack xs)
encodeWord64 :: Word64 -> [Word8]
encodeWord64 = BS.unpack . toLazyByteString . word64BE
decodeWord64 :: [Word8] -> Word64
decodeWord64 x = runGet getWord64be (BS.pack x)
|
3f793228133e99a843b11e9b408d93d6d686fd032f731462eeecf619c67eccae | Clojure2D/clojure2d-examples | ray.clj | (ns rt4.the-next-week.ch07b.ray
(:require [fastmath.vector :as v]
[fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol RayProto
(at [ray t]))
(defrecord Ray [origin direction ^double time]
RayProto
(at [_ t] (v/add origin (v/mult direction t))))
(defn ray
([m] (map->Ray (merge {:time 0.0} m)))
([origin direction] (->Ray origin direction 0.0))
([origin direction time] (->Ray origin direction time)))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/the_next_week/ch07b/ray.clj | clojure | (ns rt4.the-next-week.ch07b.ray
(:require [fastmath.vector :as v]
[fastmath.core :as m]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol RayProto
(at [ray t]))
(defrecord Ray [origin direction ^double time]
RayProto
(at [_ t] (v/add origin (v/mult direction t))))
(defn ray
([m] (map->Ray (merge {:time 0.0} m)))
([origin direction] (->Ray origin direction 0.0))
([origin direction time] (->Ray origin direction time)))
|
|
f4219cdf00302278745c4ab922b2accdc4f73295dc09942ba7f728765fe0d974 | programaker-project/Programaker-Core | automate_rest_api_programs_specific.erl | %%% @doc
%%% REST endpoint to manage knowledge collections.
%%% @end
-module(automate_rest_api_programs_specific).
-export([init/2]).
-export([ allowed_methods/2
, options/2
, is_authorized/2
, content_types_provided/2
, content_types_accepted/2
, delete_resource/2
]).
-export([ to_json/2
, accept_json_program/2
]).
-include("./records.hrl").
-include("../../automate_storage/src/records.hrl").
-define(UTILS, automate_rest_api_utils).
-define(FORMATTING, automate_rest_api_utils_formatting).
-record(state, { username :: binary()
, program_name :: binary()
, program_id :: binary()
, user_id :: undefined | binary()
}).
-spec init(_,_) -> {'cowboy_rest',_,_}.
init(Req, _Opts) ->
UserName = cowboy_req:binding(user_id, Req),
ProgramName = cowboy_req:binding(program_id, Req),
Req1 = automate_rest_api_cors:set_headers(Req),
{ok, #user_program_entry{ id=ProgramId }} = automate_storage:get_program(UserName, ProgramName),
{cowboy_rest, Req1
, #state{ username=UserName
, program_name=ProgramName
, program_id=ProgramId
, user_id=undefined
}}.
%% CORS
options(Req, State) ->
{ok, Req, State}.
%% Authentication
-spec allowed_methods(cowboy_req:req(),_) -> {[binary()], cowboy_req:req(),_}.
allowed_methods(Req, State) ->
{[<<"GET">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>], Req, State}.
is_authorized(Req, State=#state{username=Username, program_id=ProgramId}) ->
Req1 = automate_rest_api_cors:set_headers(Req),
case cowboy_req:method(Req1) of
%% Don't do authentication if it's just asking for options
<<"OPTIONS">> ->
{ true, Req1, State };
Method ->
{ok, #user_program_entry{ visibility=Visibility }} = automate_storage:get_program_from_id(ProgramId),
IsPublic = ?UTILS:is_public(Visibility),
case cowboy_req:header(<<"authorization">>, Req, undefined) of
undefined ->
case {Method, IsPublic} of
{<<"GET">>, true} ->
{ true, Req1, State };
_ ->
{ {false, <<"Authorization header not found">>} , Req1, State }
end;
X ->
{Action, Scope} = case Method of
<<"GET">> -> {read_program, { read_program, ProgramId }};
<<"PUT">> -> {edit_program, { edit_program, ProgramId }};
<<"PATCH">> -> {edit_program, { edit_program_metadata, ProgramId }};
<<"DELETE">> -> {delete_program, { delete_program, ProgramId }}
end,
case automate_rest_api_backend:is_valid_token(X, Scope) of
{true, Username} ->
{ok, {user, UId}} = automate_storage:get_userid_from_username(Username),
case automate_storage:is_user_allowed({user, UId}, ProgramId, Action) of
{ok, true} ->
{ true, Req1, State#state{user_id=UId} };
{ok, false} ->
case {Method, IsPublic} of
{<<"GET">>, true} ->
{true, Req1, State#state{user_id=UId}};
_ ->
{ { false, <<"Action not authorized">>}, Req1, State }
end;
{error, Reason} ->
automate_logging:log_api(warning, ?MODULE, {authorization_error, Reason}),
{ { false, <<"Error on authorization">>}, Req1, State }
end;
{true, AuthUser} -> %% Non matching username
{ { false, <<"Authorization not correct">>}, Req1, State };
false ->
{ { false, <<"Authorization not correct">>}, Req1, State }
end
end
end.
%% Get handler
content_types_provided(Req, State) ->
{[{{<<"application">>, <<"json">>, []}, to_json}],
Req, State}.
-spec to_json(cowboy_req:req(), #state{})
-> { stop | binary() ,cowboy_req:req(), #state{}}.
to_json(Req, State=#state{program_id=ProgramId, user_id=UserId}) ->
Qs = cowboy_req:parse_qs(Req),
IncludePages = case proplists:get_value(<<"retrieve_pages">>, Qs) of
<<"yes">> ->
true;
_ ->
false
end,
case automate_rest_api_backend:get_program(ProgramId) of
{ ok, Program=#user_program{ id=ProgramId, last_upload_time=ProgramTime } } ->
Checkpoint = case automate_storage:get_last_checkpoint_content(ProgramId) of
{ok, #user_program_checkpoint{event_time=CheckpointTime, content=Content} } ->
case ProgramTime < (CheckpointTime / 1000) of
true ->
Content;
false ->
null
end;
{error, not_found} ->
null
end,
Json = ?FORMATTING:program_data_to_json(Program, Checkpoint),
{ok, CanEdit} = automate_storage:is_user_allowed({user, UserId}, ProgramId, edit_program),
{ok, CanAdmin } = automate_storage:is_user_allowed({user, UserId}, ProgramId, admin_program),
Json2 = Json#{ readonly => not CanEdit, can_admin => CanAdmin },
Json3 = case IncludePages of
false -> Json2;
true ->
{ok, Pages} = automate_storage:get_program_pages(ProgramId),
Json#{ pages => maps:from_list(lists:map(fun (#program_pages_entry{ page_id={_, Path}
, contents=Contents}) ->
{Path, Contents}
end, Pages))
}
end,
Res1 = cowboy_req:delete_resp_header(<<"content-type">>, Req),
Res2 = cowboy_req:set_resp_header(<<"content-type">>, <<"application/json">>, Res1),
{ jiffy:encode(Json3), Res2, State };
{error, Reason} ->
Code = 500,
Output = jiffy:encode(#{ <<"success">> => false, <<"message">> => Reason }),
Res = cowboy_req:reply(Code, #{ <<"content-type">> => <<"application/json">> }, Output, Req),
{ stop, Res, State }
end.
content_types_accepted(Req, State) ->
{[{{<<"application">>, <<"json">>, []}, accept_json_program}],
Req, State}.
accept_json_program(Req, State) ->
case cowboy_req:method(Req) of
<<"PUT">> ->
update_program(Req, State);
<<"PATCH">> ->
update_program_metadata(Req, State)
end.
PUT handler
update_program(Req, State) ->
#state{program_name=ProgramName, username=Username} = State,
{ok, Body, Req1} = ?UTILS:read_body(Req),
Parsed = jiffy:decode(Body, [return_maps]),
Program = decode_program(Parsed),
case automate_rest_api_backend:update_program(Username, ProgramName, Program) of
ok ->
Req2 = send_json_output(jiffy:encode(#{ <<"success">> => true }), Req),
{ true, Req2, State };
{ error, Reason } ->
Req2 = send_json_output(jiffy:encode(#{ <<"success">> => false, <<"message">> => Reason }), Req1),
{ false, Req2, State }
end.
%% PATCH handler
update_program_metadata(Req, State) ->
#state{program_name=ProgramName, username=Username} = State,
{ok, Body, Req1} = ?UTILS:read_body(Req),
Parsed = jiffy:decode(Body, [return_maps]),
case automate_rest_api_backend:update_program_metadata(Username, ProgramName, Parsed) of
{ok, #{ <<"link">> := Link } } ->
Req2 = send_json_output(jiffy:encode(#{ <<"success">> => true, <<"link">> => Link}), Req),
{ true, Req2, State };
{ error, Reason } ->
Req2 = send_json_output(jiffy:encode(#{ <<"success">> => false, <<"message">> => Reason }), Req1),
{ false, Req2, State }
end.
%% DELETE handler
delete_resource(Req, State) ->
#state{program_name=ProgramName, username=Username} = State,
case automate_rest_api_backend:delete_program(Username, ProgramName) of
ok ->
Req1 = send_json_output(jiffy:encode(#{ <<"success">> => true}), Req),
{ true, Req1, State };
{ error, Reason } ->
Req1 = send_json_output(jiffy:encode(#{ <<"success">> => false, <<"message">> => Reason }), Req),
{ false, Req1, State }
end.
%% Converters
decode_program(P=#{ <<"type">> := ProgramType
, <<"orig">> := ProgramOrig
, <<"parsed">> := ProgramParsed
}) ->
#program_content { type=ProgramType
, orig=ProgramOrig
, parsed=ProgramParsed
, pages=case P of
#{ <<"pages">> := Pages} -> Pages;
_ -> #{}
end
}.
send_json_output(Output, Req) ->
Res1 = cowboy_req:set_resp_body(Output, Req),
Res2 = cowboy_req:delete_resp_header(<<"content-type">>, Res1),
cowboy_req:set_resp_header(<<"content-type">>, <<"application/json">>, Res2).
| null | https://raw.githubusercontent.com/programaker-project/Programaker-Core/ef10fc6d2a228b2096b121170c421f5c29f9f270/backend/apps/automate_rest_api/src/automate_rest_api_programs_specific.erl | erlang | @doc
REST endpoint to manage knowledge collections.
@end
CORS
Authentication
Don't do authentication if it's just asking for options
Non matching username
Get handler
PATCH handler
DELETE handler
Converters |
-module(automate_rest_api_programs_specific).
-export([init/2]).
-export([ allowed_methods/2
, options/2
, is_authorized/2
, content_types_provided/2
, content_types_accepted/2
, delete_resource/2
]).
-export([ to_json/2
, accept_json_program/2
]).
-include("./records.hrl").
-include("../../automate_storage/src/records.hrl").
-define(UTILS, automate_rest_api_utils).
-define(FORMATTING, automate_rest_api_utils_formatting).
-record(state, { username :: binary()
, program_name :: binary()
, program_id :: binary()
, user_id :: undefined | binary()
}).
-spec init(_,_) -> {'cowboy_rest',_,_}.
init(Req, _Opts) ->
UserName = cowboy_req:binding(user_id, Req),
ProgramName = cowboy_req:binding(program_id, Req),
Req1 = automate_rest_api_cors:set_headers(Req),
{ok, #user_program_entry{ id=ProgramId }} = automate_storage:get_program(UserName, ProgramName),
{cowboy_rest, Req1
, #state{ username=UserName
, program_name=ProgramName
, program_id=ProgramId
, user_id=undefined
}}.
options(Req, State) ->
{ok, Req, State}.
-spec allowed_methods(cowboy_req:req(),_) -> {[binary()], cowboy_req:req(),_}.
allowed_methods(Req, State) ->
{[<<"GET">>, <<"PUT">>, <<"PATCH">>, <<"DELETE">>, <<"OPTIONS">>], Req, State}.
is_authorized(Req, State=#state{username=Username, program_id=ProgramId}) ->
Req1 = automate_rest_api_cors:set_headers(Req),
case cowboy_req:method(Req1) of
<<"OPTIONS">> ->
{ true, Req1, State };
Method ->
{ok, #user_program_entry{ visibility=Visibility }} = automate_storage:get_program_from_id(ProgramId),
IsPublic = ?UTILS:is_public(Visibility),
case cowboy_req:header(<<"authorization">>, Req, undefined) of
undefined ->
case {Method, IsPublic} of
{<<"GET">>, true} ->
{ true, Req1, State };
_ ->
{ {false, <<"Authorization header not found">>} , Req1, State }
end;
X ->
{Action, Scope} = case Method of
<<"GET">> -> {read_program, { read_program, ProgramId }};
<<"PUT">> -> {edit_program, { edit_program, ProgramId }};
<<"PATCH">> -> {edit_program, { edit_program_metadata, ProgramId }};
<<"DELETE">> -> {delete_program, { delete_program, ProgramId }}
end,
case automate_rest_api_backend:is_valid_token(X, Scope) of
{true, Username} ->
{ok, {user, UId}} = automate_storage:get_userid_from_username(Username),
case automate_storage:is_user_allowed({user, UId}, ProgramId, Action) of
{ok, true} ->
{ true, Req1, State#state{user_id=UId} };
{ok, false} ->
case {Method, IsPublic} of
{<<"GET">>, true} ->
{true, Req1, State#state{user_id=UId}};
_ ->
{ { false, <<"Action not authorized">>}, Req1, State }
end;
{error, Reason} ->
automate_logging:log_api(warning, ?MODULE, {authorization_error, Reason}),
{ { false, <<"Error on authorization">>}, Req1, State }
end;
{ { false, <<"Authorization not correct">>}, Req1, State };
false ->
{ { false, <<"Authorization not correct">>}, Req1, State }
end
end
end.
content_types_provided(Req, State) ->
{[{{<<"application">>, <<"json">>, []}, to_json}],
Req, State}.
-spec to_json(cowboy_req:req(), #state{})
-> { stop | binary() ,cowboy_req:req(), #state{}}.
to_json(Req, State=#state{program_id=ProgramId, user_id=UserId}) ->
Qs = cowboy_req:parse_qs(Req),
IncludePages = case proplists:get_value(<<"retrieve_pages">>, Qs) of
<<"yes">> ->
true;
_ ->
false
end,
case automate_rest_api_backend:get_program(ProgramId) of
{ ok, Program=#user_program{ id=ProgramId, last_upload_time=ProgramTime } } ->
Checkpoint = case automate_storage:get_last_checkpoint_content(ProgramId) of
{ok, #user_program_checkpoint{event_time=CheckpointTime, content=Content} } ->
case ProgramTime < (CheckpointTime / 1000) of
true ->
Content;
false ->
null
end;
{error, not_found} ->
null
end,
Json = ?FORMATTING:program_data_to_json(Program, Checkpoint),
{ok, CanEdit} = automate_storage:is_user_allowed({user, UserId}, ProgramId, edit_program),
{ok, CanAdmin } = automate_storage:is_user_allowed({user, UserId}, ProgramId, admin_program),
Json2 = Json#{ readonly => not CanEdit, can_admin => CanAdmin },
Json3 = case IncludePages of
false -> Json2;
true ->
{ok, Pages} = automate_storage:get_program_pages(ProgramId),
Json#{ pages => maps:from_list(lists:map(fun (#program_pages_entry{ page_id={_, Path}
, contents=Contents}) ->
{Path, Contents}
end, Pages))
}
end,
Res1 = cowboy_req:delete_resp_header(<<"content-type">>, Req),
Res2 = cowboy_req:set_resp_header(<<"content-type">>, <<"application/json">>, Res1),
{ jiffy:encode(Json3), Res2, State };
{error, Reason} ->
Code = 500,
Output = jiffy:encode(#{ <<"success">> => false, <<"message">> => Reason }),
Res = cowboy_req:reply(Code, #{ <<"content-type">> => <<"application/json">> }, Output, Req),
{ stop, Res, State }
end.
content_types_accepted(Req, State) ->
{[{{<<"application">>, <<"json">>, []}, accept_json_program}],
Req, State}.
accept_json_program(Req, State) ->
case cowboy_req:method(Req) of
<<"PUT">> ->
update_program(Req, State);
<<"PATCH">> ->
update_program_metadata(Req, State)
end.
PUT handler
update_program(Req, State) ->
#state{program_name=ProgramName, username=Username} = State,
{ok, Body, Req1} = ?UTILS:read_body(Req),
Parsed = jiffy:decode(Body, [return_maps]),
Program = decode_program(Parsed),
case automate_rest_api_backend:update_program(Username, ProgramName, Program) of
ok ->
Req2 = send_json_output(jiffy:encode(#{ <<"success">> => true }), Req),
{ true, Req2, State };
{ error, Reason } ->
Req2 = send_json_output(jiffy:encode(#{ <<"success">> => false, <<"message">> => Reason }), Req1),
{ false, Req2, State }
end.
update_program_metadata(Req, State) ->
#state{program_name=ProgramName, username=Username} = State,
{ok, Body, Req1} = ?UTILS:read_body(Req),
Parsed = jiffy:decode(Body, [return_maps]),
case automate_rest_api_backend:update_program_metadata(Username, ProgramName, Parsed) of
{ok, #{ <<"link">> := Link } } ->
Req2 = send_json_output(jiffy:encode(#{ <<"success">> => true, <<"link">> => Link}), Req),
{ true, Req2, State };
{ error, Reason } ->
Req2 = send_json_output(jiffy:encode(#{ <<"success">> => false, <<"message">> => Reason }), Req1),
{ false, Req2, State }
end.
delete_resource(Req, State) ->
#state{program_name=ProgramName, username=Username} = State,
case automate_rest_api_backend:delete_program(Username, ProgramName) of
ok ->
Req1 = send_json_output(jiffy:encode(#{ <<"success">> => true}), Req),
{ true, Req1, State };
{ error, Reason } ->
Req1 = send_json_output(jiffy:encode(#{ <<"success">> => false, <<"message">> => Reason }), Req),
{ false, Req1, State }
end.
decode_program(P=#{ <<"type">> := ProgramType
, <<"orig">> := ProgramOrig
, <<"parsed">> := ProgramParsed
}) ->
#program_content { type=ProgramType
, orig=ProgramOrig
, parsed=ProgramParsed
, pages=case P of
#{ <<"pages">> := Pages} -> Pages;
_ -> #{}
end
}.
send_json_output(Output, Req) ->
Res1 = cowboy_req:set_resp_body(Output, Req),
Res2 = cowboy_req:delete_resp_header(<<"content-type">>, Res1),
cowboy_req:set_resp_header(<<"content-type">>, <<"application/json">>, Res2).
|
ff4f795dc52dc2105cf80f4fde3e23413e6c5730eb4f44b2edbd23f17eb53f8e | m4dc4p/haskelldb | PostgreSQL.hs | -----------------------------------------------------------
-- |
Module : Database . HaskellDB.Sql . PostgreSQL
Copyright : 2006
-- License : BSD-style
--
Maintainer :
-- Stability : experimental
-- Portability : non-portable
--
-- SQL generation for PostgreSQL.
--
-----------------------------------------------------------
module Database.HaskellDB.Sql.PostgreSQL (generator) where
import Database.HaskellDB.Sql
import Database.HaskellDB.Sql.Default
import Database.HaskellDB.Sql.Generate
import Database.HaskellDB.FieldType
import Database.HaskellDB.PrimQuery
import System.Locale
import System.Time
import Control.Arrow
generator :: SqlGenerator
generator = (mkSqlGenerator generator) { sqlSpecial = postgresqlSpecial
, sqlType = postgresqlType
, sqlLiteral = postgresqlLiteral
, sqlExpr = postgresqlExpr
, sqlTable = postgresqlTable
, sqlInsert = postgresqlInsert
, sqlDelete = postgresqlDelete
, sqlUpdate = postgresqlUpdate
}
postgresqlUpdate :: TableName -> [PrimExpr] -> Assoc -> SqlUpdate
postgresqlUpdate name exprs = defaultSqlUpdate generator name exprs . map (first quote)
postgresqlTable :: TableName -> Scheme -> SqlSelect
postgresqlTable tablename scheme = defaultSqlTable generator (quote tablename) (map quote scheme)
postgresqlDelete :: TableName -> [PrimExpr] -> SqlDelete
postgresqlDelete = defaultSqlDelete generator . quote
postgresqlInsert :: TableName -> Assoc -> SqlInsert
postgresqlInsert n = defaultSqlInsert generator (quote n) . map (first quote)
postgresqlSpecial :: SpecialOp -> SqlSelect -> SqlSelect
postgresqlSpecial op q = defaultSqlSpecial generator op q
Postgres > 7.1 wants a timezone with calendar time .
postgresqlLiteral :: Literal -> String
postgresqlLiteral (DateLit d) = defaultSqlQuote generator (formatCalendarTime defaultTimeLocale fmt d)
where fmt = iso8601DateFormat (Just "%H:%M:%S %Z")
postgresqlLiteral (StringLit l) = "E" ++ (defaultSqlLiteral generator (StringLit l))
postgresqlLiteral l = defaultSqlLiteral generator l
postgresqlType :: FieldType -> SqlType
postgresqlType BoolT = SqlType "boolean"
postgresqlType t = defaultSqlType generator t
postgresqlExpr :: PrimExpr -> SqlExpr
postgresqlExpr (BinExpr OpMod e1 e2) =
let e1S = defaultSqlExpr generator e1
e2S = defaultSqlExpr generator e2
in BinSqlExpr "%" e1S e2S
postgresqlExpr (AttrExpr n) = defaultSqlExpr generator $ AttrExpr $ quote n
postgresqlExpr e = defaultSqlExpr generator e
quote :: String -> String
quote x@('"':_) = x
quote x = case break (=='.') x of
(l,[]) -> q l
(l,r) -> q l ++ "." ++ q (drop 1 r)
where q w = "\"" ++ w ++ "\""
| null | https://raw.githubusercontent.com/m4dc4p/haskelldb/a1fbc8a2eca8c70ebe382bf4c022275836d9d510/src/Database/HaskellDB/Sql/PostgreSQL.hs | haskell | ---------------------------------------------------------
|
License : BSD-style
Stability : experimental
Portability : non-portable
SQL generation for PostgreSQL.
--------------------------------------------------------- | Module : Database . HaskellDB.Sql . PostgreSQL
Copyright : 2006
Maintainer :
module Database.HaskellDB.Sql.PostgreSQL (generator) where
import Database.HaskellDB.Sql
import Database.HaskellDB.Sql.Default
import Database.HaskellDB.Sql.Generate
import Database.HaskellDB.FieldType
import Database.HaskellDB.PrimQuery
import System.Locale
import System.Time
import Control.Arrow
generator :: SqlGenerator
generator = (mkSqlGenerator generator) { sqlSpecial = postgresqlSpecial
, sqlType = postgresqlType
, sqlLiteral = postgresqlLiteral
, sqlExpr = postgresqlExpr
, sqlTable = postgresqlTable
, sqlInsert = postgresqlInsert
, sqlDelete = postgresqlDelete
, sqlUpdate = postgresqlUpdate
}
postgresqlUpdate :: TableName -> [PrimExpr] -> Assoc -> SqlUpdate
postgresqlUpdate name exprs = defaultSqlUpdate generator name exprs . map (first quote)
postgresqlTable :: TableName -> Scheme -> SqlSelect
postgresqlTable tablename scheme = defaultSqlTable generator (quote tablename) (map quote scheme)
postgresqlDelete :: TableName -> [PrimExpr] -> SqlDelete
postgresqlDelete = defaultSqlDelete generator . quote
postgresqlInsert :: TableName -> Assoc -> SqlInsert
postgresqlInsert n = defaultSqlInsert generator (quote n) . map (first quote)
postgresqlSpecial :: SpecialOp -> SqlSelect -> SqlSelect
postgresqlSpecial op q = defaultSqlSpecial generator op q
Postgres > 7.1 wants a timezone with calendar time .
postgresqlLiteral :: Literal -> String
postgresqlLiteral (DateLit d) = defaultSqlQuote generator (formatCalendarTime defaultTimeLocale fmt d)
where fmt = iso8601DateFormat (Just "%H:%M:%S %Z")
postgresqlLiteral (StringLit l) = "E" ++ (defaultSqlLiteral generator (StringLit l))
postgresqlLiteral l = defaultSqlLiteral generator l
postgresqlType :: FieldType -> SqlType
postgresqlType BoolT = SqlType "boolean"
postgresqlType t = defaultSqlType generator t
postgresqlExpr :: PrimExpr -> SqlExpr
postgresqlExpr (BinExpr OpMod e1 e2) =
let e1S = defaultSqlExpr generator e1
e2S = defaultSqlExpr generator e2
in BinSqlExpr "%" e1S e2S
postgresqlExpr (AttrExpr n) = defaultSqlExpr generator $ AttrExpr $ quote n
postgresqlExpr e = defaultSqlExpr generator e
quote :: String -> String
quote x@('"':_) = x
quote x = case break (=='.') x of
(l,[]) -> q l
(l,r) -> q l ++ "." ++ q (drop 1 r)
where q w = "\"" ++ w ++ "\""
|
93d71e2c86b64cc67f4edf274b5b9c935ce5cac0c9d56a1f89864258f57e68e0 | racket/swindle | tool.rkt | Written by is Life ! ( )
Add the Swindle languages to
#lang mzscheme
(require mzlib/unit
drscheme/tool
mzlib/class
mzlib/list
mred
net/sendurl
string-constants)
(provide tool@)
(define tool@
(unit (import drscheme:tool^) (export drscheme:tool-exports^)
;; Swindle languages
(define (swindle-language module* name* entry-name* num* one-line* url*)
(class (drscheme:language:module-based-language->language-mixin
(drscheme:language:simple-module-based-language->module-based-language-mixin
(class* object%
(drscheme:language:simple-module-based-language<%>)
(define/public (get-language-numbers) `(-200 2000 ,num*))
(define/public (get-language-position)
(list (string-constant legacy-languages)
"Swindle" entry-name*))
(define/public (get-module) module*)
(define/public (get-one-line-summary) one-line*)
(define/public (get-language-url) url*)
(define/public (get-reader)
(lambda (src port)
(let ([v (read-syntax src port)])
(if (eof-object? v)
v
(namespace-syntax-introduce v)))))
(super-instantiate ()))))
(define/augment (capability-value key)
(cond
[(eq? key 'macro-stepper:enabled) #t]
[else (inner (drscheme:language:get-capability-default key)
capability-value key)]))
(define/override (use-namespace-require/copy?) #t)
(define/override (default-settings)
(drscheme:language:make-simple-settings
#t 'write 'mixed-fraction-e #f #t 'debug))
(define/override (get-language-name) name*)
(define/override (config-panel parent)
(let* ([make-panel
(lambda (msg contents)
(make-object message% msg parent)
(let ([p (instantiate vertical-panel% ()
(parent parent)
(style '(border))
(alignment '(left center)))])
(if (string? contents)
(make-object message% contents p)
(contents p))))]
[title-panel
(instantiate horizontal-panel% ()
(parent parent)
(alignment '(center center)))]
[title-pic
(make-object message%
(make-object bitmap%
(build-path (collection-path "swindle")
"swindle-logo.png"))
title-panel)]
[title (let ([p (instantiate vertical-panel% ()
(parent title-panel)
(alignment '(left center)))])
(make-object message% (format "Swindle") p)
(make-object message% (format "Setup") p)
p)]
[input-sensitive?
(make-panel (string-constant input-syntax)
(lambda (p)
(make-object check-box%
(string-constant case-sensitive-label)
p void)))]
[debugging
(make-panel
(string-constant dynamic-properties)
(lambda (p)
(instantiate radio-box% ()
(label #f)
(choices
`(,(string-constant no-debugging-or-profiling)
,(string-constant debugging)
,(string-constant debugging-and-profiling)))
(parent p)
(callback void))))])
(case-lambda
[()
(drscheme:language:make-simple-settings
(send input-sensitive? get-value)
'write 'mixed-fraction-e #f #t
(case (send debugging get-selection)
[(0) 'none]
[(1) 'debug]
[(2) 'debug/profile]))]
[(settings)
(send input-sensitive? set-value
(drscheme:language:simple-settings-case-sensitive
settings))
(send debugging set-selection
(case (drscheme:language:simple-settings-annotations
settings)
[(none) 0]
[(debug) 1]
[(debug/profile) 2]))])))
(define last-port #f)
(define/override (render-value/format value settings port width)
(unless (eq? port last-port)
(set! last-port port)
;; this is called with the value port, so copy the usual swindle
;; handlers to this port
(port-write-handler
port (port-write-handler (current-output-port)))
(port-display-handler
port (port-display-handler (current-output-port))))
;; then use them instead of the default pretty print
(write value port)
(newline port))
(super-instantiate ())))
(define (add-swindle-language name module entry-name num one-line url)
(drscheme:language-configuration:add-language
(make-object
((drscheme:language:get-default-mixin)
(swindle-language `(lib ,(string-append module ".rkt") "swindle")
name entry-name num one-line url)))))
(define phase1 void)
(define (phase2)
(for-each (lambda (args) (apply add-swindle-language `(,@args #f)))
'(("Swindle" "main" "Full Swindle" 0
"Full Swindle extensions")
("Swindle w/o CLOS" "turbo" "Swindle without CLOS" 1
"Swindle without the object system")
("Swindle Syntax" "base" "Basic syntax only" 2
"Basic Swindle syntax: keyword-arguments etc")))
(parameterize ([current-directory (collection-path "swindle")])
(define counter 100)
(define (do-customize file)
(when (regexp-match? #rx"\\.rkt$" file)
(with-input-from-file file
(lambda ()
(let ([l (read-line)])
(when (regexp-match? #rx"^;+ *CustomSwindle *$" l)
(let ([file (regexp-replace #rx"\\.rkt$" file "")]
[name #f] [dname #f] [one-line #f] [url #f])
(let loop ([l (read-line)])
(cond
[(regexp-match #rx"^;+ *([A-Z][A-Za-z]*): *(.*)$" l)
=> (lambda (m)
(let ([sym (string->symbol (cadr m))]
[val (caddr m)])
(case sym
[(|Name|) (set! name val)]
[(|DialogName|) (set! dname val)]
[(|OneLine|) (set! one-line val)]
[(|URL|) (set! url val)])
(loop (read-line))))]))
(unless name (set! name file))
(unless dname (set! dname name))
(unless one-line
(set! one-line
(string-append "Customized Swindle: " name)))
(set! counter (add1 counter))
(add-swindle-language
name file dname counter one-line url))))))))
(for-each do-customize
(sort (map path->string (directory-list)) string<?))))
))
| null | https://raw.githubusercontent.com/racket/swindle/122e38efb9842394ef6462053991efb4bd0edf3b/tool.rkt | racket | Swindle languages
this is called with the value port, so copy the usual swindle
handlers to this port
then use them instead of the default pretty print | Written by is Life ! ( )
Add the Swindle languages to
#lang mzscheme
(require mzlib/unit
drscheme/tool
mzlib/class
mzlib/list
mred
net/sendurl
string-constants)
(provide tool@)
(define tool@
(unit (import drscheme:tool^) (export drscheme:tool-exports^)
(define (swindle-language module* name* entry-name* num* one-line* url*)
(class (drscheme:language:module-based-language->language-mixin
(drscheme:language:simple-module-based-language->module-based-language-mixin
(class* object%
(drscheme:language:simple-module-based-language<%>)
(define/public (get-language-numbers) `(-200 2000 ,num*))
(define/public (get-language-position)
(list (string-constant legacy-languages)
"Swindle" entry-name*))
(define/public (get-module) module*)
(define/public (get-one-line-summary) one-line*)
(define/public (get-language-url) url*)
(define/public (get-reader)
(lambda (src port)
(let ([v (read-syntax src port)])
(if (eof-object? v)
v
(namespace-syntax-introduce v)))))
(super-instantiate ()))))
(define/augment (capability-value key)
(cond
[(eq? key 'macro-stepper:enabled) #t]
[else (inner (drscheme:language:get-capability-default key)
capability-value key)]))
(define/override (use-namespace-require/copy?) #t)
(define/override (default-settings)
(drscheme:language:make-simple-settings
#t 'write 'mixed-fraction-e #f #t 'debug))
(define/override (get-language-name) name*)
(define/override (config-panel parent)
(let* ([make-panel
(lambda (msg contents)
(make-object message% msg parent)
(let ([p (instantiate vertical-panel% ()
(parent parent)
(style '(border))
(alignment '(left center)))])
(if (string? contents)
(make-object message% contents p)
(contents p))))]
[title-panel
(instantiate horizontal-panel% ()
(parent parent)
(alignment '(center center)))]
[title-pic
(make-object message%
(make-object bitmap%
(build-path (collection-path "swindle")
"swindle-logo.png"))
title-panel)]
[title (let ([p (instantiate vertical-panel% ()
(parent title-panel)
(alignment '(left center)))])
(make-object message% (format "Swindle") p)
(make-object message% (format "Setup") p)
p)]
[input-sensitive?
(make-panel (string-constant input-syntax)
(lambda (p)
(make-object check-box%
(string-constant case-sensitive-label)
p void)))]
[debugging
(make-panel
(string-constant dynamic-properties)
(lambda (p)
(instantiate radio-box% ()
(label #f)
(choices
`(,(string-constant no-debugging-or-profiling)
,(string-constant debugging)
,(string-constant debugging-and-profiling)))
(parent p)
(callback void))))])
(case-lambda
[()
(drscheme:language:make-simple-settings
(send input-sensitive? get-value)
'write 'mixed-fraction-e #f #t
(case (send debugging get-selection)
[(0) 'none]
[(1) 'debug]
[(2) 'debug/profile]))]
[(settings)
(send input-sensitive? set-value
(drscheme:language:simple-settings-case-sensitive
settings))
(send debugging set-selection
(case (drscheme:language:simple-settings-annotations
settings)
[(none) 0]
[(debug) 1]
[(debug/profile) 2]))])))
(define last-port #f)
(define/override (render-value/format value settings port width)
(unless (eq? port last-port)
(set! last-port port)
(port-write-handler
port (port-write-handler (current-output-port)))
(port-display-handler
port (port-display-handler (current-output-port))))
(write value port)
(newline port))
(super-instantiate ())))
(define (add-swindle-language name module entry-name num one-line url)
(drscheme:language-configuration:add-language
(make-object
((drscheme:language:get-default-mixin)
(swindle-language `(lib ,(string-append module ".rkt") "swindle")
name entry-name num one-line url)))))
(define phase1 void)
(define (phase2)
(for-each (lambda (args) (apply add-swindle-language `(,@args #f)))
'(("Swindle" "main" "Full Swindle" 0
"Full Swindle extensions")
("Swindle w/o CLOS" "turbo" "Swindle without CLOS" 1
"Swindle without the object system")
("Swindle Syntax" "base" "Basic syntax only" 2
"Basic Swindle syntax: keyword-arguments etc")))
(parameterize ([current-directory (collection-path "swindle")])
(define counter 100)
(define (do-customize file)
(when (regexp-match? #rx"\\.rkt$" file)
(with-input-from-file file
(lambda ()
(let ([l (read-line)])
(when (regexp-match? #rx"^;+ *CustomSwindle *$" l)
(let ([file (regexp-replace #rx"\\.rkt$" file "")]
[name #f] [dname #f] [one-line #f] [url #f])
(let loop ([l (read-line)])
(cond
[(regexp-match #rx"^;+ *([A-Z][A-Za-z]*): *(.*)$" l)
=> (lambda (m)
(let ([sym (string->symbol (cadr m))]
[val (caddr m)])
(case sym
[(|Name|) (set! name val)]
[(|DialogName|) (set! dname val)]
[(|OneLine|) (set! one-line val)]
[(|URL|) (set! url val)])
(loop (read-line))))]))
(unless name (set! name file))
(unless dname (set! dname name))
(unless one-line
(set! one-line
(string-append "Customized Swindle: " name)))
(set! counter (add1 counter))
(add-swindle-language
name file dname counter one-line url))))))))
(for-each do-customize
(sort (map path->string (directory-list)) string<?))))
))
|
d032293dcde07cdac5c144c1d14d372f2447beeef5e34ff65cd13aa55d55922c | cdepillabout/world-peace | Product.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE EmptyCase #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE GADTs #-}
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
|
Module : Data . WorldPeace . Product
Copyright : 2017
License : BSD3
Maintainer : ( )
Stability : experimental
Portability : unknown
This module defines an open product type . This is used in the case - analysis
handler for the open sum type ( ' Data . WorldPeace . Union.catchesUnion ' ) .
Module : Data.WorldPeace.Product
Copyright : Dennis Gosnell 2017
License : BSD3
Maintainer : Dennis Gosnell ()
Stability : experimental
Portability : unknown
This module defines an open product type. This is used in the case-analysis
handler for the open sum type ('Data.WorldPeace.Union.catchesUnion').
-}
module Data.WorldPeace.Product
where
import Data.Functor.Identity (Identity(Identity))
-- $setup
-- >>> -- :set -XDataKinds
-------------
-- Product --
-------------
-- | An extensible product type. This is similar to
' Data . WorldPeace . Union . Union ' , except a product type
-- instead of a sum type.
data Product (f :: u -> *) (as :: [u]) where
Nil :: Product f '[]
Cons :: !(f a) -> Product f as -> Product f (a ': as)
-- | This type class provides a way to turn a tuple into a 'Product'.
class ToProduct (tuple :: *) (f :: u -> *) (as :: [u]) | f as -> tuple where
-- | Convert a tuple into a 'Product'. See 'tupleToProduct' for examples.
toProduct :: tuple -> Product f as
-- | Convert a single value into a 'Product'.
instance forall u (f :: u -> *) (a :: u). ToProduct (f a) f '[a] where
toProduct :: f a -> Product f '[a]
toProduct fa = Cons fa Nil
-- | Convert a tuple into a 'Product'.
instance forall u (f :: u -> *) (a :: u) (b :: u). ToProduct (f a, f b) f '[a, b] where
toProduct :: (f a, f b) -> Product f '[a, b]
toProduct (fa, fb) = Cons fa $ Cons fb Nil
| Convert a 3 - tuple into a ' Product ' .
instance forall u (f :: u -> *) (a :: u) (b :: u) (c :: u). ToProduct (f a, f b, f c) f '[a, b, c] where
toProduct :: (f a, f b, f c) -> Product f '[a, b, c]
toProduct (fa, fb, fc) = Cons fa $ Cons fb $ Cons fc Nil
| Convert a 4 - tuple into a ' Product ' .
instance forall u (f :: u -> *) (a :: u) (b :: u) (c :: u) (d :: u). ToProduct (f a, f b, f c, f d) f '[a, b, c, d] where
toProduct :: (f a, f b, f c, f d) -> Product f '[a, b, c, d]
toProduct (fa, fb, fc, fd) = Cons fa $ Cons fb $ Cons fc $ Cons fd Nil
-- | Turn a tuple into a 'Product'.
--
> > > tupleToProduct ( Identity 1 , Identity 2.0 ) : : Product Identity ' [ Int , Double ]
-- Cons (Identity 1) (Cons (Identity 2.0) Nil)
tupleToProduct :: ToProduct t f as => t -> Product f as
tupleToProduct = toProduct
-----------------
-- OpenProduct --
-----------------
-- | @'Product' 'Identity'@ is used as a standard open product type.
type OpenProduct = Product Identity
-- | 'ToOpenProduct' gives us a way to convert a tuple to an 'OpenProduct'.
-- See 'tupleToOpenProduct'.
class ToOpenProduct (tuple :: *) (as :: [*]) | as -> tuple where
toOpenProduct :: tuple -> OpenProduct as
-- | Convert a single value into an 'OpenProduct'.
instance forall (a :: *). ToOpenProduct a '[a] where
toOpenProduct :: a -> OpenProduct '[a]
toOpenProduct a = Cons (Identity a) Nil
-- | Convert a tuple into an 'OpenProduct'.
instance
forall (a :: *) (b :: *). ToOpenProduct (a, b) '[a, b] where
toOpenProduct :: (a, b) -> OpenProduct '[a, b]
toOpenProduct (a, b) = Cons (Identity a) $ Cons (Identity b) Nil
| Convert a 3 - tuple into an ' OpenProduct ' .
instance
forall (a :: *) (b :: *) (c :: *). ToOpenProduct (a, b, c) '[a, b, c] where
toOpenProduct :: (a, b, c) -> OpenProduct '[a, b, c]
toOpenProduct (a, b, c) =
Cons (Identity a) $ Cons (Identity b) $ Cons (Identity c) Nil
| Convert a 4 - tuple into an ' OpenProduct ' .
instance
forall (a :: *) (b :: *) (c :: *) (d :: *).
ToOpenProduct (a, b, c, d) '[a, b, c, d] where
toOpenProduct :: (a, b, c, d) -> OpenProduct '[a, b, c, d]
toOpenProduct (a, b, c, d) =
Cons (Identity a)
. Cons (Identity b)
. Cons (Identity c)
$ Cons (Identity d) Nil
-- | Turn a tuple into an 'OpenProduct'.
--
-- ==== __Examples__
--
-- Turn a triple into an 'OpenProduct':
--
> > > tupleToOpenProduct ( 1 , 2.0 , " hello " ) : : OpenProduct ' [ Int , Double , String ]
-- Cons (Identity 1) (Cons (Identity 2.0) (Cons (Identity "hello") Nil))
--
-- Turn a single value into an 'OpenProduct':
--
> > > tupleToOpenProduct ' c ' : : OpenProduct ' [ ]
-- Cons (Identity 'c') Nil
tupleToOpenProduct :: ToOpenProduct t as => t -> OpenProduct as
tupleToOpenProduct = toOpenProduct
---------------
-- Instances --
---------------
-- | Show 'Nil' values.
instance Show (Product f '[]) where
show :: Product f '[] -> String
show Nil = "Nil"
-- | Show 'Cons' values.
instance (Show (f a), Show (Product f as)) => Show (Product f (a ': as)) where
showsPrec :: Int -> (Product f (a ': as)) -> String -> String
showsPrec n (Cons fa prod) = showParen (n > 10) $
showString "Cons " . showsPrec 11 fa . showString " " . showsPrec 11 prod
| null | https://raw.githubusercontent.com/cdepillabout/world-peace/0596da67d792ccf9f0ddbe44b5ce71b38cbde020/src/Data/WorldPeace/Product.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
$setup
>>> -- :set -XDataKinds
-----------
Product --
-----------
| An extensible product type. This is similar to
instead of a sum type.
| This type class provides a way to turn a tuple into a 'Product'.
| Convert a tuple into a 'Product'. See 'tupleToProduct' for examples.
| Convert a single value into a 'Product'.
| Convert a tuple into a 'Product'.
| Turn a tuple into a 'Product'.
Cons (Identity 1) (Cons (Identity 2.0) Nil)
---------------
OpenProduct --
---------------
| @'Product' 'Identity'@ is used as a standard open product type.
| 'ToOpenProduct' gives us a way to convert a tuple to an 'OpenProduct'.
See 'tupleToOpenProduct'.
| Convert a single value into an 'OpenProduct'.
| Convert a tuple into an 'OpenProduct'.
| Turn a tuple into an 'OpenProduct'.
==== __Examples__
Turn a triple into an 'OpenProduct':
Cons (Identity 1) (Cons (Identity 2.0) (Cons (Identity "hello") Nil))
Turn a single value into an 'OpenProduct':
Cons (Identity 'c') Nil
-------------
Instances --
-------------
| Show 'Nil' values.
| Show 'Cons' values. | # LANGUAGE DataKinds #
# LANGUAGE EmptyCase #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE InstanceSigs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
|
Module : Data . WorldPeace . Product
Copyright : 2017
License : BSD3
Maintainer : ( )
Stability : experimental
Portability : unknown
This module defines an open product type . This is used in the case - analysis
handler for the open sum type ( ' Data . WorldPeace . Union.catchesUnion ' ) .
Module : Data.WorldPeace.Product
Copyright : Dennis Gosnell 2017
License : BSD3
Maintainer : Dennis Gosnell ()
Stability : experimental
Portability : unknown
This module defines an open product type. This is used in the case-analysis
handler for the open sum type ('Data.WorldPeace.Union.catchesUnion').
-}
module Data.WorldPeace.Product
where
import Data.Functor.Identity (Identity(Identity))
' Data . WorldPeace . Union . Union ' , except a product type
data Product (f :: u -> *) (as :: [u]) where
Nil :: Product f '[]
Cons :: !(f a) -> Product f as -> Product f (a ': as)
class ToProduct (tuple :: *) (f :: u -> *) (as :: [u]) | f as -> tuple where
toProduct :: tuple -> Product f as
instance forall u (f :: u -> *) (a :: u). ToProduct (f a) f '[a] where
toProduct :: f a -> Product f '[a]
toProduct fa = Cons fa Nil
instance forall u (f :: u -> *) (a :: u) (b :: u). ToProduct (f a, f b) f '[a, b] where
toProduct :: (f a, f b) -> Product f '[a, b]
toProduct (fa, fb) = Cons fa $ Cons fb Nil
| Convert a 3 - tuple into a ' Product ' .
instance forall u (f :: u -> *) (a :: u) (b :: u) (c :: u). ToProduct (f a, f b, f c) f '[a, b, c] where
toProduct :: (f a, f b, f c) -> Product f '[a, b, c]
toProduct (fa, fb, fc) = Cons fa $ Cons fb $ Cons fc Nil
| Convert a 4 - tuple into a ' Product ' .
instance forall u (f :: u -> *) (a :: u) (b :: u) (c :: u) (d :: u). ToProduct (f a, f b, f c, f d) f '[a, b, c, d] where
toProduct :: (f a, f b, f c, f d) -> Product f '[a, b, c, d]
toProduct (fa, fb, fc, fd) = Cons fa $ Cons fb $ Cons fc $ Cons fd Nil
> > > tupleToProduct ( Identity 1 , Identity 2.0 ) : : Product Identity ' [ Int , Double ]
tupleToProduct :: ToProduct t f as => t -> Product f as
tupleToProduct = toProduct
type OpenProduct = Product Identity
class ToOpenProduct (tuple :: *) (as :: [*]) | as -> tuple where
toOpenProduct :: tuple -> OpenProduct as
instance forall (a :: *). ToOpenProduct a '[a] where
toOpenProduct :: a -> OpenProduct '[a]
toOpenProduct a = Cons (Identity a) Nil
instance
forall (a :: *) (b :: *). ToOpenProduct (a, b) '[a, b] where
toOpenProduct :: (a, b) -> OpenProduct '[a, b]
toOpenProduct (a, b) = Cons (Identity a) $ Cons (Identity b) Nil
| Convert a 3 - tuple into an ' OpenProduct ' .
instance
forall (a :: *) (b :: *) (c :: *). ToOpenProduct (a, b, c) '[a, b, c] where
toOpenProduct :: (a, b, c) -> OpenProduct '[a, b, c]
toOpenProduct (a, b, c) =
Cons (Identity a) $ Cons (Identity b) $ Cons (Identity c) Nil
| Convert a 4 - tuple into an ' OpenProduct ' .
instance
forall (a :: *) (b :: *) (c :: *) (d :: *).
ToOpenProduct (a, b, c, d) '[a, b, c, d] where
toOpenProduct :: (a, b, c, d) -> OpenProduct '[a, b, c, d]
toOpenProduct (a, b, c, d) =
Cons (Identity a)
. Cons (Identity b)
. Cons (Identity c)
$ Cons (Identity d) Nil
> > > tupleToOpenProduct ( 1 , 2.0 , " hello " ) : : OpenProduct ' [ Int , Double , String ]
> > > tupleToOpenProduct ' c ' : : OpenProduct ' [ ]
tupleToOpenProduct :: ToOpenProduct t as => t -> OpenProduct as
tupleToOpenProduct = toOpenProduct
instance Show (Product f '[]) where
show :: Product f '[] -> String
show Nil = "Nil"
instance (Show (f a), Show (Product f as)) => Show (Product f (a ': as)) where
showsPrec :: Int -> (Product f (a ': as)) -> String -> String
showsPrec n (Cons fa prod) = showParen (n > 10) $
showString "Cons " . showsPrec 11 fa . showString " " . showsPrec 11 prod
|
b4dc269bd8c95d5ab5197eb8436832b20d6920e2d262d1fce10090736cbe93b1 | TorXakis/TorXakis | Sqatt.hs |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
# LANGUAGE GeneralizedNewtypeDeriving #
{-# LANGUAGE OverloadedStrings #-}
-- | Integration test utilities.
module Sqatt
( TxsExample(..)
, checkSMTSolvers
, checkCompilers
, checkTxsInstall
, emptyExample
, ExampleResult (..)
, javaCmd
, TxsExampleSet (..)
, SutExample (..)
, toFSSafeStr
-- * Testing
, testExamples
, testExampleSet
, testExampleSets
-- * Benchmarking
, benchmarkExampleSet
-- * Logging
, sqattLogsRoot
, mkLogDir
-- * Re-exports
, module Turtle
)
where
import Control.Applicative
import Control.Arrow
import Control.Concurrent.Async
import Control.Exception
import Control.Foldl
import Control.Monad.Except
import Control.Monad.Extra
import Criterion.Main
import Data.Either
import Data.Foldable
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Filesystem.Path
import Filesystem.Path.CurrentOS
import Prelude hiding (FilePath)
import System.Info
import qualified System.IO as IO
import System.Random
import Test.Hspec
import Turtle
-- * Data structures for specifying examples
| A description of a TorXakis example .
data TxsExample
= TxsExample {
-- | Name of the example.
exampleName :: String
-- | Action to run before testing the example.
, setupAction :: IO ()
, tearDownAction :: IO ()
| Paths to the TorXakis model files .
, txsModelFiles :: [FilePath]
-- | Paths to the files containing the commands that will be passed to the
TorXakis server . Commands are passed in the order specified by the
-- order of the files in the list.
, txsCmdsFiles :: [FilePath]
| Command line arguments to be passed to the TorXakis server command .
, txsServerArgs :: [Text]
| SUT example . This run together with TorXakis . If this field is
` Nothing ` then the example is assumed to be autonomous ( only TorXakis
-- will be run)
, sutExample :: Maybe SutExample
-- | Example's expected result.
, expectedResult :: ExampleResult
} -- deriving (Show)
instance Show TxsExample where
show = undefined
data SutExample
| A Java SUT that must be compiled and executed .
= JavaExample {
| Source file of the SUT .
javaSourcePath :: FilePath
| Arguments to be passed to the SUT .
, javaSutArgs :: [Text]
}
| A TorXakis simulated SUT . The FilePath specifies the location of the
-- commands to be input to the simulator.
| TxsSimulator FilePath
deriving (Show)
-- | A set of examples.
data TxsExampleSet
= TxsExampleSet {
-- | Description of the example set.
exampleSetdesc :: ExampleSetDesc
-- | Examples in the set.
, txsExamples :: [TxsExample]
}
-- | Description of the example set.
newtype ExampleSetDesc
= ExampleSetDesc {
-- | Name of the example set.
exampleSetName :: String
}
instance IsString ExampleSetDesc where
fromString = ExampleSetDesc
| Information about a compiled Java program .
data CompiledSut
| ` JavaCompiledSut mainClass mClassSP ` :
--
- ` mainClass ` : name of the main Java class .
--
-- - `mClassSP`: Class search path. If omitted no `-cp` option will be
-- passed to the `java` command.
--
= JavaCompiledSut Text (Maybe FilePath)
| An SUT simulated by TorXakis .
--
` TxsSimulatedSut ` :
--
- ` modelPaths ` : Paths to the TorXakis models .
-- - `cmds`: Commands to be passed to the simulator.
| TxsSimulatedSut [FilePath] FilePath
-- | A processed example, ready to be run.
--
-- Currently the only processing that takes place is the compilation of the
SUT , if any .
data RunnableExample = ExampleWithSut TxsExample CompiledSut [Text]
| StandaloneExample TxsExample
data ExampleResult = Pass | Fail | Message Text deriving (Show, Eq)
-- * Path manipulation functions
addExeSuffix :: Text -> Text
addExeSuffix path = if os == "mingw32" then path <> ".exe" else path
javaCmd :: Text
javaCmd = addExeSuffix "java"
javacCmd :: Text
javacCmd = addExeSuffix "javac"
txsServerCmd :: Text
txsServerCmd = addExeSuffix "txsserver"
txsUICmd :: Text
txsUICmd = addExeSuffix "torxakis"
txsUILinePrefix :: Text
txsUILinePrefix = "TXS >> "
class ExpectedMessage a where
expectedMessage :: a -> Text
instance ExpectedMessage ExampleResult where
expectedMessage Pass = txsUILinePrefix <> "PASS"
expectedMessage Fail = txsUILinePrefix <> "FAIL"
expectedMessage (Message msg) = txsUILinePrefix <> msg
-- | Decode a file path into a human readable text string. The decoding is
-- dependent on the operating system. An error is thrown if the decoding is not
-- successful.
decodePath :: FilePath -> Test Text
decodePath filePath =
case toText filePath of
Right path ->
return path
Left apprPath ->
throwError $ FilePathError $
"Cannot decode " <> apprPath <> " properly"
| Replace the characters that might cause problems on Windows systems .
toFSSafeStr :: String -> String
toFSSafeStr str = repl <$> str
where repl ' ' = '_'
repl ':' = '-'
repl c = c
-- * Environment checking
| Check that all the supported SMT solvers are installed .
--
-- Throws an exception on failure.
checkSMTSolvers :: IO ()
checkSMTSolvers =
traverse_ checkCommand txsSupportedSolvers
where
txsSupportedSolvers = Prelude.map addExeSuffix ["z3","cvc4"]
-- | Check that the given command exists in the search path of the host system.
checkCommand :: Text -> IO ()
checkCommand cmd = do
path <- which $ fromText cmd
case path of
Nothing -> throwIO $ ProgramNotFound $ T.pack $ show cmd
_ -> return ()
-- | Check that all the compilers are installed.
--
-- Throws an exception on failure.
checkCompilers :: IO ()
checkCompilers = traverse_ checkCommand [javaCmd, javacCmd]
| Check that the TorXakis UI and server programs are installed .
checkTxsInstall :: IO ()
checkTxsInstall = traverse_ checkCommand [txsUICmd, txsServerCmd]
-- * Compilation and testing
-- | Sqatt test monad.
newtype Test a = Test { runTest :: ExceptT SqattError IO a }
deriving (Functor, Monad, Applicative, MonadError SqattError, MonadIO)
| Test errors that can arise when running a TorXakis example .
data SqattError = CompileError Text
| ProgramNotFound Text
| UnsupportedLanguage Text
| FilePathError Text
| TestExpectationError Text
| SutAborted
| TxsServerAborted
| TestTimedOut
| TxsChecksTimedOut
| UnexpectedException Text
deriving (Show, Eq)
instance Exception SqattError
-- | Compile the system under test.
compileSut :: FilePath -> Test CompiledSut
compileSut sourcePath =
case extension sourcePath of
Just "java" ->
compileJavaSut sourcePath
_ -> do
path <- decodePath sourcePath
throwError $ UnsupportedLanguage $
"Compiler not found for file " <> path
| Compile a SUT written in Java .
compileJavaSut :: FilePath -> Test CompiledSut
compileJavaSut sourcePath = do
allJavaFiles <- Turtle.fold (mfilter (`hasExtension` "java") (ls $ directory sourcePath)) Control.Foldl.list
path <- mapM decodePath allJavaFiles
exitCode <- proc javacCmd path mempty
case exitCode of
ExitFailure code ->
throwError $ CompileError $
"Java compilation command failed with code: " <> (T.pack . show) code
ExitSuccess -> do
mClass <- decodePath $ basename sourcePath
let sPath = directory sourcePath
return $ JavaCompiledSut mClass (Just sPath)
-- | Add the class path option if a class-path is given.
getCPOptsIO :: Maybe FilePath -> IO [Text]
getCPOptsIO Nothing = return []
getCPOptsIO (Just filePath) = case toText filePath of
Left apprPath ->
throwIO $ FilePathError $
"Cannot decode " <> apprPath <> " properly"
Right path ->
return ["-cp", path]
| Timeout ( in seconds ) for running a test . For now the timeout is not
-- configurable.
sqattTimeout :: NominalDiffTime
sqattTimeout = 1800.0
| Time to allow TorXakis run the checks after the SUT terminates . After this
timeout the SUT process terminates and if TorXakis has n't terminated yet
-- the whole test fails.
txsCheckTimeout :: NominalDiffTime
txsCheckTimeout = 60.0
-- | Run TorXakis with the given example specification.
runTxsWithExample :: Maybe FilePath -- ^ Path to the logging directory for
-- the current example set, or nothing if
-- no logging is desired.
-> TxsExample -- ^ Example to run.
^ Delay before start , in seconds .
-> Concurrently (Either SqattError ())
runTxsWithExample mLogDir ex delay = Concurrently $ do
eInputModelF <- runExceptT $ runTest $ mapM decodePath (txsModelFiles ex)
case eInputModelF of
Left decodeErr -> return $ Left decodeErr
Right inputModelF -> do
sleep delay
port <- repr <$> getRandomPort
a <- async $ txsServerProc mLogDir (port : txsServerArgs ex)
runConcurrently $ timer a
<|> heartbeat
<|> txsUIProc mLogDir inputModelF port
where
heartbeat = Concurrently $ forever $ do
sleep 60.0 -- For now we don't make this configurable.
putStr "."
timer srvProc = Concurrently $ do
sleep sqattTimeout
cancel srvProc
return $ Left TestTimedOut
txsUIProc mUiLogDir imf port = Concurrently $ do
eRes <- try $ Turtle.fold txsUIShell findExpectedMsg
case eRes of
Left exception -> return $ Left exception
Right res -> return $ unless res $ Left tErr
where
inLines :: Shell Line
inLines = asum $ input <$> cmdsFile
txsUIShell :: Shell Line
txsUIShell =
case mUiLogDir of
Nothing ->
either id id <$> inprocWithErr txsUICmd
(port:imf)
inLines
Just uiLogDir -> do
h <- appendonly $ uiLogDir </> "txsui.out.log"
line <- either id id <$> inprocWithErr txsUICmd
(port:imf)
inLines
liftIO $ TIO.hPutStrLn h (lineToText line)
return line
findExpectedMsg :: Fold Line Bool
findExpectedMsg = Control.Foldl.any (T.isInfixOf searchStr . lineToText)
cmdsFile = txsCmdsFiles ex
searchStr = expectedMessage . expectedResult $ ex
tErr = TestExpectationError $
format ("Did not get expected result "%s)
(repr . expectedResult $ ex)
txsServerProc sLogDir =
runInprocNI ((</> "txsserver.out.log") <$> sLogDir) txsServerCmd
-- | Run a process.
runInproc :: Maybe FilePath -- ^ Directory where the logs will be stored, or @Nothing@ if no logging is desired.
-> Text -- ^ Command to run.
-> [Text] -- ^ Command arguments.
-> Shell Line -- ^ Lines to be input to the command.
-> IO (Either SqattError ())
runInproc mLogDir cmd cmdArgs procInput =
left (UnexpectedException . T.pack . show) <$>
case mLogDir of
Nothing -> try $ sh $ inprocWithErr cmd cmdArgs procInput :: IO (Either SomeException ())
Just logDir -> try $ output logDir $ either id id <$> inprocWithErr cmd cmdArgs procInput :: IO (Either SomeException ())
-- | Run a process without input. See `runInproc`.
--
runInprocNI :: Maybe FilePath
-> Text
-> [Text]
-> IO (Either SqattError ())
runInprocNI mLogDir cmd cmdArgs =
runInproc mLogDir cmd cmdArgs Turtle.empty
-- | Run TorXakis as system under test.
runTxsAsSut :: Maybe FilePath -- ^ Path to the logging directory for the current
-- example set, or @Nothing@ if no logging is desired.
^ List of paths to the TorXakis model .
^ Path to the commands to be input to the TorXakis model .
-> IO (Either SqattError ())
runTxsAsSut mLogDir modelFiles cmdsFile = do
eInputModelF <- runExceptT $ runTest $ mapM decodePath modelFiles
case eInputModelF of
Left decodeErr -> return $ Left decodeErr
Right inputModelF -> do
port <- repr <$> getRandomPort
runConcurrently $
txsServerProc port <|> txsUIProc inputModelF port
where
txsUIProc imf port = Concurrently $
let mCLogDir = (</> "txsui.SUT.out.log") <$> mLogDir in
runInproc mCLogDir txsUICmd (port:imf) (input cmdsFile)
txsServerProc port = Concurrently $
let mCLogDir = (</> "txsserver.SUT.out.log") <$> mLogDir in
runInprocNI mCLogDir txsServerCmd [port]
mkTest :: Maybe FilePath -> RunnableExample -> Test ()
mkTest mLogDir (ExampleWithSut ex cSUT args) = do
res <- liftIO $
runConcurrently $ runSUTWithTimeout mLogDir cSUT args
<|> runTxsWithExample mLogDir ex 0.1
case res of
Left txsErr -> throwError txsErr
Right () -> return ()
mkTest mLogDir (StandaloneExample ex) = do
res <- liftIO $ runConcurrently $ runTxsWithExample mLogDir ex 0
case res of
Left txsErr -> throwError txsErr
Right _ -> return ()
runSUTWithTimeout :: Maybe FilePath -> CompiledSut -> [Text]
-> Concurrently (Either SqattError ())
runSUTWithTimeout mLogDir cSUT args = Concurrently $ do
res <- runSUT mLogDir cSUT args
case res of
Left someErr ->
return $ Left someErr
Right _ -> do
sleep txsCheckTimeout
return (Left TxsChecksTimedOut)
runSUT :: Maybe FilePath -> CompiledSut -> [Text]
-> IO (Either SqattError ())
runSUT mLogDir (JavaCompiledSut mClass cpSP) args = do
cpOpts <- getCPOptsIO cpSP
let javaArgs = cpOpts ++ [mClass] ++ args
runInprocNI ((</> "SUT.out.log") <$> mLogDir) javaCmd javaArgs
runSUT logDir (TxsSimulatedSut modelFiles cmds) _ =
runTxsAsSut logDir modelFiles cmds
-- | Get a random port number.
getRandomPort :: IO Integer
getRandomPort = randomRIO (10000, 60000)
-- | Check that the file exists.
pathMustExist :: FilePath -> Test ()
pathMustExist path =
unlessM (testpath path) (throwError sqattErr)
where sqattErr =
FilePathError $ format ("file "%s%" does not exists ") (repr path)
-- | Retrieve all the file paths from an example
exampleInputFiles :: TxsExample -> [FilePath]
exampleInputFiles ex =
(txsCmdsFiles ex ++ txsModelFiles ex)
++ maybe [] sutInputFiles (sutExample ex)
where sutInputFiles (JavaExample jsp _) = [jsp]
sutInputFiles (TxsSimulator cmdsFile) = [cmdsFile]
-- | Execute a test.
execTest :: Maybe FilePath -> TxsExample -> Test ()
execTest mLogDir ex = do
for_ mLogDir mktree
traverse_ pathMustExist (exampleInputFiles ex)
runnableExample <- getRunnableExample
mkTest mLogDir runnableExample
where
getRunnableExample =
case sutExample ex of
Nothing ->
return (StandaloneExample ex)
Just (JavaExample sourcePath args) -> do
cmpSut <- compileSut sourcePath
return (ExampleWithSut ex cmpSut args)
Just (TxsSimulator cmds) ->
return (ExampleWithSut ex (TxsSimulatedSut (txsModelFiles ex) cmds) [])
-- | Test a single example.
testExample :: FilePath -> TxsExample -> Spec
testExample logDir ex = it (exampleName ex) $ do
setupAction ex
let mLogDir = logDirOfExample (Just logDir) (exampleName ex)
res <- runExceptT $ runTest $ execTest mLogDir ex
tearDownAction ex
unless (isRight res) (sh $ dumpToScreen $ fromJust mLogDir)
res `shouldBe` Right ()
logDirOfExample :: Maybe FilePath -> String -> Maybe FilePath
logDirOfExample topLogDir exmpName = (</> (fromString . toFSSafeStr) exmpName) <$> topLogDir
dumpToScreen :: FilePath -> Shell ()
dumpToScreen logDir = do
sleep 2.0
file <- ls logDir
liftIO $ putStrLn $ "==> " ++ encodeString file
stdout $ "> " <> input file
printf "--- EOF ---\n\n"
-- | Test a list of examples.
testExamples :: FilePath -> [TxsExample] -> Spec
testExamples logDir = traverse_ (testExample logDir)
| Make a benchmark from a TorXakis example .
mkBenchmark :: TxsExample -> Benchmark
mkBenchmark ex =
bench (exampleName ex) $ nfIO runBenchmark
where
runBenchmark = do
res <- runExceptT $ runTest $ execTest Nothing ex
unless (isRight res) (error $ "Unexpected error: " ++ show res)
| Make a list of benchmarks from a list of TorXakis examples .
mkBenchmarks :: [TxsExample] -> [Benchmark]
mkBenchmarks = (mkBenchmark <$>)
-- | Run benchmarks on a set of examples.
benchmarkExampleSet :: TxsExampleSet -> Benchmark
benchmarkExampleSet (TxsExampleSet exSetDesc exs) =
bgroup groupName benchmarks
where
groupName = exampleSetName exSetDesc
benchmarks = mkBenchmarks exs
esLogDir :: FilePath -> TxsExampleSet -> FilePath
esLogDir logRoot exSet =
logRoot </> ( fromString
. toFSSafeStr
. exampleSetName
. exampleSetdesc) exSet
-- | Test an example set.
testExampleSet :: FilePath -> TxsExampleSet -> Spec
testExampleSet logDir es@(TxsExampleSet exSetDesc exs) = do
let thisSetLogDir = esLogDir logDir es
runIO $ mktree thisSetLogDir
describe (exampleSetName exSetDesc) (testExamples thisSetLogDir exs)
-- | Test a list of example sets.
testExampleSets :: FilePath -> [TxsExampleSet] -> Spec
testExampleSets logDir exampleSets = do
runIO $ IO.hSetBuffering IO.stdout IO.NoBuffering
traverse_ (testExampleSet logDir) exampleSets
-- | For now the root directory where the logs are stored is not configurable.
sqattLogsRoot :: FilePath
sqattLogsRoot = "sqatt-logs"
-- | Create a log directory with the specified prefix.
mkLogDir :: String -> IO FilePath
mkLogDir strPrefix = do
currDate <- date
let logDir =
sqattLogsRoot </> fromString (strPrefix ++ currDateStr)
currDateStr = toFSSafeStr (show currDate)
mktree logDir
return logDir
emptyExample :: TxsExample
emptyExample = TxsExample
{ exampleName = ""
, setupAction = return ()
, tearDownAction = return ()
, txsModelFiles = []
, txsCmdsFiles = []
, txsServerArgs = []
, sutExample = Nothing
, expectedResult = Message ""
}
| null | https://raw.githubusercontent.com/TorXakis/TorXakis/038463824b3d358df6b6b3ff08732335b7dbdb53/test/sqatt/src/Sqatt.hs | haskell | # LANGUAGE OverloadedStrings #
| Integration test utilities.
* Testing
* Benchmarking
* Logging
* Re-exports
* Data structures for specifying examples
| Name of the example.
| Action to run before testing the example.
| Paths to the files containing the commands that will be passed to the
order of the files in the list.
will be run)
| Example's expected result.
deriving (Show)
commands to be input to the simulator.
| A set of examples.
| Description of the example set.
| Examples in the set.
| Description of the example set.
| Name of the example set.
- `mClassSP`: Class search path. If omitted no `-cp` option will be
passed to the `java` command.
- `cmds`: Commands to be passed to the simulator.
| A processed example, ready to be run.
Currently the only processing that takes place is the compilation of the
* Path manipulation functions
| Decode a file path into a human readable text string. The decoding is
dependent on the operating system. An error is thrown if the decoding is not
successful.
* Environment checking
Throws an exception on failure.
| Check that the given command exists in the search path of the host system.
| Check that all the compilers are installed.
Throws an exception on failure.
* Compilation and testing
| Sqatt test monad.
| Compile the system under test.
| Add the class path option if a class-path is given.
configurable.
the whole test fails.
| Run TorXakis with the given example specification.
^ Path to the logging directory for
the current example set, or nothing if
no logging is desired.
^ Example to run.
For now we don't make this configurable.
| Run a process.
^ Directory where the logs will be stored, or @Nothing@ if no logging is desired.
^ Command to run.
^ Command arguments.
^ Lines to be input to the command.
| Run a process without input. See `runInproc`.
| Run TorXakis as system under test.
^ Path to the logging directory for the current
example set, or @Nothing@ if no logging is desired.
| Get a random port number.
| Check that the file exists.
| Retrieve all the file paths from an example
| Execute a test.
| Test a single example.
| Test a list of examples.
| Run benchmarks on a set of examples.
| Test an example set.
| Test a list of example sets.
| For now the root directory where the logs are stored is not configurable.
| Create a log directory with the specified prefix. |
TorXakis - Model Based Testing
Copyright ( c ) 2015 - 2017 TNO and Radboud University
See LICENSE at root directory of this repository .
TorXakis - Model Based Testing
Copyright (c) 2015-2017 TNO and Radboud University
See LICENSE at root directory of this repository.
-}
# LANGUAGE GeneralizedNewtypeDeriving #
module Sqatt
( TxsExample(..)
, checkSMTSolvers
, checkCompilers
, checkTxsInstall
, emptyExample
, ExampleResult (..)
, javaCmd
, TxsExampleSet (..)
, SutExample (..)
, toFSSafeStr
, testExamples
, testExampleSet
, testExampleSets
, benchmarkExampleSet
, sqattLogsRoot
, mkLogDir
, module Turtle
)
where
import Control.Applicative
import Control.Arrow
import Control.Concurrent.Async
import Control.Exception
import Control.Foldl
import Control.Monad.Except
import Control.Monad.Extra
import Criterion.Main
import Data.Either
import Data.Foldable
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Filesystem.Path
import Filesystem.Path.CurrentOS
import Prelude hiding (FilePath)
import System.Info
import qualified System.IO as IO
import System.Random
import Test.Hspec
import Turtle
| A description of a TorXakis example .
data TxsExample
= TxsExample {
exampleName :: String
, setupAction :: IO ()
, tearDownAction :: IO ()
| Paths to the TorXakis model files .
, txsModelFiles :: [FilePath]
TorXakis server . Commands are passed in the order specified by the
, txsCmdsFiles :: [FilePath]
| Command line arguments to be passed to the TorXakis server command .
, txsServerArgs :: [Text]
| SUT example . This run together with TorXakis . If this field is
` Nothing ` then the example is assumed to be autonomous ( only TorXakis
, sutExample :: Maybe SutExample
, expectedResult :: ExampleResult
instance Show TxsExample where
show = undefined
data SutExample
| A Java SUT that must be compiled and executed .
= JavaExample {
| Source file of the SUT .
javaSourcePath :: FilePath
| Arguments to be passed to the SUT .
, javaSutArgs :: [Text]
}
| A TorXakis simulated SUT . The FilePath specifies the location of the
| TxsSimulator FilePath
deriving (Show)
data TxsExampleSet
= TxsExampleSet {
exampleSetdesc :: ExampleSetDesc
, txsExamples :: [TxsExample]
}
newtype ExampleSetDesc
= ExampleSetDesc {
exampleSetName :: String
}
instance IsString ExampleSetDesc where
fromString = ExampleSetDesc
| Information about a compiled Java program .
data CompiledSut
| ` JavaCompiledSut mainClass mClassSP ` :
- ` mainClass ` : name of the main Java class .
= JavaCompiledSut Text (Maybe FilePath)
| An SUT simulated by TorXakis .
` TxsSimulatedSut ` :
- ` modelPaths ` : Paths to the TorXakis models .
| TxsSimulatedSut [FilePath] FilePath
SUT , if any .
data RunnableExample = ExampleWithSut TxsExample CompiledSut [Text]
| StandaloneExample TxsExample
data ExampleResult = Pass | Fail | Message Text deriving (Show, Eq)
addExeSuffix :: Text -> Text
addExeSuffix path = if os == "mingw32" then path <> ".exe" else path
javaCmd :: Text
javaCmd = addExeSuffix "java"
javacCmd :: Text
javacCmd = addExeSuffix "javac"
txsServerCmd :: Text
txsServerCmd = addExeSuffix "txsserver"
txsUICmd :: Text
txsUICmd = addExeSuffix "torxakis"
txsUILinePrefix :: Text
txsUILinePrefix = "TXS >> "
class ExpectedMessage a where
expectedMessage :: a -> Text
instance ExpectedMessage ExampleResult where
expectedMessage Pass = txsUILinePrefix <> "PASS"
expectedMessage Fail = txsUILinePrefix <> "FAIL"
expectedMessage (Message msg) = txsUILinePrefix <> msg
decodePath :: FilePath -> Test Text
decodePath filePath =
case toText filePath of
Right path ->
return path
Left apprPath ->
throwError $ FilePathError $
"Cannot decode " <> apprPath <> " properly"
| Replace the characters that might cause problems on Windows systems .
toFSSafeStr :: String -> String
toFSSafeStr str = repl <$> str
where repl ' ' = '_'
repl ':' = '-'
repl c = c
| Check that all the supported SMT solvers are installed .
checkSMTSolvers :: IO ()
checkSMTSolvers =
traverse_ checkCommand txsSupportedSolvers
where
txsSupportedSolvers = Prelude.map addExeSuffix ["z3","cvc4"]
checkCommand :: Text -> IO ()
checkCommand cmd = do
path <- which $ fromText cmd
case path of
Nothing -> throwIO $ ProgramNotFound $ T.pack $ show cmd
_ -> return ()
checkCompilers :: IO ()
checkCompilers = traverse_ checkCommand [javaCmd, javacCmd]
| Check that the TorXakis UI and server programs are installed .
checkTxsInstall :: IO ()
checkTxsInstall = traverse_ checkCommand [txsUICmd, txsServerCmd]
newtype Test a = Test { runTest :: ExceptT SqattError IO a }
deriving (Functor, Monad, Applicative, MonadError SqattError, MonadIO)
| Test errors that can arise when running a TorXakis example .
data SqattError = CompileError Text
| ProgramNotFound Text
| UnsupportedLanguage Text
| FilePathError Text
| TestExpectationError Text
| SutAborted
| TxsServerAborted
| TestTimedOut
| TxsChecksTimedOut
| UnexpectedException Text
deriving (Show, Eq)
instance Exception SqattError
compileSut :: FilePath -> Test CompiledSut
compileSut sourcePath =
case extension sourcePath of
Just "java" ->
compileJavaSut sourcePath
_ -> do
path <- decodePath sourcePath
throwError $ UnsupportedLanguage $
"Compiler not found for file " <> path
| Compile a SUT written in Java .
compileJavaSut :: FilePath -> Test CompiledSut
compileJavaSut sourcePath = do
allJavaFiles <- Turtle.fold (mfilter (`hasExtension` "java") (ls $ directory sourcePath)) Control.Foldl.list
path <- mapM decodePath allJavaFiles
exitCode <- proc javacCmd path mempty
case exitCode of
ExitFailure code ->
throwError $ CompileError $
"Java compilation command failed with code: " <> (T.pack . show) code
ExitSuccess -> do
mClass <- decodePath $ basename sourcePath
let sPath = directory sourcePath
return $ JavaCompiledSut mClass (Just sPath)
getCPOptsIO :: Maybe FilePath -> IO [Text]
getCPOptsIO Nothing = return []
getCPOptsIO (Just filePath) = case toText filePath of
Left apprPath ->
throwIO $ FilePathError $
"Cannot decode " <> apprPath <> " properly"
Right path ->
return ["-cp", path]
| Timeout ( in seconds ) for running a test . For now the timeout is not
sqattTimeout :: NominalDiffTime
sqattTimeout = 1800.0
| Time to allow TorXakis run the checks after the SUT terminates . After this
timeout the SUT process terminates and if TorXakis has n't terminated yet
txsCheckTimeout :: NominalDiffTime
txsCheckTimeout = 60.0
^ Delay before start , in seconds .
-> Concurrently (Either SqattError ())
runTxsWithExample mLogDir ex delay = Concurrently $ do
eInputModelF <- runExceptT $ runTest $ mapM decodePath (txsModelFiles ex)
case eInputModelF of
Left decodeErr -> return $ Left decodeErr
Right inputModelF -> do
sleep delay
port <- repr <$> getRandomPort
a <- async $ txsServerProc mLogDir (port : txsServerArgs ex)
runConcurrently $ timer a
<|> heartbeat
<|> txsUIProc mLogDir inputModelF port
where
heartbeat = Concurrently $ forever $ do
putStr "."
timer srvProc = Concurrently $ do
sleep sqattTimeout
cancel srvProc
return $ Left TestTimedOut
txsUIProc mUiLogDir imf port = Concurrently $ do
eRes <- try $ Turtle.fold txsUIShell findExpectedMsg
case eRes of
Left exception -> return $ Left exception
Right res -> return $ unless res $ Left tErr
where
inLines :: Shell Line
inLines = asum $ input <$> cmdsFile
txsUIShell :: Shell Line
txsUIShell =
case mUiLogDir of
Nothing ->
either id id <$> inprocWithErr txsUICmd
(port:imf)
inLines
Just uiLogDir -> do
h <- appendonly $ uiLogDir </> "txsui.out.log"
line <- either id id <$> inprocWithErr txsUICmd
(port:imf)
inLines
liftIO $ TIO.hPutStrLn h (lineToText line)
return line
findExpectedMsg :: Fold Line Bool
findExpectedMsg = Control.Foldl.any (T.isInfixOf searchStr . lineToText)
cmdsFile = txsCmdsFiles ex
searchStr = expectedMessage . expectedResult $ ex
tErr = TestExpectationError $
format ("Did not get expected result "%s)
(repr . expectedResult $ ex)
txsServerProc sLogDir =
runInprocNI ((</> "txsserver.out.log") <$> sLogDir) txsServerCmd
-> IO (Either SqattError ())
runInproc mLogDir cmd cmdArgs procInput =
left (UnexpectedException . T.pack . show) <$>
case mLogDir of
Nothing -> try $ sh $ inprocWithErr cmd cmdArgs procInput :: IO (Either SomeException ())
Just logDir -> try $ output logDir $ either id id <$> inprocWithErr cmd cmdArgs procInput :: IO (Either SomeException ())
runInprocNI :: Maybe FilePath
-> Text
-> [Text]
-> IO (Either SqattError ())
runInprocNI mLogDir cmd cmdArgs =
runInproc mLogDir cmd cmdArgs Turtle.empty
^ List of paths to the TorXakis model .
^ Path to the commands to be input to the TorXakis model .
-> IO (Either SqattError ())
runTxsAsSut mLogDir modelFiles cmdsFile = do
eInputModelF <- runExceptT $ runTest $ mapM decodePath modelFiles
case eInputModelF of
Left decodeErr -> return $ Left decodeErr
Right inputModelF -> do
port <- repr <$> getRandomPort
runConcurrently $
txsServerProc port <|> txsUIProc inputModelF port
where
txsUIProc imf port = Concurrently $
let mCLogDir = (</> "txsui.SUT.out.log") <$> mLogDir in
runInproc mCLogDir txsUICmd (port:imf) (input cmdsFile)
txsServerProc port = Concurrently $
let mCLogDir = (</> "txsserver.SUT.out.log") <$> mLogDir in
runInprocNI mCLogDir txsServerCmd [port]
mkTest :: Maybe FilePath -> RunnableExample -> Test ()
mkTest mLogDir (ExampleWithSut ex cSUT args) = do
res <- liftIO $
runConcurrently $ runSUTWithTimeout mLogDir cSUT args
<|> runTxsWithExample mLogDir ex 0.1
case res of
Left txsErr -> throwError txsErr
Right () -> return ()
mkTest mLogDir (StandaloneExample ex) = do
res <- liftIO $ runConcurrently $ runTxsWithExample mLogDir ex 0
case res of
Left txsErr -> throwError txsErr
Right _ -> return ()
runSUTWithTimeout :: Maybe FilePath -> CompiledSut -> [Text]
-> Concurrently (Either SqattError ())
runSUTWithTimeout mLogDir cSUT args = Concurrently $ do
res <- runSUT mLogDir cSUT args
case res of
Left someErr ->
return $ Left someErr
Right _ -> do
sleep txsCheckTimeout
return (Left TxsChecksTimedOut)
runSUT :: Maybe FilePath -> CompiledSut -> [Text]
-> IO (Either SqattError ())
runSUT mLogDir (JavaCompiledSut mClass cpSP) args = do
cpOpts <- getCPOptsIO cpSP
let javaArgs = cpOpts ++ [mClass] ++ args
runInprocNI ((</> "SUT.out.log") <$> mLogDir) javaCmd javaArgs
runSUT logDir (TxsSimulatedSut modelFiles cmds) _ =
runTxsAsSut logDir modelFiles cmds
getRandomPort :: IO Integer
getRandomPort = randomRIO (10000, 60000)
pathMustExist :: FilePath -> Test ()
pathMustExist path =
unlessM (testpath path) (throwError sqattErr)
where sqattErr =
FilePathError $ format ("file "%s%" does not exists ") (repr path)
exampleInputFiles :: TxsExample -> [FilePath]
exampleInputFiles ex =
(txsCmdsFiles ex ++ txsModelFiles ex)
++ maybe [] sutInputFiles (sutExample ex)
where sutInputFiles (JavaExample jsp _) = [jsp]
sutInputFiles (TxsSimulator cmdsFile) = [cmdsFile]
execTest :: Maybe FilePath -> TxsExample -> Test ()
execTest mLogDir ex = do
for_ mLogDir mktree
traverse_ pathMustExist (exampleInputFiles ex)
runnableExample <- getRunnableExample
mkTest mLogDir runnableExample
where
getRunnableExample =
case sutExample ex of
Nothing ->
return (StandaloneExample ex)
Just (JavaExample sourcePath args) -> do
cmpSut <- compileSut sourcePath
return (ExampleWithSut ex cmpSut args)
Just (TxsSimulator cmds) ->
return (ExampleWithSut ex (TxsSimulatedSut (txsModelFiles ex) cmds) [])
testExample :: FilePath -> TxsExample -> Spec
testExample logDir ex = it (exampleName ex) $ do
setupAction ex
let mLogDir = logDirOfExample (Just logDir) (exampleName ex)
res <- runExceptT $ runTest $ execTest mLogDir ex
tearDownAction ex
unless (isRight res) (sh $ dumpToScreen $ fromJust mLogDir)
res `shouldBe` Right ()
logDirOfExample :: Maybe FilePath -> String -> Maybe FilePath
logDirOfExample topLogDir exmpName = (</> (fromString . toFSSafeStr) exmpName) <$> topLogDir
dumpToScreen :: FilePath -> Shell ()
dumpToScreen logDir = do
sleep 2.0
file <- ls logDir
liftIO $ putStrLn $ "==> " ++ encodeString file
stdout $ "> " <> input file
printf "--- EOF ---\n\n"
testExamples :: FilePath -> [TxsExample] -> Spec
testExamples logDir = traverse_ (testExample logDir)
| Make a benchmark from a TorXakis example .
mkBenchmark :: TxsExample -> Benchmark
mkBenchmark ex =
bench (exampleName ex) $ nfIO runBenchmark
where
runBenchmark = do
res <- runExceptT $ runTest $ execTest Nothing ex
unless (isRight res) (error $ "Unexpected error: " ++ show res)
| Make a list of benchmarks from a list of TorXakis examples .
mkBenchmarks :: [TxsExample] -> [Benchmark]
mkBenchmarks = (mkBenchmark <$>)
benchmarkExampleSet :: TxsExampleSet -> Benchmark
benchmarkExampleSet (TxsExampleSet exSetDesc exs) =
bgroup groupName benchmarks
where
groupName = exampleSetName exSetDesc
benchmarks = mkBenchmarks exs
esLogDir :: FilePath -> TxsExampleSet -> FilePath
esLogDir logRoot exSet =
logRoot </> ( fromString
. toFSSafeStr
. exampleSetName
. exampleSetdesc) exSet
testExampleSet :: FilePath -> TxsExampleSet -> Spec
testExampleSet logDir es@(TxsExampleSet exSetDesc exs) = do
let thisSetLogDir = esLogDir logDir es
runIO $ mktree thisSetLogDir
describe (exampleSetName exSetDesc) (testExamples thisSetLogDir exs)
testExampleSets :: FilePath -> [TxsExampleSet] -> Spec
testExampleSets logDir exampleSets = do
runIO $ IO.hSetBuffering IO.stdout IO.NoBuffering
traverse_ (testExampleSet logDir) exampleSets
sqattLogsRoot :: FilePath
sqattLogsRoot = "sqatt-logs"
mkLogDir :: String -> IO FilePath
mkLogDir strPrefix = do
currDate <- date
let logDir =
sqattLogsRoot </> fromString (strPrefix ++ currDateStr)
currDateStr = toFSSafeStr (show currDate)
mktree logDir
return logDir
emptyExample :: TxsExample
emptyExample = TxsExample
{ exampleName = ""
, setupAction = return ()
, tearDownAction = return ()
, txsModelFiles = []
, txsCmdsFiles = []
, txsServerArgs = []
, sutExample = Nothing
, expectedResult = Message ""
}
|
391c0ec57684f1815eee36cf63e699f7d79c68e27ffef4ffb235ee41c7a08a08 | SKS-Keyserver/sks-keyserver | request.ml | (***********************************************************************)
(* request.ml *)
(* *)
Copyright ( C ) 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 2010 ,
2011 , 2012 , 2013 and Contributors
(* *)
This file is part of SKS . SKS is free software ; you can
(* redistribute it and/or modify it under the terms of the GNU General *)
Public License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
(* *)
(* This program is distributed in the hope that it will be useful, but *)
(* WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *)
(* General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA or see < / > .
(***********************************************************************)
open StdLabels
open MoreLabels
open Printf
open Common
let amp = Str.regexp "&"
let chsplit c s =
let eqpos = String.index s c in
let first = Str.string_before s eqpos
and second = Str.string_after s (eqpos + 1) in
(first, second)
let eqsplit s = chsplit '=' s
type request_kind = VIndex | Index | Get | HGet | Stats
type request = { kind: request_kind;
search: string list;
fingerprint: bool;
hash: bool;
exact: bool;
machine_readable: bool;
clean: bool;
limit: int;
}
let default_request = { kind = Index;
search = [];
fingerprint = false;
hash = false;
exact = false;
machine_readable = false;
clean = true;
limit = (-1);
}
let comma_rxp = Str.regexp ","
let rec request_of_oplist ?(request=default_request) oplist =
match oplist with
[] -> request
| hd::tl ->
let new_request =
match hd with
| ("options",options) ->
let options = Str.split comma_rxp options in
if List.mem "mr" options
then { request with machine_readable = true }
else request
| ("op","stats") -> {request with kind = Stats };
| ("op","x-stats") -> {request with kind = Stats };
| ("op","index") -> {request with kind = Index };
| ("op","vindex") -> {request with kind = VIndex };
| ("op","get") -> {request with kind = Get};
| ("op","hget") -> {request with kind = HGet};
| ("op","x-hget") -> {request with kind = HGet};
| ("limit",c) -> {request with limit = (int_of_string c)};
| ("search",s) ->
{request with search =
List.rev (Utils.extract_words (Utils.lowercase s))
};
| ("fingerprint","on") -> {request with fingerprint = true};
| ("fingerprint","off") -> {request with fingerprint = false};
| ("hash","on") -> {request with hash = true};
| ("hash","off") -> {request with hash = false};
| ("x-hash","on") -> {request with hash = true};
| ("x-hash","off") -> {request with hash = false};
| ("exact","on") -> {request with exact = true};
| ("exact","off") -> {request with exact = false};
| ("clean","on") -> {request with clean = true;}
| ("clean","off") -> {request with clean = false;}
| ("x-clean","on") -> {request with clean = true;}
| ("x-clean","off") -> {request with clean = false;}
| _ -> request
in
request_of_oplist tl ~request:new_request
| null | https://raw.githubusercontent.com/SKS-Keyserver/sks-keyserver/a4e5267d817cddbdfee13d07a7fb38a9b94b3eee/request.ml | ocaml | *********************************************************************
request.ml
redistribute it and/or modify it under the terms of the GNU General
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
********************************************************************* | Copyright ( C ) 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 2010 ,
2011 , 2012 , 2013 and Contributors
This file is part of SKS . SKS is free software ; you can
Public License as published by the Free Software Foundation ; either
version 2 of the License , or ( at your option ) any later version .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307
USA or see < / > .
open StdLabels
open MoreLabels
open Printf
open Common
let amp = Str.regexp "&"
let chsplit c s =
let eqpos = String.index s c in
let first = Str.string_before s eqpos
and second = Str.string_after s (eqpos + 1) in
(first, second)
let eqsplit s = chsplit '=' s
type request_kind = VIndex | Index | Get | HGet | Stats
type request = { kind: request_kind;
search: string list;
fingerprint: bool;
hash: bool;
exact: bool;
machine_readable: bool;
clean: bool;
limit: int;
}
let default_request = { kind = Index;
search = [];
fingerprint = false;
hash = false;
exact = false;
machine_readable = false;
clean = true;
limit = (-1);
}
let comma_rxp = Str.regexp ","
let rec request_of_oplist ?(request=default_request) oplist =
match oplist with
[] -> request
| hd::tl ->
let new_request =
match hd with
| ("options",options) ->
let options = Str.split comma_rxp options in
if List.mem "mr" options
then { request with machine_readable = true }
else request
| ("op","stats") -> {request with kind = Stats };
| ("op","x-stats") -> {request with kind = Stats };
| ("op","index") -> {request with kind = Index };
| ("op","vindex") -> {request with kind = VIndex };
| ("op","get") -> {request with kind = Get};
| ("op","hget") -> {request with kind = HGet};
| ("op","x-hget") -> {request with kind = HGet};
| ("limit",c) -> {request with limit = (int_of_string c)};
| ("search",s) ->
{request with search =
List.rev (Utils.extract_words (Utils.lowercase s))
};
| ("fingerprint","on") -> {request with fingerprint = true};
| ("fingerprint","off") -> {request with fingerprint = false};
| ("hash","on") -> {request with hash = true};
| ("hash","off") -> {request with hash = false};
| ("x-hash","on") -> {request with hash = true};
| ("x-hash","off") -> {request with hash = false};
| ("exact","on") -> {request with exact = true};
| ("exact","off") -> {request with exact = false};
| ("clean","on") -> {request with clean = true;}
| ("clean","off") -> {request with clean = false;}
| ("x-clean","on") -> {request with clean = true;}
| ("x-clean","off") -> {request with clean = false;}
| _ -> request
in
request_of_oplist tl ~request:new_request
|
a5d762a9565705b7bb7337b616dcb65b8ab3b8f6f67385557e1535ed1776f149 | superhuman/rxxr2 | PatternParser.ml | type token =
| Regex of ((int * int) * ParsingData.regex)
| Mod of (int)
| Eos
open Parsing;;
let _ = parse_error;;
# 2 "PatternParser.mly"
© Copyright University of Birmingham , UK
open ParsingData
(* validate backreference *)
let re_evaluate_backref (i, pos) gcount =
let rec rebuild r clist npos = match clist with
[] -> r
|c :: t -> rebuild (make_r (Conc (r, make_r (Atom (Char c)) (npos, npos))) (r_spos r, npos)) t (npos + 1) in
let rec unparse j epos clist = match j with
|_ when j <= gcount -> rebuild (make_r (Backref j) (fst pos, epos)) clist (epos + 1)
|_ when j < 10 -> raise (ParsingData.InvalidBackreference (fst pos))
|_ -> unparse (j / 10) (epos - 1) ((Char.chr (48 + (j mod 10))) :: clist) in
unparse i (snd pos) [];;
assign capturing group identifiers and validate backreferences
let rec fix_captures r go gc = match (fst r) with
Zero | One | Dot | Pred _ | Atom _ -> (r, gc)
|Group (CAP _, m_on, m_off, r1) ->
let (_r1, gc2) = fix_captures r1 (go + 1) gc in
((Group (CAP (go + 1), m_on, m_off, _r1), snd r), gc2 + 1)
|Group (gkind, m_on, m_off, r1) ->
let (_r1, gc2) = fix_captures r1 go gc in
((Group (gkind, m_on, m_off, _r1), snd r), gc2)
|Backref i ->
(re_evaluate_backref (i, r_pos r) gc, gc)
|Conc (r1, r2) ->
let (_r1, gc2) = fix_captures r1 go gc in
let (_r2, gc3) = fix_captures r2 go gc2 in
((Conc (_r1, _r2), snd r), gc3)
|Alt (r1, r2) ->
let (_r1, gc2) = fix_captures r1 go gc in
let (_r2, gc3) = fix_captures r2 go gc in
((Alt (_r1, _r2), snd r), gc2 + (gc3 - gc))
|Kleene (qf, r1) ->
let (_r1, gc2) = fix_captures r1 go gc in
((Kleene (qf, _r1), snd r), gc2);;
# 48 "PatternParser.ml"
let yytransl_const = [|
Eos
0|]
let yytransl_block = [|
Regex
258 (* Mod *);
0|]
let yylhs = "\255\255\
\001\000\001\000\002\000\002\000\000\000"
let yylen = "\002\000\
\001\000\003\000\000\000\002\000\002\000"
let yydefred = "\000\000\
\000\000\000\000\000\000\001\000\005\000\000\000\000\000\004\000\
\002\000"
let yydgoto = "\002\000\
\005\000\007\000"
let yysindex = "\002\000\
\255\254\000\000\002\255\000\000\000\000\002\255\254\254\000\000\
\000\000"
let yyrindex = "\000\000\
\000\000\000\000\003\255\000\000\000\000\003\255\000\000\000\000\
\000\000"
let yygindex = "\000\000\
\000\000\255\255"
let yytablesize = 6
let yytable = "\003\000\
\009\000\004\000\001\000\006\000\008\000\003\000"
let yycheck = "\001\001\
\003\001\003\001\001\000\002\001\006\000\003\001"
let yynames_const = "\
Eos\000\
"
let yynames_block = "\
Regex\000\
Mod\000\
"
let yyact = [|
(fun _ -> failwith "parser")
; (fun __caml_parser_env ->
Obj.repr(
# 50 "PatternParser.mly"
( (make_r One (0, 0), 0) )
# 104 "PatternParser.ml"
: ParsingData.pattern))
; (fun __caml_parser_env ->
let _1 = (Parsing.peek_val __caml_parser_env 2 : (int * int) * ParsingData.regex) in
let _2 = (Parsing.peek_val __caml_parser_env 1 : 'mods) in
Obj.repr(
# 51 "PatternParser.mly"
( (fst (fix_captures (make_r (fst (snd _1)) (fst _1)) 0 0), _2) )
# 112 "PatternParser.ml"
: ParsingData.pattern))
; (fun __caml_parser_env ->
Obj.repr(
# 53 "PatternParser.mly"
( ParsingData.flg_dotall )
# 118 "PatternParser.ml"
: 'mods))
; (fun __caml_parser_env ->
let _1 = (Parsing.peek_val __caml_parser_env 1 : int) in
let _2 = (Parsing.peek_val __caml_parser_env 0 : 'mods) in
Obj.repr(
# 54 "PatternParser.mly"
( _1 lor _2 )
# 126 "PatternParser.ml"
: 'mods))
(* Entry parse *)
; (fun __caml_parser_env -> raise (Parsing.YYexit (Parsing.peek_val __caml_parser_env 0)))
|]
let yytables =
{ Parsing.actions=yyact;
Parsing.transl_const=yytransl_const;
Parsing.transl_block=yytransl_block;
Parsing.lhs=yylhs;
Parsing.len=yylen;
Parsing.defred=yydefred;
Parsing.dgoto=yydgoto;
Parsing.sindex=yysindex;
Parsing.rindex=yyrindex;
Parsing.gindex=yygindex;
Parsing.tablesize=yytablesize;
Parsing.table=yytable;
Parsing.check=yycheck;
Parsing.error_function=parse_error;
Parsing.names_const=yynames_const;
Parsing.names_block=yynames_block }
let parse (lexfun : Lexing.lexbuf -> token) (lexbuf : Lexing.lexbuf) =
(Parsing.yyparse yytables 1 lexfun lexbuf : ParsingData.pattern)
| null | https://raw.githubusercontent.com/superhuman/rxxr2/0eea5e9f0e0cde6c39e0fc12614f64edb6189cd5/code/PatternParser.ml | ocaml | validate backreference
Mod
Entry parse | type token =
| Regex of ((int * int) * ParsingData.regex)
| Mod of (int)
| Eos
open Parsing;;
let _ = parse_error;;
# 2 "PatternParser.mly"
© Copyright University of Birmingham , UK
open ParsingData
let re_evaluate_backref (i, pos) gcount =
let rec rebuild r clist npos = match clist with
[] -> r
|c :: t -> rebuild (make_r (Conc (r, make_r (Atom (Char c)) (npos, npos))) (r_spos r, npos)) t (npos + 1) in
let rec unparse j epos clist = match j with
|_ when j <= gcount -> rebuild (make_r (Backref j) (fst pos, epos)) clist (epos + 1)
|_ when j < 10 -> raise (ParsingData.InvalidBackreference (fst pos))
|_ -> unparse (j / 10) (epos - 1) ((Char.chr (48 + (j mod 10))) :: clist) in
unparse i (snd pos) [];;
assign capturing group identifiers and validate backreferences
let rec fix_captures r go gc = match (fst r) with
Zero | One | Dot | Pred _ | Atom _ -> (r, gc)
|Group (CAP _, m_on, m_off, r1) ->
let (_r1, gc2) = fix_captures r1 (go + 1) gc in
((Group (CAP (go + 1), m_on, m_off, _r1), snd r), gc2 + 1)
|Group (gkind, m_on, m_off, r1) ->
let (_r1, gc2) = fix_captures r1 go gc in
((Group (gkind, m_on, m_off, _r1), snd r), gc2)
|Backref i ->
(re_evaluate_backref (i, r_pos r) gc, gc)
|Conc (r1, r2) ->
let (_r1, gc2) = fix_captures r1 go gc in
let (_r2, gc3) = fix_captures r2 go gc2 in
((Conc (_r1, _r2), snd r), gc3)
|Alt (r1, r2) ->
let (_r1, gc2) = fix_captures r1 go gc in
let (_r2, gc3) = fix_captures r2 go gc in
((Alt (_r1, _r2), snd r), gc2 + (gc3 - gc))
|Kleene (qf, r1) ->
let (_r1, gc2) = fix_captures r1 go gc in
((Kleene (qf, _r1), snd r), gc2);;
# 48 "PatternParser.ml"
let yytransl_const = [|
Eos
0|]
let yytransl_block = [|
Regex
0|]
let yylhs = "\255\255\
\001\000\001\000\002\000\002\000\000\000"
let yylen = "\002\000\
\001\000\003\000\000\000\002\000\002\000"
let yydefred = "\000\000\
\000\000\000\000\000\000\001\000\005\000\000\000\000\000\004\000\
\002\000"
let yydgoto = "\002\000\
\005\000\007\000"
let yysindex = "\002\000\
\255\254\000\000\002\255\000\000\000\000\002\255\254\254\000\000\
\000\000"
let yyrindex = "\000\000\
\000\000\000\000\003\255\000\000\000\000\003\255\000\000\000\000\
\000\000"
let yygindex = "\000\000\
\000\000\255\255"
let yytablesize = 6
let yytable = "\003\000\
\009\000\004\000\001\000\006\000\008\000\003\000"
let yycheck = "\001\001\
\003\001\003\001\001\000\002\001\006\000\003\001"
let yynames_const = "\
Eos\000\
"
let yynames_block = "\
Regex\000\
Mod\000\
"
let yyact = [|
(fun _ -> failwith "parser")
; (fun __caml_parser_env ->
Obj.repr(
# 50 "PatternParser.mly"
( (make_r One (0, 0), 0) )
# 104 "PatternParser.ml"
: ParsingData.pattern))
; (fun __caml_parser_env ->
let _1 = (Parsing.peek_val __caml_parser_env 2 : (int * int) * ParsingData.regex) in
let _2 = (Parsing.peek_val __caml_parser_env 1 : 'mods) in
Obj.repr(
# 51 "PatternParser.mly"
( (fst (fix_captures (make_r (fst (snd _1)) (fst _1)) 0 0), _2) )
# 112 "PatternParser.ml"
: ParsingData.pattern))
; (fun __caml_parser_env ->
Obj.repr(
# 53 "PatternParser.mly"
( ParsingData.flg_dotall )
# 118 "PatternParser.ml"
: 'mods))
; (fun __caml_parser_env ->
let _1 = (Parsing.peek_val __caml_parser_env 1 : int) in
let _2 = (Parsing.peek_val __caml_parser_env 0 : 'mods) in
Obj.repr(
# 54 "PatternParser.mly"
( _1 lor _2 )
# 126 "PatternParser.ml"
: 'mods))
; (fun __caml_parser_env -> raise (Parsing.YYexit (Parsing.peek_val __caml_parser_env 0)))
|]
let yytables =
{ Parsing.actions=yyact;
Parsing.transl_const=yytransl_const;
Parsing.transl_block=yytransl_block;
Parsing.lhs=yylhs;
Parsing.len=yylen;
Parsing.defred=yydefred;
Parsing.dgoto=yydgoto;
Parsing.sindex=yysindex;
Parsing.rindex=yyrindex;
Parsing.gindex=yygindex;
Parsing.tablesize=yytablesize;
Parsing.table=yytable;
Parsing.check=yycheck;
Parsing.error_function=parse_error;
Parsing.names_const=yynames_const;
Parsing.names_block=yynames_block }
let parse (lexfun : Lexing.lexbuf -> token) (lexbuf : Lexing.lexbuf) =
(Parsing.yyparse yytables 1 lexfun lexbuf : ParsingData.pattern)
|
e728bc7d63bd76a199c60356e46997f46d11d433fc7f4ddf9e2175118a934a36 | bbss/cljsc2 | layer_selection.cljs | (ns cljsc2.cljs.ui.layer_selection
(:require [fulcro.client.dom :as dom]
[cljsc2.cljs.material_ui :refer [ui-button]]
[cljsc2.cljs.ui.fulcro :refer [input-with-label]]
[fulcro.client.primitives :as prim :refer [defsc]]
[fulcro.ui.form-state :as fs]))
(def feature-layer-minimap-paths
{:camera [:feature-layer-data :minimap-renders :camera]
:unit-type [:feature-layer-data :minimap-renders :unit-type]
:selected [:feature-layer-data :minimap-renders :selected]
:creep [:feature-layer-data :minimap-renders :creep]
:player-relative [:feature-layer-data :minimap-renders :player-relative]
:player-id [:feature-layer-data :minimap-renders :player-id]
:visibility-map [:feature-layer-data :minimap-renders :visibility-map]
:minimap [:render-data :minimap]})
(def feature-layer-render-paths
{:unit-hit-points [:feature-layer-data :renders :unit-hit-points]
:unit-energy-ratio [:feature-layer-data :renders :unit-energy-ratio]
:unit-shields-ratio [:feature-layer-data :renders :unit-shield-ratio]
:unit-density [:feature-layer-data :renders :unit-density]
:unit-energy [:feature-layer-data :renders :unit-energy]
:unit-type [:feature-layer-data :renders :unit-type]
:height-map [:feature-layer-data :renders :height-map]
:unit-shields [:feature-layer-data :renders :unit-shields]
:unit-density-aa [:feature-layer-data :renders :unit-density-aa]
:selected [:feature-layer-data :renders :selected]
:creep [:feature-layer-data :renders :creep]
:effects [:feature-layer-data :renders :effects]
:power [:feature-layer-data :renders :power]
:player-relative [:feature-layer-data :renders :player-relative]
:player-id [:feature-layer-data :renders :player-id]
:visibility-map [:feature-layer-data :renders :visibility-map]
:map [:render-data :map]})
(defn select-minimap-layer [this port x y ui-process-class]
(fn [evt]
(let [path (cljs.reader/read-string (.. evt -target -value))
state (prim/app-state (prim/get-reconciler this))]
(prim/set-state!
this
(assoc (prim/get-state this)
:selected-minimap-layer-path
path))
(prim/set-query!
this
ui-process-class
{:query (assoc-in (prim/get-query this @state)
[0 :process/runs 0 :run/observations 0 :feature-layer-data 0 :minimap-renders]
[(last path)])})
(prim/transact!
this
`[(cljsc2.cljc.mutations/send-action ~{:port port :x x :y y})]))))
(defn select-render-layer [this port x y ui-process-class]
(fn [evt]
(let [path (cljs.reader/read-string (.. evt -target -value))
state (prim/app-state (prim/get-reconciler this))]
(prim/set-state!
this
(assoc (prim/get-state this)
:selected-render-layer-path
path))
(when (not (or (= (last path) :minimap)
(= (last path) :map)))
(prim/set-query!
this
ui-process-class
{:query (assoc-in (prim/get-query this @state)
[0 :process/runs 0 :run/observations 0 :feature-layer-data 1 :renders] [(last path)])}))
(prim/transact!
this
`[(cljsc2.cljc.mutations/send-action ~{:port port :x x :y y})]))))
(defn size-in-screen [screen-dim element-dim distance-in-element]
(* (/ distance-in-element element-dim)
screen-dim))
(defn event->dom-coords
"Translate a javascript evt to a clj [x y] within the given dom element."
[evt dom-ele]
(let [cx (.-clientX evt)
cy (.-clientY evt)
BB (.getBoundingClientRect dom-ele)
x (- cx (.-left BB))
y (- cy (.-top BB))]
[x y]))
(defn minimap-mouse-up [this port element-size screen-size]
(fn [evt]
(let [action
(let [[x y] (event->dom-coords
evt
(dom/node this "process-feed-minimap"))]
#:SC2APIProtocol.sc2api$Action
{:action-render #:SC2APIProtocol.spatial$ActionSpatial
{:action #:SC2APIProtocol.spatial$ActionSpatial
{:camera-move #:SC2APIProtocol.spatial$ActionSpatialCameraMove
{:center-minimap #:SC2APIProtocol.common$PointI
{:x (size-in-screen
(:x screen-size)
(:x element-size)
x)
:y (size-in-screen
(:y screen-size)
(:y element-size)
y)}}}}})]
(prim/transact!
this
`[(cljsc2.cljc.mutations/send-action
~{:port port
:action action
})])
(prim/set-state! this (merge (prim/get-state this) {:selection nil}))
(prim/get-state this))))
(defn screen-mouse-move [this]
(fn [evt]
(let [state (prim/get-state this)
start-coords (get-in state
[:selection :start])]
(when start-coords
(prim/set-state!
this
(assoc-in state [:selection :end]
(event->dom-coords
evt
(dom/node this "process-feed"))))))))
(defn screen-mouse-up [this port element-size screen-size selected-ability]
(fn [evt]
(let [start-coords (get-in (prim/get-state this)
[:selection :start])
end-coords (event->dom-coords
evt
(dom/node this "process-feed"))
action
(let [[x y] start-coords]
(if selected-ability
#:SC2APIProtocol.sc2api$Action
{:action-render #:SC2APIProtocol.spatial$ActionSpatial
{:action #:SC2APIProtocol.spatial$ActionSpatial
{:unit-command #:SC2APIProtocol.spatial$ActionSpatialUnitCommand
{:target #:SC2APIProtocol.spatial$ActionSpatialUnitCommand
{:target-screen-coord #:SC2APIProtocol.common$PointI
{:x (size-in-screen
(:x screen-size)
(:x element-size)
x)
:y (size-in-screen
(:y screen-size)
(:y element-size)
y)}}
:ability-id (:ability-id selected-ability)}}}}
(if (= start-coords end-coords)
#:SC2APIProtocol.sc2api$Action
{:action-render #:SC2APIProtocol.spatial$ActionSpatial
{:action #:SC2APIProtocol.spatial$ActionSpatial
{:unit-selection-point #:SC2APIProtocol.spatial$ActionSpatialUnitSelectionPoint
{:selection-screen-coord #:SC2APIProtocol.common$PointI
{:x (size-in-screen
(:x screen-size)
(:x element-size)
x)
:y (size-in-screen
(:y screen-size)
(:y element-size)
y)}}}}}
#:SC2APIProtocol.sc2api$Action
{:action-render #:SC2APIProtocol.spatial$ActionSpatial
{:action #:SC2APIProtocol.spatial$ActionSpatial
{:unit-selection-rect #:SC2APIProtocol.spatial$ActionSpatialUnitSelectionRect
{:selection-screen-coord
[#:SC2APIProtocol.common$RectangleI
{:p0 #:SC2APIProtocol.common$PointI
{:x (size-in-screen
(:x screen-size)
(:x element-size)
x)
:y (size-in-screen
(:y screen-size)
(:y element-size)
y)}
:p1 #:SC2APIProtocol.common$PointI
{:x (size-in-screen
(:x screen-size)
(:x element-size)
(first end-coords))
:y (size-in-screen
(:y screen-size)
(:y element-size)
(second end-coords))}}]}}}})))]
(prim/transact!
this
`[(cljsc2.cljc.mutations/send-action
~{:port port
:action action
})])
(prim/set-state! this
(merge (prim/get-state this)
{:selection nil
:selected-ability nil}))
(prim/get-state this))))
(defn ui-draw-sizes [this local-state render-size minimap-size]
(dom/div
"Drawing size: "
(ui-button #js {:onClick #(prim/set-state!
this
(merge local-state
{:draw-size render-size
:draw-size-minimap minimap-size}))}
"Rendered resolution")
(ui-button #js {:onClick #(prim/set-state!
this
(merge local-state
{:draw-size {:x (* 2 (:x render-size))
:y (* 2 (:y render-size))}
:draw-size-minimap {:x (* 2 (:x minimap-size))
:y (* 2 (:y minimap-size))}}))}
"Enlarged (2x)")
(ui-button #js {:onClick #(prim/set-state!
this
(merge local-state
{:draw-size {:x (* 4 (:x render-size))
:y (* 4 (:y render-size))}
:draw-size-minimap {:x (* 4 (:x minimap-size))
:y (* 4 (:y minimap-size))}}))}
"Enlarged (4x)")))
(defn send-camera-action [this port x y]
(fn [_]
(prim/transact!
this
`[(cljsc2.cljc.mutations/send-action
~{:port port
:action
#:SC2APIProtocol.sc2api$Action
{:action-raw #:SC2APIProtocol.raw$ActionRaw
{:action #:SC2APIProtocol.raw$ActionRaw
{:camera-move #:SC2APIProtocol.raw$ActionRawCameraMove
{:center-world-space #:SC2APIProtocol.common$Point{:x x :y y}}}}}})])))
(defn ui-camera-move-arrows [this port x y]
(dom/div
(ui-button #js {:onClick (send-camera-action this port (- x 3) y)}
"left")
(ui-button #js {:onClick (send-camera-action this port x (- y 3))}
"down")
(ui-button #js {:onClick (send-camera-action this port x (+ y 3))}
"up")
(ui-button #js {:onClick (send-camera-action this port (+ x 3) y)}
"right")))
| null | https://raw.githubusercontent.com/bbss/cljsc2/70e720f5bae9b58248df86f3f50d855878ae4f49/src/cljsc2/cljs/ui/layer_selection.cljs | clojure | (ns cljsc2.cljs.ui.layer_selection
(:require [fulcro.client.dom :as dom]
[cljsc2.cljs.material_ui :refer [ui-button]]
[cljsc2.cljs.ui.fulcro :refer [input-with-label]]
[fulcro.client.primitives :as prim :refer [defsc]]
[fulcro.ui.form-state :as fs]))
(def feature-layer-minimap-paths
{:camera [:feature-layer-data :minimap-renders :camera]
:unit-type [:feature-layer-data :minimap-renders :unit-type]
:selected [:feature-layer-data :minimap-renders :selected]
:creep [:feature-layer-data :minimap-renders :creep]
:player-relative [:feature-layer-data :minimap-renders :player-relative]
:player-id [:feature-layer-data :minimap-renders :player-id]
:visibility-map [:feature-layer-data :minimap-renders :visibility-map]
:minimap [:render-data :minimap]})
(def feature-layer-render-paths
{:unit-hit-points [:feature-layer-data :renders :unit-hit-points]
:unit-energy-ratio [:feature-layer-data :renders :unit-energy-ratio]
:unit-shields-ratio [:feature-layer-data :renders :unit-shield-ratio]
:unit-density [:feature-layer-data :renders :unit-density]
:unit-energy [:feature-layer-data :renders :unit-energy]
:unit-type [:feature-layer-data :renders :unit-type]
:height-map [:feature-layer-data :renders :height-map]
:unit-shields [:feature-layer-data :renders :unit-shields]
:unit-density-aa [:feature-layer-data :renders :unit-density-aa]
:selected [:feature-layer-data :renders :selected]
:creep [:feature-layer-data :renders :creep]
:effects [:feature-layer-data :renders :effects]
:power [:feature-layer-data :renders :power]
:player-relative [:feature-layer-data :renders :player-relative]
:player-id [:feature-layer-data :renders :player-id]
:visibility-map [:feature-layer-data :renders :visibility-map]
:map [:render-data :map]})
(defn select-minimap-layer [this port x y ui-process-class]
(fn [evt]
(let [path (cljs.reader/read-string (.. evt -target -value))
state (prim/app-state (prim/get-reconciler this))]
(prim/set-state!
this
(assoc (prim/get-state this)
:selected-minimap-layer-path
path))
(prim/set-query!
this
ui-process-class
{:query (assoc-in (prim/get-query this @state)
[0 :process/runs 0 :run/observations 0 :feature-layer-data 0 :minimap-renders]
[(last path)])})
(prim/transact!
this
`[(cljsc2.cljc.mutations/send-action ~{:port port :x x :y y})]))))
(defn select-render-layer [this port x y ui-process-class]
(fn [evt]
(let [path (cljs.reader/read-string (.. evt -target -value))
state (prim/app-state (prim/get-reconciler this))]
(prim/set-state!
this
(assoc (prim/get-state this)
:selected-render-layer-path
path))
(when (not (or (= (last path) :minimap)
(= (last path) :map)))
(prim/set-query!
this
ui-process-class
{:query (assoc-in (prim/get-query this @state)
[0 :process/runs 0 :run/observations 0 :feature-layer-data 1 :renders] [(last path)])}))
(prim/transact!
this
`[(cljsc2.cljc.mutations/send-action ~{:port port :x x :y y})]))))
(defn size-in-screen [screen-dim element-dim distance-in-element]
(* (/ distance-in-element element-dim)
screen-dim))
(defn event->dom-coords
"Translate a javascript evt to a clj [x y] within the given dom element."
[evt dom-ele]
(let [cx (.-clientX evt)
cy (.-clientY evt)
BB (.getBoundingClientRect dom-ele)
x (- cx (.-left BB))
y (- cy (.-top BB))]
[x y]))
(defn minimap-mouse-up [this port element-size screen-size]
(fn [evt]
(let [action
(let [[x y] (event->dom-coords
evt
(dom/node this "process-feed-minimap"))]
#:SC2APIProtocol.sc2api$Action
{:action-render #:SC2APIProtocol.spatial$ActionSpatial
{:action #:SC2APIProtocol.spatial$ActionSpatial
{:camera-move #:SC2APIProtocol.spatial$ActionSpatialCameraMove
{:center-minimap #:SC2APIProtocol.common$PointI
{:x (size-in-screen
(:x screen-size)
(:x element-size)
x)
:y (size-in-screen
(:y screen-size)
(:y element-size)
y)}}}}})]
(prim/transact!
this
`[(cljsc2.cljc.mutations/send-action
~{:port port
:action action
})])
(prim/set-state! this (merge (prim/get-state this) {:selection nil}))
(prim/get-state this))))
(defn screen-mouse-move [this]
(fn [evt]
(let [state (prim/get-state this)
start-coords (get-in state
[:selection :start])]
(when start-coords
(prim/set-state!
this
(assoc-in state [:selection :end]
(event->dom-coords
evt
(dom/node this "process-feed"))))))))
(defn screen-mouse-up [this port element-size screen-size selected-ability]
(fn [evt]
(let [start-coords (get-in (prim/get-state this)
[:selection :start])
end-coords (event->dom-coords
evt
(dom/node this "process-feed"))
action
(let [[x y] start-coords]
(if selected-ability
#:SC2APIProtocol.sc2api$Action
{:action-render #:SC2APIProtocol.spatial$ActionSpatial
{:action #:SC2APIProtocol.spatial$ActionSpatial
{:unit-command #:SC2APIProtocol.spatial$ActionSpatialUnitCommand
{:target #:SC2APIProtocol.spatial$ActionSpatialUnitCommand
{:target-screen-coord #:SC2APIProtocol.common$PointI
{:x (size-in-screen
(:x screen-size)
(:x element-size)
x)
:y (size-in-screen
(:y screen-size)
(:y element-size)
y)}}
:ability-id (:ability-id selected-ability)}}}}
(if (= start-coords end-coords)
#:SC2APIProtocol.sc2api$Action
{:action-render #:SC2APIProtocol.spatial$ActionSpatial
{:action #:SC2APIProtocol.spatial$ActionSpatial
{:unit-selection-point #:SC2APIProtocol.spatial$ActionSpatialUnitSelectionPoint
{:selection-screen-coord #:SC2APIProtocol.common$PointI
{:x (size-in-screen
(:x screen-size)
(:x element-size)
x)
:y (size-in-screen
(:y screen-size)
(:y element-size)
y)}}}}}
#:SC2APIProtocol.sc2api$Action
{:action-render #:SC2APIProtocol.spatial$ActionSpatial
{:action #:SC2APIProtocol.spatial$ActionSpatial
{:unit-selection-rect #:SC2APIProtocol.spatial$ActionSpatialUnitSelectionRect
{:selection-screen-coord
[#:SC2APIProtocol.common$RectangleI
{:p0 #:SC2APIProtocol.common$PointI
{:x (size-in-screen
(:x screen-size)
(:x element-size)
x)
:y (size-in-screen
(:y screen-size)
(:y element-size)
y)}
:p1 #:SC2APIProtocol.common$PointI
{:x (size-in-screen
(:x screen-size)
(:x element-size)
(first end-coords))
:y (size-in-screen
(:y screen-size)
(:y element-size)
(second end-coords))}}]}}}})))]
(prim/transact!
this
`[(cljsc2.cljc.mutations/send-action
~{:port port
:action action
})])
(prim/set-state! this
(merge (prim/get-state this)
{:selection nil
:selected-ability nil}))
(prim/get-state this))))
(defn ui-draw-sizes [this local-state render-size minimap-size]
(dom/div
"Drawing size: "
(ui-button #js {:onClick #(prim/set-state!
this
(merge local-state
{:draw-size render-size
:draw-size-minimap minimap-size}))}
"Rendered resolution")
(ui-button #js {:onClick #(prim/set-state!
this
(merge local-state
{:draw-size {:x (* 2 (:x render-size))
:y (* 2 (:y render-size))}
:draw-size-minimap {:x (* 2 (:x minimap-size))
:y (* 2 (:y minimap-size))}}))}
"Enlarged (2x)")
(ui-button #js {:onClick #(prim/set-state!
this
(merge local-state
{:draw-size {:x (* 4 (:x render-size))
:y (* 4 (:y render-size))}
:draw-size-minimap {:x (* 4 (:x minimap-size))
:y (* 4 (:y minimap-size))}}))}
"Enlarged (4x)")))
(defn send-camera-action [this port x y]
(fn [_]
(prim/transact!
this
`[(cljsc2.cljc.mutations/send-action
~{:port port
:action
#:SC2APIProtocol.sc2api$Action
{:action-raw #:SC2APIProtocol.raw$ActionRaw
{:action #:SC2APIProtocol.raw$ActionRaw
{:camera-move #:SC2APIProtocol.raw$ActionRawCameraMove
{:center-world-space #:SC2APIProtocol.common$Point{:x x :y y}}}}}})])))
(defn ui-camera-move-arrows [this port x y]
(dom/div
(ui-button #js {:onClick (send-camera-action this port (- x 3) y)}
"left")
(ui-button #js {:onClick (send-camera-action this port x (- y 3))}
"down")
(ui-button #js {:onClick (send-camera-action this port x (+ y 3))}
"up")
(ui-button #js {:onClick (send-camera-action this port (+ x 3) y)}
"right")))
|
|
f4c11cb84ad9653f7f943033ad8766e6355f24b0fc85a4bfd510d50709e022d9 | ghadishayban/pex | pex_test.clj | (ns com.champbacon.pex-test
(:require [clojure.test :refer :all]
[com.champbacon.pex :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/ghadishayban/pex/aa3255f6aa9086ca867d0ff401b8bbb2a306d86c/test/com/champbacon/pex_test.clj | clojure | (ns com.champbacon.pex-test
(:require [clojure.test :refer :all]
[com.champbacon.pex :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
|
|
668fd3de9b01a2c19fdeda7d1c035c2472e347f518996db477e5d2ae35ec8d4b | OCamlPro/liquidity | liquidMichelineTypes.ml | (****************************************************************************)
(* Liquidity *)
(* *)
Copyright ( C ) 2017 - 2020 OCamlPro SAS
(* *)
(* Authors: Fabrice Le Fessant *)
(* *)
(* This program is free software: you can redistribute it and/or modify *)
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
(* (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License
(* along with this program. If not, see </>. *)
(****************************************************************************)
type env = unit
type expr = LiquidTypes.michelson_exp LiquidTypes.const
type contract = LiquidTypes.michelson_contract
type json
let empty_env _ = ()
let set_generalize_types _ _ = ()
| null | https://raw.githubusercontent.com/OCamlPro/liquidity/3578de34cf751f54b9e4c001a95625d2041b2962/tools/liquidity/without-dune-network/liquidMichelineTypes.ml | ocaml | **************************************************************************
Liquidity
Authors: Fabrice Le Fessant
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>.
************************************************************************** | Copyright ( C ) 2017 - 2020 OCamlPro SAS
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
type env = unit
type expr = LiquidTypes.michelson_exp LiquidTypes.const
type contract = LiquidTypes.michelson_contract
type json
let empty_env _ = ()
let set_generalize_types _ _ = ()
|
d037ca75237226bbdb306e52127494a2a2399d2edfcca3b4bed9efeea48dd079 | uwplse/synapse | search.rkt | #lang racket
(require "search-worker.rkt" "../engine/metasketch.rkt" "solver+.rkt" "verifier.rkt" "util.rkt"
"../bv/lang.rkt"
"../../benchmarks/all.rkt" "../metasketches/imetasketch.rkt"
"log.rkt"
(only-in rosette/solver/solution model)
rosette/solver/kodkod/kodkod (rename-in rosette/config/log [log-info log-info-r])
syntax/modresolve racket/runtime-path racket/serialize)
(provide search)
; This procedure implements the top-level search over a metasketch.
;
; * metasketch : constant? is the metasketch over which to search.
;
; * threads : natural/c is the number of threads to run in parallel.
;
; * timeout : natural/c is the timeout for individual sketches in the
metasketch , in seconds .
;
* : natural / c is the bit - width to finitize to .
;
* bit - widening : ( or / c # f ( listof natural / c -1 ) ) is a list of intermediate
to attempt first , or # f if bit widening should not occur .
; The list must be sorted and increasing, and should not include the final
; full bitwidth.
;
; * exchange-samples : boolean? decides whether to share CEXs between solvers
;
; * use-structure : boolean? decides whether to add structure constraints
(define (search
#:metasketch ms-spec
#:threads [threads 1]
#:timeout [timeout 10]
#:bitwidth [bw 32]
#:widening [bit-widening #f]
#:exchange-samples [exchange-samples #t]
#:exchange-costs [exchange-costs #t]
#:use-structure [use-structure #t]
#:incremental [incremental #t]
#:synthesizer [synthesizer% 'kodkod-incremental%]
#:verifier [verifier% 'kodkod%]
#:verbose [verbosity #f])
; record start time and set up logging
(log-start-time (current-inexact-milliseconds))
(logging? verbosity)
; create our local copy of the metasketch
(define ms (eval-metasketch ms-spec))
(unless (imeta? ms)
(raise-arguments-error 'search "need an indexed metasketch" "ms" ms))
; check arguments
(unless (>= threads 1)
(raise-arguments-error 'search "threads must be positive" "threads" threads))
;; results -------------------------------------------------------------------
; results : sketch? ↦ (or/c program? boolean?)
results[S ] is a program ? if S is SAT , # t if S was proved UNSAT , or # f if S timed out
(define results (make-hash))
; best solution and cost found so far
(define best-program #f)
(define best-cost +inf.0)
samples : ( hash / c integer ? ( listof ( listof number ? ) ) )
samples[bw ] is a list of samples collected at a given .
; each sample is a list of length (length (inputs ms)), which can be inflated
; to a solution? by calling inflate-sample
(define samples (make-hash))
(define (count-samples) (for/sum ([v (hash-values samples)]) (length v)))
;; search state --------------------------------------------------------------
workers : ( vectorof place - channel ? )
; the worker places
(define workers (make-vector threads #f))
worker->sketch : ( vectorof sketch ? )
; tracks which sketch each worker is currently running
(define worker->sketch (make-vector threads #f))
; sketch->worker : (hash/c sketch? exact-nonnegative-integer?)
tracks which worker each running sketch is on ( inverse of worker->sketch )
(define sketch->worker (make-hash))
; the stream of sketches remaining to try
(define sketch-set (sketches ms best-cost))
(define sketch-stream (set->stream sketch-set))
;; helper methods ------------------------------------------------------------
; launch a sketch on a specified worker
(define (launch-sketch sketch worker-id)
(unless (false? (vector-ref worker->sketch worker-id))
(raise-arguments-error 'launch-sketch "attempt to launch sketch on occupied worker"))
(define idx (isketch-index sketch))
(define pch (vector-ref workers worker-id))
(log-search "starting sketch ~a on worker ~a [~a remaining; ~a complete; ~a samples]"
sketch worker-id (sketches-remaining) (hash-count results) (count-samples))
(place-channel-put pch `(sketch ,idx ,best-cost ,samples))
(vector-set! worker->sketch worker-id sketch)
(hash-set! sketch->worker sketch worker-id))
find the first available worker
(define (next-available-worker)
(let loop ([idx 0])
(cond [(false? (vector-ref worker->sketch idx)) idx]
[(= idx (sub1 threads)) (error "no available workers")]
[else (loop (add1 idx))])))
; launch the next sketch on an available worker, if there are sketches remaining
(define (launch-next-sketch)
(let loop ()
(unless (stream-empty? sketch-stream)
(define sketch (stream-first sketch-stream))
(set! sketch-stream (stream-rest sketch-stream))
(if (or (hash-has-key? results sketch) (hash-has-key? sketch->worker sketch))
(loop)
(launch-sketch sketch (next-available-worker))))))
; announce that a sketch is satisfiable with a given program as solution
(define (sketch-sat sketch prog cost)
(hash-set! results sketch prog)
(when (< cost best-cost)
(new-best-cost cost prog)))
; announce that a sketch is unsatisfiable
(define (sketch-unsat sketch)
(define worker-id (hash-ref sketch->worker sketch))
(stop-working worker-id)
(unless (hash-has-key? results sketch)
(hash-set! results sketch #t))
(launch-next-sketch))
; announce that a sketch timed out
(define (sketch-timeout sketch)
(define worker-id (hash-ref sketch->worker sketch))
(stop-working worker-id)
(unless (hash-has-key? results sketch)
(hash-set! results sketch #f))
(launch-next-sketch))
; announce a new cost constraint to all running workers, and stop working on
; sketches for which the new cost constraint is trivially unsat
(define (new-best-cost c prog)
(set! best-cost c)
(set! best-program prog)
(set! sketch-set (sketches ms best-cost))
(set! sketch-stream (set->stream sketch-set))
(log-search "new best cost ~a; ~a sketches remaining" best-cost (sketches-remaining))
(for ([worker-id threads][pch workers][sketch worker->sketch]
#:unless (false? sketch))
(cond [(set-member? sketch-set sketch)
(cond [exchange-costs
(place-channel-put pch `(cost ,best-cost))]
[else ; if not exchanging costs, need to restart sketch
(stop-working worker-id)
(launch-sketch sketch worker-id)])]
[else
(unless (hash-has-key? results sketch)
(hash-set! results sketch #t))
(log-search "killing ~a because it's no longer in the set" sketch)
(stop-working worker-id)
(launch-next-sketch)])))
; announce a new set of samples to all running threads
(define (new-samples bw samps)
(when exchange-samples
(hash-set! samples bw
(remove-duplicates (append samps (hash-ref samples bw '()))))
(for ([pch workers][sketch worker->sketch]
#:unless (false? sketch))
(place-channel-put pch `(samples ,samples)))))
; tell a worker to stop doing work, and free it up for reuse
(define (stop-working worker-id)
(define sketch (vector-ref worker->sketch worker-id))
(define pch (vector-ref workers worker-id))
(place-channel-put pch `(kill))
(hash-remove! sketch->worker sketch)
(vector-set! worker->sketch worker-id #f))
; count sketches remaining to run
(define (sketches-remaining)
(define already-run (for/sum ([S (hash-keys results)]) (if (set-member? sketch-set S) 1 0)))
(- (set-count sketch-set) already-run))
;; search body ---------------------------------------------------------------
(log-search "START: sketches to try: ~a" (sketches-remaining))
; initialize the workers
(for ([worker-id threads])
(define pch (place channel (search-worker channel)))
(place-channel-put pch `(config ,worker-id ,(log-start-time) ,timeout ,verbosity
,bw ,bit-widening
,exchange-samples ,exchange-costs ,use-structure ,incremental
,synthesizer% ,verifier%))
(place-channel-put pch `(metasketch ,ms-spec))
(vector-set! workers worker-id pch))
; send sketches to each worker
(for ([worker-id threads])
(launch-next-sketch))
; wait for a place to send us a message
(let loop ()
(match (apply sync
(for/list ([pch workers][worker-id threads])
(wrap-evt pch (λ (res) (cons worker-id res)))))
[(cons worker-id result)
(define sketch (vector-ref worker->sketch worker-id))
(define idx (second result)) ; all messages are '(TYPE idx ...)
; make sure we're still running the same sketch (otherwise msg is redundant)
(when (and (not (false? sketch)) (equal? idx (isketch-index sketch)))
(match result
[(list 'sat idx c prog-ser bw samps)
(define prog (deserialize prog-ser))
(log-search "SAT ~a with cost ~a: ~v" sketch c prog)
(new-samples bw samps)
(sketch-sat sketch prog c)]
[(list 'unsat idx bw samps)
(log-search "UNSAT ~a" sketch)
(new-samples bw samps)
(sketch-unsat sketch)]
[(list 'timeout idx)
(log-search "TIMEOUT ~a" sketch)
(sketch-unsat sketch)]))])
(when (for/or ([sketch worker->sketch]) sketch)
(loop)))
(log-search "END: ~a completed; ~a remaining" (hash-count results) (sketches-remaining))
(for ([pch workers])
(place-kill pch)
(place-wait pch))
best-program
)
| null | https://raw.githubusercontent.com/uwplse/synapse/10f605f8f1fff6dade90607f516550b961a10169/opsyn/engine/search.rkt | racket | This procedure implements the top-level search over a metasketch.
* metasketch : constant? is the metasketch over which to search.
* threads : natural/c is the number of threads to run in parallel.
* timeout : natural/c is the timeout for individual sketches in the
The list must be sorted and increasing, and should not include the final
full bitwidth.
* exchange-samples : boolean? decides whether to share CEXs between solvers
* use-structure : boolean? decides whether to add structure constraints
record start time and set up logging
create our local copy of the metasketch
check arguments
results -------------------------------------------------------------------
results : sketch? ↦ (or/c program? boolean?)
best solution and cost found so far
each sample is a list of length (length (inputs ms)), which can be inflated
to a solution? by calling inflate-sample
search state --------------------------------------------------------------
the worker places
tracks which sketch each worker is currently running
sketch->worker : (hash/c sketch? exact-nonnegative-integer?)
the stream of sketches remaining to try
helper methods ------------------------------------------------------------
launch a sketch on a specified worker
launch the next sketch on an available worker, if there are sketches remaining
announce that a sketch is satisfiable with a given program as solution
announce that a sketch is unsatisfiable
announce that a sketch timed out
announce a new cost constraint to all running workers, and stop working on
sketches for which the new cost constraint is trivially unsat
if not exchanging costs, need to restart sketch
announce a new set of samples to all running threads
tell a worker to stop doing work, and free it up for reuse
count sketches remaining to run
search body ---------------------------------------------------------------
initialize the workers
send sketches to each worker
wait for a place to send us a message
all messages are '(TYPE idx ...)
make sure we're still running the same sketch (otherwise msg is redundant) | #lang racket
(require "search-worker.rkt" "../engine/metasketch.rkt" "solver+.rkt" "verifier.rkt" "util.rkt"
"../bv/lang.rkt"
"../../benchmarks/all.rkt" "../metasketches/imetasketch.rkt"
"log.rkt"
(only-in rosette/solver/solution model)
rosette/solver/kodkod/kodkod (rename-in rosette/config/log [log-info log-info-r])
syntax/modresolve racket/runtime-path racket/serialize)
(provide search)
metasketch , in seconds .
* : natural / c is the bit - width to finitize to .
* bit - widening : ( or / c # f ( listof natural / c -1 ) ) is a list of intermediate
to attempt first , or # f if bit widening should not occur .
(define (search
#:metasketch ms-spec
#:threads [threads 1]
#:timeout [timeout 10]
#:bitwidth [bw 32]
#:widening [bit-widening #f]
#:exchange-samples [exchange-samples #t]
#:exchange-costs [exchange-costs #t]
#:use-structure [use-structure #t]
#:incremental [incremental #t]
#:synthesizer [synthesizer% 'kodkod-incremental%]
#:verifier [verifier% 'kodkod%]
#:verbose [verbosity #f])
(log-start-time (current-inexact-milliseconds))
(logging? verbosity)
(define ms (eval-metasketch ms-spec))
(unless (imeta? ms)
(raise-arguments-error 'search "need an indexed metasketch" "ms" ms))
(unless (>= threads 1)
(raise-arguments-error 'search "threads must be positive" "threads" threads))
results[S ] is a program ? if S is SAT , # t if S was proved UNSAT , or # f if S timed out
(define results (make-hash))
(define best-program #f)
(define best-cost +inf.0)
samples : ( hash / c integer ? ( listof ( listof number ? ) ) )
samples[bw ] is a list of samples collected at a given .
(define samples (make-hash))
(define (count-samples) (for/sum ([v (hash-values samples)]) (length v)))
workers : ( vectorof place - channel ? )
(define workers (make-vector threads #f))
worker->sketch : ( vectorof sketch ? )
(define worker->sketch (make-vector threads #f))
tracks which worker each running sketch is on ( inverse of worker->sketch )
(define sketch->worker (make-hash))
(define sketch-set (sketches ms best-cost))
(define sketch-stream (set->stream sketch-set))
(define (launch-sketch sketch worker-id)
(unless (false? (vector-ref worker->sketch worker-id))
(raise-arguments-error 'launch-sketch "attempt to launch sketch on occupied worker"))
(define idx (isketch-index sketch))
(define pch (vector-ref workers worker-id))
(log-search "starting sketch ~a on worker ~a [~a remaining; ~a complete; ~a samples]"
sketch worker-id (sketches-remaining) (hash-count results) (count-samples))
(place-channel-put pch `(sketch ,idx ,best-cost ,samples))
(vector-set! worker->sketch worker-id sketch)
(hash-set! sketch->worker sketch worker-id))
find the first available worker
(define (next-available-worker)
(let loop ([idx 0])
(cond [(false? (vector-ref worker->sketch idx)) idx]
[(= idx (sub1 threads)) (error "no available workers")]
[else (loop (add1 idx))])))
(define (launch-next-sketch)
(let loop ()
(unless (stream-empty? sketch-stream)
(define sketch (stream-first sketch-stream))
(set! sketch-stream (stream-rest sketch-stream))
(if (or (hash-has-key? results sketch) (hash-has-key? sketch->worker sketch))
(loop)
(launch-sketch sketch (next-available-worker))))))
(define (sketch-sat sketch prog cost)
(hash-set! results sketch prog)
(when (< cost best-cost)
(new-best-cost cost prog)))
(define (sketch-unsat sketch)
(define worker-id (hash-ref sketch->worker sketch))
(stop-working worker-id)
(unless (hash-has-key? results sketch)
(hash-set! results sketch #t))
(launch-next-sketch))
(define (sketch-timeout sketch)
(define worker-id (hash-ref sketch->worker sketch))
(stop-working worker-id)
(unless (hash-has-key? results sketch)
(hash-set! results sketch #f))
(launch-next-sketch))
(define (new-best-cost c prog)
(set! best-cost c)
(set! best-program prog)
(set! sketch-set (sketches ms best-cost))
(set! sketch-stream (set->stream sketch-set))
(log-search "new best cost ~a; ~a sketches remaining" best-cost (sketches-remaining))
(for ([worker-id threads][pch workers][sketch worker->sketch]
#:unless (false? sketch))
(cond [(set-member? sketch-set sketch)
(cond [exchange-costs
(place-channel-put pch `(cost ,best-cost))]
(stop-working worker-id)
(launch-sketch sketch worker-id)])]
[else
(unless (hash-has-key? results sketch)
(hash-set! results sketch #t))
(log-search "killing ~a because it's no longer in the set" sketch)
(stop-working worker-id)
(launch-next-sketch)])))
(define (new-samples bw samps)
(when exchange-samples
(hash-set! samples bw
(remove-duplicates (append samps (hash-ref samples bw '()))))
(for ([pch workers][sketch worker->sketch]
#:unless (false? sketch))
(place-channel-put pch `(samples ,samples)))))
(define (stop-working worker-id)
(define sketch (vector-ref worker->sketch worker-id))
(define pch (vector-ref workers worker-id))
(place-channel-put pch `(kill))
(hash-remove! sketch->worker sketch)
(vector-set! worker->sketch worker-id #f))
(define (sketches-remaining)
(define already-run (for/sum ([S (hash-keys results)]) (if (set-member? sketch-set S) 1 0)))
(- (set-count sketch-set) already-run))
(log-search "START: sketches to try: ~a" (sketches-remaining))
(for ([worker-id threads])
(define pch (place channel (search-worker channel)))
(place-channel-put pch `(config ,worker-id ,(log-start-time) ,timeout ,verbosity
,bw ,bit-widening
,exchange-samples ,exchange-costs ,use-structure ,incremental
,synthesizer% ,verifier%))
(place-channel-put pch `(metasketch ,ms-spec))
(vector-set! workers worker-id pch))
(for ([worker-id threads])
(launch-next-sketch))
(let loop ()
(match (apply sync
(for/list ([pch workers][worker-id threads])
(wrap-evt pch (λ (res) (cons worker-id res)))))
[(cons worker-id result)
(define sketch (vector-ref worker->sketch worker-id))
(when (and (not (false? sketch)) (equal? idx (isketch-index sketch)))
(match result
[(list 'sat idx c prog-ser bw samps)
(define prog (deserialize prog-ser))
(log-search "SAT ~a with cost ~a: ~v" sketch c prog)
(new-samples bw samps)
(sketch-sat sketch prog c)]
[(list 'unsat idx bw samps)
(log-search "UNSAT ~a" sketch)
(new-samples bw samps)
(sketch-unsat sketch)]
[(list 'timeout idx)
(log-search "TIMEOUT ~a" sketch)
(sketch-unsat sketch)]))])
(when (for/or ([sketch worker->sketch]) sketch)
(loop)))
(log-search "END: ~a completed; ~a remaining" (hash-count results) (sketches-remaining))
(for ([pch workers])
(place-kill pch)
(place-wait pch))
best-program
)
|
3e392a28f0ff5b3e9d9d68f40cdd1d5d00b7082d50cfd67f7c1734b2de780177 | clojurewerkz/statistiker | kmeans_test.clj | (ns clojurewerkz.statistiker.clustering.kmeans-test
(:require [clojure.test :refer :all]
[clojurewerkz.statistiker.clustering.kmeans :refer :all]))
(deftest cluster-test
(let [c (cluster [(with-meta [1 1 1] {:a 1}) [2 2 2] [3 3 3]
[50 50 50] [51 51 51] [53 53 53]]
2
100)
c (sort-by #(get-in % [:center 0]) c)]
(is (= 1.0 (-> c first :points ffirst)))
(is (= {:a 1} (-> c first :points first meta)))
(is (= 50.0 (-> c second :points ffirst)))))
(defn find-cluster
[clusters item-pred]
(->> clusters
(filter (fn [points] (some item-pred points)))
first
set))
(deftest cluster-by-test
(let [c (cluster-by [{:a 1 :b 1 :c 1}
{:a 2 :b 2 :c 2}
{:a 3 :b 3 :c 3}
{:a 50 :b 50 :c 50}
{:a 51 :b 51 :c 51}
{:a 53 :b 53 :c 53}
{:a 54 :b 54 :c 54}]
[:a :b :c]
2
100)
clusters (mapv second (vec (group-by :cluster-id c)))]
(let [cluster-with-1 (find-cluster clusters #(= 1 (:a %)))]
(= 3 (count cluster-with-1))
(is (some #(= 2 (:a %)) cluster-with-1))
(is (some #(= 3 (:a %)) cluster-with-1)))
(let [cluster-with-50 (find-cluster clusters #(= 50 (:a %)))]
(= 4 (count cluster-with-50))
(is (some #(= 51 (:a %)) cluster-with-50))
(is (some #(= 53 (:a %)) cluster-with-50))
(is (some #(= 54 (:a %)) cluster-with-50)))))
| null | https://raw.githubusercontent.com/clojurewerkz/statistiker/f056f68c975cf3d6e0f1c8212aef9114d4eb657c/test/clj/clojurewerkz/statistiker/clustering/kmeans_test.clj | clojure | (ns clojurewerkz.statistiker.clustering.kmeans-test
(:require [clojure.test :refer :all]
[clojurewerkz.statistiker.clustering.kmeans :refer :all]))
(deftest cluster-test
(let [c (cluster [(with-meta [1 1 1] {:a 1}) [2 2 2] [3 3 3]
[50 50 50] [51 51 51] [53 53 53]]
2
100)
c (sort-by #(get-in % [:center 0]) c)]
(is (= 1.0 (-> c first :points ffirst)))
(is (= {:a 1} (-> c first :points first meta)))
(is (= 50.0 (-> c second :points ffirst)))))
(defn find-cluster
[clusters item-pred]
(->> clusters
(filter (fn [points] (some item-pred points)))
first
set))
(deftest cluster-by-test
(let [c (cluster-by [{:a 1 :b 1 :c 1}
{:a 2 :b 2 :c 2}
{:a 3 :b 3 :c 3}
{:a 50 :b 50 :c 50}
{:a 51 :b 51 :c 51}
{:a 53 :b 53 :c 53}
{:a 54 :b 54 :c 54}]
[:a :b :c]
2
100)
clusters (mapv second (vec (group-by :cluster-id c)))]
(let [cluster-with-1 (find-cluster clusters #(= 1 (:a %)))]
(= 3 (count cluster-with-1))
(is (some #(= 2 (:a %)) cluster-with-1))
(is (some #(= 3 (:a %)) cluster-with-1)))
(let [cluster-with-50 (find-cluster clusters #(= 50 (:a %)))]
(= 4 (count cluster-with-50))
(is (some #(= 51 (:a %)) cluster-with-50))
(is (some #(= 53 (:a %)) cluster-with-50))
(is (some #(= 54 (:a %)) cluster-with-50)))))
|
|
98624abd9cc5dfed3493175ffd0c1981dad62824a87d70880621e161dcce8d82 | aristidb/aws | DeleteAccessKey.hs | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
module Aws.Iam.Commands.DeleteAccessKey
( DeleteAccessKey(..)
, DeleteAccessKeyResponse(..)
) where
import Aws.Core
import Aws.Iam.Core
import Aws.Iam.Internal
import Control.Applicative
import Data.Text (Text)
import Data.Typeable
import Prelude
-- | Deletes the access key associated with the specified user.
--
-- <>
data DeleteAccessKey
= DeleteAccessKey {
dakAccessKeyId :: Text
-- ^ ID of the access key to be deleted.
, dakUserName :: Maybe Text
-- ^ User name with which the access key is associated.
}
deriving (Eq, Ord, Show, Typeable)
instance SignQuery DeleteAccessKey where
type ServiceConfiguration DeleteAccessKey = IamConfiguration
signQuery DeleteAccessKey{..}
= iamAction' "DeleteAccessKey" [
Just ("AccessKeyId", dakAccessKeyId)
, ("UserName",) <$> dakUserName
]
data DeleteAccessKeyResponse = DeleteAccessKeyResponse
deriving (Eq, Ord, Show, Typeable)
instance ResponseConsumer DeleteAccessKey DeleteAccessKeyResponse where
type ResponseMetadata DeleteAccessKeyResponse = IamMetadata
responseConsumer _ _
= iamResponseConsumer (const $ return DeleteAccessKeyResponse)
instance Transaction DeleteAccessKey DeleteAccessKeyResponse
instance AsMemoryResponse DeleteAccessKeyResponse where
type MemoryResponse DeleteAccessKeyResponse = DeleteAccessKeyResponse
loadToMemory = return
| null | https://raw.githubusercontent.com/aristidb/aws/a99113ed7768f9758346052c0d8939b66c6efa87/Aws/Iam/Commands/DeleteAccessKey.hs | haskell | | Deletes the access key associated with the specified user.
<>
^ ID of the access key to be deleted.
^ User name with which the access key is associated. | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
module Aws.Iam.Commands.DeleteAccessKey
( DeleteAccessKey(..)
, DeleteAccessKeyResponse(..)
) where
import Aws.Core
import Aws.Iam.Core
import Aws.Iam.Internal
import Control.Applicative
import Data.Text (Text)
import Data.Typeable
import Prelude
data DeleteAccessKey
= DeleteAccessKey {
dakAccessKeyId :: Text
, dakUserName :: Maybe Text
}
deriving (Eq, Ord, Show, Typeable)
instance SignQuery DeleteAccessKey where
type ServiceConfiguration DeleteAccessKey = IamConfiguration
signQuery DeleteAccessKey{..}
= iamAction' "DeleteAccessKey" [
Just ("AccessKeyId", dakAccessKeyId)
, ("UserName",) <$> dakUserName
]
data DeleteAccessKeyResponse = DeleteAccessKeyResponse
deriving (Eq, Ord, Show, Typeable)
instance ResponseConsumer DeleteAccessKey DeleteAccessKeyResponse where
type ResponseMetadata DeleteAccessKeyResponse = IamMetadata
responseConsumer _ _
= iamResponseConsumer (const $ return DeleteAccessKeyResponse)
instance Transaction DeleteAccessKey DeleteAccessKeyResponse
instance AsMemoryResponse DeleteAccessKeyResponse where
type MemoryResponse DeleteAccessKeyResponse = DeleteAccessKeyResponse
loadToMemory = return
|
3e6e448361cf6e117a26fcb5eb2eb11bde701005d6f14028f42a0096e7dde373 | adamwalker/clash-utils | IIRFilter.hs | --Infinite impulse response filters
module Clash.DSP.IIRFilter (
iirDirectI,
iirDirectII,
iirTransposedI,
iirTransposedII
) where
import Clash.Prelude
{- | Direct form I: <> -}
iirDirectI
:: (HiddenClockResetEnable dom, Num a, KnownNat n, NFDataX a)
=> Vec (n + 2) a -- ^ Numerator coefficients
-> Vec (n + 1) a -- ^ Denominator coefficients
-> Signal dom Bool -- ^ Input enable
-> Signal dom a -- ^ Input sample
-> Signal dom a -- ^ Output sample
iirDirectI coeffsN coeffsD en x = res
where
res = fir + iir
fir = dotP (map pure coeffsN) (iterateI (regEn 0 en) x)
iir = dotP (map pure coeffsD) (iterateI (regEn 0 en) (regEn 0 en res))
dotP as bs = fold (+) (zipWith (*) as bs)
| Direct form II : < >
iirDirectII
:: (HiddenClockResetEnable dom, Num a, KnownNat n, NFDataX a)
=> Vec (n + 2) a -- ^ Numerator coefficients
-> Vec (n + 1) a -- ^ Denominator coefficients
-> Signal dom Bool -- ^ Input enable
-> Signal dom a -- ^ Input sample
-> Signal dom a -- ^ Output sample
iirDirectII coeffsN coeffsD en x = dotP (map pure coeffsN) delayed
where
delayed = iterateI (regEn 0 en) mid
mid = x + dotP (map pure coeffsD) (tail delayed)
dotP as bs = fold (+) (zipWith (*) as bs)
{- | Transposed form I: <> -}
iirTransposedI
:: (HiddenClockResetEnable dom, Num a, KnownNat n, NFDataX a)
=> Vec (n + 2) a -- ^ Numerator coefficients
-> Vec (n + 1) a -- ^ Denominator coefficients
-> Signal dom Bool -- ^ Input enable
-> Signal dom a -- ^ Input sample
-> Signal dom a -- ^ Output sample
iirTransposedI coeffsN coeffsD en x = foldl1 func $ reverse $ map (* v) (pure <$> coeffsN)
where
v = x + regEn 0 en (foldl1 func $ reverse $ map (* v) (pure <$> coeffsD))
func accum x = x + regEn 0 en accum
| Transposed form II : < >
iirTransposedII
:: (HiddenClockResetEnable dom, Num a, KnownNat n, NFDataX a)
=> Vec (n + 2) a -- ^ Numerator coefficients
-> Vec (n + 1) a -- ^ Denominator coefficients
-> Signal dom Bool -- ^ Input enable
-> Signal dom a -- ^ Input sample
-> Signal dom a -- ^ Output sample
iirTransposedII coeffsN coeffsD en x = res
where
res = head fir + regEn 0 en t
fir = map (* x) (pure <$> coeffsN)
iir = map (* res) (pure <$> coeffsD)
ts = reverse $ zipWith (+) (tail fir) iir
t = foldl1 (\accum inp -> regEn 0 en accum + inp) ts
| null | https://raw.githubusercontent.com/adamwalker/clash-utils/375c61131e21e9a239b80bdb929ae77f156d056f/src/Clash/DSP/IIRFilter.hs | haskell | Infinite impulse response filters
| Direct form I: <>
^ Numerator coefficients
^ Denominator coefficients
^ Input enable
^ Input sample
^ Output sample
^ Numerator coefficients
^ Denominator coefficients
^ Input enable
^ Input sample
^ Output sample
| Transposed form I: <>
^ Numerator coefficients
^ Denominator coefficients
^ Input enable
^ Input sample
^ Output sample
^ Numerator coefficients
^ Denominator coefficients
^ Input enable
^ Input sample
^ Output sample | module Clash.DSP.IIRFilter (
iirDirectI,
iirDirectII,
iirTransposedI,
iirTransposedII
) where
import Clash.Prelude
iirDirectI
:: (HiddenClockResetEnable dom, Num a, KnownNat n, NFDataX a)
iirDirectI coeffsN coeffsD en x = res
where
res = fir + iir
fir = dotP (map pure coeffsN) (iterateI (regEn 0 en) x)
iir = dotP (map pure coeffsD) (iterateI (regEn 0 en) (regEn 0 en res))
dotP as bs = fold (+) (zipWith (*) as bs)
| Direct form II : < >
iirDirectII
:: (HiddenClockResetEnable dom, Num a, KnownNat n, NFDataX a)
iirDirectII coeffsN coeffsD en x = dotP (map pure coeffsN) delayed
where
delayed = iterateI (regEn 0 en) mid
mid = x + dotP (map pure coeffsD) (tail delayed)
dotP as bs = fold (+) (zipWith (*) as bs)
iirTransposedI
:: (HiddenClockResetEnable dom, Num a, KnownNat n, NFDataX a)
iirTransposedI coeffsN coeffsD en x = foldl1 func $ reverse $ map (* v) (pure <$> coeffsN)
where
v = x + regEn 0 en (foldl1 func $ reverse $ map (* v) (pure <$> coeffsD))
func accum x = x + regEn 0 en accum
| Transposed form II : < >
iirTransposedII
:: (HiddenClockResetEnable dom, Num a, KnownNat n, NFDataX a)
iirTransposedII coeffsN coeffsD en x = res
where
res = head fir + regEn 0 en t
fir = map (* x) (pure <$> coeffsN)
iir = map (* res) (pure <$> coeffsD)
ts = reverse $ zipWith (+) (tail fir) iir
t = foldl1 (\accum inp -> regEn 0 en accum + inp) ts
|
e3f4613c356c646609cd0ade6881e886e977dee91a2ea8e14cb20652346577b9 | FranklinChen/hugs98-plus-Sep2006 | BCC.hs | module Data.Graph.Inductive.Query.BCC(
bcc
) where
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Query.DFS
import Data.Graph.Inductive.Query.ArtPoint
------------------------------------------------------------------------------
-- Given a graph g, this function computes the subgraphs which are
-- g's connected components.
------------------------------------------------------------------------------
gComponents :: DynGraph gr => gr a b -> [gr a b]
gComponents g = map (\(x,y)-> mkGraph x y) (zip ln le)
where ln = map (\x->[(u,l)|(u,l)<-vs,elem u x]) cc
le = map (\x->[(u,v,l)|(u,v,l)<-es,elem u x]) cc
(vs,es,cc) = (labNodes g,labEdges g,components g)
embedContexts :: DynGraph gr => Context a b -> [gr a b] -> [gr a b]
embedContexts (_,v,l,s) gs = map (\(x,y)-> x & y) (zip lc gs)
where lc = map (\e->(e,v,l,e)) lc'
lc'= map (\g->[ e | e <- s, gelem (snd e) g]) gs
------------------------------------------------------------------------------
-- Given a node v and a list of graphs, this functions returns the graph which
-- v belongs to.
------------------------------------------------------------------------------
findGraph :: DynGraph gr => Node -> [gr a b] -> Decomp gr a b
findGraph _ [] = error "findGraph: empty graph list"
findGraph v (g:gs) = case match v g of
(Nothing, _) -> findGraph v gs
(Just c, g') -> (Just c, g')
------------------------------------------------------------------------------
-- Given a graph g and its articulation points, this function disconnects g
-- for each articulation point and returns the connected components of the
-- resulting disconnected graph.
------------------------------------------------------------------------------
splitGraphs :: DynGraph gr => [gr a b] -> [Node] -> [gr a b]
splitGraphs gs [] = gs
splitGraphs [] _ = error "splitGraphs: empty graph list"
splitGraphs (g:gs) (v:vs) = splitGraphs (gs''++gs) vs
where gs'' = embedContexts c gs'
gs' = gComponents g'
(Just c,g') = findGraph v (g:gs)
|
Finds the bi - connected components of an undirected connected graph .
It first finds the articulation points of the graph . Then it disconnects the
graph on each articulation point and computes the connected components .
Finds the bi-connected components of an undirected connected graph.
It first finds the articulation points of the graph. Then it disconnects the
graph on each articulation point and computes the connected components.
-}
bcc :: DynGraph gr => gr a b -> [gr a b]
bcc g = splitGraphs [g] (ap g)
| null | https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/fgl/Data/Graph/Inductive/Query/BCC.hs | haskell | ----------------------------------------------------------------------------
Given a graph g, this function computes the subgraphs which are
g's connected components.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Given a node v and a list of graphs, this functions returns the graph which
v belongs to.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Given a graph g and its articulation points, this function disconnects g
for each articulation point and returns the connected components of the
resulting disconnected graph.
---------------------------------------------------------------------------- | module Data.Graph.Inductive.Query.BCC(
bcc
) where
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Query.DFS
import Data.Graph.Inductive.Query.ArtPoint
gComponents :: DynGraph gr => gr a b -> [gr a b]
gComponents g = map (\(x,y)-> mkGraph x y) (zip ln le)
where ln = map (\x->[(u,l)|(u,l)<-vs,elem u x]) cc
le = map (\x->[(u,v,l)|(u,v,l)<-es,elem u x]) cc
(vs,es,cc) = (labNodes g,labEdges g,components g)
embedContexts :: DynGraph gr => Context a b -> [gr a b] -> [gr a b]
embedContexts (_,v,l,s) gs = map (\(x,y)-> x & y) (zip lc gs)
where lc = map (\e->(e,v,l,e)) lc'
lc'= map (\g->[ e | e <- s, gelem (snd e) g]) gs
findGraph :: DynGraph gr => Node -> [gr a b] -> Decomp gr a b
findGraph _ [] = error "findGraph: empty graph list"
findGraph v (g:gs) = case match v g of
(Nothing, _) -> findGraph v gs
(Just c, g') -> (Just c, g')
splitGraphs :: DynGraph gr => [gr a b] -> [Node] -> [gr a b]
splitGraphs gs [] = gs
splitGraphs [] _ = error "splitGraphs: empty graph list"
splitGraphs (g:gs) (v:vs) = splitGraphs (gs''++gs) vs
where gs'' = embedContexts c gs'
gs' = gComponents g'
(Just c,g') = findGraph v (g:gs)
|
Finds the bi - connected components of an undirected connected graph .
It first finds the articulation points of the graph . Then it disconnects the
graph on each articulation point and computes the connected components .
Finds the bi-connected components of an undirected connected graph.
It first finds the articulation points of the graph. Then it disconnects the
graph on each articulation point and computes the connected components.
-}
bcc :: DynGraph gr => gr a b -> [gr a b]
bcc g = splitGraphs [g] (ap g)
|
2beddcb15579e1197470d9d48430c0baa1f77b34b6319d0303ef0f36cfac2731 | weavejester/flupot | dom.clj | (ns flupot.dom
(:refer-clojure :exclude [map meta time])
(:require [clojure.core :as core]
[clojure.string :as str]
[flupot.core :as flupot]
[flupot.core.parsing :as p]))
(def tags
'[a abbr address area article aside audio b base bdi bdo big blockquote body br
button canvas caption cite code col colgroup data datalist dd del details dfn
dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5
h6 head header hr html i iframe img input ins kbd keygen label legend li link
main map mark menu menuitem meta meter nav noscript object ol optgroup option
output p param picture pre progress q rp rt ruby s samp script section select
small source span strong style sub summary sup table tbody td textarea tfoot th
thead time title tr track u ul var video wbr])
(def ^:private attr-opts
{:accept-charset :acceptCharset
:accesskey :accessKey
:allowfullscreen :allowFullScreen
:autocomplete :autoComplete
:autofocus :autoFocus
:autoplay :autoPlay
:class :className
:colspan :colSpan
:contenteditable :contentEditable
:contextmenu :contextMenu
:crossorigin :crossOrigin
:datetime :dateTime
:enctype :encType
:formaction :formAction
:formenctype :formEncType
:formmethod :formMethod
:formnovalidate :formNoValidate
:formTarget :formtarget
:hreflang :hrefLang
:for :htmlFor
:http-equiv :httpEquiv
:maxlength :maxLength
:mediagroup :mediaGroup
:novalidate :noValidate
:onabort :onAbort
:onblur :onBlur
:oncancel :onCancel
:oncanplay :onCanPlay
:oncanplaythrough :onCanPlayThrough
:onchange :onChange
:onclick :onClick
:oncontextmenu :onContextMenu
:oncompositionend :onCompositionEnd
:oncompositionstart :onCompositionStart
:oncompositionupdate :onCompositionUpdate
:oncopy :onCopy
:oncut :onCut
:ondblclick :onDoubleClick
:ondrag :onDrag
:ondragend :onDragEnd
:ondragenter :onDragEnter
:ondragexit :onDragExit
:ondragleave :onDragLeave
:ondragover :onDragOver
:ondragstart :onDragStart
:ondrop :onDrop
:ondurationchange :onDurationChange
:onemptied :onEmptied
:onencrypted :onEncrypted
:onended :onEnded
:onerror :onError
:onfocus :onFocus
:oninput :onInput
:onkeydown :onKeyDown
:onkeypress :onKeyPress
:onkeyup :onKeyUp
:onload :onLoad
:onloadeddata :onLoadedData
:onloadedmetadata :onLoadedMetadata
:onloadstart :onLoadStart
:onmousedown :onMouseDown
:onmouseenter :onMouseEnter
:onmouseleave :onMouseLeave
:onmousemove :onMouseMove
:onmouseout :onMouseOut
:onmouseover :onMouseOver
:onmouseup :onMouseUp
:onpaste :onPaste
:onpause :onPause
:onplay :onPlay
:onplaying :onPlaying
:onprogress :onProgress
:onratechange :onRateChange
:onscroll :onScroll
:onseeked :onSeeked
:onseeking :onSeeking
:onselect :onSelect
:onstalled :onStalled
:onsubmit :onSubmit
:onsuspend :onSuspend
:ontimeupdate :onTimeUpdate
:ontouchcancel :onTouchCancel
:ontouchend :onTouchEnd
:ontouchmove :onTouchMove
:ontouchstart :onTouchStart
:onvolumechange :onVolumeChange
:onwaiting :onWaiting
:onwheel :onWheel
:rowspan :rowSpan
:spellcheck :spellCheck
:srcdoc :srcDoc
:srcset :srcSet
:tabindex :tabIndex
:usemap :useMap})
(defn- mapm [fk fv m]
(reduce-kv (fn [m k v] (assoc m (fk k) (fv v))) {} m))
(defmacro generate-attr-opts []
(flupot/clj->js (mapm name name attr-opts)))
(defn- dom-symbol [tag]
(symbol "js" (str "React.DOM." (name tag))))
(defmacro define-dom-fns []
`(do ~@(for [t tags]
`(flupot/defelement-fn ~t
:elemf ~(dom-symbol t)
:attrf attrs->react))))
(defn- boolean? [v]
(or (true? v) (false? v)))
(defn- to-str [x]
(cond
(keyword? x) (name x)
(p/quoted? x) (to-str (second x))
:else (str x)))
(defn- fix-class [m]
(let [cls (:class m)]
(cond
(and (or (vector? cls) (set? cls)) (every? p/literal? cls))
(assoc m :class (str/join " " (core/map to-str cls)))
(or (nil? cls) (string? cls) (number? cls) (boolean? cls))
m
:else
(assoc m :class `(flupot.dom/fix-class ~cls)))))
(defn- attrs->react [m]
(flupot/clj->js (mapm #(name (attr-opts % %)) identity (fix-class m))))
(defmacro define-dom-macros []
`(do ~@(for [t tags]
`(flupot/defelement-macro ~t
:elemf ~(dom-symbol t)
:attrf attrs->react
:attrm attrs->react))))
(define-dom-macros)
| null | https://raw.githubusercontent.com/weavejester/flupot/59f96a563436589d1f41fe74192bbbb0f1d25a5e/src/flupot/dom.clj | clojure | (ns flupot.dom
(:refer-clojure :exclude [map meta time])
(:require [clojure.core :as core]
[clojure.string :as str]
[flupot.core :as flupot]
[flupot.core.parsing :as p]))
(def tags
'[a abbr address area article aside audio b base bdi bdo big blockquote body br
button canvas caption cite code col colgroup data datalist dd del details dfn
dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5
h6 head header hr html i iframe img input ins kbd keygen label legend li link
main map mark menu menuitem meta meter nav noscript object ol optgroup option
output p param picture pre progress q rp rt ruby s samp script section select
small source span strong style sub summary sup table tbody td textarea tfoot th
thead time title tr track u ul var video wbr])
(def ^:private attr-opts
{:accept-charset :acceptCharset
:accesskey :accessKey
:allowfullscreen :allowFullScreen
:autocomplete :autoComplete
:autofocus :autoFocus
:autoplay :autoPlay
:class :className
:colspan :colSpan
:contenteditable :contentEditable
:contextmenu :contextMenu
:crossorigin :crossOrigin
:datetime :dateTime
:enctype :encType
:formaction :formAction
:formenctype :formEncType
:formmethod :formMethod
:formnovalidate :formNoValidate
:formTarget :formtarget
:hreflang :hrefLang
:for :htmlFor
:http-equiv :httpEquiv
:maxlength :maxLength
:mediagroup :mediaGroup
:novalidate :noValidate
:onabort :onAbort
:onblur :onBlur
:oncancel :onCancel
:oncanplay :onCanPlay
:oncanplaythrough :onCanPlayThrough
:onchange :onChange
:onclick :onClick
:oncontextmenu :onContextMenu
:oncompositionend :onCompositionEnd
:oncompositionstart :onCompositionStart
:oncompositionupdate :onCompositionUpdate
:oncopy :onCopy
:oncut :onCut
:ondblclick :onDoubleClick
:ondrag :onDrag
:ondragend :onDragEnd
:ondragenter :onDragEnter
:ondragexit :onDragExit
:ondragleave :onDragLeave
:ondragover :onDragOver
:ondragstart :onDragStart
:ondrop :onDrop
:ondurationchange :onDurationChange
:onemptied :onEmptied
:onencrypted :onEncrypted
:onended :onEnded
:onerror :onError
:onfocus :onFocus
:oninput :onInput
:onkeydown :onKeyDown
:onkeypress :onKeyPress
:onkeyup :onKeyUp
:onload :onLoad
:onloadeddata :onLoadedData
:onloadedmetadata :onLoadedMetadata
:onloadstart :onLoadStart
:onmousedown :onMouseDown
:onmouseenter :onMouseEnter
:onmouseleave :onMouseLeave
:onmousemove :onMouseMove
:onmouseout :onMouseOut
:onmouseover :onMouseOver
:onmouseup :onMouseUp
:onpaste :onPaste
:onpause :onPause
:onplay :onPlay
:onplaying :onPlaying
:onprogress :onProgress
:onratechange :onRateChange
:onscroll :onScroll
:onseeked :onSeeked
:onseeking :onSeeking
:onselect :onSelect
:onstalled :onStalled
:onsubmit :onSubmit
:onsuspend :onSuspend
:ontimeupdate :onTimeUpdate
:ontouchcancel :onTouchCancel
:ontouchend :onTouchEnd
:ontouchmove :onTouchMove
:ontouchstart :onTouchStart
:onvolumechange :onVolumeChange
:onwaiting :onWaiting
:onwheel :onWheel
:rowspan :rowSpan
:spellcheck :spellCheck
:srcdoc :srcDoc
:srcset :srcSet
:tabindex :tabIndex
:usemap :useMap})
(defn- mapm [fk fv m]
(reduce-kv (fn [m k v] (assoc m (fk k) (fv v))) {} m))
(defmacro generate-attr-opts []
(flupot/clj->js (mapm name name attr-opts)))
(defn- dom-symbol [tag]
(symbol "js" (str "React.DOM." (name tag))))
(defmacro define-dom-fns []
`(do ~@(for [t tags]
`(flupot/defelement-fn ~t
:elemf ~(dom-symbol t)
:attrf attrs->react))))
(defn- boolean? [v]
(or (true? v) (false? v)))
(defn- to-str [x]
(cond
(keyword? x) (name x)
(p/quoted? x) (to-str (second x))
:else (str x)))
(defn- fix-class [m]
(let [cls (:class m)]
(cond
(and (or (vector? cls) (set? cls)) (every? p/literal? cls))
(assoc m :class (str/join " " (core/map to-str cls)))
(or (nil? cls) (string? cls) (number? cls) (boolean? cls))
m
:else
(assoc m :class `(flupot.dom/fix-class ~cls)))))
(defn- attrs->react [m]
(flupot/clj->js (mapm #(name (attr-opts % %)) identity (fix-class m))))
(defmacro define-dom-macros []
`(do ~@(for [t tags]
`(flupot/defelement-macro ~t
:elemf ~(dom-symbol t)
:attrf attrs->react
:attrm attrs->react))))
(define-dom-macros)
|
|
9846d375bda7812295b8a31695090a2ddd9689c8cfe6f5b722f813f5fb0e576f | theoremoon/silk | typ.ml | open Error
type typ =
|UnitT
|IntT
|BoolT
|VarT of string
|FunT of typ * typ
let is_funt t =
match t with
|FunT(_, _) -> true
|_ -> false
let arg_type funt =
match funt with
|FunT(argt, _) -> argt
|_ -> raise (TypeError "function type requried")
let ret_type funt =
match funt with
|FunT(_, rett) -> rett
|_ -> raise (TypeError "function type requried")
let make_funt argtypes rettype =
let rec make_funt' argtypes rettype =
match argtypes with
|argt::xs ->
FunT(argt, make_funt' xs rettype)
|[] -> rettype
in
match argtypes with
|[] -> make_funt' [UnitT] rettype
|_ -> make_funt' argtypes rettype
let rec string_of_type t =
match t with
|UnitT -> "Unit"
|IntT -> "Int"
|BoolT -> "Bool"
|VarT(name) -> name
|FunT(a, r) -> (string_of_type a)^"->"^(string_of_type r)
| null | https://raw.githubusercontent.com/theoremoon/silk/b3c913cfebad03fc180f41695ca8c6e5dcbd2867/typ.ml | ocaml | open Error
type typ =
|UnitT
|IntT
|BoolT
|VarT of string
|FunT of typ * typ
let is_funt t =
match t with
|FunT(_, _) -> true
|_ -> false
let arg_type funt =
match funt with
|FunT(argt, _) -> argt
|_ -> raise (TypeError "function type requried")
let ret_type funt =
match funt with
|FunT(_, rett) -> rett
|_ -> raise (TypeError "function type requried")
let make_funt argtypes rettype =
let rec make_funt' argtypes rettype =
match argtypes with
|argt::xs ->
FunT(argt, make_funt' xs rettype)
|[] -> rettype
in
match argtypes with
|[] -> make_funt' [UnitT] rettype
|_ -> make_funt' argtypes rettype
let rec string_of_type t =
match t with
|UnitT -> "Unit"
|IntT -> "Int"
|BoolT -> "Bool"
|VarT(name) -> name
|FunT(a, r) -> (string_of_type a)^"->"^(string_of_type r)
|
|
94a12edab7b6bca039f0bac4e49dad83a07d717e2d5de51e2914137c94df2241 | fossas/fossa-cli | NimbleLock.hs | # LANGUAGE LambdaCase #
module Strategy.Nim.NimbleLock (
analyze,
analyze',
-- * for testing
NimbleLock (..),
PackageName (..),
NimPackage (..),
NimbleDownloadMethod (..),
NimbleDump (..),
NimbleRequire (..),
buildGraph,
) where
import Algebra.Graph.AdjacencyMap qualified as AM
import Control.Effect.Diagnostics (
Diagnostics,
ToDiagnostic (renderDiagnostic),
context,
errCtx,
recover,
warnOnErr,
)
import Data.Aeson (
FromJSON (parseJSON),
FromJSONKey,
Value,
withObject,
withText,
(.:),
)
import Data.Aeson.KeyMap qualified as Object
import Data.Aeson.Types (Parser)
import Data.Map (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (mapMaybe)
import Data.Set qualified as Set
import Data.String.Conversion (toText)
import Data.Text (Text)
import Data.Traversable (for)
import DepTypes (
DepType (GitType),
Dependency (Dependency),
VerConstraint (CEq),
)
import Effect.Exec (AllowErr (Always), Command (..), Exec, execJson)
import Effect.ReadFS (Has, ReadFS, readContentsJson)
import GHC.Generics (Generic)
import Graphing (
Graphing,
directs,
gmap,
induceJust,
toAdjacencyMap,
unfoldDeep,
)
import Path (Abs, Dir, File, Path)
import Types (GraphBreadth (..))
-- | Represents nimble lock file.
-- Reference: -lang/nimble#nimble-lock
newtype NimbleLock = NimbleLock {packages :: [NimPackage]}
deriving (Show, Eq, Ord)
data NimPackage = NimPackage
{ -- Name of the package.
name :: PackageName
, -- Version of the packages.
version :: Text
, -- The URL of the repository of the package.
url :: Text
, -- The download method: git or hg according to the type of the repository at url.
downloadMethod :: NimbleDownloadMethod
, -- The revision at which the dependency is locked.
vcsRevision :: Text
, -- The direct dependencies of the package.
dependencies :: [PackageName]
}
deriving (Show, Eq, Ord)
instance FromJSON NimbleLock where
parseJSON = withObject "NimbleLock" $ \obj -> do
pkgs <- parsePkgs =<< (obj .: "packages")
pure $ NimbleLock pkgs
where
parsePkgs :: Value -> Parser [NimPackage]
parsePkgs = withObject "NimPackage" $ \o ->
for (Object.toList o) $ \(pkgName, pkgMeta) ->
parseNimPackageWithName (PackageName $ toText pkgName) pkgMeta
parseNimPackageWithName :: PackageName -> Value -> Parser NimPackage
parseNimPackageWithName name = withObject "parseNimPackageWithName" $ \metaO ->
NimPackage name
<$> metaO .: "version"
<*> metaO .: "url"
<*> metaO .: "downloadMethod"
<*> metaO .: "vcsRevision"
<*> metaO .: "dependencies"
data NimbleDownloadMethod
= NimbleDownloadMethodGit
| NimbleDownloadMethodOther
deriving (Show, Eq, Ord)
instance FromJSON NimbleDownloadMethod where
parseJSON = withText "NimbleDownloadMethod" $ \case
"git" -> pure NimbleDownloadMethodGit
_ -> pure NimbleDownloadMethodOther
newtype PackageName = PackageName {unPackageName :: Text}
deriving (Show, Eq, Ord, Generic, FromJSONKey)
instance FromJSON PackageName where
parseJSON = withText "PackageName" $ \s -> pure $ PackageName s
-- | Builds the graph from nimble lock file, and enriches with output of nimble dump.
buildGraph :: NimbleLock -> Maybe NimbleDump -> Graphing Dependency
buildGraph lockFile nimbleDump =
Graphing.induceJust
. Graphing.gmap toDependency
. applyDirect
$ Graphing.unfoldDeep (packages lockFile) getTransitives id
where
pkgRegistry :: Map PackageName NimPackage
pkgRegistry = Map.fromList $ map (\p -> (name p, p)) (packages lockFile)
getTransitives :: NimPackage -> [NimPackage]
getTransitives pkg = mapMaybe (`Map.lookup` pkgRegistry) (dependencies pkg)
getVerticesWithoutPredecessors :: Graphing NimPackage -> [NimPackage]
getVerticesWithoutPredecessors gr = filter (\a -> Set.null $ AM.preSet a $ Graphing.toAdjacencyMap gr) (packages lockFile)
-- When nimble dump command fails to retrieve direct dependencies,
-- Approximate by inferring dependencies which do not have any incoming edges as direct!
-- This should hold for *most* cases, but fails when you have, direct dependency requiring another direct dependency.
--
Failure Case :
-- (A: direct) → (B: indirect)
-- ↓
-- (D: direct)
--
-- When nimble dump command succeeds, use provided direct dependencies.
applyDirect :: Graphing NimPackage -> Graphing NimPackage
applyDirect gr = case nimbleDump of
Nothing -> Graphing.directs (getVerticesWithoutPredecessors gr) <> gr
Just nd -> Graphing.directs (mapMaybe ((`Map.lookup` pkgRegistry) . nameOf) (requires nd)) <> gr
toDependency :: NimPackage -> Maybe Dependency
toDependency nimPkg = case downloadMethod nimPkg of
NimbleDownloadMethodOther -> Nothing
NimbleDownloadMethodGit ->
Just $
Dependency
GitType
(url nimPkg)
(Just $ CEq $ vcsRevision nimPkg)
[]
mempty
mempty
| Performs ' nimble dump --json ' and is tolerant to non - zero exit status .
nimbleDumpJsonCmd :: Command
nimbleDumpJsonCmd =
Command
{ cmdName = "nimble"
, cmdArgs = ["dump", "--json"]
, cmdAllowErr = Always
}
-- | Represents content retrieved from @nimbleDumpJsonCmd@.
newtype NimbleDump = NimbleDump {requires :: [NimbleRequire]} deriving (Show, Eq, Ord)
newtype NimbleRequire = NimbleRequire {nameOf :: PackageName} deriving (Show, Eq, Ord)
instance FromJSON NimbleDump where
parseJSON = withObject "NimbleDump" $ \obj ->
NimbleDump <$> obj .: "requires"
instance FromJSON NimbleRequire where
parseJSON = withObject "NimbleRequire" $ \obj ->
NimbleRequire <$> obj .: "name"
analyze ::
( Has ReadFS sig m
, Has Exec sig m
, Has Diagnostics sig m
) =>
Path Abs Dir ->
Path Abs File ->
m (Graphing Dependency, GraphBreadth)
analyze dir lockFile = do
lockContents <- context "Reading nimble.lock" $ readContentsJson lockFile
nimbleDumpContent :: Maybe NimbleDump <-
recover
. context "Performing nimble dump --json to identify direct dependencies"
. warnOnErr MissingEdgesBetweenDirectDeps
. errCtx CmdNimbleDumpFailed
$ execJson dir nimbleDumpJsonCmd
context "building graphing from nimble.lock" $ pure (buildGraph lockContents nimbleDumpContent, Complete)
analyze' ::
( Has ReadFS sig m
, Has Diagnostics sig m
) =>
Path Abs Dir ->
Path Abs File ->
m (Graphing Dependency, GraphBreadth)
analyze' _ lockFile = do
lockContents <- context "Reading nimble.lock" $ readContentsJson lockFile
context "building graphing from nimble.lock" $ pure (buildGraph lockContents Nothing, Complete)
data MissingEdgesBetweenDirectDeps = MissingEdgesBetweenDirectDeps
instance ToDiagnostic MissingEdgesBetweenDirectDeps where
renderDiagnostic _ = "Could not infer edges between direct dependencies."
data CmdNimbleDumpFailed = CmdNimbleDumpFailed
instance ToDiagnostic CmdNimbleDumpFailed where
renderDiagnostic _ = "We could not retrieve nimble packages metadata using nimble's dump subcommand."
| null | https://raw.githubusercontent.com/fossas/fossa-cli/187f19afec2133466d1998c89fc7f1c77107c2b0/src/Strategy/Nim/NimbleLock.hs | haskell | * for testing
| Represents nimble lock file.
Reference: -lang/nimble#nimble-lock
Name of the package.
Version of the packages.
The URL of the repository of the package.
The download method: git or hg according to the type of the repository at url.
The revision at which the dependency is locked.
The direct dependencies of the package.
| Builds the graph from nimble lock file, and enriches with output of nimble dump.
When nimble dump command fails to retrieve direct dependencies,
Approximate by inferring dependencies which do not have any incoming edges as direct!
This should hold for *most* cases, but fails when you have, direct dependency requiring another direct dependency.
(A: direct) → (B: indirect)
↓
(D: direct)
When nimble dump command succeeds, use provided direct dependencies.
json ' and is tolerant to non - zero exit status .
| Represents content retrieved from @nimbleDumpJsonCmd@. | # LANGUAGE LambdaCase #
module Strategy.Nim.NimbleLock (
analyze,
analyze',
NimbleLock (..),
PackageName (..),
NimPackage (..),
NimbleDownloadMethod (..),
NimbleDump (..),
NimbleRequire (..),
buildGraph,
) where
import Algebra.Graph.AdjacencyMap qualified as AM
import Control.Effect.Diagnostics (
Diagnostics,
ToDiagnostic (renderDiagnostic),
context,
errCtx,
recover,
warnOnErr,
)
import Data.Aeson (
FromJSON (parseJSON),
FromJSONKey,
Value,
withObject,
withText,
(.:),
)
import Data.Aeson.KeyMap qualified as Object
import Data.Aeson.Types (Parser)
import Data.Map (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (mapMaybe)
import Data.Set qualified as Set
import Data.String.Conversion (toText)
import Data.Text (Text)
import Data.Traversable (for)
import DepTypes (
DepType (GitType),
Dependency (Dependency),
VerConstraint (CEq),
)
import Effect.Exec (AllowErr (Always), Command (..), Exec, execJson)
import Effect.ReadFS (Has, ReadFS, readContentsJson)
import GHC.Generics (Generic)
import Graphing (
Graphing,
directs,
gmap,
induceJust,
toAdjacencyMap,
unfoldDeep,
)
import Path (Abs, Dir, File, Path)
import Types (GraphBreadth (..))
newtype NimbleLock = NimbleLock {packages :: [NimPackage]}
deriving (Show, Eq, Ord)
data NimPackage = NimPackage
name :: PackageName
version :: Text
url :: Text
downloadMethod :: NimbleDownloadMethod
vcsRevision :: Text
dependencies :: [PackageName]
}
deriving (Show, Eq, Ord)
instance FromJSON NimbleLock where
parseJSON = withObject "NimbleLock" $ \obj -> do
pkgs <- parsePkgs =<< (obj .: "packages")
pure $ NimbleLock pkgs
where
parsePkgs :: Value -> Parser [NimPackage]
parsePkgs = withObject "NimPackage" $ \o ->
for (Object.toList o) $ \(pkgName, pkgMeta) ->
parseNimPackageWithName (PackageName $ toText pkgName) pkgMeta
parseNimPackageWithName :: PackageName -> Value -> Parser NimPackage
parseNimPackageWithName name = withObject "parseNimPackageWithName" $ \metaO ->
NimPackage name
<$> metaO .: "version"
<*> metaO .: "url"
<*> metaO .: "downloadMethod"
<*> metaO .: "vcsRevision"
<*> metaO .: "dependencies"
data NimbleDownloadMethod
= NimbleDownloadMethodGit
| NimbleDownloadMethodOther
deriving (Show, Eq, Ord)
instance FromJSON NimbleDownloadMethod where
parseJSON = withText "NimbleDownloadMethod" $ \case
"git" -> pure NimbleDownloadMethodGit
_ -> pure NimbleDownloadMethodOther
newtype PackageName = PackageName {unPackageName :: Text}
deriving (Show, Eq, Ord, Generic, FromJSONKey)
instance FromJSON PackageName where
parseJSON = withText "PackageName" $ \s -> pure $ PackageName s
buildGraph :: NimbleLock -> Maybe NimbleDump -> Graphing Dependency
buildGraph lockFile nimbleDump =
Graphing.induceJust
. Graphing.gmap toDependency
. applyDirect
$ Graphing.unfoldDeep (packages lockFile) getTransitives id
where
pkgRegistry :: Map PackageName NimPackage
pkgRegistry = Map.fromList $ map (\p -> (name p, p)) (packages lockFile)
getTransitives :: NimPackage -> [NimPackage]
getTransitives pkg = mapMaybe (`Map.lookup` pkgRegistry) (dependencies pkg)
getVerticesWithoutPredecessors :: Graphing NimPackage -> [NimPackage]
getVerticesWithoutPredecessors gr = filter (\a -> Set.null $ AM.preSet a $ Graphing.toAdjacencyMap gr) (packages lockFile)
Failure Case :
applyDirect :: Graphing NimPackage -> Graphing NimPackage
applyDirect gr = case nimbleDump of
Nothing -> Graphing.directs (getVerticesWithoutPredecessors gr) <> gr
Just nd -> Graphing.directs (mapMaybe ((`Map.lookup` pkgRegistry) . nameOf) (requires nd)) <> gr
toDependency :: NimPackage -> Maybe Dependency
toDependency nimPkg = case downloadMethod nimPkg of
NimbleDownloadMethodOther -> Nothing
NimbleDownloadMethodGit ->
Just $
Dependency
GitType
(url nimPkg)
(Just $ CEq $ vcsRevision nimPkg)
[]
mempty
mempty
nimbleDumpJsonCmd :: Command
nimbleDumpJsonCmd =
Command
{ cmdName = "nimble"
, cmdArgs = ["dump", "--json"]
, cmdAllowErr = Always
}
newtype NimbleDump = NimbleDump {requires :: [NimbleRequire]} deriving (Show, Eq, Ord)
newtype NimbleRequire = NimbleRequire {nameOf :: PackageName} deriving (Show, Eq, Ord)
instance FromJSON NimbleDump where
parseJSON = withObject "NimbleDump" $ \obj ->
NimbleDump <$> obj .: "requires"
instance FromJSON NimbleRequire where
parseJSON = withObject "NimbleRequire" $ \obj ->
NimbleRequire <$> obj .: "name"
analyze ::
( Has ReadFS sig m
, Has Exec sig m
, Has Diagnostics sig m
) =>
Path Abs Dir ->
Path Abs File ->
m (Graphing Dependency, GraphBreadth)
analyze dir lockFile = do
lockContents <- context "Reading nimble.lock" $ readContentsJson lockFile
nimbleDumpContent :: Maybe NimbleDump <-
recover
. context "Performing nimble dump --json to identify direct dependencies"
. warnOnErr MissingEdgesBetweenDirectDeps
. errCtx CmdNimbleDumpFailed
$ execJson dir nimbleDumpJsonCmd
context "building graphing from nimble.lock" $ pure (buildGraph lockContents nimbleDumpContent, Complete)
analyze' ::
( Has ReadFS sig m
, Has Diagnostics sig m
) =>
Path Abs Dir ->
Path Abs File ->
m (Graphing Dependency, GraphBreadth)
analyze' _ lockFile = do
lockContents <- context "Reading nimble.lock" $ readContentsJson lockFile
context "building graphing from nimble.lock" $ pure (buildGraph lockContents Nothing, Complete)
data MissingEdgesBetweenDirectDeps = MissingEdgesBetweenDirectDeps
instance ToDiagnostic MissingEdgesBetweenDirectDeps where
renderDiagnostic _ = "Could not infer edges between direct dependencies."
data CmdNimbleDumpFailed = CmdNimbleDumpFailed
instance ToDiagnostic CmdNimbleDumpFailed where
renderDiagnostic _ = "We could not retrieve nimble packages metadata using nimble's dump subcommand."
|
829278bece4a30dd6fb0a0a04c586925670147d05ad952d43d00ed81fbb99322 | workframers/stillsuit | project.clj | (defproject com.workframe/stillsuit "0.19.0-SNAPSHOT"
:description "lacinia-datomic interface library"
:url ""
:scm {:name "git" :url ""}
:pedantic? :warn
:min-lein-version "2.8.1"
:license {:name "Apache 2.0"
:url "-2.0"}
:dependencies [[org.clojure/clojure "1.10.0" :scope "provided"]
[org.clojure/tools.cli "0.4.1"]
[mvxcvi/puget "1.1.0"]
[fipp "0.6.17"]
[funcool/cuerdas "2.1.0"]
[io.aviso/pretty "0.1.37"]
[com.walmartlabs/lacinia "0.38.0"]
[clojure.java-time "0.3.2"]
[org.clojure/tools.logging "0.4.1"]
[org.clojure/tools.reader "1.3.2"]
[com.datomic/datomic-free "0.9.5697"
:optional true
:scope "provided"
:exclusions [org.slf4j/slf4j-nop]]]
:source-paths ["src"]
:test-selectors {:watch :watch}
:codox {:metadata {:doc/format :markdown}
:themes [:rdash]
:source-uri "/{filepath}#L{line}"}
:asciidoctor [{:sources "doc/manual/*.adoc"
:format :html5
:source-highlight true
:to-dir "target/manual"}]
:profiles {:dev {:plugins [[lein-cloverage "1.1.1" :exclusions [org.clojure/clojure]]
[lein-shell "0.5.0"]
[com.jakemccrary/lein-test-refresh "0.23.0"]]
:dependencies [[vvvvalvalval/datomock "0.2.2"]
[io.forward/yaml "1.0.9"]
[org.apache.logging.log4j/log4j-core "2.11.2"]
[org.apache.logging.log4j/log4j-slf4j-impl "2.11.2"]]}
:free {:dependencies [[com.datomic/datomic-free "0.9.5697"
:exclusions [org.slf4j/slf4j-nop]]]}
:docs {:plugins [[lein-codox "0.10.6"]
[lein-asciidoctor "0.1.17" :exclusions [org.slf4j/slf4j-api]]]
:dependencies [[codox-theme-rdash "0.1.2"]]}
:ancient {:plugins [[lein-ancient "0.6.15"]]}
:ultra {:plugins [[venantius/ultra "0.6.0" :exclusions [org.clojure/clojure]]]}
:test {:resource-paths ["test/resources"]}
:workframe {:plugins [[s3-wagon-private "1.3.2" :exclusions [commons-logging]]]
:repositories [["workframe-private"
{:url "s3p/"
:no-auth true
:sign-releases false}]]}}
:aliases {"refresh" ["with-profile" "+ultra,+free" "test-refresh" ":watch"]}
:release-tasks [;; Make sure we're up to date
["vcs" "assert-committed"]
["shell" "git" "checkout" "develop"]
["shell" "git" "pull"]
["shell" "git" "checkout" "master"]
["shell" "git" "pull"]
;; Merge develop into master
["shell" "git" "merge" "develop"]
;; Update version to non-snapshot version, commit change to master, tag
["change" "version" "leiningen.release/bump-version" "release"]
["vcs" "commit"]
["vcs" "tag" "stillsuit-" "--no-sign"]
Merge master back into develop ( we 'll now have the non - SNAPSHOT version )
["shell" "git" "checkout" "develop"]
["shell" "git" "merge" "master"]
Bump up SNAPSHOT version in develop and commit
["change" "version" "leiningen.release/bump-version" "minor"]
["vcs" "commit"]
;; All done
["shell" "echo"]
["shell" "echo" "Release tagged in master; develop bumped to ${:version}."]
["shell" "echo" "To push it, run 'git push origin develop master --tags'"]])
| null | https://raw.githubusercontent.com/workframers/stillsuit/f73d87d97971b458a4f717fccfa2445dc82f9b72/project.clj | clojure | Make sure we're up to date
Merge develop into master
Update version to non-snapshot version, commit change to master, tag
All done | (defproject com.workframe/stillsuit "0.19.0-SNAPSHOT"
:description "lacinia-datomic interface library"
:url ""
:scm {:name "git" :url ""}
:pedantic? :warn
:min-lein-version "2.8.1"
:license {:name "Apache 2.0"
:url "-2.0"}
:dependencies [[org.clojure/clojure "1.10.0" :scope "provided"]
[org.clojure/tools.cli "0.4.1"]
[mvxcvi/puget "1.1.0"]
[fipp "0.6.17"]
[funcool/cuerdas "2.1.0"]
[io.aviso/pretty "0.1.37"]
[com.walmartlabs/lacinia "0.38.0"]
[clojure.java-time "0.3.2"]
[org.clojure/tools.logging "0.4.1"]
[org.clojure/tools.reader "1.3.2"]
[com.datomic/datomic-free "0.9.5697"
:optional true
:scope "provided"
:exclusions [org.slf4j/slf4j-nop]]]
:source-paths ["src"]
:test-selectors {:watch :watch}
:codox {:metadata {:doc/format :markdown}
:themes [:rdash]
:source-uri "/{filepath}#L{line}"}
:asciidoctor [{:sources "doc/manual/*.adoc"
:format :html5
:source-highlight true
:to-dir "target/manual"}]
:profiles {:dev {:plugins [[lein-cloverage "1.1.1" :exclusions [org.clojure/clojure]]
[lein-shell "0.5.0"]
[com.jakemccrary/lein-test-refresh "0.23.0"]]
:dependencies [[vvvvalvalval/datomock "0.2.2"]
[io.forward/yaml "1.0.9"]
[org.apache.logging.log4j/log4j-core "2.11.2"]
[org.apache.logging.log4j/log4j-slf4j-impl "2.11.2"]]}
:free {:dependencies [[com.datomic/datomic-free "0.9.5697"
:exclusions [org.slf4j/slf4j-nop]]]}
:docs {:plugins [[lein-codox "0.10.6"]
[lein-asciidoctor "0.1.17" :exclusions [org.slf4j/slf4j-api]]]
:dependencies [[codox-theme-rdash "0.1.2"]]}
:ancient {:plugins [[lein-ancient "0.6.15"]]}
:ultra {:plugins [[venantius/ultra "0.6.0" :exclusions [org.clojure/clojure]]]}
:test {:resource-paths ["test/resources"]}
:workframe {:plugins [[s3-wagon-private "1.3.2" :exclusions [commons-logging]]]
:repositories [["workframe-private"
{:url "s3p/"
:no-auth true
:sign-releases false}]]}}
:aliases {"refresh" ["with-profile" "+ultra,+free" "test-refresh" ":watch"]}
["vcs" "assert-committed"]
["shell" "git" "checkout" "develop"]
["shell" "git" "pull"]
["shell" "git" "checkout" "master"]
["shell" "git" "pull"]
["shell" "git" "merge" "develop"]
["change" "version" "leiningen.release/bump-version" "release"]
["vcs" "commit"]
["vcs" "tag" "stillsuit-" "--no-sign"]
Merge master back into develop ( we 'll now have the non - SNAPSHOT version )
["shell" "git" "checkout" "develop"]
["shell" "git" "merge" "master"]
Bump up SNAPSHOT version in develop and commit
["change" "version" "leiningen.release/bump-version" "minor"]
["vcs" "commit"]
["shell" "echo"]
["shell" "echo" "Release tagged in master; develop bumped to ${:version}."]
["shell" "echo" "To push it, run 'git push origin develop master --tags'"]])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.