_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
|
---|---|---|---|---|---|---|---|---|
9c816946032d780c8bf5e46f09c4d0b76aa606096a530a6c06d4253121ff441f | babashka/bbin | cli.clj | (ns babashka.bbin.cli
(:require [babashka.cli :as cli]
[babashka.bbin.scripts :as scripts]
[babashka.bbin.util :as util]
[clojure.string :as str]))
(declare print-commands)
(defn- run [command-fn {:keys [opts]}]
(util/check-legacy-paths)
(if (and (:version opts) (not (:help opts)))
(util/print-version)
(command-fn opts)))
(defn- add-global-aliases [commands]
(map #(assoc-in % [:aliases :h] :help) commands))
(defn- base-commands
[& {:keys [install-fn uninstall-fn ls-fn bin-fn]}]
[{:cmds ["commands"]
:fn #(run print-commands %)}
{:cmds ["help"]
:fn #(run util/print-help %)}
{:cmds ["install"]
:fn #(run install-fn %)
:args->opts [:script/lib]
:aliases {:T :tool}}
{:cmds ["uninstall"]
:fn #(run uninstall-fn %)
:args->opts [:script/lib]}
{:cmds ["ls"]
:fn #(run ls-fn %)}
{:cmds ["bin"]
:fn #(run bin-fn %)}
{:cmds ["version"]
:fn #(run util/print-version %)}
{:cmds []
:fn #(run util/print-help %)}])
(defn- full-commands [& {:as run-opts}]
(add-global-aliases (base-commands run-opts)))
(defn- print-commands [_]
(println (str/join " " (keep #(first (:cmds %)) (full-commands)))))
(def default-run-opts
{:install-fn scripts/install
:uninstall-fn scripts/uninstall
:ls-fn scripts/ls
:bin-fn scripts/bin})
(defn bbin [main-args & {:as run-opts}]
(let [run-opts' (merge default-run-opts run-opts)]
(util/set-logging-config! (cli/parse-opts main-args))
(cli/dispatch (full-commands run-opts') main-args {})))
(defn -main [& args]
(bbin args))
(when (= *file* (System/getProperty "babashka.file"))
(util/check-min-bb-version)
(apply -main *command-line-args*))
| null | https://raw.githubusercontent.com/babashka/bbin/6fde1b1dbfaef3063eb1eba4899a730bf703c792/src/babashka/bbin/cli.clj | clojure | (ns babashka.bbin.cli
(:require [babashka.cli :as cli]
[babashka.bbin.scripts :as scripts]
[babashka.bbin.util :as util]
[clojure.string :as str]))
(declare print-commands)
(defn- run [command-fn {:keys [opts]}]
(util/check-legacy-paths)
(if (and (:version opts) (not (:help opts)))
(util/print-version)
(command-fn opts)))
(defn- add-global-aliases [commands]
(map #(assoc-in % [:aliases :h] :help) commands))
(defn- base-commands
[& {:keys [install-fn uninstall-fn ls-fn bin-fn]}]
[{:cmds ["commands"]
:fn #(run print-commands %)}
{:cmds ["help"]
:fn #(run util/print-help %)}
{:cmds ["install"]
:fn #(run install-fn %)
:args->opts [:script/lib]
:aliases {:T :tool}}
{:cmds ["uninstall"]
:fn #(run uninstall-fn %)
:args->opts [:script/lib]}
{:cmds ["ls"]
:fn #(run ls-fn %)}
{:cmds ["bin"]
:fn #(run bin-fn %)}
{:cmds ["version"]
:fn #(run util/print-version %)}
{:cmds []
:fn #(run util/print-help %)}])
(defn- full-commands [& {:as run-opts}]
(add-global-aliases (base-commands run-opts)))
(defn- print-commands [_]
(println (str/join " " (keep #(first (:cmds %)) (full-commands)))))
(def default-run-opts
{:install-fn scripts/install
:uninstall-fn scripts/uninstall
:ls-fn scripts/ls
:bin-fn scripts/bin})
(defn bbin [main-args & {:as run-opts}]
(let [run-opts' (merge default-run-opts run-opts)]
(util/set-logging-config! (cli/parse-opts main-args))
(cli/dispatch (full-commands run-opts') main-args {})))
(defn -main [& args]
(bbin args))
(when (= *file* (System/getProperty "babashka.file"))
(util/check-min-bb-version)
(apply -main *command-line-args*))
|
|
42b6a9bb7b06ee80064c81f703debf1510e28762a46338b88a290c09419a7246 | jaspervdj/digestive-functors | QTests.hs | --------------------------------------------------------------------------------
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - orphans #
module Text.Digestive.Form.QTests
( tests
) where
--------------------------------------------------------------------------------
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck hiding (Success)
--------------------------------------------------------------------------------
import Text.Digestive.Form.Internal
import Text.Digestive.Form.Internal.Field
import Text.Digestive.Types
--------------------------------------------------------------------------------
import Control.Monad
import Control.Monad.Identity
import Data.Maybe
import Data.Monoid (Monoid)
import Data.Text (Text, pack)
--------------------------------------------------------------------------------
tests :: Test
tests = testGroup "Text.Digestive.Types.Tests"
[
testProperty "Mapping consistency" prop_viewcons
, testProperty "Label consistency - map" prop_refcons
, testProperty "Child count consistency - label" prop_pushcons
, testProperty "Labelling consistency - monadic" prop_refmoncons
]
--------------------------------------------------------------------------------
-- Mapping on the view does not change the child count
prop_viewcons :: FormTree Identity String Identity Int -> Bool
prop_viewcons ft = (length . children $ ft) ==
(length . children $ formMapView (length) ft)
--------------------------------------------------------------------------------
-- Adding a label does not change the child count
prop_pushcons :: FormTree Identity String Identity Int -> Bool
prop_pushcons ft = lc ft == lc ("empty" .: ft)
where lc = length . children
--------------------------------------------------------------------------------
-- Sanity check - adding a ref and popping it yields the same Result
prop_refcons :: Text -> FormTree Identity String Identity Int -> Bool
prop_refcons ref ft = isJust ref' && fromJust ref' == ref
where ref' = getRef (ref .: ft)
--------------------------------------------------------------------------------
-- Sanity check - monadic wrap does not affect reference consistency
prop_refmoncons :: Text -> FormTree Identity String Identity Int -> Bool
prop_refmoncons ref ft = isJust ref' && fromJust ref' == ref
where ref' = getRef (monadic . return $ (ref .: ft))
--------------------------------------------------------------------------------
Limited arbitrary instance for form trees
instance (Monad t, Monad m, Monoid v, Arbitrary a) => Arbitrary (FormTree t v m a)
where arbitrary = sized (innerarb $ liftM Pure arbitrary)
where innerarb g 0 = g
innerarb g n = innerarb g' (n-1)
where g' = oneof
[
arbitrary >>= \r -> liftM (Ref r) g
,liftM (Monadic . return) g
,liftM (Map (return . Success . id)) g
,liftM2 App (liftM (fmap const) g) g
]
--------------------------------------------------------------------------------
Arbitrary SomeFields - encompasses all field types except for choice .
instance (Arbitrary v) => Arbitrary (SomeField v)
where arbitrary =
oneof [
liftM (SomeField . Singleton) (arbitrary :: Gen Int)
, liftM (SomeField . Text) arbitrary
, liftM (SomeField . Bool) arbitrary
, liftM SomeField $ elements [File]
]
--------------------------------------------------------------------------------
Arbitrary Fields - limited to Singleton fields
instance (Arbitrary a) => Arbitrary (Field v a)
where arbitrary = liftM Singleton (arbitrary)
--------------------------------------------------------------------------------
-- Arbitrary Text - should be factored out
instance Arbitrary Text
where arbitrary = liftM pack arbitrary
--------------------------------------------------------------------------------
-- Show instance - should probably be moved to Field.hs
instance (Show v) => Show (SomeField v)
where show (SomeField f) = show f
| null | https://raw.githubusercontent.com/jaspervdj/digestive-functors/5827b47404a93b103cc57ad0f54f4dc0bdf94e24/digestive-functors/tests/Text/Digestive/Form/QTests.hs | haskell | ------------------------------------------------------------------------------
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Mapping on the view does not change the child count
------------------------------------------------------------------------------
Adding a label does not change the child count
------------------------------------------------------------------------------
Sanity check - adding a ref and popping it yields the same Result
------------------------------------------------------------------------------
Sanity check - monadic wrap does not affect reference consistency
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Arbitrary Text - should be factored out
------------------------------------------------------------------------------
Show instance - should probably be moved to Field.hs | # OPTIONS_GHC -fno - warn - orphans #
module Text.Digestive.Form.QTests
( tests
) where
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck hiding (Success)
import Text.Digestive.Form.Internal
import Text.Digestive.Form.Internal.Field
import Text.Digestive.Types
import Control.Monad
import Control.Monad.Identity
import Data.Maybe
import Data.Monoid (Monoid)
import Data.Text (Text, pack)
tests :: Test
tests = testGroup "Text.Digestive.Types.Tests"
[
testProperty "Mapping consistency" prop_viewcons
, testProperty "Label consistency - map" prop_refcons
, testProperty "Child count consistency - label" prop_pushcons
, testProperty "Labelling consistency - monadic" prop_refmoncons
]
prop_viewcons :: FormTree Identity String Identity Int -> Bool
prop_viewcons ft = (length . children $ ft) ==
(length . children $ formMapView (length) ft)
prop_pushcons :: FormTree Identity String Identity Int -> Bool
prop_pushcons ft = lc ft == lc ("empty" .: ft)
where lc = length . children
prop_refcons :: Text -> FormTree Identity String Identity Int -> Bool
prop_refcons ref ft = isJust ref' && fromJust ref' == ref
where ref' = getRef (ref .: ft)
prop_refmoncons :: Text -> FormTree Identity String Identity Int -> Bool
prop_refmoncons ref ft = isJust ref' && fromJust ref' == ref
where ref' = getRef (monadic . return $ (ref .: ft))
Limited arbitrary instance for form trees
instance (Monad t, Monad m, Monoid v, Arbitrary a) => Arbitrary (FormTree t v m a)
where arbitrary = sized (innerarb $ liftM Pure arbitrary)
where innerarb g 0 = g
innerarb g n = innerarb g' (n-1)
where g' = oneof
[
arbitrary >>= \r -> liftM (Ref r) g
,liftM (Monadic . return) g
,liftM (Map (return . Success . id)) g
,liftM2 App (liftM (fmap const) g) g
]
Arbitrary SomeFields - encompasses all field types except for choice .
instance (Arbitrary v) => Arbitrary (SomeField v)
where arbitrary =
oneof [
liftM (SomeField . Singleton) (arbitrary :: Gen Int)
, liftM (SomeField . Text) arbitrary
, liftM (SomeField . Bool) arbitrary
, liftM SomeField $ elements [File]
]
Arbitrary Fields - limited to Singleton fields
instance (Arbitrary a) => Arbitrary (Field v a)
where arbitrary = liftM Singleton (arbitrary)
instance Arbitrary Text
where arbitrary = liftM pack arbitrary
instance (Show v) => Show (SomeField v)
where show (SomeField f) = show f
|
3a1f00cafbc2fb0779642b92994042b919734d4d5598c3278b169349af646b4d | ardoq/ardoq-docker-compose-addon | client.clj | (ns ardoq.client
(:require [org.httpkit.client :as http]
[clojure.data.json :as json]))
(defprotocol ArdoqResource
(resource-path [this]))
(defrecord Workspace [name description componentTemplate]
ArdoqResource
(resource-path [_] "workspace"))
(defn workspace []
(map->Workspace {}))
(defrecord Component [name description rootWorkspace model typeId parent]
ArdoqResource
(resource-path [_] "component"))
(defrecord Model [name description]
ArdoqResource
(resource-path [_] "model"))
(defn model []
(map->Model {}))
(defrecord Reference [rootWorkspace source target]
ArdoqResource
(resource-path [_] "reference"))
(defrecord Field [label name type model componentType]
ArdoqResource
(resource-path [_] "field"))
(defrecord Tag [name description rootWorkspace components references]
ArdoqResource
(resource-path [_] "tag"))
(defn- to-component-type-map
"Takes the root of a model and flattens it returning a typeId->type-map map"
[model]
(when model
(letfn [(flatten-model [nodes res]
(if (empty? nodes)
res
(let [{id :id children :children :as node} (first nodes)
r (assoc res (keyword id) (update-in node [:children] #(vec (map (comp name first) %))))
updated-children (map (fn [[_ i]] (assoc i :parent id)) children)]
(flatten-model (concat (rest nodes) updated-children) r))))]
(flatten-model (map (fn [[_ i]] (assoc i :parent nil)) (:root model)) {}))))
(defn type-id-by-name [model type-name]
(some->> (to-component-type-map model)
(vals)
(filter #(= type-name (:name %)))
(first)
(:id)))
(defn client [{:keys [url token org]}]
(let [default-options {:timeout 2000
:query-params {:org org}}
client {:url url
:options (merge-with merge default-options {:headers {"Authorization" (str "Token token=" token)
"Content-Type" "application/json"
"User-Agent" "ardoq-clojure-client"}})}]
(println "Client configuration: " client)
client))
(defn- ok? [status]
(and (< status 300)
(> status 199)))
(defn- new-by-name
[class-name & args]
(clojure.lang.Reflector/invokeStaticMethod
(clojure.lang.RT/classForName class-name)
"create"
(into-array Object args)))
(defn- coerce-response [resource data]
(new-by-name (.getName (class resource)) data))
(defn find-by-id [resource client]
(let [url (str (:url client) "/api/" (resource-path resource) "/" (:_id resource))
{:keys [status body]} @(http/get url (:options client))]
(cond
(ok? status) (coerce-response resource (json/read-json body true))
:else (throw (ex-info "client-exception" {:status status :body body})))))
(defn find-all [resource client & parameters]
(let [url (str (:url client) "/api/" (resource-path resource) (first parameters))
{:keys [status body]} @(http/get url (:options client))]
(cond
(ok? status) (map (partial coerce-response resource) (json/read-json body true))
:else (throw (ex-info "client-exception" {:status status :body body})))))
(defn create [resource client]
(let [url (str (:url client) "/api/" (resource-path resource))
{:keys [status body]} @(http/post url (assoc (:options client) :body (json/write-str resource)))]
(cond
(ok? status) (coerce-response resource (json/read-json body true))
:else (throw (ex-info "client-exception" {:status status :body body})))))
(defn update [resource client]
(let [url (str (:url client) "/api/" (resource-path resource) "/" (:_id resource))
{:keys [status body]} @(http/put url (assoc (:options client) :body (json/write-str resource)))]
(cond
(ok? status) (coerce-response resource (json/read-json body true))
:else (throw (ex-info "client-exception" {:status status :body body})))))
(defn delete [resource client]
(let [url (str (:url client) "/api/" (resource-path resource) "/" (:_id resource))
{:keys [status body]} @(http/delete url (:options client))]
(if-not (ok? status)
(throw (ex-info "client-exception" {:status status :body body})))))
(defn aggregated-workspace [resource client]
(let [url (str (:url client) "/api/" (resource-path resource) "/" (:_id resource) "/aggregated")
{:keys [status body]} @(http/get url (:options client))]
(if-not (ok? status)
(throw (ex-info "client-exception" {:status status :body body})))))
(defn find-or-create-model [client model]
(if-let [model (first (filter #(= model (:name %)) (find-all (map->Model {}) client)))]
model
(if-let [model (first (filter #(= model (:name %)) (find-all (map->Model {}) client "?includeCommon=true")))]
(create model client))))
| null | https://raw.githubusercontent.com/ardoq/ardoq-docker-compose-addon/be09e3bbdef819a4f47411d7b784e3d5906e5c44/src/ardoq/client.clj | clojure | (ns ardoq.client
(:require [org.httpkit.client :as http]
[clojure.data.json :as json]))
(defprotocol ArdoqResource
(resource-path [this]))
(defrecord Workspace [name description componentTemplate]
ArdoqResource
(resource-path [_] "workspace"))
(defn workspace []
(map->Workspace {}))
(defrecord Component [name description rootWorkspace model typeId parent]
ArdoqResource
(resource-path [_] "component"))
(defrecord Model [name description]
ArdoqResource
(resource-path [_] "model"))
(defn model []
(map->Model {}))
(defrecord Reference [rootWorkspace source target]
ArdoqResource
(resource-path [_] "reference"))
(defrecord Field [label name type model componentType]
ArdoqResource
(resource-path [_] "field"))
(defrecord Tag [name description rootWorkspace components references]
ArdoqResource
(resource-path [_] "tag"))
(defn- to-component-type-map
"Takes the root of a model and flattens it returning a typeId->type-map map"
[model]
(when model
(letfn [(flatten-model [nodes res]
(if (empty? nodes)
res
(let [{id :id children :children :as node} (first nodes)
r (assoc res (keyword id) (update-in node [:children] #(vec (map (comp name first) %))))
updated-children (map (fn [[_ i]] (assoc i :parent id)) children)]
(flatten-model (concat (rest nodes) updated-children) r))))]
(flatten-model (map (fn [[_ i]] (assoc i :parent nil)) (:root model)) {}))))
(defn type-id-by-name [model type-name]
(some->> (to-component-type-map model)
(vals)
(filter #(= type-name (:name %)))
(first)
(:id)))
(defn client [{:keys [url token org]}]
(let [default-options {:timeout 2000
:query-params {:org org}}
client {:url url
:options (merge-with merge default-options {:headers {"Authorization" (str "Token token=" token)
"Content-Type" "application/json"
"User-Agent" "ardoq-clojure-client"}})}]
(println "Client configuration: " client)
client))
(defn- ok? [status]
(and (< status 300)
(> status 199)))
(defn- new-by-name
[class-name & args]
(clojure.lang.Reflector/invokeStaticMethod
(clojure.lang.RT/classForName class-name)
"create"
(into-array Object args)))
(defn- coerce-response [resource data]
(new-by-name (.getName (class resource)) data))
(defn find-by-id [resource client]
(let [url (str (:url client) "/api/" (resource-path resource) "/" (:_id resource))
{:keys [status body]} @(http/get url (:options client))]
(cond
(ok? status) (coerce-response resource (json/read-json body true))
:else (throw (ex-info "client-exception" {:status status :body body})))))
(defn find-all [resource client & parameters]
(let [url (str (:url client) "/api/" (resource-path resource) (first parameters))
{:keys [status body]} @(http/get url (:options client))]
(cond
(ok? status) (map (partial coerce-response resource) (json/read-json body true))
:else (throw (ex-info "client-exception" {:status status :body body})))))
(defn create [resource client]
(let [url (str (:url client) "/api/" (resource-path resource))
{:keys [status body]} @(http/post url (assoc (:options client) :body (json/write-str resource)))]
(cond
(ok? status) (coerce-response resource (json/read-json body true))
:else (throw (ex-info "client-exception" {:status status :body body})))))
(defn update [resource client]
(let [url (str (:url client) "/api/" (resource-path resource) "/" (:_id resource))
{:keys [status body]} @(http/put url (assoc (:options client) :body (json/write-str resource)))]
(cond
(ok? status) (coerce-response resource (json/read-json body true))
:else (throw (ex-info "client-exception" {:status status :body body})))))
(defn delete [resource client]
(let [url (str (:url client) "/api/" (resource-path resource) "/" (:_id resource))
{:keys [status body]} @(http/delete url (:options client))]
(if-not (ok? status)
(throw (ex-info "client-exception" {:status status :body body})))))
(defn aggregated-workspace [resource client]
(let [url (str (:url client) "/api/" (resource-path resource) "/" (:_id resource) "/aggregated")
{:keys [status body]} @(http/get url (:options client))]
(if-not (ok? status)
(throw (ex-info "client-exception" {:status status :body body})))))
(defn find-or-create-model [client model]
(if-let [model (first (filter #(= model (:name %)) (find-all (map->Model {}) client)))]
model
(if-let [model (first (filter #(= model (:name %)) (find-all (map->Model {}) client "?includeCommon=true")))]
(create model client))))
|
|
45809b8ee92a497df82e327f3c73c5d574a170d9fd74671393507bf6feff95af | mzp/coq-ruby | heap.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : heap.mli 6621 2005 - 01 - 21 17:24:37Z herbelin $ i
(* Heaps *)
module type Ordered = sig
type t
val compare : t -> t -> int
end
module type S =sig
(* Type of functional heaps *)
type t
(* Type of elements *)
type elt
(* The empty heap *)
val empty : t
(* [add x h] returns a new heap containing the elements of [h], plus [x];
complexity $O(log(n))$ *)
val add : elt -> t -> t
(* [maximum h] returns the maximum element of [h]; raises [EmptyHeap]
when [h] is empty; complexity $O(1)$ *)
val maximum : t -> elt
(* [remove h] returns a new heap containing the elements of [h], except
the maximum of [h]; raises [EmptyHeap] when [h] is empty;
complexity $O(log(n))$ *)
val remove : t -> t
(* usual iterators and combinators; elements are presented in
arbitrary order *)
val iter : (elt -> unit) -> t -> unit
val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
end
exception EmptyHeap
(*S Functional implementation. *)
module Functional(X: Ordered) : S with type elt=X.t
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/lib/heap.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Heaps
Type of functional heaps
Type of elements
The empty heap
[add x h] returns a new heap containing the elements of [h], plus [x];
complexity $O(log(n))$
[maximum h] returns the maximum element of [h]; raises [EmptyHeap]
when [h] is empty; complexity $O(1)$
[remove h] returns a new heap containing the elements of [h], except
the maximum of [h]; raises [EmptyHeap] when [h] is empty;
complexity $O(log(n))$
usual iterators and combinators; elements are presented in
arbitrary order
S Functional implementation. | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : heap.mli 6621 2005 - 01 - 21 17:24:37Z herbelin $ i
module type Ordered = sig
type t
val compare : t -> t -> int
end
module type S =sig
type t
type elt
val empty : t
val add : elt -> t -> t
val maximum : t -> elt
val remove : t -> t
val iter : (elt -> unit) -> t -> unit
val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
end
exception EmptyHeap
module Functional(X: Ordered) : S with type elt=X.t
|
2b7a2b3c78335e4c57f59cffdec2e1d306f9fccde7ed2b54c6aa90bac1bd491f | OCamlPro/liquidity | liquidNamespace.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 </>. *)
(****************************************************************************)
open LiquidTypes
exception Unknown_namespace of string list * location
type 'a namespace_res =
| Current_namespace
| Contract_namespace of 'a contract * string list
(* Recursively look for value in (projection of) upper level contracts *)
let rec rec_find ?(quiet=false) s env proj =
try StringMap.find s (proj env), env
with Not_found ->
match env.top_env with
| None -> raise Not_found
| Some top_env ->
if not env.is_module && !LiquidOptions.target_lang = Love_lang then begin
if not quiet then
Format.eprintf "Contracts must be self contained in Love. \
%S was not found in contract %s.@." s env.contractname;
raise Not_found
end
else
rec_find ~quiet s top_env proj
let unqualify s =
match List.rev (String.split_on_char '.' s) with
| [] -> assert false
| s :: rpath -> List.rev rpath, s
let common_path p1 p2 =
let rec aux acc p1 p2 = match p1, p2 with
| [], _ | _, [] -> List.rev acc, p1, p2
| x1 :: p1, x2 :: p2 ->
if x1 = x2 then aux (x1 :: acc) p1 p2
else List.rev acc, x1 :: p1, x2 :: p2 in
aux [] p1 p2
let qualify_name ?from_env ~at s =
let from = match from_env with
| Some e -> e.path
| None -> [] (* top level *) in
let _common, _remain_from, path = common_path from at in
String.concat "." (path @ [snd @@ unqualify s])
let add_path_name path s = String.concat "." (path @ [s])
(* Find namespace in a tree of (sub-)contracts *)
let find_namespace ~loc fullpath subs =
match fullpath with
| [] -> Current_namespace
| _ ->
let rec find reached_path path subs =
match path with
| [] -> raise (Unknown_namespace (fullpath, loc))
| [p] ->
begin
try Contract_namespace
(List.find (fun c -> c.contract_name = p) subs,
List.rev reached_path)
with Not_found -> raise (Unknown_namespace (fullpath, loc))
end
| p :: path ->
try
let c = List.find (fun c -> c.contract_name = p) subs in
find (p :: reached_path) path c.subs
with Not_found -> raise (Unknown_namespace (fullpath, loc))
in
find [] fullpath subs
(* Lookup for a qualified value in the corresponding
namespace or upper levels *)
(* let rec_lookup ~loc env contracts (path, s) proj =
* match find_namespace ~loc path contracts with
* | Current_namespace -> rec_find s env proj
* | Contract_namespace (c, path) ->
* StringMap.find s (proj c.ty_env), c.ty_env *)
let rec find_env ~loc fullpath path env =
match path with
| [] -> env
| p :: path ->
let env =
try StringMap.find p env.others
with Not_found ->
if StringMap.mem p env.unreachable_others then
LiquidLoc.warn loc
(WOther (Printf.sprintf
"Namespace %s is known \
but not reachable when compiling to Love, \
contracts must be self-contained"
(String.concat "." fullpath)));
raise (Unknown_namespace (fullpath, loc))
in
find_env ~loc fullpath path env
let find_env ~loc path env = find_env ~loc path path env
let unalias path env =
try
let e = find_env ~loc:noloc path env in
if e.path = env.path @ path then None
else Some e.path
with Unknown_namespace _ -> None
let rec find ?quiet ~loc s env proj =
let path, s = unqualify s in
let env = find_env ~loc path env in
if path = [] then
rec_find ?quiet s env proj
else
StringMap.find s (proj env), env
let find_type ~loc s env subst =
let (mk, _), found_env = find ~loc s env (fun env -> env.types) in
mk subst, found_env
(* Necessary for encoding phases where some dependencies information
is not kept *)
let rec find_type_loose ~loc s env subst =
try find_type ~loc s env subst
with (Not_found | Unknown_namespace _ as e) ->
StringMap.fold (fun _ env acc ->
match acc with
| Some _ -> acc
| None ->
try Some (find_type_loose ~loc s env subst)
with Not_found | Unknown_namespace _ -> None
) env.others None
|> function
| Some res -> res
| None -> match env.top_env with
| None -> raise e
| Some env -> find_type_loose ~loc s env subst
let rec find_contract_type_aux ~loc s env =
let path, tn = unqualify s in
let qs = match unalias (path @ [tn]) env with
| None -> s
| Some p -> String.concat "." p in
try find ~loc qs env (fun env -> env.contract_types)
with (Not_found | Unknown_namespace _ as e) ->
match env.top_env with
| None -> raise e
| Some env -> find_contract_type_aux ~loc s env
let rec normalize_type ?from_env ~in_env ty =
match ty with
| Tunit | Tbool | Tint | Tnat | Ttez | Tstring | Tbytes | Ttimestamp
| Tkey | Tkey_hash | Tsignature | Toperation | Taddress | Tfail | Tchainid ->
ty
| Ttuple l -> Ttuple (List.map (normalize_type ?from_env ~in_env) l)
| Toption t -> Toption (normalize_type ?from_env ~in_env t)
| Tlist t -> Tlist (normalize_type ?from_env ~in_env t)
| Tset t -> Tset (normalize_type ?from_env ~in_env t)
| Tmap (t1, t2) ->
Tmap (normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2)
| Tbigmap (t1, t2) ->
Tbigmap (normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2)
| Tor (t1, t2) ->
Tor (normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2)
| Tlambda (t1, t2, u) ->
Tlambda (normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2, u)
| Tcontract_handle (e, ty) ->
Tcontract_handle (e, normalize_type ?from_env ~in_env ty)
| Tcontract_view (v, t1, t2) ->
Tcontract_view (v,
normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2)
| Tcontract c_sig ->
Tcontract (normalize_contract_sig ?from_env ~in_env ~build_sig_env:false c_sig)
| Trecord (name, fields) ->
let _, found_env =
try find_type_loose ~loc:noloc name in_env []
with Not_found | Unknown_namespace _ -> assert false in
Trecord (qualify_name ?from_env ~at:found_env.path name,
List.map (fun (f, ty) ->
qualify_name ?from_env ~at:found_env.path f,
normalize_type ?from_env ~in_env ty) fields)
| Tsum (None, constrs) ->
Tsum (None,
List.map (fun (c, ty) ->
c, normalize_type ?from_env ~in_env ty) constrs)
| Tsum (Some name, constrs) ->
let _, found_env =
try find_type_loose ~loc:noloc name in_env []
with Not_found | Unknown_namespace _ -> assert false in
Tsum (Some (qualify_name ?from_env ~at:found_env.path name),
List.map (fun (c, ty) ->
qualify_name ?from_env ~at:found_env.path c,
normalize_type ?from_env ~in_env ty) constrs)
| Tclosure ((t1, t2), t3, u) ->
Tclosure ((normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2),
normalize_type ?from_env ~in_env t3, u)
| Tvar tvr ->
let tv = Ref.get tvr in
begin match tv.tyo with
| None -> ty
| Some ty2 ->
(Ref.set tvr)
{ tv with tyo = Some (normalize_type ?from_env ~in_env ty2) };
ty
end
| Tpartial _ -> raise (Invalid_argument "normalize_type")
and normalize_contract_sig ?from_env ~in_env ~build_sig_env c_sig =
match c_sig.sig_name with
TODO
| Some s ->
let rec env_of_contract_type_name s env =
try find_contract_type_aux ~loc:noloc s env |> snd
with (Not_found | Unknown_namespace _ as e) ->
StringMap.fold (fun _ env acc ->
match acc with
| Some _ -> acc
| None ->
try Some (env_of_contract_type_name s env)
with Not_found | Unknown_namespace _ -> None
) env.others None
|> function
| None -> raise e
| Some env -> env in
let found_env = env_of_contract_type_name s in_env in
let sig_env =
if not build_sig_env then in_env
else
try find_env ~loc:noloc ( [unqualify s |> snd]) found_env
with Not_found | Unknown_namespace _ ->
(* for built-in signatures *)
found_env
in
{ sig_name = Some (qualify_name ?from_env ~at:found_env.path s);
entries_sig =
List.map (fun e ->
{ e with
parameter = normalize_type ?from_env ~in_env:sig_env e.parameter;
return = match e.return with
| None -> None
| Some r -> Some (normalize_type ?from_env ~in_env:sig_env r)
}
) c_sig.entries_sig }
let find_type ~loc s env subst =
let ty, found_env = find_type ~loc s env subst in
normalize_type ~from_env:env ~in_env:found_env ty
let find_contract_type ~loc s env =
let csig, found_env = find_contract_type_aux ~loc s env in
normalize_contract_sig ~from_env:env ~in_env:found_env ~build_sig_env:true csig
let find_label_ty_name ~loc s env =
let (tn, i), found_env = find ~loc s env (fun env -> env.labels) in
tn, i, found_env
let find_constr_ty_name ~loc s env =
let (tn, i), found_env = find ~loc s env (fun env -> env.constrs) in
tn, i, found_env
let find_label ~loc s env =
let n, i, found_env = find_label_ty_name ~loc s env in
let ty = find_type ~loc n found_env [] in
let ty = normalize_type ~from_env:env ~in_env:found_env ty in
let label_name, label_ty = match ty with
| Trecord (_, l) -> List.nth l i
| _ -> assert false in
ty, (label_name, label_ty, i)
let find_constr ~loc s env =
let n, i, found_env = find_constr_ty_name ~loc s env in
let ty = find_type ~loc n found_env [] in
let ty = normalize_type ~from_env:env ~in_env:found_env ty in
let constr_name, constr_ty = match ty with
| Tsum (_, l) -> List.nth l i
| _ -> assert false in
ty, (constr_name, constr_ty, i)
let find_extprim ?quiet ~loc s env =
let e, found_env = find ?quiet ~loc s env (fun env -> env.ext_prims) in
{ e with
atys = List.map (normalize_type ~from_env:env ~in_env:found_env) e.atys;
rty = normalize_type ~from_env:env ~in_env:found_env e.rty }
let is_extprim s env =
try find_extprim ~quiet:true ~loc:noloc s env |> ignore; true
with Not_found | Unknown_namespace _ -> false
let find_extprim ~loc s env = find_extprim ~loc s env
(* ------------------------- *)
(* Precondition: s must be unaliased (call with unalias_name s) *)
let lookup_global_value ~loc s env =
let path, s = unqualify s in
let path = match unalias path env.env with
| None -> path
| Some path -> path in
match find_namespace ~loc path env.visible_contracts with
| Current_namespace -> raise Not_found
| Contract_namespace (c, _) ->
let v = List.find (fun v -> not v.val_private && v.val_name = s) c.values in
let ty = normalize_type
~from_env:env.env
~in_env:c.ty_env v.val_exp.ty in
{ v with val_exp = { v.val_exp with ty } }
| exception Unknown_namespace (
["Current" | "Account" | "Map" | "Set" | "List" | "Contract"
| "Crypto" | "Bytes" | "String" ], _ ) ->
(* Better error messages for typos *)
raise Not_found
let find_contract ~loc s env contracts =
let path, s = unqualify s in
let path = match unalias path env with
| None -> path
| Some path -> path in
match find_namespace ~loc path (StringMap.bindings contracts |> List.map snd) with
| Current_namespace ->
StringMap.find s contracts
| Contract_namespace (c, _) ->
List.find (fun c -> c.contract_name = s) c.subs
let find_module ~loc path env contracts =
let path = match unalias path env with
| None -> path
| Some path -> path in
match find_namespace ~loc path contracts with
| Current_namespace -> raise Not_found
| Contract_namespace (c, _) -> c
let qual_contract_name c =
match c.ty_env.path with
| [] -> c.contract_name
| p -> String.concat "." p
let unalias_name s env =
let path, s' = unqualify s in
match unalias path env with
| None -> s
| Some path -> add_path_name path s'
| null | https://raw.githubusercontent.com/OCamlPro/liquidity/3578de34cf751f54b9e4c001a95625d2041b2962/tools/liquidity/liquidNamespace.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 </>.
**************************************************************************
Recursively look for value in (projection of) upper level contracts
top level
Find namespace in a tree of (sub-)contracts
Lookup for a qualified value in the corresponding
namespace or upper levels
let rec_lookup ~loc env contracts (path, s) proj =
* match find_namespace ~loc path contracts with
* | Current_namespace -> rec_find s env proj
* | Contract_namespace (c, path) ->
* StringMap.find s (proj c.ty_env), c.ty_env
Necessary for encoding phases where some dependencies information
is not kept
for built-in signatures
-------------------------
Precondition: s must be unaliased (call with unalias_name s)
Better error messages for typos | 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
open LiquidTypes
exception Unknown_namespace of string list * location
type 'a namespace_res =
| Current_namespace
| Contract_namespace of 'a contract * string list
let rec rec_find ?(quiet=false) s env proj =
try StringMap.find s (proj env), env
with Not_found ->
match env.top_env with
| None -> raise Not_found
| Some top_env ->
if not env.is_module && !LiquidOptions.target_lang = Love_lang then begin
if not quiet then
Format.eprintf "Contracts must be self contained in Love. \
%S was not found in contract %s.@." s env.contractname;
raise Not_found
end
else
rec_find ~quiet s top_env proj
let unqualify s =
match List.rev (String.split_on_char '.' s) with
| [] -> assert false
| s :: rpath -> List.rev rpath, s
let common_path p1 p2 =
let rec aux acc p1 p2 = match p1, p2 with
| [], _ | _, [] -> List.rev acc, p1, p2
| x1 :: p1, x2 :: p2 ->
if x1 = x2 then aux (x1 :: acc) p1 p2
else List.rev acc, x1 :: p1, x2 :: p2 in
aux [] p1 p2
let qualify_name ?from_env ~at s =
let from = match from_env with
| Some e -> e.path
let _common, _remain_from, path = common_path from at in
String.concat "." (path @ [snd @@ unqualify s])
let add_path_name path s = String.concat "." (path @ [s])
let find_namespace ~loc fullpath subs =
match fullpath with
| [] -> Current_namespace
| _ ->
let rec find reached_path path subs =
match path with
| [] -> raise (Unknown_namespace (fullpath, loc))
| [p] ->
begin
try Contract_namespace
(List.find (fun c -> c.contract_name = p) subs,
List.rev reached_path)
with Not_found -> raise (Unknown_namespace (fullpath, loc))
end
| p :: path ->
try
let c = List.find (fun c -> c.contract_name = p) subs in
find (p :: reached_path) path c.subs
with Not_found -> raise (Unknown_namespace (fullpath, loc))
in
find [] fullpath subs
let rec find_env ~loc fullpath path env =
match path with
| [] -> env
| p :: path ->
let env =
try StringMap.find p env.others
with Not_found ->
if StringMap.mem p env.unreachable_others then
LiquidLoc.warn loc
(WOther (Printf.sprintf
"Namespace %s is known \
but not reachable when compiling to Love, \
contracts must be self-contained"
(String.concat "." fullpath)));
raise (Unknown_namespace (fullpath, loc))
in
find_env ~loc fullpath path env
let find_env ~loc path env = find_env ~loc path path env
let unalias path env =
try
let e = find_env ~loc:noloc path env in
if e.path = env.path @ path then None
else Some e.path
with Unknown_namespace _ -> None
let rec find ?quiet ~loc s env proj =
let path, s = unqualify s in
let env = find_env ~loc path env in
if path = [] then
rec_find ?quiet s env proj
else
StringMap.find s (proj env), env
let find_type ~loc s env subst =
let (mk, _), found_env = find ~loc s env (fun env -> env.types) in
mk subst, found_env
let rec find_type_loose ~loc s env subst =
try find_type ~loc s env subst
with (Not_found | Unknown_namespace _ as e) ->
StringMap.fold (fun _ env acc ->
match acc with
| Some _ -> acc
| None ->
try Some (find_type_loose ~loc s env subst)
with Not_found | Unknown_namespace _ -> None
) env.others None
|> function
| Some res -> res
| None -> match env.top_env with
| None -> raise e
| Some env -> find_type_loose ~loc s env subst
let rec find_contract_type_aux ~loc s env =
let path, tn = unqualify s in
let qs = match unalias (path @ [tn]) env with
| None -> s
| Some p -> String.concat "." p in
try find ~loc qs env (fun env -> env.contract_types)
with (Not_found | Unknown_namespace _ as e) ->
match env.top_env with
| None -> raise e
| Some env -> find_contract_type_aux ~loc s env
let rec normalize_type ?from_env ~in_env ty =
match ty with
| Tunit | Tbool | Tint | Tnat | Ttez | Tstring | Tbytes | Ttimestamp
| Tkey | Tkey_hash | Tsignature | Toperation | Taddress | Tfail | Tchainid ->
ty
| Ttuple l -> Ttuple (List.map (normalize_type ?from_env ~in_env) l)
| Toption t -> Toption (normalize_type ?from_env ~in_env t)
| Tlist t -> Tlist (normalize_type ?from_env ~in_env t)
| Tset t -> Tset (normalize_type ?from_env ~in_env t)
| Tmap (t1, t2) ->
Tmap (normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2)
| Tbigmap (t1, t2) ->
Tbigmap (normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2)
| Tor (t1, t2) ->
Tor (normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2)
| Tlambda (t1, t2, u) ->
Tlambda (normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2, u)
| Tcontract_handle (e, ty) ->
Tcontract_handle (e, normalize_type ?from_env ~in_env ty)
| Tcontract_view (v, t1, t2) ->
Tcontract_view (v,
normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2)
| Tcontract c_sig ->
Tcontract (normalize_contract_sig ?from_env ~in_env ~build_sig_env:false c_sig)
| Trecord (name, fields) ->
let _, found_env =
try find_type_loose ~loc:noloc name in_env []
with Not_found | Unknown_namespace _ -> assert false in
Trecord (qualify_name ?from_env ~at:found_env.path name,
List.map (fun (f, ty) ->
qualify_name ?from_env ~at:found_env.path f,
normalize_type ?from_env ~in_env ty) fields)
| Tsum (None, constrs) ->
Tsum (None,
List.map (fun (c, ty) ->
c, normalize_type ?from_env ~in_env ty) constrs)
| Tsum (Some name, constrs) ->
let _, found_env =
try find_type_loose ~loc:noloc name in_env []
with Not_found | Unknown_namespace _ -> assert false in
Tsum (Some (qualify_name ?from_env ~at:found_env.path name),
List.map (fun (c, ty) ->
qualify_name ?from_env ~at:found_env.path c,
normalize_type ?from_env ~in_env ty) constrs)
| Tclosure ((t1, t2), t3, u) ->
Tclosure ((normalize_type ?from_env ~in_env t1,
normalize_type ?from_env ~in_env t2),
normalize_type ?from_env ~in_env t3, u)
| Tvar tvr ->
let tv = Ref.get tvr in
begin match tv.tyo with
| None -> ty
| Some ty2 ->
(Ref.set tvr)
{ tv with tyo = Some (normalize_type ?from_env ~in_env ty2) };
ty
end
| Tpartial _ -> raise (Invalid_argument "normalize_type")
and normalize_contract_sig ?from_env ~in_env ~build_sig_env c_sig =
match c_sig.sig_name with
TODO
| Some s ->
let rec env_of_contract_type_name s env =
try find_contract_type_aux ~loc:noloc s env |> snd
with (Not_found | Unknown_namespace _ as e) ->
StringMap.fold (fun _ env acc ->
match acc with
| Some _ -> acc
| None ->
try Some (env_of_contract_type_name s env)
with Not_found | Unknown_namespace _ -> None
) env.others None
|> function
| None -> raise e
| Some env -> env in
let found_env = env_of_contract_type_name s in_env in
let sig_env =
if not build_sig_env then in_env
else
try find_env ~loc:noloc ( [unqualify s |> snd]) found_env
with Not_found | Unknown_namespace _ ->
found_env
in
{ sig_name = Some (qualify_name ?from_env ~at:found_env.path s);
entries_sig =
List.map (fun e ->
{ e with
parameter = normalize_type ?from_env ~in_env:sig_env e.parameter;
return = match e.return with
| None -> None
| Some r -> Some (normalize_type ?from_env ~in_env:sig_env r)
}
) c_sig.entries_sig }
let find_type ~loc s env subst =
let ty, found_env = find_type ~loc s env subst in
normalize_type ~from_env:env ~in_env:found_env ty
let find_contract_type ~loc s env =
let csig, found_env = find_contract_type_aux ~loc s env in
normalize_contract_sig ~from_env:env ~in_env:found_env ~build_sig_env:true csig
let find_label_ty_name ~loc s env =
let (tn, i), found_env = find ~loc s env (fun env -> env.labels) in
tn, i, found_env
let find_constr_ty_name ~loc s env =
let (tn, i), found_env = find ~loc s env (fun env -> env.constrs) in
tn, i, found_env
let find_label ~loc s env =
let n, i, found_env = find_label_ty_name ~loc s env in
let ty = find_type ~loc n found_env [] in
let ty = normalize_type ~from_env:env ~in_env:found_env ty in
let label_name, label_ty = match ty with
| Trecord (_, l) -> List.nth l i
| _ -> assert false in
ty, (label_name, label_ty, i)
let find_constr ~loc s env =
let n, i, found_env = find_constr_ty_name ~loc s env in
let ty = find_type ~loc n found_env [] in
let ty = normalize_type ~from_env:env ~in_env:found_env ty in
let constr_name, constr_ty = match ty with
| Tsum (_, l) -> List.nth l i
| _ -> assert false in
ty, (constr_name, constr_ty, i)
let find_extprim ?quiet ~loc s env =
let e, found_env = find ?quiet ~loc s env (fun env -> env.ext_prims) in
{ e with
atys = List.map (normalize_type ~from_env:env ~in_env:found_env) e.atys;
rty = normalize_type ~from_env:env ~in_env:found_env e.rty }
let is_extprim s env =
try find_extprim ~quiet:true ~loc:noloc s env |> ignore; true
with Not_found | Unknown_namespace _ -> false
let find_extprim ~loc s env = find_extprim ~loc s env
let lookup_global_value ~loc s env =
let path, s = unqualify s in
let path = match unalias path env.env with
| None -> path
| Some path -> path in
match find_namespace ~loc path env.visible_contracts with
| Current_namespace -> raise Not_found
| Contract_namespace (c, _) ->
let v = List.find (fun v -> not v.val_private && v.val_name = s) c.values in
let ty = normalize_type
~from_env:env.env
~in_env:c.ty_env v.val_exp.ty in
{ v with val_exp = { v.val_exp with ty } }
| exception Unknown_namespace (
["Current" | "Account" | "Map" | "Set" | "List" | "Contract"
| "Crypto" | "Bytes" | "String" ], _ ) ->
raise Not_found
let find_contract ~loc s env contracts =
let path, s = unqualify s in
let path = match unalias path env with
| None -> path
| Some path -> path in
match find_namespace ~loc path (StringMap.bindings contracts |> List.map snd) with
| Current_namespace ->
StringMap.find s contracts
| Contract_namespace (c, _) ->
List.find (fun c -> c.contract_name = s) c.subs
let find_module ~loc path env contracts =
let path = match unalias path env with
| None -> path
| Some path -> path in
match find_namespace ~loc path contracts with
| Current_namespace -> raise Not_found
| Contract_namespace (c, _) -> c
let qual_contract_name c =
match c.ty_env.path with
| [] -> c.contract_name
| p -> String.concat "." p
let unalias_name s env =
let path, s' = unqualify s in
match unalias path env with
| None -> s
| Some path -> add_path_name path s'
|
6557358cbd860ca36bb46fcc1a220c2946a44e440dee0c3e783e8669b07b4b10 | fizruk/lambdaconf-2019-workshop | AFrame.hs | {-# LANGUAGE OverloadedStrings #-}
module ARCube.Utils.AFrame where
import qualified Data.List as List
import Data.Monoid ((<>))
import Miso
import Miso.String (MisoString, ToMisoString (..), ms)
import ARCube.Utils.Miso
-- | Set up a VR scene.
sceneVR :: [View action] -> View action
sceneVR wrapped = nodeHtml "a-scene" []
[ nodeHtml "a-entity"
[ prop_ "camera" ""
, prop_ "look-controls" ""
, prop_ "wasd-controls" ""
] [ nodeHtml "a-cursor" [] [] ]
, nodeHtml "a-sky" [ prop_ "color" "#CCDCEC" ] []
, nodeHtml "a-entity"
[ prop_ "position" "0 0 -3"
, prop_ "rotation" "90 0 0"
] wrapped
]
-- | Set up an AR scene.
sceneAR :: [View action] -> View action
sceneAR wrapped = nodeHtml "a-scene"
[ prop_ "embedded" ""
, prop_ "arjs" "sourceType: webcam; debugUIEnabled: false;"
, prop_ "vr-mode-ui" "enabled: false"
]
[ nodeHtml "a-marker"
[ prop_ "preset" "custom"
, prop_ "type" "pattern"
, prop_ "url" "assets/markers/lc-2019-marker.patt"
, prop_ "emitevents" "true"
, prop_ "cursor" "rayOrigin: mouse"
]
wrapped
, nodeHtml "a-entity" [ prop_ "camera" "" ] []
]
-- * Primitives
box :: [Attribute action] -> [View action]
box attrs = wrapTag "a-box" attrs []
box_ :: [View action]
box_ = box []
sphere :: [Attribute action] -> [View action]
sphere attrs = wrapTag "a-sphere" attrs []
sphere_ :: [View action]
sphere_ = sphere []
-- * Relative positioning, orientation and scaling
translated :: Float -> Float -> Float -> [View action] -> [View action]
translated x y z = wrapEntity [ prop_ "position" (msListOf show [x, y, z]) ]
rotated :: Float -> Float -> Float -> [View action] -> [View action]
rotated x y z = wrapEntity [ prop_ "rotation" (msListOf show [x, y, z]) ]
scaled :: Float -> Float -> Float -> [View action] -> [View action]
scaled x y z = wrapEntity [ prop_ "scale" (msListOf show [x, y, z]) ]
rotatedAnim
:: MisoString
-> (Float, Float, Float)
-> (Float, Float, Float)
-> [View action]
-> [View action]
rotatedAnim name (fx, fy, fz) (tx, ty, tz) = wrapEntity
[ prop_ ("animation__" <> name) $ mconcat
[ "property: rotation; "
, "from: " <> msListOf show [fx, fy, fz] <> "; "
, "to: " <> msListOf show [tx, ty, tz] <> "; "
, "dur: 1000"
, "easing: easeInOutSine"
] ]
-- * Helpers
wrapTag :: MisoString -> [Attribute action] -> [View action] -> [View action]
wrapTag name attrs contents =
[ nodeHtml name attrs contents ]
wrapEntity :: [Attribute action] -> [View action] -> [View action]
wrapEntity = wrapTag "a-entity"
msListOf :: ToMisoString s => (a -> s) -> [a] -> MisoString
msListOf f = mconcat . List.intersperse " " . map (ms . f)
| null | https://raw.githubusercontent.com/fizruk/lambdaconf-2019-workshop/1a7caa4dd03ff1b09877b27d8adf79ca35fcc888/project/ar-cube/src/ARCube/Utils/AFrame.hs | haskell | # LANGUAGE OverloadedStrings #
| Set up a VR scene.
| Set up an AR scene.
* Primitives
* Relative positioning, orientation and scaling
* Helpers | module ARCube.Utils.AFrame where
import qualified Data.List as List
import Data.Monoid ((<>))
import Miso
import Miso.String (MisoString, ToMisoString (..), ms)
import ARCube.Utils.Miso
sceneVR :: [View action] -> View action
sceneVR wrapped = nodeHtml "a-scene" []
[ nodeHtml "a-entity"
[ prop_ "camera" ""
, prop_ "look-controls" ""
, prop_ "wasd-controls" ""
] [ nodeHtml "a-cursor" [] [] ]
, nodeHtml "a-sky" [ prop_ "color" "#CCDCEC" ] []
, nodeHtml "a-entity"
[ prop_ "position" "0 0 -3"
, prop_ "rotation" "90 0 0"
] wrapped
]
sceneAR :: [View action] -> View action
sceneAR wrapped = nodeHtml "a-scene"
[ prop_ "embedded" ""
, prop_ "arjs" "sourceType: webcam; debugUIEnabled: false;"
, prop_ "vr-mode-ui" "enabled: false"
]
[ nodeHtml "a-marker"
[ prop_ "preset" "custom"
, prop_ "type" "pattern"
, prop_ "url" "assets/markers/lc-2019-marker.patt"
, prop_ "emitevents" "true"
, prop_ "cursor" "rayOrigin: mouse"
]
wrapped
, nodeHtml "a-entity" [ prop_ "camera" "" ] []
]
box :: [Attribute action] -> [View action]
box attrs = wrapTag "a-box" attrs []
box_ :: [View action]
box_ = box []
sphere :: [Attribute action] -> [View action]
sphere attrs = wrapTag "a-sphere" attrs []
sphere_ :: [View action]
sphere_ = sphere []
translated :: Float -> Float -> Float -> [View action] -> [View action]
translated x y z = wrapEntity [ prop_ "position" (msListOf show [x, y, z]) ]
rotated :: Float -> Float -> Float -> [View action] -> [View action]
rotated x y z = wrapEntity [ prop_ "rotation" (msListOf show [x, y, z]) ]
scaled :: Float -> Float -> Float -> [View action] -> [View action]
scaled x y z = wrapEntity [ prop_ "scale" (msListOf show [x, y, z]) ]
rotatedAnim
:: MisoString
-> (Float, Float, Float)
-> (Float, Float, Float)
-> [View action]
-> [View action]
rotatedAnim name (fx, fy, fz) (tx, ty, tz) = wrapEntity
[ prop_ ("animation__" <> name) $ mconcat
[ "property: rotation; "
, "from: " <> msListOf show [fx, fy, fz] <> "; "
, "to: " <> msListOf show [tx, ty, tz] <> "; "
, "dur: 1000"
, "easing: easeInOutSine"
] ]
wrapTag :: MisoString -> [Attribute action] -> [View action] -> [View action]
wrapTag name attrs contents =
[ nodeHtml name attrs contents ]
wrapEntity :: [Attribute action] -> [View action] -> [View action]
wrapEntity = wrapTag "a-entity"
msListOf :: ToMisoString s => (a -> s) -> [a] -> MisoString
msListOf f = mconcat . List.intersperse " " . map (ms . f)
|
d89314b5a505f3a33aaa10d52f9a99b90a297f2c012da391b503bdcd8795dee4 | atlas-engineer/nyxt | bookmark.lisp | SPDX - FileCopyrightText : Atlas Engineer LLC
SPDX - License - Identifier : BSD-3 - Clause
(in-package :nyxt/tests)
(define-test toggle-bookmark-mode ()
(let ((buffer (make-instance 'modable-buffer)))
(with-current-buffer buffer
(assert-true (enable-modes* 'nyxt/bookmark-mode:bookmark-mode buffer))
(assert-true (disable-modes* 'nyxt/bookmark-mode:bookmark-mode buffer)))))
| null | https://raw.githubusercontent.com/atlas-engineer/nyxt/65a9aa568b16c109281fa403a7c045b3b6d87025/tests/offline/mode/bookmark.lisp | lisp | SPDX - FileCopyrightText : Atlas Engineer LLC
SPDX - License - Identifier : BSD-3 - Clause
(in-package :nyxt/tests)
(define-test toggle-bookmark-mode ()
(let ((buffer (make-instance 'modable-buffer)))
(with-current-buffer buffer
(assert-true (enable-modes* 'nyxt/bookmark-mode:bookmark-mode buffer))
(assert-true (disable-modes* 'nyxt/bookmark-mode:bookmark-mode buffer)))))
|
|
b48a70c567c28a4d83aeff489241ad4127597b2ce59835c199c1316180a15952 | juxt/jinx | jsonpointer.cljc | Copyright © 2019 - 2021 , JUXT LTD .
(ns juxt.jinx.alpha.jsonpointer
(:require
[clojure.string :as str]))
(def reference-token-pattern #"/((?:[^/~]|~0|~1)*)")
(defn decode [token]
(-> token
(str/replace "~1" "/")
(str/replace "~0" "~")))
(defn reference-tokens [s]
(map decode (map second (re-seq reference-token-pattern s))))
(defn json-pointer [doc pointer]
(loop [tokens (reference-tokens (or pointer ""))
subdoc doc]
(if (seq tokens)
(recur
(next tokens)
(cond
(map? subdoc)
(let [subsubdoc (get subdoc (first tokens))]
(if (some? subsubdoc) subsubdoc
(throw (ex-info "Failed to locate" {:json-pointer pointer
:subsubdoc subsubdoc
:subdoc subdoc
:tokens tokens
:first-token (first tokens)
:type-subdoc (type subdoc)
:doc doc
:debug (get subdoc (first tokens))
}))))
(sequential? subdoc)
(if (re-matches #"[0-9]+" (first tokens))
(let [subsubdoc
(get subdoc #?(:clj (Integer/parseInt (first tokens))
:cljs (js/Number (first tokens))))]
(if (some? subsubdoc)
subsubdoc
(throw (ex-info "Failed to locate" {:json-pointer pointer
:subdoc subdoc
:doc doc}))))
(throw (ex-info "Failed to locate, must be a number" {:json-pointer pointer
:subdoc subdoc
:doc doc})))))
subdoc)))
(comment
(json-pointer
{"a" [{"b" "alpha"} {"b" [{"c" {"greek" "delta"}}]}]}
"/a/1/b/0/c/greek"))
(comment
(json-pointer
{"a" [{"b" "alpha"} {"b" [{"c" {"greek" "delta"}}]}]}
nil))
| null | https://raw.githubusercontent.com/juxt/jinx/48c889486e5606e39144043946063803ad6effa8/src/juxt/jinx/alpha/jsonpointer.cljc | clojure | Copyright © 2019 - 2021 , JUXT LTD .
(ns juxt.jinx.alpha.jsonpointer
(:require
[clojure.string :as str]))
(def reference-token-pattern #"/((?:[^/~]|~0|~1)*)")
(defn decode [token]
(-> token
(str/replace "~1" "/")
(str/replace "~0" "~")))
(defn reference-tokens [s]
(map decode (map second (re-seq reference-token-pattern s))))
(defn json-pointer [doc pointer]
(loop [tokens (reference-tokens (or pointer ""))
subdoc doc]
(if (seq tokens)
(recur
(next tokens)
(cond
(map? subdoc)
(let [subsubdoc (get subdoc (first tokens))]
(if (some? subsubdoc) subsubdoc
(throw (ex-info "Failed to locate" {:json-pointer pointer
:subsubdoc subsubdoc
:subdoc subdoc
:tokens tokens
:first-token (first tokens)
:type-subdoc (type subdoc)
:doc doc
:debug (get subdoc (first tokens))
}))))
(sequential? subdoc)
(if (re-matches #"[0-9]+" (first tokens))
(let [subsubdoc
(get subdoc #?(:clj (Integer/parseInt (first tokens))
:cljs (js/Number (first tokens))))]
(if (some? subsubdoc)
subsubdoc
(throw (ex-info "Failed to locate" {:json-pointer pointer
:subdoc subdoc
:doc doc}))))
(throw (ex-info "Failed to locate, must be a number" {:json-pointer pointer
:subdoc subdoc
:doc doc})))))
subdoc)))
(comment
(json-pointer
{"a" [{"b" "alpha"} {"b" [{"c" {"greek" "delta"}}]}]}
"/a/1/b/0/c/greek"))
(comment
(json-pointer
{"a" [{"b" "alpha"} {"b" [{"c" {"greek" "delta"}}]}]}
nil))
|
|
93825c50f161e2151c3644790480918ec30d050768dcf1f6b694c5a2dae0c23c | txkaduo/weixin-mp-sdk | Site.hs | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE TupleSections #
# LANGUAGE ViewPatterns #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE UndecidableInstances #
module WeiXin.PublicPlatform.Yesod.Site
( module WeiXin.PublicPlatform.Yesod.Site
, module WeiXin.PublicPlatform.Yesod.Site.Data
) where
{ { { 1 imports
import ClassyPrelude
#if MIN_VERSION_base(4, 13, 0)
import Control . ( MonadFail ( .. ) )
#else
#endif
import Control.Arrow
import Yesod
import qualified Control.Exception.Safe as ExcSafe
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Base64.URL as B64L
import qualified Data.ByteString.Char8 as C8
import qualified Data.Text as T
import qualified Data.Set as Set
import Control.Monad.Except (runExceptT, ExceptT(..), throwError, catchError, mapExceptT)
import Control.Monad.Trans.Maybe (runMaybeT, MaybeT(..))
import Control.Concurrent (forkIO)
import Network.URI ( parseURI, uriQuery, uriToString )
import Network.HTTP ( urlEncode )
import Yesod.Default.Util ( widgetFileReload )
import Data.Time ( addUTCTime )
import Web.Cookie (SetCookie(..))
import Yesod.Helpers.Handler ( httpErrorRetryWithValidParams
, reqPathPieceParamPostGet
, getCurrentUrl
)
import Yesod.Helpers.Logger
import Yesod.Helpers.Utils (urlUpdateQueryText, randomString)
import Control.Monad.Logger
import Network.Wai (lazyRequestBody)
import Text.XML (renderText, parseLBS)
import Text.XML.Cursor (fromDocument)
import Data.Default (def)
import qualified Data.Text.Lazy as LT
import Yesod.Core.Types (HandlerContents(HCError))
import Data.Yaml (decodeEither')
import qualified Data.List.NonEmpty as LNE
import Network.HTTP.Types.Status (mkStatus)
import Data.Conduit
import Data.Conduit.Binary (sinkLbs)
import qualified Data.Conduit.List as CL
import qualified Data.Conduit.Combinators as CC
import qualified Data.Aeson as A
import Database.Persist.Sql
import WeiXin.PublicPlatform.Yesod.Utils (handlerGetWeixinClientVersion)
import WeiXin.PublicPlatform.Yesod.Model
import WeiXin.PublicPlatform.Yesod.Site.Data
import WeiXin.PublicPlatform.Class
import WeiXin.PublicPlatform.Security
import WeiXin.PublicPlatform.Message
import WeiXin.PublicPlatform.Error
import WeiXin.PublicPlatform.WS
import WeiXin.PublicPlatform.EndUser
import WeiXin.PublicPlatform.QRCode
import WeiXin.PublicPlatform.OAuth
import WeiXin.PublicPlatform.ThirdParty
import WeiXin.PublicPlatform.Utils
import Yesod.Compat
#if MIN_VERSION_classy_prelude(1, 5, 0)
import Control.Concurrent (threadDelay)
#endif
} } } 1
withWxppSubHandler :: (WxppSub -> SubHandlerOf MaybeWxppSub master a)
-> SubHandlerOf MaybeWxppSub master a
withWxppSubHandler f = do
getSubYesodCompat
>>= liftIO . unMaybeWxppSub
>>= maybe notFound return
>>= f
checkSignature :: (HasWxppToken a, RenderMessage master FormMessage)
=> a
-> Text -- ^ GET param name of signature
-> Text -- ^ signed message text
-> SubHandlerOf site master ()
{ { { 1
checkSignature foundation sign_param msg = do
let token = getWxppToken foundation
check_sign (tt, nn, sign) =
if B16.encodeBase16 sign0 == T.toLower sign
then Right ()
else Left $ "invalid signature"
where
sign0 = wxppSignature token tt nn msg
(tt, nn, sign) <- liftMonadHandlerToSub $ runInputGet $
(,,) <$> (TimeStampS <$> ireq textField "timestamp")
<*> (Nonce <$> ireq textField "nonce")
<*> ireq textField sign_param
case check_sign (tt, nn, sign) of
Left err -> do $logErrorS wxppLogSource $ "got invalid signature: " <> sign_param
invalidArgs $ return err
Right _ -> return ()
} } } 1
| 用于修改 HandlerT
withWxppSubLogging :: (LoggingTRunner r)
=> r
-> SubHandlerOf site master a
-> SubHandlerOf site master a
withWxppSubLogging foundation h = do
runLoggingTWith foundation $ LoggingT $ \log_func -> do
withLogFuncInSubHandler log_func h
getMessageR :: (RenderMessage master FormMessage) => SubHandlerOf MaybeWxppSub master Text
getMessageR = withWxppSubHandler $ \ foundation -> do
withWxppSubLogging foundation $ do
checkSignature foundation "signature" ""
runInputGet $ ireq textField "echostr"
postMessageR :: (RenderMessage master FormMessage) => SubHandlerOf MaybeWxppSub master Text
postMessageR = withWxppSubHandler $ \ foundation -> withWxppSubLogging foundation $ do
let app_id = getWxppAppID foundation
realHandlerMsg foundation (ProcAppSingle app_id)
realHandlerMsg :: forall site master a.
( RenderMessage master FormMessage
, HasWxppToken a, HasAesKeys a, HasWxppProcessor a
)
=> a
-> ProcAppIdInfo
-> SubHandlerOf site master Text
{ { { 1
realHandlerMsg foundation app_info = do
checkSignature foundation "signature" ""
m_enc_type <- lookupGetParam "encrypt_type"
enc <- case m_enc_type of
Nothing -> return False
Just "" -> return False
Just "aes" -> return True
Just x -> do
$(logErrorS) wxppLogSource $
"unknown/unsupported encrypt_type: " <> x
httpErrorRetryWithValidParams $ T.pack $
"Retry with valid parameters: encrypt_type(not supported)"
req <- waiRequest
lbs <- liftIO $ lazyRequestBody req
let aks = getAesKeys foundation
app_token = getWxppToken foundation
processor = getWxppProcessor foundation
err_or_resp <- runExceptT $ do
(decrypted_xml0, m_enc_akey) <-
if enc
then do
(either throwError return $ parse_xml_lbs lbs >>= wxppTryDecryptByteStringDocumentE my_app_id aks)
>>= maybe (throwError $ "Internal Error: no AesKey available to decrypt")
(return . (LB.fromStrict *** Just))
else return (lbs, Nothing)
let err_or_parsed = parse_xml_lbs decrypted_xml0 >>= wxppInMsgEntityFromDocument
m_ime0 <- case err_or_parsed of
Left err -> do
$logErrorS wxppLogSource $ fromString $ "Error when parsing incoming XML: " ++ err
return Nothing
Right x -> return $ Just x
ime0 <- case m_ime0 of
Nothing -> do
-- cannot parse incoming XML message
liftIO $ wxppOnParseInMsgError processor app_info lbs
throwError $ "Cannot parse incoming XML"
Just x -> return x
pre_result <- liftIO $ wxppPreProcessInMsg processor app_info decrypted_xml0 ime0
case pre_result of
Left err -> do
$logErrorS wxppLogSource $ "wxppPreProcessInMsg failed: " <> fromString err
throwError "程序内部错误,请稍后重试"
Right Nothing -> do
$logDebugS wxppLogSource $ "message handle skipped because middleware return Nothing"
return ("", Nothing)
Right (Just (decrypted_xml, ime)) -> do
log_func <- askLoggerIO
let user_open_id = wxppInFromUserName ime
target_username = wxppInToUserName ime
let handle_msg = wxppMsgHandler processor
try_handle_msg = mapExceptT liftIO $ ExceptT $ flip runLoggingT log_func $ do
ExcSafe.tryAny (liftIO $ handle_msg app_info decrypted_xml ime)
>>= \err_or_x -> do
case err_or_x of
Left err -> do
$logErrorS wxppLogSource $
"error when handling incoming message: " <> tshow err
return $ Left $ show err
Right x -> return x
let post_handle_msg = wxppPostProcessInMsg processor
do_post_handle_msg out_res0 = mapExceptT liftIO $ ExceptT $ flip runLoggingT log_func $ do
ExcSafe.tryAny (liftIO $ post_handle_msg app_info decrypted_xml ime out_res0)
>>= \err_or_x -> do
case err_or_x of
Left err -> do
$logErrorS wxppLogSource $
"error when post-handling incoming message: " <> tshow err
return $ Left $ show err
Right x -> return x
let do_on_error err = ExceptT $
liftIO (wxppOnProcessInMsgError processor app_info decrypted_xml ime err)
out_res <- (try_handle_msg `catchError` \err -> do_on_error err >> throwError err)
>>= do_post_handle_msg
let (primary_out_msgs, secondary_out_msgs) = (map snd *** map snd) $ partition fst out_res
-- 只要有 primary 的回应,就忽略非primary的回应
如果没 primary 回应,而 secondary 回应有多个,则只选择第一个
let split_head ls = case ls of
[] -> (Nothing, [])
(x:xs) -> (Just x, xs)
let (m_resp_out_msg, other_out_msgs) =
if null primary_out_msgs
then (, []) $ listToMaybe $ catMaybes secondary_out_msgs
else split_head $ catMaybes primary_out_msgs
now <- liftIO getCurrentTime
let mk_out_msg_entity x = WxppOutMsgEntity
user_open_id
target_username
now
x
let extra_data = map (user_open_id,) other_out_msgs
liftM (, Just extra_data) $
fmap (fromMaybe "") $ forM m_resp_out_msg $ \out_msg -> do
liftM (LT.toStrict . renderText def) $ do
let out_msg_entity = mk_out_msg_entity out_msg
case m_enc_akey of
Just enc_akey ->
ExceptT $ wxppOutMsgEntityToDocumentE
my_app_id app_token enc_akey out_msg_entity
Nothing ->
return $ wxppOutMsgEntityToDocument out_msg_entity
case err_or_resp of
Left err -> do
$(logErrorS) wxppLogSource $ fromString $
"cannot encode outgoing message into XML: " <> err
liftIO $ throwIO $ HCError $
InternalError "cannot encode outgoing message into XML"
Right (xmls, m_extra_data) -> do
forM_ m_extra_data $ \other_out_msgs -> do
when (not $ null other_out_msgs) $ do
void $ liftIO $ async $ do
-- 本来延迟一点点只是为了希望能保持多个信息之间的顺序
threadDelay $ 1000 * 100
wxppSendOutMsgs processor to_app_id other_out_msgs
return xmls
where
parse_xml_lbs x = case parseLBS def x of
Left ex -> Left $ "Failed to parse XML: " <> show ex
Right xdoc -> return xdoc
to_app_id = procAppIdInfoReceiverId app_info
my_app_id = procAppIdInfoMyId app_info
} } } 1
-- | 生成随机字串作为 oauth 的state参数之用
这是按官方文档的思路,用于防 csrf
所生成的随机字串会放在 cookieNameWxppOAuthState cookie 里
-- CAUTION: 不要使用会话变量,因为会话可能因为超时而突然变成另一个新会话
wxppOAuthMakeRandomState :: (MonadHandler m)
=> WxppAppID
-> m Text
{ { { 1
wxppOAuthMakeRandomState app_id = do
m_oauth_random_st <- lookupCookie (cookieNameWxppOAuthState app_id)
case m_oauth_random_st of
Just x | not (null x) -> do
return x
_ -> do
random_state <- fmap pack $ randomString 32 (['0'..'9'] <> ['a'..'z'] <> ['A'..'Z'])
setCookie (def { setCookieName = encodeUtf8 (cookieNameWxppOAuthState app_id), setCookieValue = encodeUtf8 random_state })
return random_state
} } } 1
wxppOAuthLoginRedirectUrl :: (MonadHandler m)
=> (Route MaybeWxppSub -> [(Text, Text)] -> m Text)
-> Maybe WxppAppID
^
-> WxppAppID
-> OAuthScope
-> Text -- ^ oauth's state param
-> UrlText -- ^ return URL
-> m UrlText
{ { { 1
wxppOAuthLoginRedirectUrl url_render m_comp_app_id app_id scope user_st return_url = do
random_state <- wxppOAuthMakeRandomState app_id
let state = random_state <> ":" <> user_st
oauth_retrurn_url <- liftM UrlText $
url_render OAuthCallbackR [ ("return", unUrlText return_url) ]
let auth_url = wxppOAuthRequestAuthInsideWx m_comp_app_id app_id scope
oauth_retrurn_url
state
return auth_url
} } } 1
sessionKeyWxppUser :: WxppAppID -> Text
sessionKeyWxppUser app_id = "wx|" <> unWxppAppID app_id
cookieNameWxppOAuthState :: WxppAppID -> Text
cookieNameWxppOAuthState app_id = "wx-oauth-st|" <> unWxppAppID app_id
sessionKeyWxppUnionId :: Text
sessionKeyWxppUnionId = "wx-union-id"
sessionMarkWxppUser :: MonadHandler m
=> WxppAppID
-> WxppOpenID
-> Maybe WxppUnionID
-> m ()
{ { { 1
sessionMarkWxppUser app_id open_id m_union_id = do
setSession (sessionKeyWxppUser app_id) (unWxppOpenID open_id)
-- XXX: union id 目前设在一个指定的键下面。
-- 下面的做法不能支持多个系统的union id
case fmap unWxppUnionID m_union_id of
Just union_id | not (null union_id) -> setSession sessionKeyWxppUnionId union_id
_ -> deleteSession sessionKeyWxppUnionId
} } } 1
| 从 session
sessionGetWxppUser :: MonadHandler m
=> WxppAppID
-> m (Maybe WxppOpenID)
sessionGetWxppUser app_id = fmap (fmap WxppOpenID) $ lookupSession (sessionKeyWxppUser app_id)
| 从 session 及 WxppUnionID
sessionGetWxppUserU :: MonadHandler m => WxppAppID -> m (Maybe (WxppAppOpenID, Maybe WxppUnionID))
sessionGetWxppUserU app_id = runMaybeT $ do
open_id <- MaybeT $ sessionGetWxppUser app_id
m_union_id <- lift $ fmap WxppUnionID <$> lookupSession sessionKeyWxppUnionId
return (WxppAppOpenID app_id open_id, m_union_id)
getOAuthCallbackR :: Yesod master => SubHandlerOf MaybeWxppSub master Html
{ { { 1
getOAuthCallbackR = withWxppSubHandler $ \sub -> do
m_code <- lookupGetParam "code"
return_url <- reqPathPieceParamPostGet "return"
let app_id = getWxppAppID sub
secret = getWxppSecret sub
cache = wxppSubCacheBackend sub
oauth_state <- liftM (fromMaybe "") $ lookupGetParam "state"
let (expected_st, state') = T.breakOn ":" oauth_state
m_expected_state <- lookupCookie (cookieNameWxppOAuthState app_id)
unless (m_expected_state == Just expected_st) $ do
$logErrorS wxppLogSource $
"OAuth state check failed, got: " <> oauth_state
liftIO $ throwIO $ HCError NotAuthenticated
let state = fromMaybe state' $ T.stripPrefix ":" state'
let api_env = wxppSubApiEnv sub
case fmap OAuthCode m_code of
Just code | not (deniedOAuthCode code) -> do
-- 用户同意授权
handler functions in new version yesod may not derive MonadCatch instance
-- we need to run wxpp call in (LoggingT IO)
log_func <- askLoggerIO
err_or_atk_info <- liftIO $ flip runLoggingT log_func $
tryWxppWsResult $ flip runReaderT api_env $
wxppOAuthGetAccessToken app_id secret code
atk_info <- case err_or_atk_info of
Left err -> do
$logErrorS wxppLogSource $
"wxppOAuthGetAccessToken failed: " <> tshow err
liftIO $ throwIO $ HCError NotAuthenticated
Right x -> return x
now <- liftIO getCurrentTime
let expiry = addUTCTime (oauthAtkTTL atk_info) now
open_id = oauthAtkOpenID atk_info
scopes = oauthAtkScopes atk_info
atk_p = getOAuthAccessTokenPkg (app_id, atk_info)
let get_union_id1 = MaybeT $ return $ oauthAtkUnionID atk_info
get_union_id2 = do
guard $ any oauthScopeCanGetUserInfo scopes
err_or_oauth_user_info <- liftIO $ flip runLoggingT log_func $
tryWxppWsResult $ flip runReaderT api_env $
wxppOAuthGetUserInfo' atk_p
case err_or_oauth_user_info of
Left err -> do $logErrorS wxppLogSource $ "wxppOAuthGetUserInfo' failed: " <> tshow err
mzero
Right oauth_user_info -> do
liftIO $ wxppCacheAddSnsUserInfo cache app_id "zh_CN" oauth_user_info
MaybeT $ return $ oauthUserInfoUnionID oauth_user_info
m_union_id <- runMaybeT $ get_union_id1 <|> get_union_id2
liftIO $ wxppCacheAddOAuthAccessToken cache atk_p expiry
sessionMarkWxppUser app_id open_id m_union_id
let rdr_url = case parseURI return_url of
Just uri ->
let qs = uriQuery uri
qs' = case qs of
_ | null qs -> qs ++ "?"
| qs == "?" -> qs
| otherwise -> qs ++ "&"
new_uri = uri { uriQuery =
qs' ++ "state=" ++ urlEncode (T.unpack state)
}
in uriToString id new_uri ""
_ -> return_url
--- $logDebugS wxppLogSource $ "redirecting to: " <> T.pack rdr_url
redirect rdr_url
_ -> do
-- 授权失败
liftMonadHandlerToSub $ defaultLayout $ do
$(widgetFileReload def "oauth/user_denied")
} } } 1
-- | 比较通用的处理从 oauth 重定向回来时的Handler的逻辑
-- 如果用户通过授权,则返回 open id 及 oauth token 相关信息
wxppHandlerOAuthReturnGetInfo :: (MonadHandler m
#if MIN_VERSION_yesod(1, 6, 0)
, MonadLogger m
#else
, MonadLogger m
#endif
, RenderMessage (HandlerSite m) FormMessage)
=> SomeWxppApiBroker
-> WxppAppID
-> m (Maybe (WxppOpenID, OAuthTokenInfo))
{ { { 1
wxppHandlerOAuthReturnGetInfo broker app_id = do
m_code <- fmap (fmap OAuthCode) $ runInputGet $ iopt textField "code"
case m_code of
Just code | not (deniedOAuthCode code) -> do
-- 用户同意授权
err_or_muid <- runExceptT $ do
err_or_atk_res <- liftIO $ wxppApiBrokerOAuthGetAccessToken broker app_id code
atk_res <- case err_or_atk_res of
Nothing -> do
$logErrorS wxppLogSource $ "Broker call failed: no such app"
throwError $ asString "no such app"
Just (WxppWsResp (Left err)) -> do
$logErrorS wxppLogSource $
"wxppApiBrokerOAuthGetAccessToken failed: " <> tshow err
throwError "wxppApiBrokerOAuthGetAccessToken failed"
Just (WxppWsResp (Right x)) -> return x
let open_id = oauthAtkOpenID atk_res
now <- liftIO getCurrentTime
let atk_info = fromOAuthAccessTokenResult now atk_res
lift $ setSession (sessionKeyWxppUser app_id) (unWxppOpenID open_id)
return (open_id, atk_info)
return $ either (const Nothing) Just $ err_or_muid
_ -> do
$logErrorS wxppLogSource $ "should never reach here"
return Nothing
} } } 1
-- | 测试是否已经过微信用户授权,是则执行执行指定的函数
-- 否则重定向至微信授权页面,待用户授权成功后再重定向回到当前页面
wxppOAuthHandler :: (ExcSafe.MonadThrow m, MonadHandler m, WxppCacheTemp c)
=> c
-> (Route MaybeWxppSub -> [(Text, Text)] -> m Text)
-> Maybe WxppAppID
^
-> WxppAppID
-> OAuthScope
-> ( OAuthAccessTokenPkg -> m a )
-> m a
{ { { 1
wxppOAuthHandler cache render_url m_comp_app_id app_id scope f = do
m_atk_p <- wxppOAuthHandlerGetAccessTokenPkg cache app_id scope
case m_atk_p of
Nothing -> do
is_wx <- isJust <$> handlerGetWeixinClientVersion
unless is_wx $ do
permissionDenied "请用在微信里打开此网页"
url <- getCurrentUrl
wxppOAuthLoginRedirectUrl render_url m_comp_app_id app_id scope "" (UrlText url)
>>= redirect . unUrlText
Just atk_p -> f atk_p
} } } 1
wxppOAuthHandlerGetAccessTokenPkg :: (MonadHandler m, WxppCacheTemp c)
=> c
-> WxppAppID
-> OAuthScope
-> m (Maybe OAuthAccessTokenPkg)
{ { { 1
wxppOAuthHandlerGetAccessTokenPkg cache app_id scope = do
m_oauth_st <- sessionGetWxppUser app_id
case m_oauth_st of
Nothing -> return Nothing
Just open_id -> do
m_atk_info <- liftIO $ wxppCacheGetOAuthAccessToken cache
app_id open_id (Set.singleton scope)
case m_atk_info of
Nothing -> return Nothing
Just atk_info -> return $ Just (packOAuthTokenInfo app_id open_id atk_info)
} } } 1
-- | 演示/测试微信 oauth 授权的页面
getOAuthTestR :: SubHandlerOf MaybeWxppSub master Text
getOAuthTestR = withWxppSubHandler $ \sub -> do
let app_id = getWxppAppID sub
m_oauth_st <- sessionGetWxppUser app_id
case m_oauth_st of
Nothing -> return "no open id, authorization failed"
Just open_id -> return $ "Your open id is: " <> unWxppOpenID open_id
checkWaiReqThen :: (WxppSub -> SubHandlerOf MaybeWxppSub master a)
-> SubHandlerOf MaybeWxppSub master a
checkWaiReqThen f = withWxppSubHandler $ \foundation -> withWxppSubLogging foundation $ do
b <- waiRequest >>= liftIO . (wxppSubTrustedWaiReq $ wxppSubOptions foundation)
if b
then f foundation
else permissionDenied "denied by security check"
mimicInvalidAppID :: SubHandlerOf MaybeWxppSub master a
mimicInvalidAppID = sendResponse $ toJSON $
WxppAppError
(WxppErrorX $ Right WxppInvalidAppID)
"invalid app id"
mimicServerBusy :: Text -> SubHandlerOf MaybeWxppSub master a
mimicServerBusy s = sendResponse $ toJSON $
WxppAppError
(WxppErrorX $ Right WxppServerBusy)
s
forwardWsResult :: (ToJSON a)
=> String
-> Either WxppWsCallError a
-> SubHandlerOf MaybeWxppSub master Value
{ { { 1
forwardWsResult op_name res = do
case res of
Left (WxppWsErrorApp err) -> do
sendResponse $ toJSON err
Left err -> do
$logErrorS wxppLogSource $ fromString $
op_name ++ " failed: " ++ show err
mimicServerBusy $ fromString $ op_name ++ " failed"
Right x -> do
return $ toJSON x
} } } 1
-- | 提供 access-token
-- 为重用代码,错误报文格式与微信平台接口一样
逻辑上的返回值是 AccessToken
getGetAccessTokenR :: SubHandlerOf MaybeWxppSub master Value
getGetAccessTokenR = checkWaiReqThen $ \foundation -> do
alreadyExpired
liftM toJSON $ getAccessTokenSubHandler' foundation
| 找 OpenID 对应的 UnionID
-- 为重用代码,错误报文格式与微信平台接口一样
逻辑上的返回值是 Maybe
getGetUnionIDR :: WxppOpenID -> SubHandlerOf MaybeWxppSub master Value
{ { { 1
getGetUnionIDR open_id = checkWaiReqThen $ \foundation -> do
alreadyExpired
let sm_mode = wxppSubMakeupUnionID $ wxppSubOptions foundation
if sm_mode
then do
return $ toJSON $ Just $ fakeUnionID open_id
else do
let app_id = getWxppAppID foundation
let cache = wxppSubCacheBackend foundation
(liftIO $ tryWxppWsResult $ wxppCacheLookupUserInfo cache app_id open_id)
>>= forwardWsResult "wxppCacheLookupUserInfo"
} } } 1
-- | 初始化 WxppUserCachedInfo 表的数据
getInitCachedUsersR :: SubHandlerOf MaybeWxppSub master Value
{ { { 1
getInitCachedUsersR = checkWaiReqThen $ \foundation -> do
alreadyExpired
atk <- getAccessTokenSubHandler' foundation
let api_env = wxppSubApiEnv foundation
_ <- liftIO $ forkIO $ wxppSubRunLoggingT foundation $ do
_ <- runWxppDB (wxppSubRunDBAction foundation) $ initWxppUserDbCacheOfApp api_env (return atk)
return ()
return $ toJSON ("run in background" :: Text)
} } } 1
| 为客户端调用平台的 wxppQueryEndUserInfo 接口
-- 逻辑返回值是 EndUserQueryResult
getQueryUserInfoR :: WxppOpenID -> SubHandlerOf MaybeWxppSub master Value
{ { { 1
getQueryUserInfoR open_id = checkWaiReqThen $ \foundation -> do
alreadyExpired
atk <- getAccessTokenSubHandler' foundation
let sm_mode = wxppSubMakeupUnionID $ wxppSubOptions foundation
fix_uid qres =
if sm_mode
then endUserQueryResultSetUnionID (Just $ fakeUnionID open_id) <$> qres
else qres
log_func <- askLoggerIO
liftIO (flip runLoggingT log_func $ tryWxppWsResult
(flip runReaderT (wxppSubApiEnv foundation) $ wxppQueryEndUserInfo atk open_id)
)
>>= return . fix_uid
>>= forwardWsResult "wxppQueryEndUserInfo"
} } } 1
-- | 模仿创建永久场景的二维码
行为接近微信平台的接口,区别是
输入仅仅是一个 WxppScene
postCreateQrCodePersistR :: SubHandlerOf MaybeWxppSub master Value
{ { { 1
postCreateQrCodePersistR = checkWaiReqThen $ \foundation -> do
let api_env = wxppSubApiEnv foundation
alreadyExpired
scene <- decodePostBodyAsYaml
let sm_mode = wxppSubFakeQRTicket $ wxppSubOptions foundation
if sm_mode
then do
to_parent <- getRouteToParent
render_url <- liftMonadHandlerToSub getUrlRender
let qrcode_base_url = render_url $ to_parent ShowSimulatedQRCodeR
let fake_ticket = (scene, qrcode_base_url)
return $ toJSON $ B64L.encodeBase64 $ LB.toStrict $ A.encode fake_ticket
else do
atk <- getAccessTokenSubHandler' foundation
flip runReaderT api_env $ do
liftM toJSON $ wxppQrCodeCreatePersist atk scene
} } } 1
-- | 返回一个二维码图像
其内容是 WxppScene 用 JSON 格式表示之后的字节流
getShowSimulatedQRCodeR :: SubHandlerOf MaybeWxppSub master TypedContent
{ { { 1
getShowSimulatedQRCodeR = do
ticket_s <- lookupGetParam "ticket"
>>= maybe (httpErrorRetryWithValidParams ("missing ticket" :: Text)) return
(ticket :: FakeQRTicket) <- case B64L.decodeBase64 (C8.pack $ T.unpack ticket_s) of
Left _ -> httpErrorRetryWithValidParams ("invalid ticket" :: Text)
Right bs -> case decodeEither' bs of
Left err -> do
$logErrorS wxppLogSource $ fromString $
"cannot decode request body as YAML: " ++ show err
sendResponseStatus (mkStatus 449 "Retry With") $
("retry wtih valid request JSON body" :: Text)
Right (x, y) -> return (x, UrlText y)
let scene = fst ticket
let input = C8.unpack $ LB.toStrict $ A.encode scene
let bs = encodeStringQRCodeJpeg 5 input
return $ toTypedContent (typeSvg, toContent bs)
} } } 1
| 返回与输入的 union i d 匹配的所有 open i d 及 相应的 app_id
getLookupOpenIDByUnionIDR :: WxppUnionID -> SubHandlerOf WxppSubNoApp master Value
getLookupOpenIDByUnionIDR union_id = checkWaiReqThenNA $ \foundation -> do
alreadyExpired
liftM toJSON $ liftIO $ wxppSubNoAppUnionIdByOpenId foundation union_id
-- | 接收第三方平台的事件通知
-- GET 方法用于echo检验
-- POST 方法真正处理业务逻辑
getTpEventNoticeR :: (RenderMessage master FormMessage) => SubHandlerOf WxppTpSub master Text
getTpEventNoticeR = do
foundation <- getSubYesodCompat
withWxppSubLogging foundation $ do
checkSignature foundation "signature" ""
runInputGet $ ireq textField "echostr"
postTpEventNoticeR :: (Yesod master, RenderMessage master FormMessage)
=> SubHandlerOf WxppTpSub master Text
{ { { 1
postTpEventNoticeR = do
foundation <- getSubYesodCompat
req <- waiRequest
lbs <- liftIO $ lazyRequestBody req
let enc_key = LNE.head $ wxppTpSubAesKeys foundation
my_app_id = wxppTpSubComponentAppId foundation
err_or_resp <- runExceptT $ do
encrypted_xml_t <- either throwError return
(parse_xml_lbs lbs >>= wxppEncryptedTextInDocumentE)
lift $ checkSignature foundation "msg_signature" encrypted_xml_t
decrypted_xml0 <- either throwError (return . fromStrict) $ do
left T.unpack (B64.decodeBase64 (encodeUtf8 encrypted_xml_t))
>>= wxppDecrypt my_app_id enc_key
let err_or_parsed = parse_xml_lbs decrypted_xml0 >>= wxppTpDiagramFromCursor . fromDocument
uts_or_notice <- case err_or_parsed of
Left err -> do
$logErrorS wxppLogSource $ fromString $ "Error when parsing incoming XML: " ++ err
throwError "Cannot parse XML document"
Right x -> return x
case uts_or_notice of
Left unknown_info_type -> do
$logErrorS wxppLogSource $
"Failed to handle event notice: unknown InfoType: "
<> unknown_info_type
throwError $ "Unknown or unsupported InfoType"
Right notice -> do
ExceptT $ wxppTpSubHandlerEventNotice foundation notice
case err_or_resp of
Left err -> do
$(logErrorS) wxppLogSource $ fromString $
"Cannot handle third-party event notice: " <> err
liftIO $ throwIO $ HCError $
InternalError "Cannot handle third-party event notice"
Right output -> do
return output
where
parse_xml_lbs x = case parseLBS def x of
Left ex -> Left $ "Failed to parse XML: " <> show ex
Right xdoc -> return xdoc
} } } 1
-- | 第三方平台接收公众号消息与事件的端点入口
-- GET 方法用于通讯检测
POST
getTpMessageR :: (RenderMessage master FormMessage)
=> WxppAppID -> SubHandlerOf WxppTpSub master Text
getTpMessageR _auther_app_id = do
foundation <- getSubYesodCompat
checkSignature foundation "signature" ""
runInputGet $ ireq textField "echostr"
postTpMessageR :: (RenderMessage master FormMessage)
=> WxppAppID -> SubHandlerOf WxppTpSub master Text
postTpMessageR auther_app_id = do
foundation <- getSubYesodCompat
let comp_app_id = getWxppAppID foundation
realHandlerMsg foundation (ProcAppThirdParty comp_app_id auther_app_id)
instance (Yesod master, RenderMessage master FormMessage) =>
YesodSubDispatch
MaybeWxppSub
#if MIN_VERSION_yesod(1, 6, 0)
master
#else
(HandlerOf master)
#endif
where yesodSubDispatch = $(mkYesodSubDispatch resourcesMaybeWxppSub)
instance
YesodSubDispatch
WxppSubNoApp
#if MIN_VERSION_yesod(1, 6, 0)
master
#else
(HandlerOf master)
#endif
where yesodSubDispatch = $(mkYesodSubDispatch resourcesWxppSubNoApp)
instance (Yesod master, RenderMessage master FormMessage)
=> YesodSubDispatch
WxppTpSub
#if MIN_VERSION_yesod(1, 6, 0)
master
#else
(HandlerOf master)
#endif
where yesodSubDispatch = $(mkYesodSubDispatch resourcesWxppTpSub)
--------------------------------------------------------------------------------
checkWaiReqThenNA :: (WxppSubNoApp -> SubHandlerOf WxppSubNoApp master a)
-> SubHandlerOf WxppSubNoApp master a
checkWaiReqThenNA f = do
foundation <- getSubYesodCompat
wxppSubNoAppRunLoggingT foundation $ LoggingT $ \ log_func -> do
withLogFuncInSubHandler log_func $ do
b <- waiRequest >>= liftIO . wxppSubNoAppCheckWaiReq foundation
if b
then f foundation
else permissionDenied "denied by security check"
decodePostBodyAsYaml :: (FromJSON a)
=> SubHandlerOf MaybeWxppSub master a
{ { { 1
decodePostBodyAsYaml = do
body <- runConduit $ rawRequestBody .| sinkLbs
case decodeEither' (LB.toStrict body) of
Left err -> do
$logErrorS wxppLogSource $ fromString $
"cannot decode request body as YAML: " ++ show err
sendResponseStatus (mkStatus 449 "Retry With") $
("retry wtih valid request JSON body" :: Text)
Right x -> return x
} } } 1
getAccessTokenSubHandler' :: WxppSub
-> SubHandlerOf MaybeWxppSub master AccessToken
getAccessTokenSubHandler' foundation = do
let cache = wxppSubCacheBackend foundation
let app_id = getWxppAppID foundation
(liftIO $ wxppCacheGetAccessToken cache app_id)
>>= maybe (mimicServerBusy "no access token available") (return . fst)
fakeUnionID :: WxppOpenID -> WxppUnionID
fakeUnionID (WxppOpenID x) = WxppUnionID $ "fu_" <> x
-- | initialize db table: WxppUserCachedInfo
initWxppUserDbCacheOfApp :: ( MonadIO m, MonadLogger m)
=> WxppApiEnv
-> m AccessToken
-> ReaderT WxppDbBackend m Int
{ { { 1
initWxppUserDbCacheOfApp api_env get_atk = do
atk <- lift get_atk
flip runReaderT api_env $ do
runConduit $
wxppGetEndUserSource' (lift $ lift get_atk)
.| CL.concatMap wxppOpenIdListInGetUserResult
.| save_to_db atk
.| CC.length
where
save_to_db atk = awaitForever $ \open_id -> do
let app_id = accessTokenApp atk
now <- liftIO getCurrentTime
_ <- lift $ do
m_old <- lift $ getBy $ UniqueWxppUserCachedInfo open_id app_id
case m_old of
Just _ -> do
假定 open i d 及 union i d 对于固定的 app 是固定的
-- 已有的记录暂时不更新了
-- 因为调用平台接口有点慢
return ()
Nothing -> do
qres <- wxppQueryEndUserInfo atk open_id
_ <- lift $ insertBy $ WxppUserCachedInfo app_id
(endUserQueryResultOpenID qres)
(endUserQueryResultUnionID qres)
now
return ()
lift transactionSave
yield ()
} } } 1
-- | 若当前会话未经过微信登录,则调用 yesodComeBackWithWxLogin
-- 否则从会话中取已登录的微信用户信息
yesodMakeSureInWxLoggedIn :: ( MonadHandler m, MonadLoggerIO m
, ExcSafe . MonadThrow m
, RenderMessage (HandlerSite m) FormMessage
, HasWxppUrlConfig e, HasWreqSession e
, WxppCacheTemp c
)
=> e
-> c
-> (WxppAppID -> m (Maybe WxppAppSecret))
-> (UrlText -> m UrlText)
-- ^ 修改微信返回地址
-> OAuthScope
-> WxppAppID
-> m a
-- ^ 确实不能取得 open id 时调用
-> (WxppOpenID -> Maybe WxppUnionID -> Maybe OAuthGetUserInfoResult-> m a)
^ 取得 open_id
假定微信的回调参数 code , state 不会影响这部分的逻辑
-- OAuthGetUserInfoResult 是副产品,不一定有
openid / unionid 会尽量尝试从session里取得
-> m a
{ { { 1
yesodMakeSureInWxLoggedIn wx_api_env cache get_secret fix_return_url scope app_id h_no_id h = do
m_wx_id <- sessionGetWxppUserU app_id
case m_wx_id of
Just (open_id, m_union_id) -> h (getWxppOpenID open_id) m_union_id Nothing
Nothing -> yesodComeBackWithWxLogin wx_api_env cache get_secret fix_return_url scope app_id h_no_id h
} } } 1
| 调用微信 oauth 取 open i d 再继续处理下一步逻辑
注意:这里使用当前页面作为微信返回地址,因此query string参数不要与微信的冲突
不适用于第三方平台(因 wxppOAuthRequestAuthOutsideWx 不能处理第三方平台的情况 )
yesodComeBackWithWxLogin :: ( MonadHandler m, MonadLoggerIO m
, ExcSafe . MonadThrow m
, RenderMessage (HandlerSite m) FormMessage
, HasWxppUrlConfig e, HasWreqSession e
, WxppCacheTemp c
)
=> e
-> c
-> (WxppAppID -> m (Maybe WxppAppSecret))
-> (UrlText -> m UrlText)
-- ^ 修改微信返回地址
-> OAuthScope
-> WxppAppID
-> m a
-- ^ 确实不能取得 open id 时调用
-> (WxppOpenID -> Maybe WxppUnionID -> Maybe OAuthGetUserInfoResult -> m a)
^ 取得 open_id
假定微信的回调参数 code , state 不会影响这部分的逻辑
-- OAuthGetUserInfoResult 是副产品,不一定有
openid / unionid 会尽量尝试从session里取得
-> m a
{ { { 1
yesodComeBackWithWxLogin wx_api_env cache get_secret fix_return_url scope app_id0 h_no_id h = do
yesodComeBackWithWxLogin' wx_api_env cache get_oauth_atk fix_return_url scope app_id0 h_no_id h
where
get_oauth_atk app_id code = runExceptT $ do
m_secret <- lift $ get_secret app_id
secret <- case m_secret of
Nothing -> do
$logErrorS wxppLogSource $ "cannot get app secret from cache server"
throwError $ asString "no secret"
Just x -> return x
log_func <- askLoggerIO
err_or_atk_info <- liftIO $ flip runLoggingT log_func $ tryWxppWsResult $ flip runReaderT wx_api_env $
wxppOAuthGetAccessToken app_id secret code
case err_or_atk_info of
Left err -> do
if fmap wxppToErrorCodeX (wxppCallWxError err) == Just (wxppToErrorCode WxppOAuthCodeHasBeenUsed)
then do
$logDebugS wxppLogSource $ "OAuth Code has been used, retry"
return Nothing
else do
$logErrorS wxppLogSource $
"wxppOAuthGetAccessToken failed: " <> tshow err
throwError "wxppOAuthGetAccessToken failed"
Right x -> return $ Just x
} } } 1
| 调用微信 oauth 取 open i d 再继续处理下一步逻辑
注意:这里使用当前页面作为微信返回地址,因此query string参数不要与微信的冲突
不适用于第三方平台(因 wxppOAuthRequestAuthOutsideWx 不能处理第三方平台的情况 )
yesodComeBackWithWxLogin' :: ( MonadHandler m, MonadLoggerIO m
, ExcSafe . MonadThrow m
, RenderMessage (HandlerSite m) FormMessage
, HasWxppUrlConfig e, HasWreqSession e
, WxppCacheTemp c
)
=> e
-> c
-> (WxppAppID -> OAuthCode -> m (Either String (Maybe OAuthAccessTokenResult)))
-- ^ 取 oauth token 的函数
-- 若返回Nothing,会重新发起oauth
-> (UrlText -> m UrlText)
-- ^ 修改微信返回地址
-> OAuthScope
-> WxppAppID
-> m a
-- ^ 确实不能取得 open id 时调用
-> (WxppOpenID -> Maybe WxppUnionID -> Maybe OAuthGetUserInfoResult -> m a)
^ 取得 open_id
假定微信的回调参数 code , state 不会影响这部分的逻辑
-- OAuthGetUserInfoResult 是副产品,不一定有
openid / unionid 会尽量尝试从session里取得
-> m a
{ { { 1
yesodComeBackWithWxLogin' wx_api_env cache get_oauth_atk fix_return_url scope app_id h_no_id h = do
is_client_wx <- isJust <$> handlerGetWeixinClientVersion
m_code <- fmap (fmap OAuthCode) $ runInputGet $ iopt hiddenField "code"
case m_code of
Just code | not (deniedOAuthCode code) -> do
err_or_wx_id <- runExceptT $ do
实测表明,oauth重定向的url经常被不明来源重播
-- 因此,我们强制state参数必须有值
m_state <- lift $ lookupGetParam "state"
state <- case m_state of
Just x -> return x
Nothing -> do
$logErrorS wxppLogSource $ "OAuth state param is empty."
invalidArgs ["state"]
m_expected_state <- lift $ lookupCookie (cookieNameWxppOAuthState app_id)
unless (m_expected_state == Just state) $ do
$logDebugS wxppLogSource $
"OAuth state check failed, got: " <> tshow state
<> ", expect: " <> tshow m_expected_state
<> ", app_id: " <> unWxppAppID app_id
-- invalidArgs ["state"]
lift $ void $ start_oauth is_client_wx
m_oauth_atk_info <- ExceptT $ get_oauth_atk app_id code
case m_oauth_atk_info of
Nothing -> return Nothing
Just oauth_atk_info -> fmap Just $ do
let open_id = oauthAtkOpenID oauth_atk_info
scopes = oauthAtkScopes oauth_atk_info
if any oauthScopeCanGetUserInfo scopes
then do
let oauth_atk_pkg = getOAuthAccessTokenPkg (app_id, oauth_atk_info)
lang = "zh_CN"
log_func <- askLoggerIO
oauth_user_info <- mapExceptT (liftIO . flip runLoggingT log_func . flip runReaderT wx_api_env) $
tryWxppWsResultE "wxppOAuthGetUserInfo" $
wxppOAuthGetUserInfo lang oauth_atk_pkg
liftIO $ wxppCacheAddSnsUserInfo cache app_id lang oauth_user_info
return $ (open_id, Just oauth_user_info)
else do
return $ (open_id, Nothing)
case err_or_wx_id of
Left err -> do $logErrorS wxppLogSource $ "WX api error: " <> fromString err
liftIO $ throwIO $ userError "微信接口错误,请稍后重试"
Right Nothing -> start_oauth is_client_wx
Right (Just (open_id, m_oauth_uinfo)) ->
h open_id
(join $ oauthUserInfoUnionID <$> m_oauth_uinfo)
m_oauth_uinfo
_ -> do
m_state <- runInputGet $ iopt textField "state"
if isJust m_state
then do
-- 说明当前已经是从微信认证回来的回调
h_no_id
else start_oauth is_client_wx
where
start_oauth is_client_wx = do
random_state <- wxppOAuthMakeRandomState app_id
current_url <- getCurrentUrl
let oauth_return_url = UrlText $ fromMaybe current_url $ fmap pack $
urlUpdateQueryText
(filter (flip onotElem ["state", "code"] . fst))
(unpack current_url)
oauth_retrurn_url2 <- fix_return_url oauth_return_url
let oauth_url = if is_client_wx
then wxppOAuthRequestAuthInsideWx
Nothing -- not third-prty
app_id
scope
oauth_retrurn_url2
random_state
else wxppOAuthRequestAuthOutsideWx
app_id
oauth_retrurn_url2
random_state
redirect oauth_url
} } } 1
vim : set = marker :
| null | https://raw.githubusercontent.com/txkaduo/weixin-mp-sdk/5bab123eb3e1c74b4cae14d30003bc4e6b75b3b3/WeiXin/PublicPlatform/Yesod/Site.hs | haskell | ^ GET param name of signature
^ signed message text
cannot parse incoming XML message
只要有 primary 的回应,就忽略非primary的回应
本来延迟一点点只是为了希望能保持多个信息之间的顺序
| 生成随机字串作为 oauth 的state参数之用
CAUTION: 不要使用会话变量,因为会话可能因为超时而突然变成另一个新会话
^ oauth's state param
^ return URL
XXX: union id 目前设在一个指定的键下面。
下面的做法不能支持多个系统的union id
用户同意授权
we need to run wxpp call in (LoggingT IO)
- $logDebugS wxppLogSource $ "redirecting to: " <> T.pack rdr_url
授权失败
| 比较通用的处理从 oauth 重定向回来时的Handler的逻辑
如果用户通过授权,则返回 open id 及 oauth token 相关信息
用户同意授权
| 测试是否已经过微信用户授权,是则执行执行指定的函数
否则重定向至微信授权页面,待用户授权成功后再重定向回到当前页面
| 演示/测试微信 oauth 授权的页面
| 提供 access-token
为重用代码,错误报文格式与微信平台接口一样
为重用代码,错误报文格式与微信平台接口一样
| 初始化 WxppUserCachedInfo 表的数据
逻辑返回值是 EndUserQueryResult
| 模仿创建永久场景的二维码
| 返回一个二维码图像
| 接收第三方平台的事件通知
GET 方法用于echo检验
POST 方法真正处理业务逻辑
| 第三方平台接收公众号消息与事件的端点入口
GET 方法用于通讯检测
------------------------------------------------------------------------------
| initialize db table: WxppUserCachedInfo
已有的记录暂时不更新了
因为调用平台接口有点慢
| 若当前会话未经过微信登录,则调用 yesodComeBackWithWxLogin
否则从会话中取已登录的微信用户信息
^ 修改微信返回地址
^ 确实不能取得 open id 时调用
OAuthGetUserInfoResult 是副产品,不一定有
^ 修改微信返回地址
^ 确实不能取得 open id 时调用
OAuthGetUserInfoResult 是副产品,不一定有
^ 取 oauth token 的函数
若返回Nothing,会重新发起oauth
^ 修改微信返回地址
^ 确实不能取得 open id 时调用
OAuthGetUserInfoResult 是副产品,不一定有
因此,我们强制state参数必须有值
invalidArgs ["state"]
说明当前已经是从微信认证回来的回调
not third-prty | # OPTIONS_GHC -fno - warn - orphans #
# LANGUAGE TupleSections #
# LANGUAGE ViewPatterns #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE UndecidableInstances #
module WeiXin.PublicPlatform.Yesod.Site
( module WeiXin.PublicPlatform.Yesod.Site
, module WeiXin.PublicPlatform.Yesod.Site.Data
) where
{ { { 1 imports
import ClassyPrelude
#if MIN_VERSION_base(4, 13, 0)
import Control . ( MonadFail ( .. ) )
#else
#endif
import Control.Arrow
import Yesod
import qualified Control.Exception.Safe as ExcSafe
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Base64.URL as B64L
import qualified Data.ByteString.Char8 as C8
import qualified Data.Text as T
import qualified Data.Set as Set
import Control.Monad.Except (runExceptT, ExceptT(..), throwError, catchError, mapExceptT)
import Control.Monad.Trans.Maybe (runMaybeT, MaybeT(..))
import Control.Concurrent (forkIO)
import Network.URI ( parseURI, uriQuery, uriToString )
import Network.HTTP ( urlEncode )
import Yesod.Default.Util ( widgetFileReload )
import Data.Time ( addUTCTime )
import Web.Cookie (SetCookie(..))
import Yesod.Helpers.Handler ( httpErrorRetryWithValidParams
, reqPathPieceParamPostGet
, getCurrentUrl
)
import Yesod.Helpers.Logger
import Yesod.Helpers.Utils (urlUpdateQueryText, randomString)
import Control.Monad.Logger
import Network.Wai (lazyRequestBody)
import Text.XML (renderText, parseLBS)
import Text.XML.Cursor (fromDocument)
import Data.Default (def)
import qualified Data.Text.Lazy as LT
import Yesod.Core.Types (HandlerContents(HCError))
import Data.Yaml (decodeEither')
import qualified Data.List.NonEmpty as LNE
import Network.HTTP.Types.Status (mkStatus)
import Data.Conduit
import Data.Conduit.Binary (sinkLbs)
import qualified Data.Conduit.List as CL
import qualified Data.Conduit.Combinators as CC
import qualified Data.Aeson as A
import Database.Persist.Sql
import WeiXin.PublicPlatform.Yesod.Utils (handlerGetWeixinClientVersion)
import WeiXin.PublicPlatform.Yesod.Model
import WeiXin.PublicPlatform.Yesod.Site.Data
import WeiXin.PublicPlatform.Class
import WeiXin.PublicPlatform.Security
import WeiXin.PublicPlatform.Message
import WeiXin.PublicPlatform.Error
import WeiXin.PublicPlatform.WS
import WeiXin.PublicPlatform.EndUser
import WeiXin.PublicPlatform.QRCode
import WeiXin.PublicPlatform.OAuth
import WeiXin.PublicPlatform.ThirdParty
import WeiXin.PublicPlatform.Utils
import Yesod.Compat
#if MIN_VERSION_classy_prelude(1, 5, 0)
import Control.Concurrent (threadDelay)
#endif
} } } 1
withWxppSubHandler :: (WxppSub -> SubHandlerOf MaybeWxppSub master a)
-> SubHandlerOf MaybeWxppSub master a
withWxppSubHandler f = do
getSubYesodCompat
>>= liftIO . unMaybeWxppSub
>>= maybe notFound return
>>= f
checkSignature :: (HasWxppToken a, RenderMessage master FormMessage)
=> a
-> SubHandlerOf site master ()
{ { { 1
checkSignature foundation sign_param msg = do
let token = getWxppToken foundation
check_sign (tt, nn, sign) =
if B16.encodeBase16 sign0 == T.toLower sign
then Right ()
else Left $ "invalid signature"
where
sign0 = wxppSignature token tt nn msg
(tt, nn, sign) <- liftMonadHandlerToSub $ runInputGet $
(,,) <$> (TimeStampS <$> ireq textField "timestamp")
<*> (Nonce <$> ireq textField "nonce")
<*> ireq textField sign_param
case check_sign (tt, nn, sign) of
Left err -> do $logErrorS wxppLogSource $ "got invalid signature: " <> sign_param
invalidArgs $ return err
Right _ -> return ()
} } } 1
| 用于修改 HandlerT
withWxppSubLogging :: (LoggingTRunner r)
=> r
-> SubHandlerOf site master a
-> SubHandlerOf site master a
withWxppSubLogging foundation h = do
runLoggingTWith foundation $ LoggingT $ \log_func -> do
withLogFuncInSubHandler log_func h
getMessageR :: (RenderMessage master FormMessage) => SubHandlerOf MaybeWxppSub master Text
getMessageR = withWxppSubHandler $ \ foundation -> do
withWxppSubLogging foundation $ do
checkSignature foundation "signature" ""
runInputGet $ ireq textField "echostr"
postMessageR :: (RenderMessage master FormMessage) => SubHandlerOf MaybeWxppSub master Text
postMessageR = withWxppSubHandler $ \ foundation -> withWxppSubLogging foundation $ do
let app_id = getWxppAppID foundation
realHandlerMsg foundation (ProcAppSingle app_id)
realHandlerMsg :: forall site master a.
( RenderMessage master FormMessage
, HasWxppToken a, HasAesKeys a, HasWxppProcessor a
)
=> a
-> ProcAppIdInfo
-> SubHandlerOf site master Text
{ { { 1
realHandlerMsg foundation app_info = do
checkSignature foundation "signature" ""
m_enc_type <- lookupGetParam "encrypt_type"
enc <- case m_enc_type of
Nothing -> return False
Just "" -> return False
Just "aes" -> return True
Just x -> do
$(logErrorS) wxppLogSource $
"unknown/unsupported encrypt_type: " <> x
httpErrorRetryWithValidParams $ T.pack $
"Retry with valid parameters: encrypt_type(not supported)"
req <- waiRequest
lbs <- liftIO $ lazyRequestBody req
let aks = getAesKeys foundation
app_token = getWxppToken foundation
processor = getWxppProcessor foundation
err_or_resp <- runExceptT $ do
(decrypted_xml0, m_enc_akey) <-
if enc
then do
(either throwError return $ parse_xml_lbs lbs >>= wxppTryDecryptByteStringDocumentE my_app_id aks)
>>= maybe (throwError $ "Internal Error: no AesKey available to decrypt")
(return . (LB.fromStrict *** Just))
else return (lbs, Nothing)
let err_or_parsed = parse_xml_lbs decrypted_xml0 >>= wxppInMsgEntityFromDocument
m_ime0 <- case err_or_parsed of
Left err -> do
$logErrorS wxppLogSource $ fromString $ "Error when parsing incoming XML: " ++ err
return Nothing
Right x -> return $ Just x
ime0 <- case m_ime0 of
Nothing -> do
liftIO $ wxppOnParseInMsgError processor app_info lbs
throwError $ "Cannot parse incoming XML"
Just x -> return x
pre_result <- liftIO $ wxppPreProcessInMsg processor app_info decrypted_xml0 ime0
case pre_result of
Left err -> do
$logErrorS wxppLogSource $ "wxppPreProcessInMsg failed: " <> fromString err
throwError "程序内部错误,请稍后重试"
Right Nothing -> do
$logDebugS wxppLogSource $ "message handle skipped because middleware return Nothing"
return ("", Nothing)
Right (Just (decrypted_xml, ime)) -> do
log_func <- askLoggerIO
let user_open_id = wxppInFromUserName ime
target_username = wxppInToUserName ime
let handle_msg = wxppMsgHandler processor
try_handle_msg = mapExceptT liftIO $ ExceptT $ flip runLoggingT log_func $ do
ExcSafe.tryAny (liftIO $ handle_msg app_info decrypted_xml ime)
>>= \err_or_x -> do
case err_or_x of
Left err -> do
$logErrorS wxppLogSource $
"error when handling incoming message: " <> tshow err
return $ Left $ show err
Right x -> return x
let post_handle_msg = wxppPostProcessInMsg processor
do_post_handle_msg out_res0 = mapExceptT liftIO $ ExceptT $ flip runLoggingT log_func $ do
ExcSafe.tryAny (liftIO $ post_handle_msg app_info decrypted_xml ime out_res0)
>>= \err_or_x -> do
case err_or_x of
Left err -> do
$logErrorS wxppLogSource $
"error when post-handling incoming message: " <> tshow err
return $ Left $ show err
Right x -> return x
let do_on_error err = ExceptT $
liftIO (wxppOnProcessInMsgError processor app_info decrypted_xml ime err)
out_res <- (try_handle_msg `catchError` \err -> do_on_error err >> throwError err)
>>= do_post_handle_msg
let (primary_out_msgs, secondary_out_msgs) = (map snd *** map snd) $ partition fst out_res
如果没 primary 回应,而 secondary 回应有多个,则只选择第一个
let split_head ls = case ls of
[] -> (Nothing, [])
(x:xs) -> (Just x, xs)
let (m_resp_out_msg, other_out_msgs) =
if null primary_out_msgs
then (, []) $ listToMaybe $ catMaybes secondary_out_msgs
else split_head $ catMaybes primary_out_msgs
now <- liftIO getCurrentTime
let mk_out_msg_entity x = WxppOutMsgEntity
user_open_id
target_username
now
x
let extra_data = map (user_open_id,) other_out_msgs
liftM (, Just extra_data) $
fmap (fromMaybe "") $ forM m_resp_out_msg $ \out_msg -> do
liftM (LT.toStrict . renderText def) $ do
let out_msg_entity = mk_out_msg_entity out_msg
case m_enc_akey of
Just enc_akey ->
ExceptT $ wxppOutMsgEntityToDocumentE
my_app_id app_token enc_akey out_msg_entity
Nothing ->
return $ wxppOutMsgEntityToDocument out_msg_entity
case err_or_resp of
Left err -> do
$(logErrorS) wxppLogSource $ fromString $
"cannot encode outgoing message into XML: " <> err
liftIO $ throwIO $ HCError $
InternalError "cannot encode outgoing message into XML"
Right (xmls, m_extra_data) -> do
forM_ m_extra_data $ \other_out_msgs -> do
when (not $ null other_out_msgs) $ do
void $ liftIO $ async $ do
threadDelay $ 1000 * 100
wxppSendOutMsgs processor to_app_id other_out_msgs
return xmls
where
parse_xml_lbs x = case parseLBS def x of
Left ex -> Left $ "Failed to parse XML: " <> show ex
Right xdoc -> return xdoc
to_app_id = procAppIdInfoReceiverId app_info
my_app_id = procAppIdInfoMyId app_info
} } } 1
这是按官方文档的思路,用于防 csrf
所生成的随机字串会放在 cookieNameWxppOAuthState cookie 里
wxppOAuthMakeRandomState :: (MonadHandler m)
=> WxppAppID
-> m Text
{ { { 1
wxppOAuthMakeRandomState app_id = do
m_oauth_random_st <- lookupCookie (cookieNameWxppOAuthState app_id)
case m_oauth_random_st of
Just x | not (null x) -> do
return x
_ -> do
random_state <- fmap pack $ randomString 32 (['0'..'9'] <> ['a'..'z'] <> ['A'..'Z'])
setCookie (def { setCookieName = encodeUtf8 (cookieNameWxppOAuthState app_id), setCookieValue = encodeUtf8 random_state })
return random_state
} } } 1
wxppOAuthLoginRedirectUrl :: (MonadHandler m)
=> (Route MaybeWxppSub -> [(Text, Text)] -> m Text)
-> Maybe WxppAppID
^
-> WxppAppID
-> OAuthScope
-> m UrlText
{ { { 1
wxppOAuthLoginRedirectUrl url_render m_comp_app_id app_id scope user_st return_url = do
random_state <- wxppOAuthMakeRandomState app_id
let state = random_state <> ":" <> user_st
oauth_retrurn_url <- liftM UrlText $
url_render OAuthCallbackR [ ("return", unUrlText return_url) ]
let auth_url = wxppOAuthRequestAuthInsideWx m_comp_app_id app_id scope
oauth_retrurn_url
state
return auth_url
} } } 1
sessionKeyWxppUser :: WxppAppID -> Text
sessionKeyWxppUser app_id = "wx|" <> unWxppAppID app_id
cookieNameWxppOAuthState :: WxppAppID -> Text
cookieNameWxppOAuthState app_id = "wx-oauth-st|" <> unWxppAppID app_id
sessionKeyWxppUnionId :: Text
sessionKeyWxppUnionId = "wx-union-id"
sessionMarkWxppUser :: MonadHandler m
=> WxppAppID
-> WxppOpenID
-> Maybe WxppUnionID
-> m ()
{ { { 1
sessionMarkWxppUser app_id open_id m_union_id = do
setSession (sessionKeyWxppUser app_id) (unWxppOpenID open_id)
case fmap unWxppUnionID m_union_id of
Just union_id | not (null union_id) -> setSession sessionKeyWxppUnionId union_id
_ -> deleteSession sessionKeyWxppUnionId
} } } 1
| 从 session
sessionGetWxppUser :: MonadHandler m
=> WxppAppID
-> m (Maybe WxppOpenID)
sessionGetWxppUser app_id = fmap (fmap WxppOpenID) $ lookupSession (sessionKeyWxppUser app_id)
| 从 session 及 WxppUnionID
sessionGetWxppUserU :: MonadHandler m => WxppAppID -> m (Maybe (WxppAppOpenID, Maybe WxppUnionID))
sessionGetWxppUserU app_id = runMaybeT $ do
open_id <- MaybeT $ sessionGetWxppUser app_id
m_union_id <- lift $ fmap WxppUnionID <$> lookupSession sessionKeyWxppUnionId
return (WxppAppOpenID app_id open_id, m_union_id)
getOAuthCallbackR :: Yesod master => SubHandlerOf MaybeWxppSub master Html
{ { { 1
getOAuthCallbackR = withWxppSubHandler $ \sub -> do
m_code <- lookupGetParam "code"
return_url <- reqPathPieceParamPostGet "return"
let app_id = getWxppAppID sub
secret = getWxppSecret sub
cache = wxppSubCacheBackend sub
oauth_state <- liftM (fromMaybe "") $ lookupGetParam "state"
let (expected_st, state') = T.breakOn ":" oauth_state
m_expected_state <- lookupCookie (cookieNameWxppOAuthState app_id)
unless (m_expected_state == Just expected_st) $ do
$logErrorS wxppLogSource $
"OAuth state check failed, got: " <> oauth_state
liftIO $ throwIO $ HCError NotAuthenticated
let state = fromMaybe state' $ T.stripPrefix ":" state'
let api_env = wxppSubApiEnv sub
case fmap OAuthCode m_code of
Just code | not (deniedOAuthCode code) -> do
handler functions in new version yesod may not derive MonadCatch instance
log_func <- askLoggerIO
err_or_atk_info <- liftIO $ flip runLoggingT log_func $
tryWxppWsResult $ flip runReaderT api_env $
wxppOAuthGetAccessToken app_id secret code
atk_info <- case err_or_atk_info of
Left err -> do
$logErrorS wxppLogSource $
"wxppOAuthGetAccessToken failed: " <> tshow err
liftIO $ throwIO $ HCError NotAuthenticated
Right x -> return x
now <- liftIO getCurrentTime
let expiry = addUTCTime (oauthAtkTTL atk_info) now
open_id = oauthAtkOpenID atk_info
scopes = oauthAtkScopes atk_info
atk_p = getOAuthAccessTokenPkg (app_id, atk_info)
let get_union_id1 = MaybeT $ return $ oauthAtkUnionID atk_info
get_union_id2 = do
guard $ any oauthScopeCanGetUserInfo scopes
err_or_oauth_user_info <- liftIO $ flip runLoggingT log_func $
tryWxppWsResult $ flip runReaderT api_env $
wxppOAuthGetUserInfo' atk_p
case err_or_oauth_user_info of
Left err -> do $logErrorS wxppLogSource $ "wxppOAuthGetUserInfo' failed: " <> tshow err
mzero
Right oauth_user_info -> do
liftIO $ wxppCacheAddSnsUserInfo cache app_id "zh_CN" oauth_user_info
MaybeT $ return $ oauthUserInfoUnionID oauth_user_info
m_union_id <- runMaybeT $ get_union_id1 <|> get_union_id2
liftIO $ wxppCacheAddOAuthAccessToken cache atk_p expiry
sessionMarkWxppUser app_id open_id m_union_id
let rdr_url = case parseURI return_url of
Just uri ->
let qs = uriQuery uri
qs' = case qs of
_ | null qs -> qs ++ "?"
| qs == "?" -> qs
| otherwise -> qs ++ "&"
new_uri = uri { uriQuery =
qs' ++ "state=" ++ urlEncode (T.unpack state)
}
in uriToString id new_uri ""
_ -> return_url
redirect rdr_url
_ -> do
liftMonadHandlerToSub $ defaultLayout $ do
$(widgetFileReload def "oauth/user_denied")
} } } 1
wxppHandlerOAuthReturnGetInfo :: (MonadHandler m
#if MIN_VERSION_yesod(1, 6, 0)
, MonadLogger m
#else
, MonadLogger m
#endif
, RenderMessage (HandlerSite m) FormMessage)
=> SomeWxppApiBroker
-> WxppAppID
-> m (Maybe (WxppOpenID, OAuthTokenInfo))
{ { { 1
wxppHandlerOAuthReturnGetInfo broker app_id = do
m_code <- fmap (fmap OAuthCode) $ runInputGet $ iopt textField "code"
case m_code of
Just code | not (deniedOAuthCode code) -> do
err_or_muid <- runExceptT $ do
err_or_atk_res <- liftIO $ wxppApiBrokerOAuthGetAccessToken broker app_id code
atk_res <- case err_or_atk_res of
Nothing -> do
$logErrorS wxppLogSource $ "Broker call failed: no such app"
throwError $ asString "no such app"
Just (WxppWsResp (Left err)) -> do
$logErrorS wxppLogSource $
"wxppApiBrokerOAuthGetAccessToken failed: " <> tshow err
throwError "wxppApiBrokerOAuthGetAccessToken failed"
Just (WxppWsResp (Right x)) -> return x
let open_id = oauthAtkOpenID atk_res
now <- liftIO getCurrentTime
let atk_info = fromOAuthAccessTokenResult now atk_res
lift $ setSession (sessionKeyWxppUser app_id) (unWxppOpenID open_id)
return (open_id, atk_info)
return $ either (const Nothing) Just $ err_or_muid
_ -> do
$logErrorS wxppLogSource $ "should never reach here"
return Nothing
} } } 1
wxppOAuthHandler :: (ExcSafe.MonadThrow m, MonadHandler m, WxppCacheTemp c)
=> c
-> (Route MaybeWxppSub -> [(Text, Text)] -> m Text)
-> Maybe WxppAppID
^
-> WxppAppID
-> OAuthScope
-> ( OAuthAccessTokenPkg -> m a )
-> m a
{ { { 1
wxppOAuthHandler cache render_url m_comp_app_id app_id scope f = do
m_atk_p <- wxppOAuthHandlerGetAccessTokenPkg cache app_id scope
case m_atk_p of
Nothing -> do
is_wx <- isJust <$> handlerGetWeixinClientVersion
unless is_wx $ do
permissionDenied "请用在微信里打开此网页"
url <- getCurrentUrl
wxppOAuthLoginRedirectUrl render_url m_comp_app_id app_id scope "" (UrlText url)
>>= redirect . unUrlText
Just atk_p -> f atk_p
} } } 1
wxppOAuthHandlerGetAccessTokenPkg :: (MonadHandler m, WxppCacheTemp c)
=> c
-> WxppAppID
-> OAuthScope
-> m (Maybe OAuthAccessTokenPkg)
{ { { 1
wxppOAuthHandlerGetAccessTokenPkg cache app_id scope = do
m_oauth_st <- sessionGetWxppUser app_id
case m_oauth_st of
Nothing -> return Nothing
Just open_id -> do
m_atk_info <- liftIO $ wxppCacheGetOAuthAccessToken cache
app_id open_id (Set.singleton scope)
case m_atk_info of
Nothing -> return Nothing
Just atk_info -> return $ Just (packOAuthTokenInfo app_id open_id atk_info)
} } } 1
getOAuthTestR :: SubHandlerOf MaybeWxppSub master Text
getOAuthTestR = withWxppSubHandler $ \sub -> do
let app_id = getWxppAppID sub
m_oauth_st <- sessionGetWxppUser app_id
case m_oauth_st of
Nothing -> return "no open id, authorization failed"
Just open_id -> return $ "Your open id is: " <> unWxppOpenID open_id
checkWaiReqThen :: (WxppSub -> SubHandlerOf MaybeWxppSub master a)
-> SubHandlerOf MaybeWxppSub master a
checkWaiReqThen f = withWxppSubHandler $ \foundation -> withWxppSubLogging foundation $ do
b <- waiRequest >>= liftIO . (wxppSubTrustedWaiReq $ wxppSubOptions foundation)
if b
then f foundation
else permissionDenied "denied by security check"
mimicInvalidAppID :: SubHandlerOf MaybeWxppSub master a
mimicInvalidAppID = sendResponse $ toJSON $
WxppAppError
(WxppErrorX $ Right WxppInvalidAppID)
"invalid app id"
mimicServerBusy :: Text -> SubHandlerOf MaybeWxppSub master a
mimicServerBusy s = sendResponse $ toJSON $
WxppAppError
(WxppErrorX $ Right WxppServerBusy)
s
forwardWsResult :: (ToJSON a)
=> String
-> Either WxppWsCallError a
-> SubHandlerOf MaybeWxppSub master Value
{ { { 1
forwardWsResult op_name res = do
case res of
Left (WxppWsErrorApp err) -> do
sendResponse $ toJSON err
Left err -> do
$logErrorS wxppLogSource $ fromString $
op_name ++ " failed: " ++ show err
mimicServerBusy $ fromString $ op_name ++ " failed"
Right x -> do
return $ toJSON x
} } } 1
逻辑上的返回值是 AccessToken
getGetAccessTokenR :: SubHandlerOf MaybeWxppSub master Value
getGetAccessTokenR = checkWaiReqThen $ \foundation -> do
alreadyExpired
liftM toJSON $ getAccessTokenSubHandler' foundation
| 找 OpenID 对应的 UnionID
逻辑上的返回值是 Maybe
getGetUnionIDR :: WxppOpenID -> SubHandlerOf MaybeWxppSub master Value
{ { { 1
getGetUnionIDR open_id = checkWaiReqThen $ \foundation -> do
alreadyExpired
let sm_mode = wxppSubMakeupUnionID $ wxppSubOptions foundation
if sm_mode
then do
return $ toJSON $ Just $ fakeUnionID open_id
else do
let app_id = getWxppAppID foundation
let cache = wxppSubCacheBackend foundation
(liftIO $ tryWxppWsResult $ wxppCacheLookupUserInfo cache app_id open_id)
>>= forwardWsResult "wxppCacheLookupUserInfo"
} } } 1
getInitCachedUsersR :: SubHandlerOf MaybeWxppSub master Value
{ { { 1
getInitCachedUsersR = checkWaiReqThen $ \foundation -> do
alreadyExpired
atk <- getAccessTokenSubHandler' foundation
let api_env = wxppSubApiEnv foundation
_ <- liftIO $ forkIO $ wxppSubRunLoggingT foundation $ do
_ <- runWxppDB (wxppSubRunDBAction foundation) $ initWxppUserDbCacheOfApp api_env (return atk)
return ()
return $ toJSON ("run in background" :: Text)
} } } 1
| 为客户端调用平台的 wxppQueryEndUserInfo 接口
getQueryUserInfoR :: WxppOpenID -> SubHandlerOf MaybeWxppSub master Value
{ { { 1
getQueryUserInfoR open_id = checkWaiReqThen $ \foundation -> do
alreadyExpired
atk <- getAccessTokenSubHandler' foundation
let sm_mode = wxppSubMakeupUnionID $ wxppSubOptions foundation
fix_uid qres =
if sm_mode
then endUserQueryResultSetUnionID (Just $ fakeUnionID open_id) <$> qres
else qres
log_func <- askLoggerIO
liftIO (flip runLoggingT log_func $ tryWxppWsResult
(flip runReaderT (wxppSubApiEnv foundation) $ wxppQueryEndUserInfo atk open_id)
)
>>= return . fix_uid
>>= forwardWsResult "wxppQueryEndUserInfo"
} } } 1
行为接近微信平台的接口,区别是
输入仅仅是一个 WxppScene
postCreateQrCodePersistR :: SubHandlerOf MaybeWxppSub master Value
{ { { 1
postCreateQrCodePersistR = checkWaiReqThen $ \foundation -> do
let api_env = wxppSubApiEnv foundation
alreadyExpired
scene <- decodePostBodyAsYaml
let sm_mode = wxppSubFakeQRTicket $ wxppSubOptions foundation
if sm_mode
then do
to_parent <- getRouteToParent
render_url <- liftMonadHandlerToSub getUrlRender
let qrcode_base_url = render_url $ to_parent ShowSimulatedQRCodeR
let fake_ticket = (scene, qrcode_base_url)
return $ toJSON $ B64L.encodeBase64 $ LB.toStrict $ A.encode fake_ticket
else do
atk <- getAccessTokenSubHandler' foundation
flip runReaderT api_env $ do
liftM toJSON $ wxppQrCodeCreatePersist atk scene
} } } 1
其内容是 WxppScene 用 JSON 格式表示之后的字节流
getShowSimulatedQRCodeR :: SubHandlerOf MaybeWxppSub master TypedContent
{ { { 1
getShowSimulatedQRCodeR = do
ticket_s <- lookupGetParam "ticket"
>>= maybe (httpErrorRetryWithValidParams ("missing ticket" :: Text)) return
(ticket :: FakeQRTicket) <- case B64L.decodeBase64 (C8.pack $ T.unpack ticket_s) of
Left _ -> httpErrorRetryWithValidParams ("invalid ticket" :: Text)
Right bs -> case decodeEither' bs of
Left err -> do
$logErrorS wxppLogSource $ fromString $
"cannot decode request body as YAML: " ++ show err
sendResponseStatus (mkStatus 449 "Retry With") $
("retry wtih valid request JSON body" :: Text)
Right (x, y) -> return (x, UrlText y)
let scene = fst ticket
let input = C8.unpack $ LB.toStrict $ A.encode scene
let bs = encodeStringQRCodeJpeg 5 input
return $ toTypedContent (typeSvg, toContent bs)
} } } 1
| 返回与输入的 union i d 匹配的所有 open i d 及 相应的 app_id
getLookupOpenIDByUnionIDR :: WxppUnionID -> SubHandlerOf WxppSubNoApp master Value
getLookupOpenIDByUnionIDR union_id = checkWaiReqThenNA $ \foundation -> do
alreadyExpired
liftM toJSON $ liftIO $ wxppSubNoAppUnionIdByOpenId foundation union_id
getTpEventNoticeR :: (RenderMessage master FormMessage) => SubHandlerOf WxppTpSub master Text
getTpEventNoticeR = do
foundation <- getSubYesodCompat
withWxppSubLogging foundation $ do
checkSignature foundation "signature" ""
runInputGet $ ireq textField "echostr"
postTpEventNoticeR :: (Yesod master, RenderMessage master FormMessage)
=> SubHandlerOf WxppTpSub master Text
{ { { 1
postTpEventNoticeR = do
foundation <- getSubYesodCompat
req <- waiRequest
lbs <- liftIO $ lazyRequestBody req
let enc_key = LNE.head $ wxppTpSubAesKeys foundation
my_app_id = wxppTpSubComponentAppId foundation
err_or_resp <- runExceptT $ do
encrypted_xml_t <- either throwError return
(parse_xml_lbs lbs >>= wxppEncryptedTextInDocumentE)
lift $ checkSignature foundation "msg_signature" encrypted_xml_t
decrypted_xml0 <- either throwError (return . fromStrict) $ do
left T.unpack (B64.decodeBase64 (encodeUtf8 encrypted_xml_t))
>>= wxppDecrypt my_app_id enc_key
let err_or_parsed = parse_xml_lbs decrypted_xml0 >>= wxppTpDiagramFromCursor . fromDocument
uts_or_notice <- case err_or_parsed of
Left err -> do
$logErrorS wxppLogSource $ fromString $ "Error when parsing incoming XML: " ++ err
throwError "Cannot parse XML document"
Right x -> return x
case uts_or_notice of
Left unknown_info_type -> do
$logErrorS wxppLogSource $
"Failed to handle event notice: unknown InfoType: "
<> unknown_info_type
throwError $ "Unknown or unsupported InfoType"
Right notice -> do
ExceptT $ wxppTpSubHandlerEventNotice foundation notice
case err_or_resp of
Left err -> do
$(logErrorS) wxppLogSource $ fromString $
"Cannot handle third-party event notice: " <> err
liftIO $ throwIO $ HCError $
InternalError "Cannot handle third-party event notice"
Right output -> do
return output
where
parse_xml_lbs x = case parseLBS def x of
Left ex -> Left $ "Failed to parse XML: " <> show ex
Right xdoc -> return xdoc
} } } 1
POST
getTpMessageR :: (RenderMessage master FormMessage)
=> WxppAppID -> SubHandlerOf WxppTpSub master Text
getTpMessageR _auther_app_id = do
foundation <- getSubYesodCompat
checkSignature foundation "signature" ""
runInputGet $ ireq textField "echostr"
postTpMessageR :: (RenderMessage master FormMessage)
=> WxppAppID -> SubHandlerOf WxppTpSub master Text
postTpMessageR auther_app_id = do
foundation <- getSubYesodCompat
let comp_app_id = getWxppAppID foundation
realHandlerMsg foundation (ProcAppThirdParty comp_app_id auther_app_id)
instance (Yesod master, RenderMessage master FormMessage) =>
YesodSubDispatch
MaybeWxppSub
#if MIN_VERSION_yesod(1, 6, 0)
master
#else
(HandlerOf master)
#endif
where yesodSubDispatch = $(mkYesodSubDispatch resourcesMaybeWxppSub)
instance
YesodSubDispatch
WxppSubNoApp
#if MIN_VERSION_yesod(1, 6, 0)
master
#else
(HandlerOf master)
#endif
where yesodSubDispatch = $(mkYesodSubDispatch resourcesWxppSubNoApp)
instance (Yesod master, RenderMessage master FormMessage)
=> YesodSubDispatch
WxppTpSub
#if MIN_VERSION_yesod(1, 6, 0)
master
#else
(HandlerOf master)
#endif
where yesodSubDispatch = $(mkYesodSubDispatch resourcesWxppTpSub)
checkWaiReqThenNA :: (WxppSubNoApp -> SubHandlerOf WxppSubNoApp master a)
-> SubHandlerOf WxppSubNoApp master a
checkWaiReqThenNA f = do
foundation <- getSubYesodCompat
wxppSubNoAppRunLoggingT foundation $ LoggingT $ \ log_func -> do
withLogFuncInSubHandler log_func $ do
b <- waiRequest >>= liftIO . wxppSubNoAppCheckWaiReq foundation
if b
then f foundation
else permissionDenied "denied by security check"
decodePostBodyAsYaml :: (FromJSON a)
=> SubHandlerOf MaybeWxppSub master a
{ { { 1
decodePostBodyAsYaml = do
body <- runConduit $ rawRequestBody .| sinkLbs
case decodeEither' (LB.toStrict body) of
Left err -> do
$logErrorS wxppLogSource $ fromString $
"cannot decode request body as YAML: " ++ show err
sendResponseStatus (mkStatus 449 "Retry With") $
("retry wtih valid request JSON body" :: Text)
Right x -> return x
} } } 1
getAccessTokenSubHandler' :: WxppSub
-> SubHandlerOf MaybeWxppSub master AccessToken
getAccessTokenSubHandler' foundation = do
let cache = wxppSubCacheBackend foundation
let app_id = getWxppAppID foundation
(liftIO $ wxppCacheGetAccessToken cache app_id)
>>= maybe (mimicServerBusy "no access token available") (return . fst)
fakeUnionID :: WxppOpenID -> WxppUnionID
fakeUnionID (WxppOpenID x) = WxppUnionID $ "fu_" <> x
initWxppUserDbCacheOfApp :: ( MonadIO m, MonadLogger m)
=> WxppApiEnv
-> m AccessToken
-> ReaderT WxppDbBackend m Int
{ { { 1
initWxppUserDbCacheOfApp api_env get_atk = do
atk <- lift get_atk
flip runReaderT api_env $ do
runConduit $
wxppGetEndUserSource' (lift $ lift get_atk)
.| CL.concatMap wxppOpenIdListInGetUserResult
.| save_to_db atk
.| CC.length
where
save_to_db atk = awaitForever $ \open_id -> do
let app_id = accessTokenApp atk
now <- liftIO getCurrentTime
_ <- lift $ do
m_old <- lift $ getBy $ UniqueWxppUserCachedInfo open_id app_id
case m_old of
Just _ -> do
假定 open i d 及 union i d 对于固定的 app 是固定的
return ()
Nothing -> do
qres <- wxppQueryEndUserInfo atk open_id
_ <- lift $ insertBy $ WxppUserCachedInfo app_id
(endUserQueryResultOpenID qres)
(endUserQueryResultUnionID qres)
now
return ()
lift transactionSave
yield ()
} } } 1
yesodMakeSureInWxLoggedIn :: ( MonadHandler m, MonadLoggerIO m
, ExcSafe . MonadThrow m
, RenderMessage (HandlerSite m) FormMessage
, HasWxppUrlConfig e, HasWreqSession e
, WxppCacheTemp c
)
=> e
-> c
-> (WxppAppID -> m (Maybe WxppAppSecret))
-> (UrlText -> m UrlText)
-> OAuthScope
-> WxppAppID
-> m a
-> (WxppOpenID -> Maybe WxppUnionID -> Maybe OAuthGetUserInfoResult-> m a)
^ 取得 open_id
假定微信的回调参数 code , state 不会影响这部分的逻辑
openid / unionid 会尽量尝试从session里取得
-> m a
{ { { 1
yesodMakeSureInWxLoggedIn wx_api_env cache get_secret fix_return_url scope app_id h_no_id h = do
m_wx_id <- sessionGetWxppUserU app_id
case m_wx_id of
Just (open_id, m_union_id) -> h (getWxppOpenID open_id) m_union_id Nothing
Nothing -> yesodComeBackWithWxLogin wx_api_env cache get_secret fix_return_url scope app_id h_no_id h
} } } 1
| 调用微信 oauth 取 open i d 再继续处理下一步逻辑
注意:这里使用当前页面作为微信返回地址,因此query string参数不要与微信的冲突
不适用于第三方平台(因 wxppOAuthRequestAuthOutsideWx 不能处理第三方平台的情况 )
yesodComeBackWithWxLogin :: ( MonadHandler m, MonadLoggerIO m
, ExcSafe . MonadThrow m
, RenderMessage (HandlerSite m) FormMessage
, HasWxppUrlConfig e, HasWreqSession e
, WxppCacheTemp c
)
=> e
-> c
-> (WxppAppID -> m (Maybe WxppAppSecret))
-> (UrlText -> m UrlText)
-> OAuthScope
-> WxppAppID
-> m a
-> (WxppOpenID -> Maybe WxppUnionID -> Maybe OAuthGetUserInfoResult -> m a)
^ 取得 open_id
假定微信的回调参数 code , state 不会影响这部分的逻辑
openid / unionid 会尽量尝试从session里取得
-> m a
{ { { 1
yesodComeBackWithWxLogin wx_api_env cache get_secret fix_return_url scope app_id0 h_no_id h = do
yesodComeBackWithWxLogin' wx_api_env cache get_oauth_atk fix_return_url scope app_id0 h_no_id h
where
get_oauth_atk app_id code = runExceptT $ do
m_secret <- lift $ get_secret app_id
secret <- case m_secret of
Nothing -> do
$logErrorS wxppLogSource $ "cannot get app secret from cache server"
throwError $ asString "no secret"
Just x -> return x
log_func <- askLoggerIO
err_or_atk_info <- liftIO $ flip runLoggingT log_func $ tryWxppWsResult $ flip runReaderT wx_api_env $
wxppOAuthGetAccessToken app_id secret code
case err_or_atk_info of
Left err -> do
if fmap wxppToErrorCodeX (wxppCallWxError err) == Just (wxppToErrorCode WxppOAuthCodeHasBeenUsed)
then do
$logDebugS wxppLogSource $ "OAuth Code has been used, retry"
return Nothing
else do
$logErrorS wxppLogSource $
"wxppOAuthGetAccessToken failed: " <> tshow err
throwError "wxppOAuthGetAccessToken failed"
Right x -> return $ Just x
} } } 1
| 调用微信 oauth 取 open i d 再继续处理下一步逻辑
注意:这里使用当前页面作为微信返回地址,因此query string参数不要与微信的冲突
不适用于第三方平台(因 wxppOAuthRequestAuthOutsideWx 不能处理第三方平台的情况 )
yesodComeBackWithWxLogin' :: ( MonadHandler m, MonadLoggerIO m
, ExcSafe . MonadThrow m
, RenderMessage (HandlerSite m) FormMessage
, HasWxppUrlConfig e, HasWreqSession e
, WxppCacheTemp c
)
=> e
-> c
-> (WxppAppID -> OAuthCode -> m (Either String (Maybe OAuthAccessTokenResult)))
-> (UrlText -> m UrlText)
-> OAuthScope
-> WxppAppID
-> m a
-> (WxppOpenID -> Maybe WxppUnionID -> Maybe OAuthGetUserInfoResult -> m a)
^ 取得 open_id
假定微信的回调参数 code , state 不会影响这部分的逻辑
openid / unionid 会尽量尝试从session里取得
-> m a
{ { { 1
yesodComeBackWithWxLogin' wx_api_env cache get_oauth_atk fix_return_url scope app_id h_no_id h = do
is_client_wx <- isJust <$> handlerGetWeixinClientVersion
m_code <- fmap (fmap OAuthCode) $ runInputGet $ iopt hiddenField "code"
case m_code of
Just code | not (deniedOAuthCode code) -> do
err_or_wx_id <- runExceptT $ do
实测表明,oauth重定向的url经常被不明来源重播
m_state <- lift $ lookupGetParam "state"
state <- case m_state of
Just x -> return x
Nothing -> do
$logErrorS wxppLogSource $ "OAuth state param is empty."
invalidArgs ["state"]
m_expected_state <- lift $ lookupCookie (cookieNameWxppOAuthState app_id)
unless (m_expected_state == Just state) $ do
$logDebugS wxppLogSource $
"OAuth state check failed, got: " <> tshow state
<> ", expect: " <> tshow m_expected_state
<> ", app_id: " <> unWxppAppID app_id
lift $ void $ start_oauth is_client_wx
m_oauth_atk_info <- ExceptT $ get_oauth_atk app_id code
case m_oauth_atk_info of
Nothing -> return Nothing
Just oauth_atk_info -> fmap Just $ do
let open_id = oauthAtkOpenID oauth_atk_info
scopes = oauthAtkScopes oauth_atk_info
if any oauthScopeCanGetUserInfo scopes
then do
let oauth_atk_pkg = getOAuthAccessTokenPkg (app_id, oauth_atk_info)
lang = "zh_CN"
log_func <- askLoggerIO
oauth_user_info <- mapExceptT (liftIO . flip runLoggingT log_func . flip runReaderT wx_api_env) $
tryWxppWsResultE "wxppOAuthGetUserInfo" $
wxppOAuthGetUserInfo lang oauth_atk_pkg
liftIO $ wxppCacheAddSnsUserInfo cache app_id lang oauth_user_info
return $ (open_id, Just oauth_user_info)
else do
return $ (open_id, Nothing)
case err_or_wx_id of
Left err -> do $logErrorS wxppLogSource $ "WX api error: " <> fromString err
liftIO $ throwIO $ userError "微信接口错误,请稍后重试"
Right Nothing -> start_oauth is_client_wx
Right (Just (open_id, m_oauth_uinfo)) ->
h open_id
(join $ oauthUserInfoUnionID <$> m_oauth_uinfo)
m_oauth_uinfo
_ -> do
m_state <- runInputGet $ iopt textField "state"
if isJust m_state
then do
h_no_id
else start_oauth is_client_wx
where
start_oauth is_client_wx = do
random_state <- wxppOAuthMakeRandomState app_id
current_url <- getCurrentUrl
let oauth_return_url = UrlText $ fromMaybe current_url $ fmap pack $
urlUpdateQueryText
(filter (flip onotElem ["state", "code"] . fst))
(unpack current_url)
oauth_retrurn_url2 <- fix_return_url oauth_return_url
let oauth_url = if is_client_wx
then wxppOAuthRequestAuthInsideWx
app_id
scope
oauth_retrurn_url2
random_state
else wxppOAuthRequestAuthOutsideWx
app_id
oauth_retrurn_url2
random_state
redirect oauth_url
} } } 1
vim : set = marker :
|
7017cd4041c72085fad244fb9ddef9a29487775675ab7e9845b1197db154377d | clojure/core.typed | array_old.clj | ; some old tests that don't type check anymore but look useful
(ns clojure.core.typed.test.array-old
(:require [clojure.core.typed :refer [ann check-ns into-array> cf print-env ann-form]
:as t]
[clojure.repl :refer [pst]]))
(ann my-integer-array [-> (Array Integer)])
(defn my-integer-array [] (into-array> Integer (map int [1 2])))
(ann my-int-array [-> (Array int)])
(defn my-int-array [] (into-array> int (map int [1 2])))
(ann sum [(ReadOnlyArray Number) -> Number])
(defn sum [arr]
(t/loop [idx :- long 0,
ret :- Number 0]
(if (< idx (alength arr))
(recur
(unchecked-inc idx)
(+ (aget arr idx) ret))
ret)))
(fn [] (sum (my-integer-array)))
(ann write-integer-to-zero [(Array2 Integer t/Any) -> nil])
(defn write-integer-to-zero [arr]
(aset arr 0 (int 12))
nil)
(ann write-int-to-zero [(Array2 int t/Any) -> nil])
(defn write-int-to-zero [arr]
(aset arr 0 (int 12))
nil)
(fn [] (write-integer-to-zero my-integer-array))
(fn [] (write-int-to-zero (my-int-array)))
(ann bad-modify-array [(Array Number) -> nil])
#_(defn bad-modify-array [ar]
(let [ar2 (ann-form ar (Array2 Number Object))]
(aset ar2 0 (new java.util.Observable))
nil))
| null | https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/test/clojure/core/typed/test/array_old.clj | clojure | some old tests that don't type check anymore but look useful | (ns clojure.core.typed.test.array-old
(:require [clojure.core.typed :refer [ann check-ns into-array> cf print-env ann-form]
:as t]
[clojure.repl :refer [pst]]))
(ann my-integer-array [-> (Array Integer)])
(defn my-integer-array [] (into-array> Integer (map int [1 2])))
(ann my-int-array [-> (Array int)])
(defn my-int-array [] (into-array> int (map int [1 2])))
(ann sum [(ReadOnlyArray Number) -> Number])
(defn sum [arr]
(t/loop [idx :- long 0,
ret :- Number 0]
(if (< idx (alength arr))
(recur
(unchecked-inc idx)
(+ (aget arr idx) ret))
ret)))
(fn [] (sum (my-integer-array)))
(ann write-integer-to-zero [(Array2 Integer t/Any) -> nil])
(defn write-integer-to-zero [arr]
(aset arr 0 (int 12))
nil)
(ann write-int-to-zero [(Array2 int t/Any) -> nil])
(defn write-int-to-zero [arr]
(aset arr 0 (int 12))
nil)
(fn [] (write-integer-to-zero my-integer-array))
(fn [] (write-int-to-zero (my-int-array)))
(ann bad-modify-array [(Array Number) -> nil])
#_(defn bad-modify-array [ar]
(let [ar2 (ann-form ar (Array2 Number Object))]
(aset ar2 0 (new java.util.Observable))
nil))
|
f0318db862d2f400148892a48ad952e52594fd2cad3280ffd2fdb82f81dab1b7 | koji-kojiro/cl-repl | highlight.lisp | (in-package :cl-repl)
(defun escape-name (name)
(ppcre:regex-replace-all
"\\+"
(ppcre:regex-replace-all
"\\*"
name "\\\\*")
"\\\\+"))
(defun list-regex (lst)
(format nil
"((?<=\\s)|^|(?<=\\()|(?<=\\)))(~{~a|~})(?=(\\s|\\(|\\)|$))"
(sort lst #'string>)))
(destructuring-bind (functions specials)
(loop :for sym :being :the :external-symbols :of :cl
:when (handler-case (symbol-function sym) (error () nil))
:collect (escape-name (string-downcase sym)) :into functions
:when (special-operator-p sym)
:collect (escape-name (string-downcase sym)) :into specials
:finally (return (list functions specials)))
(defvar *syntax-table*
(list
:magic (list *magic-syntax-color* "^%\\S+")
:string (list *string-syntax-color* "\".*?\"")
:variable (list *variable-syntax-color* "([\\*])\\S+\\1")
:constant (list *constant-syntax-color* "([\\+])\\S+\\1")
:keyword (list *keyword-syntax-color* "((?<=\\s)|^):\\S+(?=\\b)")
:definition (list *definition-syntax-color*
"((?<=defun)|(?<=defmacro)|(?<=defmethod)|(?<=defgeneric))\\s\\S+(?=\\b)")
:lambda (list *lambda-syntax-color*
(list-regex '("&allow-other-keys" "&aux" "&body" "&environment" "&key" "&optional" "&rest" "&whole")))
:special (list *special-syntax-color* (list-regex specials))
:function (list *function-syntax-color* (list-regex functions))
:boolean (list *boolean-syntax-color* (list-regex '("nil" "t")))
:normal (list *normal-syntax-color* "."))))
(defun map-syntax (syntax text &optional syntax-map)
(unless syntax-map
(setf syntax-map (make-list (length text) :initial-element nil)))
(destructuring-bind (color regex) (getf *syntax-table* syntax)
(ppcre:do-matches (start end regex text)
(loop :for n :from start :below end
:unless (elt syntax-map n)
:do (setf (elt syntax-map n) (color color (elt text n))))))
syntax-map)
(defun highlight-text (text)
(let ((syntax-map))
(loop :for (syntax val) :on *syntax-table* :by #'cddr
:do (setf syntax-map (map-syntax syntax text syntax-map)))
(format nil "~{~a~}"
(loop :for raw :across text
:for colored :in syntax-map
:collect (or colored raw)))))
(defun redisplay-with-highlight ()
(rl:redisplay)
(format t "~c[2K~c~a~a~c[~aD"
#\esc
#\return
rl:*display-prompt*
(highlight-text rl:*line-buffer*)
#\esc
(- rl:+end+ rl:*point*))
(when (= rl:+end+ rl:*point*)
(format t "~c[1C" #\esc))
(finish-output))
(defvar *syntax-enabled* nil)
(defun enable-syntax ()
(setf *syntax-enabled* t)
(rl:register-function :redisplay #'redisplay-with-highlight))
(defun disable-syntax ()
(setf *syntax-enabled* nil)
(rl:register-function :redisplay #'rl:redisplay))
| null | https://raw.githubusercontent.com/koji-kojiro/cl-repl/bfd1521f856a9f8020611e8d8b34634fe75fbbc8/src/highlight.lisp | lisp | (in-package :cl-repl)
(defun escape-name (name)
(ppcre:regex-replace-all
"\\+"
(ppcre:regex-replace-all
"\\*"
name "\\\\*")
"\\\\+"))
(defun list-regex (lst)
(format nil
"((?<=\\s)|^|(?<=\\()|(?<=\\)))(~{~a|~})(?=(\\s|\\(|\\)|$))"
(sort lst #'string>)))
(destructuring-bind (functions specials)
(loop :for sym :being :the :external-symbols :of :cl
:when (handler-case (symbol-function sym) (error () nil))
:collect (escape-name (string-downcase sym)) :into functions
:when (special-operator-p sym)
:collect (escape-name (string-downcase sym)) :into specials
:finally (return (list functions specials)))
(defvar *syntax-table*
(list
:magic (list *magic-syntax-color* "^%\\S+")
:string (list *string-syntax-color* "\".*?\"")
:variable (list *variable-syntax-color* "([\\*])\\S+\\1")
:constant (list *constant-syntax-color* "([\\+])\\S+\\1")
:keyword (list *keyword-syntax-color* "((?<=\\s)|^):\\S+(?=\\b)")
:definition (list *definition-syntax-color*
"((?<=defun)|(?<=defmacro)|(?<=defmethod)|(?<=defgeneric))\\s\\S+(?=\\b)")
:lambda (list *lambda-syntax-color*
(list-regex '("&allow-other-keys" "&aux" "&body" "&environment" "&key" "&optional" "&rest" "&whole")))
:special (list *special-syntax-color* (list-regex specials))
:function (list *function-syntax-color* (list-regex functions))
:boolean (list *boolean-syntax-color* (list-regex '("nil" "t")))
:normal (list *normal-syntax-color* "."))))
(defun map-syntax (syntax text &optional syntax-map)
(unless syntax-map
(setf syntax-map (make-list (length text) :initial-element nil)))
(destructuring-bind (color regex) (getf *syntax-table* syntax)
(ppcre:do-matches (start end regex text)
(loop :for n :from start :below end
:unless (elt syntax-map n)
:do (setf (elt syntax-map n) (color color (elt text n))))))
syntax-map)
(defun highlight-text (text)
(let ((syntax-map))
(loop :for (syntax val) :on *syntax-table* :by #'cddr
:do (setf syntax-map (map-syntax syntax text syntax-map)))
(format nil "~{~a~}"
(loop :for raw :across text
:for colored :in syntax-map
:collect (or colored raw)))))
(defun redisplay-with-highlight ()
(rl:redisplay)
(format t "~c[2K~c~a~a~c[~aD"
#\esc
#\return
rl:*display-prompt*
(highlight-text rl:*line-buffer*)
#\esc
(- rl:+end+ rl:*point*))
(when (= rl:+end+ rl:*point*)
(format t "~c[1C" #\esc))
(finish-output))
(defvar *syntax-enabled* nil)
(defun enable-syntax ()
(setf *syntax-enabled* t)
(rl:register-function :redisplay #'redisplay-with-highlight))
(defun disable-syntax ()
(setf *syntax-enabled* nil)
(rl:register-function :redisplay #'rl:redisplay))
|
|
7504cdcf27db0fd4fc30eada340089b95bac86caa38d4d58102acacd062af7c9 | input-output-hk/cardano-coin-selection | Utilities.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE NumericUnderscores #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -fno - warn - orphans #
-- | Utility functions, types, and type class instances used purely for testing.
--
Copyright : © 2018 - 2020 IOHK
-- License: Apache-2.0
--
module Cardano.Test.Utilities
(
-- * Input Identifiers
InputId
, mkInputId
, genInputId
-- * Output Identifiers
, OutputId
, mkOutputId
, genOutputId
-- * Formatting
, ShowFmt (..)
-- * UTxO Operations
, excluding
, isSubsetOf
, restrictedBy
, restrictedTo
-- * Unsafe Operations
, unsafeCoin
, unsafeDustThreshold
, unsafeFee
, unsafeFromHex
) where
import Prelude
import Cardano.CoinSelection
( CoinMap (..), CoinMapEntry (..), CoinSelection (..), coinMapToList )
import Cardano.CoinSelection.Fee
( DustThreshold (..), Fee (..) )
import Control.DeepSeq
( NFData (..) )
import Data.ByteArray.Encoding
( Base (Base16), convertFromBase, convertToBase )
import Data.ByteString
( ByteString )
import Data.Maybe
( fromMaybe )
import Data.Proxy
( Proxy (..) )
import Data.Set
( Set )
import Fmt
( Buildable (..), blockListF, fmt, listF, nameF )
import GHC.Generics
( Generic )
import GHC.Stack
( HasCallStack )
import GHC.TypeLits
( KnownSymbol, Symbol, symbolVal )
import Internal.Coin
( Coin, coinFromIntegral )
import Numeric.Natural
( Natural )
import Test.QuickCheck
( Gen, arbitraryBoundedIntegral, vectorOf )
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Internal.Coin as C
--------------------------------------------------------------------------------
-- Unique Identifiers
--------------------------------------------------------------------------------
newtype UniqueId (tag :: Symbol) = UniqueId { unUniqueId :: ByteString }
deriving stock (Eq, Generic, Ord)
instance NFData (UniqueId tag)
-- Generate a unique identifier of a given length in bytes.
genUniqueId :: Int -> Gen (UniqueId tag)
genUniqueId n = UniqueId . BS.pack <$> vectorOf n arbitraryBoundedIntegral
instance forall tag . KnownSymbol tag => Show (UniqueId tag) where
show
= ((<>) (symbolVal (Proxy :: Proxy tag)))
. ((<>) " ")
. T.unpack
. T.decodeUtf8
. convertToBase Base16
. unUniqueId
instance KnownSymbol tag => Buildable (UniqueId tag) where
build = build . show
--------------------------------------------------------------------------------
-- Input Identifiers
--------------------------------------------------------------------------------
type InputId = UniqueId "InputId"
mkInputId :: ByteString -> InputId
mkInputId = UniqueId
genInputId :: Int -> Gen InputId
genInputId = genUniqueId
--------------------------------------------------------------------------------
-- Output Identifiers
--------------------------------------------------------------------------------
type OutputId = UniqueId "OutputId"
genOutputId :: Int -> Gen OutputId
genOutputId = genUniqueId
mkOutputId :: ByteString -> OutputId
mkOutputId = UniqueId
--------------------------------------------------------------------------------
Unsafe Operations
--------------------------------------------------------------------------------
unsafeCoin :: (Integral i, Show i) => i -> Coin
unsafeCoin i = fromMaybe die $ coinFromIntegral i
where
die = error $ mconcat
[ "Test suite attempted to create a coin with negative value: "
, show i
]
unsafeDustThreshold :: (Integral i, Show i) => i -> DustThreshold
unsafeDustThreshold i = DustThreshold $ fromMaybe die $ coinFromIntegral i
where
die = error $ mconcat
[ "Test suite attempted to create a dust theshold with negative value: "
, show i
]
unsafeFee :: (Integral i, Show i) => i -> Fee
unsafeFee i = Fee $ fromMaybe die $ coinFromIntegral i
where
die = error $ mconcat
[ "Test suite attempted to create a fee with negative value: "
, show i
]
| Decode an hex - encoded ' ByteString ' into raw bytes , or fail .
unsafeFromHex :: HasCallStack => ByteString -> ByteString
unsafeFromHex =
either (error . show) id . convertFromBase @ByteString @ByteString Base16
--------------------------------------------------------------------------------
-- Formatting
--------------------------------------------------------------------------------
-- | A polymorphic wrapper type with a custom 'Show' instance to display data
-- through 'Buildable' instances.
newtype ShowFmt a = ShowFmt { unShowFmt :: a }
deriving (Generic, Eq, Ord)
instance NFData a => NFData (ShowFmt a)
instance Buildable a => Show (ShowFmt a) where
show (ShowFmt a) = fmt (build a)
--------------------------------------------------------------------------------
-- UTxO Operations
--------------------------------------------------------------------------------
-- | ins⋪ u
excluding :: Ord u => CoinMap u -> Set u -> CoinMap u
excluding (CoinMap utxo) =
CoinMap . Map.withoutKeys utxo
-- | a ⊆ b
isSubsetOf :: Ord u => CoinMap u -> CoinMap u -> Bool
isSubsetOf (CoinMap a) (CoinMap b) =
a `Map.isSubmapOf` b
-- | ins⊲ u
restrictedBy :: Ord u => CoinMap u -> Set u -> CoinMap u
restrictedBy (CoinMap utxo) =
CoinMap . Map.restrictKeys utxo
-- | u ⊳ outs
restrictedTo :: CoinMap u -> Set Coin -> CoinMap u
restrictedTo (CoinMap utxo) outs =
CoinMap $ Map.filter (`Set.member` outs) utxo
--------------------------------------------------------------------------------
-- Buildable Instances
--------------------------------------------------------------------------------
instance Buildable Coin where
build = build . fromIntegral @Natural @Integer . C.coinToIntegral
instance Buildable a => Buildable (CoinMapEntry a) where
build a = mempty
<> build (entryKey a)
<> ":"
<> build (entryValue a)
instance (Buildable i, Buildable o) => Buildable (CoinSelection i o) where
build s = mempty
<> nameF "inputs"
(blockListF $ coinMapToList $ inputs s)
<> nameF "outputs"
(blockListF $ coinMapToList $ outputs s)
<> nameF "change"
(listF $ change s)
| null | https://raw.githubusercontent.com/input-output-hk/cardano-coin-selection/cff368d674fe58bc1a12e6564a26ccea21eb5aac/src/test/Cardano/Test/Utilities.hs | haskell | # LANGUAGE OverloadedStrings #
| Utility functions, types, and type class instances used purely for testing.
License: Apache-2.0
* Input Identifiers
* Output Identifiers
* Formatting
* UTxO Operations
* Unsafe Operations
------------------------------------------------------------------------------
Unique Identifiers
------------------------------------------------------------------------------
Generate a unique identifier of a given length in bytes.
------------------------------------------------------------------------------
Input Identifiers
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Output Identifiers
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Formatting
------------------------------------------------------------------------------
| A polymorphic wrapper type with a custom 'Show' instance to display data
through 'Buildable' instances.
------------------------------------------------------------------------------
UTxO Operations
------------------------------------------------------------------------------
| ins⋪ u
| a ⊆ b
| ins⊲ u
| u ⊳ outs
------------------------------------------------------------------------------
Buildable Instances
------------------------------------------------------------------------------ | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE NumericUnderscores #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# OPTIONS_GHC -fno - warn - orphans #
Copyright : © 2018 - 2020 IOHK
module Cardano.Test.Utilities
(
InputId
, mkInputId
, genInputId
, OutputId
, mkOutputId
, genOutputId
, ShowFmt (..)
, excluding
, isSubsetOf
, restrictedBy
, restrictedTo
, unsafeCoin
, unsafeDustThreshold
, unsafeFee
, unsafeFromHex
) where
import Prelude
import Cardano.CoinSelection
( CoinMap (..), CoinMapEntry (..), CoinSelection (..), coinMapToList )
import Cardano.CoinSelection.Fee
( DustThreshold (..), Fee (..) )
import Control.DeepSeq
( NFData (..) )
import Data.ByteArray.Encoding
( Base (Base16), convertFromBase, convertToBase )
import Data.ByteString
( ByteString )
import Data.Maybe
( fromMaybe )
import Data.Proxy
( Proxy (..) )
import Data.Set
( Set )
import Fmt
( Buildable (..), blockListF, fmt, listF, nameF )
import GHC.Generics
( Generic )
import GHC.Stack
( HasCallStack )
import GHC.TypeLits
( KnownSymbol, Symbol, symbolVal )
import Internal.Coin
( Coin, coinFromIntegral )
import Numeric.Natural
( Natural )
import Test.QuickCheck
( Gen, arbitraryBoundedIntegral, vectorOf )
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Internal.Coin as C
newtype UniqueId (tag :: Symbol) = UniqueId { unUniqueId :: ByteString }
deriving stock (Eq, Generic, Ord)
instance NFData (UniqueId tag)
genUniqueId :: Int -> Gen (UniqueId tag)
genUniqueId n = UniqueId . BS.pack <$> vectorOf n arbitraryBoundedIntegral
instance forall tag . KnownSymbol tag => Show (UniqueId tag) where
show
= ((<>) (symbolVal (Proxy :: Proxy tag)))
. ((<>) " ")
. T.unpack
. T.decodeUtf8
. convertToBase Base16
. unUniqueId
instance KnownSymbol tag => Buildable (UniqueId tag) where
build = build . show
type InputId = UniqueId "InputId"
mkInputId :: ByteString -> InputId
mkInputId = UniqueId
genInputId :: Int -> Gen InputId
genInputId = genUniqueId
type OutputId = UniqueId "OutputId"
genOutputId :: Int -> Gen OutputId
genOutputId = genUniqueId
mkOutputId :: ByteString -> OutputId
mkOutputId = UniqueId
Unsafe Operations
unsafeCoin :: (Integral i, Show i) => i -> Coin
unsafeCoin i = fromMaybe die $ coinFromIntegral i
where
die = error $ mconcat
[ "Test suite attempted to create a coin with negative value: "
, show i
]
unsafeDustThreshold :: (Integral i, Show i) => i -> DustThreshold
unsafeDustThreshold i = DustThreshold $ fromMaybe die $ coinFromIntegral i
where
die = error $ mconcat
[ "Test suite attempted to create a dust theshold with negative value: "
, show i
]
unsafeFee :: (Integral i, Show i) => i -> Fee
unsafeFee i = Fee $ fromMaybe die $ coinFromIntegral i
where
die = error $ mconcat
[ "Test suite attempted to create a fee with negative value: "
, show i
]
| Decode an hex - encoded ' ByteString ' into raw bytes , or fail .
unsafeFromHex :: HasCallStack => ByteString -> ByteString
unsafeFromHex =
either (error . show) id . convertFromBase @ByteString @ByteString Base16
newtype ShowFmt a = ShowFmt { unShowFmt :: a }
deriving (Generic, Eq, Ord)
instance NFData a => NFData (ShowFmt a)
instance Buildable a => Show (ShowFmt a) where
show (ShowFmt a) = fmt (build a)
excluding :: Ord u => CoinMap u -> Set u -> CoinMap u
excluding (CoinMap utxo) =
CoinMap . Map.withoutKeys utxo
isSubsetOf :: Ord u => CoinMap u -> CoinMap u -> Bool
isSubsetOf (CoinMap a) (CoinMap b) =
a `Map.isSubmapOf` b
restrictedBy :: Ord u => CoinMap u -> Set u -> CoinMap u
restrictedBy (CoinMap utxo) =
CoinMap . Map.restrictKeys utxo
restrictedTo :: CoinMap u -> Set Coin -> CoinMap u
restrictedTo (CoinMap utxo) outs =
CoinMap $ Map.filter (`Set.member` outs) utxo
instance Buildable Coin where
build = build . fromIntegral @Natural @Integer . C.coinToIntegral
instance Buildable a => Buildable (CoinMapEntry a) where
build a = mempty
<> build (entryKey a)
<> ":"
<> build (entryValue a)
instance (Buildable i, Buildable o) => Buildable (CoinSelection i o) where
build s = mempty
<> nameF "inputs"
(blockListF $ coinMapToList $ inputs s)
<> nameF "outputs"
(blockListF $ coinMapToList $ outputs s)
<> nameF "change"
(listF $ change s)
|
e28efaf91ee3c763b1a66575ffd7764ac20d1d6c1436b7a9d44ca05ca8aa47ca | silky/quipper | TeleportGeneric.hs | This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the
-- file COPYRIGHT for a list of authors, copyright holders, licensing,
-- and other details. All rights reserved.
--
-- ======================================================================
import Quipper
import QuipperLib.Simulation
import System.Random
import System.Environment
import System.CPUTime
plus_minus :: (QShape a qa ca) => a -> Circ qa
plus_minus a = do
qs <- qinit a
qs <- mapUnary hadamard qs
return qs
share :: (QShape a qa ca) => qa -> Circ (qa, qa)
share qa = do
qb <- qinit (qc_false qa)
(qb, qa) <- mapBinary controlled_not qb qa
return (qa, qb)
bell00 :: (QShape a qa ca) => a -> Circ (qa, qa)
bell00 shape = do
qa <- plus_minus shape
(qa, qb) <- share qa
return (qa, qb)
alice :: (QShape a qa ca) => qa -> qa -> Circ (ca,ca)
alice q a = do
(a, q) <- mapBinary controlled_not a q
q <- mapUnary hadamard q
(x,y) <- measure (q,a)
return (x,y)
bob :: (QShape a qa ca) => qa -> (ca,ca) -> Circ qa
bob b (x,y) = do
(b, y) <- mapBinary_c controlled_X b y
(b, x) <- mapBinary_c controlled_Z b x
cdiscard (x,y)
return b
where
controlled_X b x = do
gate_X b `controlled` x
return (b,x)
controlled_Z b x = do
gate_Z b `controlled` x
return (b,x)
teleport :: (QData qa) => qa -> Circ qa
teleport q = do
(a,b) <- bell00 (qc_false q)
(x,y) <- alice q a
b <- bob b (x,y)
return b
teleport_labeled :: (QData qa) => qa -> Circ qa
teleport_labeled q = do
comment_with_label "ENTER: teleport_labeled" q "q"
comment "ENTER: bell00"
(a,b) <- bell00 (qc_false q)
comment_with_label "EXIT: bell00" (a,b) ("a","b")
comment "ENTER: alice"
(x,y) <- alice q a
comment_with_label "EXIT: alice" (x,y) ("x","y")
comment "ENTER: bob"
b <- bob b (x,y)
comment_with_label "EXIT: bob" b "b"
comment "EXIT: teleport_labeled"
return b
-- | A test that should help see how many qubits we can simulate
test_teleport :: [Bool] -> IO [Bool]
test_teleport = run_clifford_generic teleport
data What = Sim | Circ | Usage deriving Eq
-- | The main method deals with command line arguments, and timing of the simulation
main :: IO ()
main = do
args <- getArgs
if (length args /= 2) then usage else do
let arg1 = head args
let flag = case arg1 of
"--sim" -> Sim
"--circ" -> Circ
_ -> Usage
if (flag == Usage) then usage else do
let arg = head (tail args)
case reads arg of
[(n,_)] -> do
if (n < 0) then usage else do
if (flag == Circ) then print_generic Preview teleport_labeled (replicate n qubit) else do
input <- randomBools n
putStrLn ("Input: " ++ show input)
start <- getCPUTime
output <- test_teleport input
end <- getCPUTime
putStrLn ("Output: " ++ show output)
let time = end - start
putStrLn ("Time: (" ++ show time ++ ")")
show_time time
_ -> usage
-- | Produce the given number of random boolean values
randomBools :: Int -> IO [Bool]
randomBools 0 = return []
randomBools n = do
b <- randomIO
bs <- randomBools (n-1)
return (b:bs)
-- | Give a usage message if not being run from GHCI
usage :: IO ()
usage = do
name <- getProgName
if name == "<interactive>" then prompt else do
putStrLn ("usage: " ++ name ++ " flag num_qubits")
putStrLn (" where flag = --sim or --circ")
-- | If we're in GHCI then we can prompt for the number of qubits to teleport
prompt :: IO ()
prompt = do
putStrLn "Enter flag (--sim or --circ): "
f <- getLine
putStrLn "Enter number of qubits: "
n <- getLine
withArgs [f,n] main
-- | Display an integer representing pico-seconds in a more readable format
show_time :: Integer -> IO ()
show_time t = case range t of
Pico -> putStrLn (show t ++ " " ++ show Pico ++ ".")
r -> do
putStr (show (div t (ps' r)) ++ " " ++ show r ++ ", ")
show_time (rem t (ps' r))
-- | Helper data-type for show_time function
data Range = Pico | Nano | Micro | Milli | Seconds | Minutes | Hours | Days
deriving Eq
instance Show Range where
show Pico = "picoseconds"
show Nano = "nanoseconds"
show Micro = "microseconds"
show Milli = "milliseconds"
show Seconds = "seconds"
show Minutes = "minutes"
show Hours = "hours"
show Days = "days"
-- | Helper function for show_time function
ps' :: Range -> Integer
ps' Pico = 1
ps' Nano = 10^3 * ps' Pico
ps' Micro = 10^3 * ps' Nano
ps' Milli = 10^3 * ps' Micro
ps' Seconds = 10^3 * ps' Milli
ps' Minutes = 60 * ps' Seconds
ps' Hours = 60 * ps' Minutes
ps' Days = 24 * ps' Hours
-- | Helper function for show_time function
range :: Integer -> Range
range t =
if (t < 10^3) then Pico else
if (t < 10^6) then Nano else
if (t < 10^9) then Micro else
if (t < 10^12) then Milli else
if (t < 60*(10^12)) then Seconds else
if (t < 60*60*(10^12)) then Minutes else
if (t < 24*60*60*(10^12)) then Hours else Days
| null | https://raw.githubusercontent.com/silky/quipper/1ef6d031984923d8b7ded1c14f05db0995791633/tests/TeleportGeneric.hs | haskell | file COPYRIGHT for a list of authors, copyright holders, licensing,
and other details. All rights reserved.
======================================================================
| A test that should help see how many qubits we can simulate
| The main method deals with command line arguments, and timing of the simulation
| Produce the given number of random boolean values
| Give a usage message if not being run from GHCI
| If we're in GHCI then we can prompt for the number of qubits to teleport
| Display an integer representing pico-seconds in a more readable format
| Helper data-type for show_time function
| Helper function for show_time function
| Helper function for show_time function | This file is part of Quipper . Copyright ( C ) 2011 - 2016 . Please see the
import Quipper
import QuipperLib.Simulation
import System.Random
import System.Environment
import System.CPUTime
plus_minus :: (QShape a qa ca) => a -> Circ qa
plus_minus a = do
qs <- qinit a
qs <- mapUnary hadamard qs
return qs
share :: (QShape a qa ca) => qa -> Circ (qa, qa)
share qa = do
qb <- qinit (qc_false qa)
(qb, qa) <- mapBinary controlled_not qb qa
return (qa, qb)
bell00 :: (QShape a qa ca) => a -> Circ (qa, qa)
bell00 shape = do
qa <- plus_minus shape
(qa, qb) <- share qa
return (qa, qb)
alice :: (QShape a qa ca) => qa -> qa -> Circ (ca,ca)
alice q a = do
(a, q) <- mapBinary controlled_not a q
q <- mapUnary hadamard q
(x,y) <- measure (q,a)
return (x,y)
bob :: (QShape a qa ca) => qa -> (ca,ca) -> Circ qa
bob b (x,y) = do
(b, y) <- mapBinary_c controlled_X b y
(b, x) <- mapBinary_c controlled_Z b x
cdiscard (x,y)
return b
where
controlled_X b x = do
gate_X b `controlled` x
return (b,x)
controlled_Z b x = do
gate_Z b `controlled` x
return (b,x)
teleport :: (QData qa) => qa -> Circ qa
teleport q = do
(a,b) <- bell00 (qc_false q)
(x,y) <- alice q a
b <- bob b (x,y)
return b
teleport_labeled :: (QData qa) => qa -> Circ qa
teleport_labeled q = do
comment_with_label "ENTER: teleport_labeled" q "q"
comment "ENTER: bell00"
(a,b) <- bell00 (qc_false q)
comment_with_label "EXIT: bell00" (a,b) ("a","b")
comment "ENTER: alice"
(x,y) <- alice q a
comment_with_label "EXIT: alice" (x,y) ("x","y")
comment "ENTER: bob"
b <- bob b (x,y)
comment_with_label "EXIT: bob" b "b"
comment "EXIT: teleport_labeled"
return b
test_teleport :: [Bool] -> IO [Bool]
test_teleport = run_clifford_generic teleport
data What = Sim | Circ | Usage deriving Eq
main :: IO ()
main = do
args <- getArgs
if (length args /= 2) then usage else do
let arg1 = head args
let flag = case arg1 of
"--sim" -> Sim
"--circ" -> Circ
_ -> Usage
if (flag == Usage) then usage else do
let arg = head (tail args)
case reads arg of
[(n,_)] -> do
if (n < 0) then usage else do
if (flag == Circ) then print_generic Preview teleport_labeled (replicate n qubit) else do
input <- randomBools n
putStrLn ("Input: " ++ show input)
start <- getCPUTime
output <- test_teleport input
end <- getCPUTime
putStrLn ("Output: " ++ show output)
let time = end - start
putStrLn ("Time: (" ++ show time ++ ")")
show_time time
_ -> usage
randomBools :: Int -> IO [Bool]
randomBools 0 = return []
randomBools n = do
b <- randomIO
bs <- randomBools (n-1)
return (b:bs)
usage :: IO ()
usage = do
name <- getProgName
if name == "<interactive>" then prompt else do
putStrLn ("usage: " ++ name ++ " flag num_qubits")
putStrLn (" where flag = --sim or --circ")
prompt :: IO ()
prompt = do
putStrLn "Enter flag (--sim or --circ): "
f <- getLine
putStrLn "Enter number of qubits: "
n <- getLine
withArgs [f,n] main
show_time :: Integer -> IO ()
show_time t = case range t of
Pico -> putStrLn (show t ++ " " ++ show Pico ++ ".")
r -> do
putStr (show (div t (ps' r)) ++ " " ++ show r ++ ", ")
show_time (rem t (ps' r))
data Range = Pico | Nano | Micro | Milli | Seconds | Minutes | Hours | Days
deriving Eq
instance Show Range where
show Pico = "picoseconds"
show Nano = "nanoseconds"
show Micro = "microseconds"
show Milli = "milliseconds"
show Seconds = "seconds"
show Minutes = "minutes"
show Hours = "hours"
show Days = "days"
ps' :: Range -> Integer
ps' Pico = 1
ps' Nano = 10^3 * ps' Pico
ps' Micro = 10^3 * ps' Nano
ps' Milli = 10^3 * ps' Micro
ps' Seconds = 10^3 * ps' Milli
ps' Minutes = 60 * ps' Seconds
ps' Hours = 60 * ps' Minutes
ps' Days = 24 * ps' Hours
range :: Integer -> Range
range t =
if (t < 10^3) then Pico else
if (t < 10^6) then Nano else
if (t < 10^9) then Micro else
if (t < 10^12) then Milli else
if (t < 60*(10^12)) then Seconds else
if (t < 60*60*(10^12)) then Minutes else
if (t < 24*60*60*(10^12)) then Hours else Days
|
7ec4b47c98ad78b4f4e8ecc5c942b6d2778cfda554fabb11b4d9b0e1fe010249 | MegaLoler/Music | util.lisp | (in-package :music)
(defun symbol-from-char (char &optional (eof-p t) eof-v)
"Return a symbol from a string designator."
(read-from-string (string char) eof-p eof-v))
(defun num-char-p (c)
"Whether a character is a number character."
(find c "0123456789+-"))
(defun not-num-char-p (c)
"Whether a character is not a number character."
(not (num-char-p c)))
(defun read-until (until stream &optional escape consume-final-char)
"Read from stream until a character.
`until' can be either a single character or a string of possible characters or a function."
(loop
:with result = (make-array 0
:element-type 'character
:fill-pointer 0
:adjustable t)
:for c = (peek-char nil stream nil nil)
:until (or (null c)
(cond ((stringp until)
(position c until))
((functionp until)
(funcall until c))
(t (char= c until))))
:if (and escape (char= c escape))
:do (progn
(read-char stream)
(vector-push-extend (read-char stream) result))
:else :do (vector-push-extend (read-char stream) result)
:finally (progn
(when consume-final-char
(read-char stream))
(return result))))
(defun read-until-not (until stream &optional escape consume-final-char)
"Read from stream until reaching a character that does not match any char in `until'."
(read-until (lambda (c)
(cond ((stringp until)
(not (position c until)))
((functionp until)
(not (funcall until c)))
(t (not (char= c until)))))
stream escape consume-final-char))
(defun diatonic-to-chromatic-value (value)
"Convert a diatonic value to a chromatic value."
(declare (type (integer 1) value))
(let ((multiple (floor (1- value) 7)))
(+ (* 12 multiple)
(case (diatonic-class value)
(1 0)
(2 2)
(3 4)
(4 5)
(5 7)
(6 9)
(7 11)
(otherwise (error "Invalid value!"))))))
(defun add-diatonic-values (a b)
"Add two diatonic values together."
(declare (type (integer 1) a b))
(+ -1 a b))
(defun subtract-diatonic-values (a b)
"Return the difference between two diatonic values."
(declare (type (integer 1) a b))
(1+ (abs (- (1- a) (1- b)))))
(defun diatonic-mod (diatonic-value divisor)
"Modulo a diatonic value."
(declare (type (integer 1) diatonic-value divisor))
(1+ (mod (1- diatonic-value) divisor)))
(defmethod diatonic-class ((diatonic-value integer))
"Return the class of a diatonic value."
(diatonic-mod diatonic-value 7))
(defun rotate-left (list)
"Rotate a list to the left."
(append (cdr list) (list (car list))))
(defun rotate-right (list)
"Rotate a list to the right."
(cons (car (last list))
(subseq list 0 (1- (length list)))))
(defmacro fset (location value)
"Perform `setf' but return the old value."
`(let* ((old ,location))
(setf ,location ,value)
old))
(defmacro finc (location value)
"Perform `incf' but return the old value."
`(let* ((old ,location))
(incf ,location ,value)
old))
(defmacro fdec (location value)
"Perform `decf' but return the old value."
`(let* ((old ,location))
(decf ,location ,value)
old))
(defun reciprocal (value)
"Return the reciprocal of a value."
(/ 1 value))
(defun any-p (object objects)
"Whether an object is any of a list of objects."
(find-if (lambda (s)
(equalp object s))
objects))
(defmethod repeat ((list list) &optional (n 2))
"Repeat a list `n' times."
(case n
(0 nil)
(1 list)
(otherwise (append list (repeat list (1- n))))))
(defun sort-val (val)
"T is sorted as 1 and nil is sorted as 0."
(cond ((eq val t) 1)
((eq val nil) 0)
(t val)))
(defun score-sort (list &rest functions)
"Sort a list using a series of functions to score items."
(if functions
(apply #'append
(loop
:with groupings = (gather (sort (score list (car functions))
(lambda (a b)
(> (sort-val (cdr a))
(sort-val (cdr b)))))
(lambda (a b)
(eq (cdr a)
(cdr b))))
:for grouping :in groupings
:collect (apply #'score-sort
(cons (mapcar #'car grouping)
(cdr functions)))))
list))
(defun score (list fn)
"Give items a score using a function."
(mapcar (lambda (item)
(cons item (funcall fn item)))
list))
(defun gather (list &optional (predicate #'equalp) buffer)
"Group consecutive equal items in a list."
(if list
(if buffer
(if (funcall predicate (car list) (car buffer))
(gather (cdr list) predicate (cons (car list) buffer))
(cons buffer (gather (cdr list) predicate (list (car list)))))
(gather (cdr list) predicate (list (car list))))
(list buffer)))
(defun flatten (l)
(cond ((null l) nil)
((atom l) (list l))
(t (loop for a in l appending (flatten a)))))
| null | https://raw.githubusercontent.com/MegaLoler/Music/6d69042f6ed98994d3f2ec474c71c569e0ee06be/src/util.lisp | lisp | (in-package :music)
(defun symbol-from-char (char &optional (eof-p t) eof-v)
"Return a symbol from a string designator."
(read-from-string (string char) eof-p eof-v))
(defun num-char-p (c)
"Whether a character is a number character."
(find c "0123456789+-"))
(defun not-num-char-p (c)
"Whether a character is not a number character."
(not (num-char-p c)))
(defun read-until (until stream &optional escape consume-final-char)
"Read from stream until a character.
`until' can be either a single character or a string of possible characters or a function."
(loop
:with result = (make-array 0
:element-type 'character
:fill-pointer 0
:adjustable t)
:for c = (peek-char nil stream nil nil)
:until (or (null c)
(cond ((stringp until)
(position c until))
((functionp until)
(funcall until c))
(t (char= c until))))
:if (and escape (char= c escape))
:do (progn
(read-char stream)
(vector-push-extend (read-char stream) result))
:else :do (vector-push-extend (read-char stream) result)
:finally (progn
(when consume-final-char
(read-char stream))
(return result))))
(defun read-until-not (until stream &optional escape consume-final-char)
"Read from stream until reaching a character that does not match any char in `until'."
(read-until (lambda (c)
(cond ((stringp until)
(not (position c until)))
((functionp until)
(not (funcall until c)))
(t (not (char= c until)))))
stream escape consume-final-char))
(defun diatonic-to-chromatic-value (value)
"Convert a diatonic value to a chromatic value."
(declare (type (integer 1) value))
(let ((multiple (floor (1- value) 7)))
(+ (* 12 multiple)
(case (diatonic-class value)
(1 0)
(2 2)
(3 4)
(4 5)
(5 7)
(6 9)
(7 11)
(otherwise (error "Invalid value!"))))))
(defun add-diatonic-values (a b)
"Add two diatonic values together."
(declare (type (integer 1) a b))
(+ -1 a b))
(defun subtract-diatonic-values (a b)
"Return the difference between two diatonic values."
(declare (type (integer 1) a b))
(1+ (abs (- (1- a) (1- b)))))
(defun diatonic-mod (diatonic-value divisor)
"Modulo a diatonic value."
(declare (type (integer 1) diatonic-value divisor))
(1+ (mod (1- diatonic-value) divisor)))
(defmethod diatonic-class ((diatonic-value integer))
"Return the class of a diatonic value."
(diatonic-mod diatonic-value 7))
(defun rotate-left (list)
"Rotate a list to the left."
(append (cdr list) (list (car list))))
(defun rotate-right (list)
"Rotate a list to the right."
(cons (car (last list))
(subseq list 0 (1- (length list)))))
(defmacro fset (location value)
"Perform `setf' but return the old value."
`(let* ((old ,location))
(setf ,location ,value)
old))
(defmacro finc (location value)
"Perform `incf' but return the old value."
`(let* ((old ,location))
(incf ,location ,value)
old))
(defmacro fdec (location value)
"Perform `decf' but return the old value."
`(let* ((old ,location))
(decf ,location ,value)
old))
(defun reciprocal (value)
"Return the reciprocal of a value."
(/ 1 value))
(defun any-p (object objects)
"Whether an object is any of a list of objects."
(find-if (lambda (s)
(equalp object s))
objects))
(defmethod repeat ((list list) &optional (n 2))
"Repeat a list `n' times."
(case n
(0 nil)
(1 list)
(otherwise (append list (repeat list (1- n))))))
(defun sort-val (val)
"T is sorted as 1 and nil is sorted as 0."
(cond ((eq val t) 1)
((eq val nil) 0)
(t val)))
(defun score-sort (list &rest functions)
"Sort a list using a series of functions to score items."
(if functions
(apply #'append
(loop
:with groupings = (gather (sort (score list (car functions))
(lambda (a b)
(> (sort-val (cdr a))
(sort-val (cdr b)))))
(lambda (a b)
(eq (cdr a)
(cdr b))))
:for grouping :in groupings
:collect (apply #'score-sort
(cons (mapcar #'car grouping)
(cdr functions)))))
list))
(defun score (list fn)
"Give items a score using a function."
(mapcar (lambda (item)
(cons item (funcall fn item)))
list))
(defun gather (list &optional (predicate #'equalp) buffer)
"Group consecutive equal items in a list."
(if list
(if buffer
(if (funcall predicate (car list) (car buffer))
(gather (cdr list) predicate (cons (car list) buffer))
(cons buffer (gather (cdr list) predicate (list (car list)))))
(gather (cdr list) predicate (list (car list))))
(list buffer)))
(defun flatten (l)
(cond ((null l) nil)
((atom l) (list l))
(t (loop for a in l appending (flatten a)))))
|
|
616bde239cc3a1c2f86e9dac38284c472b3d57a0833b8626796f8e45e380d900 | dwayne/eopl3 | parser.rkt | #lang eopl
;; Program ::= Expression
;;
;; Expression ::= Number
;;
;; ::= Identifier
;;
;; ::= -(Expression, Expression)
;;
;; ::= zero?(Expression)
;;
;; ::= if Expression then Expression else Expression
;;
;; ::= let Identifier = Expression in Expression
;;
;; ::= proc (Identifier) Expression
;;
;; ::= (Expression Expression)
(provide
AST
program
a-program
expression expression?
const-exp
var-exp
diff-exp
zero?-exp
if-exp
let-exp
proc-exp
call-exp
nameless-var-exp
nameless-let-exp
nameless-proc-exp
Parser
parse)
(define scanner-spec
'((number (digit (arbno digit)) number)
(identifier (letter (arbno letter)) symbol)
(ws ((arbno whitespace)) skip)))
(define grammar
'((program (expression)
a-program)
(expression (number)
const-exp)
(expression (identifier)
var-exp)
(expression ("-" "(" expression "," expression ")")
diff-exp)
(expression ("zero?" "(" expression ")")
zero?-exp)
(expression ("if" expression "then" expression "else" expression)
if-exp)
(expression ("let" identifier "=" expression "in" expression)
let-exp)
(expression ("proc" "(" identifier ")" expression)
proc-exp)
(expression ("(" expression expression ")")
call-exp)
(expression ("%lexref" number)
nameless-var-exp)
(expression ("%let" expression "in" expression)
nameless-let-exp)
(expression ("%lexproc" expression)
nameless-proc-exp)))
(sllgen:make-define-datatypes scanner-spec grammar)
(define parse
(sllgen:make-string-parser scanner-spec grammar))
| null | https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/03-ch3/interpreters/racket/NAMELESS-PROC-3.42-ATTEMPT-1/parser.rkt | racket | Program ::= Expression
Expression ::= Number
::= Identifier
::= -(Expression, Expression)
::= zero?(Expression)
::= if Expression then Expression else Expression
::= let Identifier = Expression in Expression
::= proc (Identifier) Expression
::= (Expression Expression) | #lang eopl
(provide
AST
program
a-program
expression expression?
const-exp
var-exp
diff-exp
zero?-exp
if-exp
let-exp
proc-exp
call-exp
nameless-var-exp
nameless-let-exp
nameless-proc-exp
Parser
parse)
(define scanner-spec
'((number (digit (arbno digit)) number)
(identifier (letter (arbno letter)) symbol)
(ws ((arbno whitespace)) skip)))
(define grammar
'((program (expression)
a-program)
(expression (number)
const-exp)
(expression (identifier)
var-exp)
(expression ("-" "(" expression "," expression ")")
diff-exp)
(expression ("zero?" "(" expression ")")
zero?-exp)
(expression ("if" expression "then" expression "else" expression)
if-exp)
(expression ("let" identifier "=" expression "in" expression)
let-exp)
(expression ("proc" "(" identifier ")" expression)
proc-exp)
(expression ("(" expression expression ")")
call-exp)
(expression ("%lexref" number)
nameless-var-exp)
(expression ("%let" expression "in" expression)
nameless-let-exp)
(expression ("%lexproc" expression)
nameless-proc-exp)))
(sllgen:make-define-datatypes scanner-spec grammar)
(define parse
(sllgen:make-string-parser scanner-spec grammar))
|
55e7353926d695bb37eb8ea6f56790e01b2d9346b397847b8021ab86e7ca735d | scicloj/scicloj.ml | core.clj | (ns scicloj.ml.core
Autogenerated from scicloj.ml.template.core-- DO NOT EDIT
"Core functions for machine learninig and pipeline execution.
Requiring this namesspace registers as well the model in:
* scicloj.ml.smile.classification
* scicloj.ml.smile.regression
* scicloj.ml.xgboost
Functions are re-exported from:
* scicloj.metamorph.ml.*
* scicloj.metamorph.core
"
(:require [scicloj.ml.template.core]
[scicloj.metamorph.core]
[scicloj.metamorph.ml]
[scicloj.metamorph.ml.classification]
[scicloj.metamorph.ml.gridsearch]
[scicloj.metamorph.ml.loss]))
(defn ->pipeline
"Create pipeline from declarative description."
([ops]
(scicloj.metamorph.core/->pipeline ops))
([config ops]
(scicloj.metamorph.core/->pipeline config ops)))
(defn categorical
"Given a vector a categorical values create a gridsearch definition."
([value-vec]
(scicloj.metamorph.ml.gridsearch/categorical value-vec)))
(defn classification-accuracy
"correct/total.
Model output is a sequence of probability distributions.
label-seq is a sequence of values. The answer is considered correct
if the key highest probability in the model output entry matches
that label."
(^{:tag double} [lhs rhs]
(scicloj.metamorph.ml.loss/classification-accuracy lhs rhs)))
(defn classification-loss
"1.0 - classification-accuracy."
(^{:tag double} [lhs rhs]
(scicloj.metamorph.ml.loss/classification-loss lhs rhs)))
(defn confusion-map
([predicted-labels labels normalize]
(scicloj.metamorph.ml.classification/confusion-map predicted-labels labels normalize))
([predicted-labels labels]
(scicloj.metamorph.ml.classification/confusion-map predicted-labels labels)))
(defn confusion-map->ds
([conf-matrix-map normalize]
(scicloj.metamorph.ml.classification/confusion-map->ds conf-matrix-map normalize))
([conf-matrix-map]
(scicloj.metamorph.ml.classification/confusion-map->ds conf-matrix-map)))
(defmacro def-ctx
"Convenience macro for defining pipelined operations that
bind the current value of the context to a var, for simple
debugging purposes."
([varname]
`(scicloj.ml.template.core/def-ctx ~varname)))
(defn default-loss-fn
"Given a datset which must have exactly 1 inference target column return a default
loss fn. If column is categorical, loss is tech.v3.ml.loss/classification-loss, else
the loss is tech.v3.ml.loss/mae (mean average error)."
([dataset]
(scicloj.metamorph.ml/default-loss-fn dataset)))
(defn default-result-dissoc-in-fn
([result]
(scicloj.metamorph.ml/default-result-dissoc-in-fn result)))
(def default-result-dissoc-in-seq scicloj.metamorph.ml/default-result-dissoc-in-seq)
(defn define-model!
"Create a model definition. An ml model is a function that takes a dataset and an
options map and returns a model. A model is something that, combined with a dataset,
produces a inferred dataset."
([model-kwd train-fn predict-fn opts]
(scicloj.metamorph.ml/define-model! model-kwd train-fn predict-fn opts)))
(defn do-ctx
"Apply f:: ctx -> any, ignore the result, leaving
pipeline unaffected. Akin to using doseq for side-effecting
operations like printing, visualization, or binding to vars
for debugging."
([f]
(scicloj.metamorph.core/do-ctx f)))
(defn ensemble-pipe
([pipes]
(scicloj.metamorph.ml/ensemble-pipe pipes)))
(defn evaluate-pipelines
"Evaluates the performance of a seq of metamorph pipelines, which are suposed to have a model as last step under key :model,
which behaves correctly in mode :fit and :transform. The function `scicloj.metamorph.ml/model` is such function behaving correctly.
This function calculates the accuracy or loss, given as `metric-fn` of each pipeline in `pipeline-fn-seq` using all the train-test splits
given in `train-test-split-seq`.
It runs the pipelines in mode :fit and in mode :transform for each pipeline-fn in `pipe-fn-seq` for each split in `train-test-split-seq`.
The function returns a seq of seqs of evaluation results per pipe-fn per train-test split.
Each of teh evaluation results is a context map, which is specified in the malli schema attached to this function.
* `pipe-fn-or-decl-seq` need to be sequence of pipeline functions or pipline declarations which follow the metamorph approach.
These type of functions get produced typically by calling `scicloj.metamorph/pipeline`. Documentation is here:
* `train-test-split-seq` need to be a sequence of maps containing the train and test dataset (being tech.ml.dataset) at keys :train and :test.
`tableclot.api/split->seq` produces such splits. Supervised models require both keys (:train and :test), while unsupervised models only use :train
* `metric-fn` Metric function to use. Typically comming from `tech.v3.ml.loss`. For supervised models the metric-fn receives the trueth
and predicted vales as double arrays and should return a single double number. For unsupervised models he function receives the fitted ctx
and should return a singel double number as well. This metric will be used to sort and eventualy filter the result, depending on the options
(:return-best-pipeline-only and :return-best-crossvalidation-only). The notion of `best` comes from metric-fn combined with loss-and-accuracy
* `loss-or-accuracy` If the metric-fn is a loss or accuracy calculation. Can be :loss or :accuracy. Decided the notion of `best` model.
In case of :loss pipelines with lower metric are better, in case of :accuracy pipelines with higher value are better.
* `options` map controls some mainly performance related parameters. These function can potentialy result in a large ammount of data,
able to bring the JVM into out-of-memory. We can control how many details the function returns by the following parameter:
The default are quite aggresive in removing details, and this can be tweaked further into more or less details via:
* `:return-best-pipeline-only` - Only return information of the best performing pipeline. Default is true.
* `:return-best-crossvalidation-only` - Only return information of the best crossvalidation (per pipeline returned). Default is true.
* `:map-fn` - Controls parallelism, so if we use map (:map) , pmap (:pmap) or :mapv to map over different pipelines. Default :pmap
* `:evaluation-handler-fn` - Gets called once with the complete result of an individual pipeline evaluation.
It can be used to adapt the data returned for each evaluation and / or to make side effects using
the evaluatio data.
The result of this function is taken as evaluation result. It need to contain as a minumum this 2 key paths:
[:train-transform :metric]
[:test-transform :metric]
All other evalution data can be removed, if desired.
It can be used for side effects as well, like experiment tracking on disk.
The passed in evaluation result is a map with all information on the current evaluation, including the datasets used.
The default handler function is: `scicloj.metamorph.ml/default-result-dissoc--in-fn` which removes the often large
model object and the training data.
`identity` can be use to get all evaluation data.
`scicloj.metamorph.ml/result-dissoc-in-seq--all` reduces even more agressively.
* `:other-metrices` Specifies other metrices to be calculated during evaluation
This function expects as well the ground truth of the target variable into
a specific key in the context at key `:model :scicloj.metamorph.ml/target-ds`
See here for the simplest way to set this up:
The function [[scicloj.ml.metamorph/model]] does this correctly.
"
([pipe-fn-or-decl-seq train-test-split-seq metric-fn loss-or-accuracy options]
(scicloj.metamorph.ml/evaluate-pipelines pipe-fn-or-decl-seq train-test-split-seq metric-fn loss-or-accuracy options))
([pipe-fn-seq train-test-split-seq metric-fn loss-or-accuracy]
(scicloj.metamorph.ml/evaluate-pipelines pipe-fn-seq train-test-split-seq metric-fn loss-or-accuracy)))
(defn explain
"Explain (if possible) an ml model. A model explanation is a model-specific map
of data that usually indicates some level of mapping between features and importance"
([model & args]
(apply scicloj.metamorph.ml/explain model args)))
(defn fit
"Helper function which executes pipeline op(s) in mode :fit on the given data and returns the fitted ctx.
Main use is for cases in which the pipeline gets executed ones and no model is part of the pipeline."
([data & args]
(apply scicloj.metamorph.core/fit data args)))
(defn fit-pipe
"Helper function which executes pipeline op(s) in mode :fit on the given data and returns the fitted ctx.
Main use is for cases in which the pipeline gets executed ones and no model is part of the pipeline."
([data pipe-fn]
(scicloj.metamorph.core/fit-pipe data pipe-fn)))
(defn format-fn-sources
([fn-sources]
(scicloj.metamorph.ml/format-fn-sources fn-sources)))
(defn get-nice-source-info
([pipeline-decl pipe-fns-ns pipe-fns-source-file]
(scicloj.metamorph.ml/get-nice-source-info pipeline-decl pipe-fns-ns pipe-fns-source-file)))
(defn hyperparameters
"Get the hyperparameters for this model definition"
([model-kwd]
(scicloj.metamorph.ml/hyperparameters model-kwd)))
(defn lift
"Create context aware version of the given `op` function. `:metamorph/data` will be used as a first parameter.
Result of the `op` function will be stored under `:metamorph/data`"
([op & args]
(apply scicloj.metamorph.core/lift op args)))
(defn linear
"Create a gridsearch definition which does a linear search.
* res-dtype-or-space map be either a datatype keyword or a vector
of categorical values."
([start end n-steps res-dtype-or-space]
(scicloj.metamorph.ml.gridsearch/linear start end n-steps res-dtype-or-space))
([start end n-steps]
(scicloj.metamorph.ml.gridsearch/linear start end n-steps))
([start end]
(scicloj.metamorph.ml.gridsearch/linear start end)))
(defn lookup-tables-consistent?
([train-lookup-table prediction-lookup-table]
(scicloj.metamorph.ml/lookup-tables-consistent? train-lookup-table prediction-lookup-table)))
(defn mae
"mean absolute error"
(^{:tag double} [predictions labels]
(scicloj.metamorph.ml.loss/mae predictions labels)))
(defn model-definition-names
"Return a list of all registered model defintion names."
([]
(scicloj.metamorph.ml/model-definition-names )))
(def model-definitions* scicloj.metamorph.ml/model-definitions*)
(defn mse
"mean squared error"
(^{:tag double} [predictions labels]
(scicloj.metamorph.ml.loss/mse predictions labels)))
(defn options->model-def
"Return the model definition that corresponse to the :model-type option"
(^{:pre [(contains? options :model-type)]} [options]
(scicloj.metamorph.ml/options->model-def options)))
(defn pipe-it
"Takes a data objects, executes the pipeline op(s) with it in :metamorph/data
in mode :fit and returns content of :metamorph/data.
Usefull to use execute a pipeline of pure data->data functions on some data"
([data & args]
(apply scicloj.metamorph.core/pipe-it data args)))
(defn pipeline
"Create a metamorph pipeline function out of operators.
`ops` are metamorph compliant functions (basicaly fn, which takle a ctx as first argument)
This function returns a function, whcih can ve execute with a ctx as parameter.
"
([& args]
(apply scicloj.metamorph.core/pipeline args)))
(defn predict
"Predict returns a dataset with only the predictions in it.
* For regression, a single column dataset is returned with the column named after the
target
* For classification, a dataset is returned with a float64 column for each target
value and values that describe the probability distribution."
([dataset model]
(scicloj.metamorph.ml/predict dataset model)))
(defn probability-distributions->labels
([prob-dists]
(scicloj.metamorph.ml.classification/probability-distributions->labels prob-dists)))
(defn reduce-result
([r result-dissoc-in-seq]
(scicloj.metamorph.ml/reduce-result r result-dissoc-in-seq)))
(def result-dissoc-in-seq--all scicloj.metamorph.ml/result-dissoc-in-seq--all)
(defn result-dissoc-in-seq--all-fn
([result]
(scicloj.metamorph.ml/result-dissoc-in-seq--all-fn result)))
(def result-dissoc-in-seq--ctxs scicloj.metamorph.ml/result-dissoc-in-seq--ctxs)
(defn result-dissoc-in-seq-ctx-fn
([result]
(scicloj.metamorph.ml/result-dissoc-in-seq-ctx-fn result)))
(defn rmse
"root mean squared error"
(^{:tag double} [predictions labels]
(scicloj.metamorph.ml.loss/rmse predictions labels)))
(defn sobol-gridsearch
"Given an map of key->values where some of the values are gridsearch definitions
produce a sequence of fully defined maps.
```clojure
user> (require '[tech.v3.ml.gridsearch :as ml-gs])
nil
user> (def opt-map {:a (ml-gs/categorical [:a :b :c])
:b (ml-gs/linear 0.01 1 10)
:c :not-searched})
user> opt-map
{:a
{:tech.v3.ml.gridsearch/type :linear,
:start 0.0,
:end 2.0,
:n-steps 3,
:result-space [:a :b :c]}
...
user> (ml-gs/sobol-gridsearch opt-map)
({:a :b, :b 0.56, :c :not-searched}
{:a :c, :b 0.22999999999999998, :c :not-searched}
{:a :b, :b 0.78, :c :not-searched}
...
```
"
([opt-map start-idx]
(scicloj.metamorph.ml.gridsearch/sobol-gridsearch opt-map start-idx))
([opt-map]
(scicloj.metamorph.ml.gridsearch/sobol-gridsearch opt-map)))
(defn thaw-model
"Thaw a model. Model's returned from train may be 'frozen' meaning a 'thaw'
operation is needed in order to use the model. This happens for you during predict
but you may also cached the 'thawed' model on the model map under the
':thawed-model' keyword in order to do fast predictions on small datasets."
([model opts]
(scicloj.metamorph.ml/thaw-model model opts))
([model]
(scicloj.metamorph.ml/thaw-model model)))
(defn train
"Given a dataset and an options map produce a model. The model-type keyword in the
options map selects which model definition to use to train the model. Returns a map
containing at least:
* `:model-data` - the result of that definitions's train-fn.
* `:options` - the options passed in.
* `:id` - new randomly generated UUID.
* `:feature-columns` - vector of column names.
* `:target-columns` - vector of column names."
([dataset options]
(scicloj.metamorph.ml/train dataset options)))
(defn transform-pipe
"Helper functions which execute the passed `pipe-fn` on the given `data` in mode :transform.
It merges the data into the provided `ctx` while doing so."
([data pipe-fn ctx]
(scicloj.metamorph.core/transform-pipe data pipe-fn ctx)))
(defn validate-lookup-tables
([model predict-ds-classification target-col]
(scicloj.metamorph.ml/validate-lookup-tables model predict-ds-classification target-col)))
| null | https://raw.githubusercontent.com/scicloj/scicloj.ml/74822932075e1575fe9779b0a165c0640b5d4740/src/scicloj/ml/core.clj | clojure | (ns scicloj.ml.core
Autogenerated from scicloj.ml.template.core-- DO NOT EDIT
"Core functions for machine learninig and pipeline execution.
Requiring this namesspace registers as well the model in:
* scicloj.ml.smile.classification
* scicloj.ml.smile.regression
* scicloj.ml.xgboost
Functions are re-exported from:
* scicloj.metamorph.ml.*
* scicloj.metamorph.core
"
(:require [scicloj.ml.template.core]
[scicloj.metamorph.core]
[scicloj.metamorph.ml]
[scicloj.metamorph.ml.classification]
[scicloj.metamorph.ml.gridsearch]
[scicloj.metamorph.ml.loss]))
(defn ->pipeline
"Create pipeline from declarative description."
([ops]
(scicloj.metamorph.core/->pipeline ops))
([config ops]
(scicloj.metamorph.core/->pipeline config ops)))
(defn categorical
"Given a vector a categorical values create a gridsearch definition."
([value-vec]
(scicloj.metamorph.ml.gridsearch/categorical value-vec)))
(defn classification-accuracy
"correct/total.
Model output is a sequence of probability distributions.
label-seq is a sequence of values. The answer is considered correct
if the key highest probability in the model output entry matches
that label."
(^{:tag double} [lhs rhs]
(scicloj.metamorph.ml.loss/classification-accuracy lhs rhs)))
(defn classification-loss
"1.0 - classification-accuracy."
(^{:tag double} [lhs rhs]
(scicloj.metamorph.ml.loss/classification-loss lhs rhs)))
(defn confusion-map
([predicted-labels labels normalize]
(scicloj.metamorph.ml.classification/confusion-map predicted-labels labels normalize))
([predicted-labels labels]
(scicloj.metamorph.ml.classification/confusion-map predicted-labels labels)))
(defn confusion-map->ds
([conf-matrix-map normalize]
(scicloj.metamorph.ml.classification/confusion-map->ds conf-matrix-map normalize))
([conf-matrix-map]
(scicloj.metamorph.ml.classification/confusion-map->ds conf-matrix-map)))
(defmacro def-ctx
"Convenience macro for defining pipelined operations that
bind the current value of the context to a var, for simple
debugging purposes."
([varname]
`(scicloj.ml.template.core/def-ctx ~varname)))
(defn default-loss-fn
"Given a datset which must have exactly 1 inference target column return a default
loss fn. If column is categorical, loss is tech.v3.ml.loss/classification-loss, else
the loss is tech.v3.ml.loss/mae (mean average error)."
([dataset]
(scicloj.metamorph.ml/default-loss-fn dataset)))
(defn default-result-dissoc-in-fn
([result]
(scicloj.metamorph.ml/default-result-dissoc-in-fn result)))
(def default-result-dissoc-in-seq scicloj.metamorph.ml/default-result-dissoc-in-seq)
(defn define-model!
"Create a model definition. An ml model is a function that takes a dataset and an
options map and returns a model. A model is something that, combined with a dataset,
produces a inferred dataset."
([model-kwd train-fn predict-fn opts]
(scicloj.metamorph.ml/define-model! model-kwd train-fn predict-fn opts)))
(defn do-ctx
"Apply f:: ctx -> any, ignore the result, leaving
pipeline unaffected. Akin to using doseq for side-effecting
operations like printing, visualization, or binding to vars
for debugging."
([f]
(scicloj.metamorph.core/do-ctx f)))
(defn ensemble-pipe
([pipes]
(scicloj.metamorph.ml/ensemble-pipe pipes)))
(defn evaluate-pipelines
"Evaluates the performance of a seq of metamorph pipelines, which are suposed to have a model as last step under key :model,
which behaves correctly in mode :fit and :transform. The function `scicloj.metamorph.ml/model` is such function behaving correctly.
This function calculates the accuracy or loss, given as `metric-fn` of each pipeline in `pipeline-fn-seq` using all the train-test splits
given in `train-test-split-seq`.
It runs the pipelines in mode :fit and in mode :transform for each pipeline-fn in `pipe-fn-seq` for each split in `train-test-split-seq`.
The function returns a seq of seqs of evaluation results per pipe-fn per train-test split.
Each of teh evaluation results is a context map, which is specified in the malli schema attached to this function.
* `pipe-fn-or-decl-seq` need to be sequence of pipeline functions or pipline declarations which follow the metamorph approach.
These type of functions get produced typically by calling `scicloj.metamorph/pipeline`. Documentation is here:
* `train-test-split-seq` need to be a sequence of maps containing the train and test dataset (being tech.ml.dataset) at keys :train and :test.
`tableclot.api/split->seq` produces such splits. Supervised models require both keys (:train and :test), while unsupervised models only use :train
* `metric-fn` Metric function to use. Typically comming from `tech.v3.ml.loss`. For supervised models the metric-fn receives the trueth
and predicted vales as double arrays and should return a single double number. For unsupervised models he function receives the fitted ctx
and should return a singel double number as well. This metric will be used to sort and eventualy filter the result, depending on the options
(:return-best-pipeline-only and :return-best-crossvalidation-only). The notion of `best` comes from metric-fn combined with loss-and-accuracy
* `loss-or-accuracy` If the metric-fn is a loss or accuracy calculation. Can be :loss or :accuracy. Decided the notion of `best` model.
In case of :loss pipelines with lower metric are better, in case of :accuracy pipelines with higher value are better.
* `options` map controls some mainly performance related parameters. These function can potentialy result in a large ammount of data,
able to bring the JVM into out-of-memory. We can control how many details the function returns by the following parameter:
The default are quite aggresive in removing details, and this can be tweaked further into more or less details via:
* `:return-best-pipeline-only` - Only return information of the best performing pipeline. Default is true.
* `:return-best-crossvalidation-only` - Only return information of the best crossvalidation (per pipeline returned). Default is true.
* `:map-fn` - Controls parallelism, so if we use map (:map) , pmap (:pmap) or :mapv to map over different pipelines. Default :pmap
* `:evaluation-handler-fn` - Gets called once with the complete result of an individual pipeline evaluation.
It can be used to adapt the data returned for each evaluation and / or to make side effects using
the evaluatio data.
The result of this function is taken as evaluation result. It need to contain as a minumum this 2 key paths:
[:train-transform :metric]
[:test-transform :metric]
All other evalution data can be removed, if desired.
It can be used for side effects as well, like experiment tracking on disk.
The passed in evaluation result is a map with all information on the current evaluation, including the datasets used.
The default handler function is: `scicloj.metamorph.ml/default-result-dissoc--in-fn` which removes the often large
model object and the training data.
`identity` can be use to get all evaluation data.
`scicloj.metamorph.ml/result-dissoc-in-seq--all` reduces even more agressively.
* `:other-metrices` Specifies other metrices to be calculated during evaluation
This function expects as well the ground truth of the target variable into
a specific key in the context at key `:model :scicloj.metamorph.ml/target-ds`
See here for the simplest way to set this up:
The function [[scicloj.ml.metamorph/model]] does this correctly.
"
([pipe-fn-or-decl-seq train-test-split-seq metric-fn loss-or-accuracy options]
(scicloj.metamorph.ml/evaluate-pipelines pipe-fn-or-decl-seq train-test-split-seq metric-fn loss-or-accuracy options))
([pipe-fn-seq train-test-split-seq metric-fn loss-or-accuracy]
(scicloj.metamorph.ml/evaluate-pipelines pipe-fn-seq train-test-split-seq metric-fn loss-or-accuracy)))
(defn explain
"Explain (if possible) an ml model. A model explanation is a model-specific map
of data that usually indicates some level of mapping between features and importance"
([model & args]
(apply scicloj.metamorph.ml/explain model args)))
(defn fit
"Helper function which executes pipeline op(s) in mode :fit on the given data and returns the fitted ctx.
Main use is for cases in which the pipeline gets executed ones and no model is part of the pipeline."
([data & args]
(apply scicloj.metamorph.core/fit data args)))
(defn fit-pipe
"Helper function which executes pipeline op(s) in mode :fit on the given data and returns the fitted ctx.
Main use is for cases in which the pipeline gets executed ones and no model is part of the pipeline."
([data pipe-fn]
(scicloj.metamorph.core/fit-pipe data pipe-fn)))
(defn format-fn-sources
([fn-sources]
(scicloj.metamorph.ml/format-fn-sources fn-sources)))
(defn get-nice-source-info
([pipeline-decl pipe-fns-ns pipe-fns-source-file]
(scicloj.metamorph.ml/get-nice-source-info pipeline-decl pipe-fns-ns pipe-fns-source-file)))
(defn hyperparameters
"Get the hyperparameters for this model definition"
([model-kwd]
(scicloj.metamorph.ml/hyperparameters model-kwd)))
(defn lift
"Create context aware version of the given `op` function. `:metamorph/data` will be used as a first parameter.
Result of the `op` function will be stored under `:metamorph/data`"
([op & args]
(apply scicloj.metamorph.core/lift op args)))
(defn linear
"Create a gridsearch definition which does a linear search.
* res-dtype-or-space map be either a datatype keyword or a vector
of categorical values."
([start end n-steps res-dtype-or-space]
(scicloj.metamorph.ml.gridsearch/linear start end n-steps res-dtype-or-space))
([start end n-steps]
(scicloj.metamorph.ml.gridsearch/linear start end n-steps))
([start end]
(scicloj.metamorph.ml.gridsearch/linear start end)))
(defn lookup-tables-consistent?
([train-lookup-table prediction-lookup-table]
(scicloj.metamorph.ml/lookup-tables-consistent? train-lookup-table prediction-lookup-table)))
(defn mae
"mean absolute error"
(^{:tag double} [predictions labels]
(scicloj.metamorph.ml.loss/mae predictions labels)))
(defn model-definition-names
"Return a list of all registered model defintion names."
([]
(scicloj.metamorph.ml/model-definition-names )))
(def model-definitions* scicloj.metamorph.ml/model-definitions*)
(defn mse
"mean squared error"
(^{:tag double} [predictions labels]
(scicloj.metamorph.ml.loss/mse predictions labels)))
(defn options->model-def
"Return the model definition that corresponse to the :model-type option"
(^{:pre [(contains? options :model-type)]} [options]
(scicloj.metamorph.ml/options->model-def options)))
(defn pipe-it
"Takes a data objects, executes the pipeline op(s) with it in :metamorph/data
in mode :fit and returns content of :metamorph/data.
Usefull to use execute a pipeline of pure data->data functions on some data"
([data & args]
(apply scicloj.metamorph.core/pipe-it data args)))
(defn pipeline
"Create a metamorph pipeline function out of operators.
`ops` are metamorph compliant functions (basicaly fn, which takle a ctx as first argument)
This function returns a function, whcih can ve execute with a ctx as parameter.
"
([& args]
(apply scicloj.metamorph.core/pipeline args)))
(defn predict
"Predict returns a dataset with only the predictions in it.
* For regression, a single column dataset is returned with the column named after the
target
* For classification, a dataset is returned with a float64 column for each target
value and values that describe the probability distribution."
([dataset model]
(scicloj.metamorph.ml/predict dataset model)))
(defn probability-distributions->labels
([prob-dists]
(scicloj.metamorph.ml.classification/probability-distributions->labels prob-dists)))
(defn reduce-result
([r result-dissoc-in-seq]
(scicloj.metamorph.ml/reduce-result r result-dissoc-in-seq)))
(def result-dissoc-in-seq--all scicloj.metamorph.ml/result-dissoc-in-seq--all)
(defn result-dissoc-in-seq--all-fn
([result]
(scicloj.metamorph.ml/result-dissoc-in-seq--all-fn result)))
(def result-dissoc-in-seq--ctxs scicloj.metamorph.ml/result-dissoc-in-seq--ctxs)
(defn result-dissoc-in-seq-ctx-fn
([result]
(scicloj.metamorph.ml/result-dissoc-in-seq-ctx-fn result)))
(defn rmse
"root mean squared error"
(^{:tag double} [predictions labels]
(scicloj.metamorph.ml.loss/rmse predictions labels)))
(defn sobol-gridsearch
"Given an map of key->values where some of the values are gridsearch definitions
produce a sequence of fully defined maps.
```clojure
user> (require '[tech.v3.ml.gridsearch :as ml-gs])
nil
user> (def opt-map {:a (ml-gs/categorical [:a :b :c])
:b (ml-gs/linear 0.01 1 10)
:c :not-searched})
user> opt-map
{:a
{:tech.v3.ml.gridsearch/type :linear,
:start 0.0,
:end 2.0,
:n-steps 3,
:result-space [:a :b :c]}
...
user> (ml-gs/sobol-gridsearch opt-map)
({:a :b, :b 0.56, :c :not-searched}
{:a :c, :b 0.22999999999999998, :c :not-searched}
{:a :b, :b 0.78, :c :not-searched}
...
```
"
([opt-map start-idx]
(scicloj.metamorph.ml.gridsearch/sobol-gridsearch opt-map start-idx))
([opt-map]
(scicloj.metamorph.ml.gridsearch/sobol-gridsearch opt-map)))
(defn thaw-model
"Thaw a model. Model's returned from train may be 'frozen' meaning a 'thaw'
operation is needed in order to use the model. This happens for you during predict
but you may also cached the 'thawed' model on the model map under the
':thawed-model' keyword in order to do fast predictions on small datasets."
([model opts]
(scicloj.metamorph.ml/thaw-model model opts))
([model]
(scicloj.metamorph.ml/thaw-model model)))
(defn train
"Given a dataset and an options map produce a model. The model-type keyword in the
options map selects which model definition to use to train the model. Returns a map
containing at least:
* `:model-data` - the result of that definitions's train-fn.
* `:options` - the options passed in.
* `:id` - new randomly generated UUID.
* `:feature-columns` - vector of column names.
* `:target-columns` - vector of column names."
([dataset options]
(scicloj.metamorph.ml/train dataset options)))
(defn transform-pipe
"Helper functions which execute the passed `pipe-fn` on the given `data` in mode :transform.
It merges the data into the provided `ctx` while doing so."
([data pipe-fn ctx]
(scicloj.metamorph.core/transform-pipe data pipe-fn ctx)))
(defn validate-lookup-tables
([model predict-ds-classification target-col]
(scicloj.metamorph.ml/validate-lookup-tables model predict-ds-classification target-col)))
|
|
cc78605af80f8da1c34a3352cc07563e63ac68eb23438be48da0293450ca1b88 | clojure-lsp/clojure-lsp | test_tree.clj | (ns clojure-lsp.feature.test-tree
(:require
[clojure-lsp.queries :as q]
[clojure-lsp.shared :as shared]))
(set! *warn-on-reflection* true)
(defn ^:private ->testings-children [testings]
(let [root-testings (remove (fn [testing]
(some #(and (shared/inside? testing %)
(not= % testing)) testings))
testings)]
(mapv (fn [root-testing]
(let [inside-testings (filter (fn [testing]
(and (shared/inside? testing root-testing)
(not= testing root-testing)))
testings)]
(shared/assoc-some
{:name (str
(or (-> root-testing :context :clojure.test :testing-str) ;; not always a string
""))
:range (shared/->scope-range root-testing)
:name-range (shared/->range root-testing)
:kind :testing}
:children (when (seq inside-testings) (->testings-children inside-testings)))))
root-testings)))
(defn ^:private deftest->tree [deftest testings]
(let [local-testings (filter #(shared/inside? % deftest) testings)]
{:name (str (:name deftest))
:range (shared/->scope-range deftest)
:name-range (shared/->range deftest)
:kind :deftest
:children (->testings-children local-testings)}))
(defn tree [uri db]
(let [ns-element (q/find-namespace-definition-by-uri db uri)
local-buckets (get-in db [:analysis uri])
deftests (into []
(filter #(contains? '#{clojure.test/deftest cljs.test/deftest}
(:defined-by %)))
(:var-definitions local-buckets))
testings (into []
(filter #(and (= 'testing (:name %))
(contains? '#{clojure.test cljs.test} (:to %))))
(:var-usages local-buckets))
tests-tree (mapv #(deftest->tree % testings) deftests)]
(when (seq tests-tree)
{:uri uri
:tree {:name (str (:name ns-element))
:range (shared/->scope-range ns-element)
:name-range (shared/->range ns-element)
:kind :namespace
:children tests-tree}})))
| null | https://raw.githubusercontent.com/clojure-lsp/clojure-lsp/d6ca21a6d2235d7438fd8901db93930b80ae257b/lib/src/clojure_lsp/feature/test_tree.clj | clojure | not always a string | (ns clojure-lsp.feature.test-tree
(:require
[clojure-lsp.queries :as q]
[clojure-lsp.shared :as shared]))
(set! *warn-on-reflection* true)
(defn ^:private ->testings-children [testings]
(let [root-testings (remove (fn [testing]
(some #(and (shared/inside? testing %)
(not= % testing)) testings))
testings)]
(mapv (fn [root-testing]
(let [inside-testings (filter (fn [testing]
(and (shared/inside? testing root-testing)
(not= testing root-testing)))
testings)]
(shared/assoc-some
{:name (str
""))
:range (shared/->scope-range root-testing)
:name-range (shared/->range root-testing)
:kind :testing}
:children (when (seq inside-testings) (->testings-children inside-testings)))))
root-testings)))
(defn ^:private deftest->tree [deftest testings]
(let [local-testings (filter #(shared/inside? % deftest) testings)]
{:name (str (:name deftest))
:range (shared/->scope-range deftest)
:name-range (shared/->range deftest)
:kind :deftest
:children (->testings-children local-testings)}))
(defn tree [uri db]
(let [ns-element (q/find-namespace-definition-by-uri db uri)
local-buckets (get-in db [:analysis uri])
deftests (into []
(filter #(contains? '#{clojure.test/deftest cljs.test/deftest}
(:defined-by %)))
(:var-definitions local-buckets))
testings (into []
(filter #(and (= 'testing (:name %))
(contains? '#{clojure.test cljs.test} (:to %))))
(:var-usages local-buckets))
tests-tree (mapv #(deftest->tree % testings) deftests)]
(when (seq tests-tree)
{:uri uri
:tree {:name (str (:name ns-element))
:range (shared/->scope-range ns-element)
:name-range (shared/->range ns-element)
:kind :namespace
:children tests-tree}})))
|
190203d01759f7c62e6bf51e95beed27432dc02ab51b3cafc7bfe8610606334a | marianoguerra/immutant-recipes | init.clj | (ns immutant.init
(:use
[ring.util.response :only (redirect)]
[cemerick.friend.util :only (gets)]
ring-router.core
[clojure.data.json :only (read-json json-str)])
(:require [cemerick.friend :as friend]
(cemerick.friend [workflows :as workflows]
[credentials :as creds])
[marianoguerra.friend-json-workflow :as json-auth]
[ring.middleware.file :as ring-file]
[ring.middleware.file-info :as ring-file-info]
[ring.middleware.session :as ring-session]
[ring.util.response :as response]
[immutant.web :as web]))
(def users {"root" {:username "root"
:password (creds/hash-bcrypt "admin_password")
:roles #{::admin}}
"jane" {:username "jane"
:password (creds/hash-bcrypt "user_password")
:roles #{::user}}})
(defn not-found [request]
{:status 404
:header {"Content-Type" "text/plain"}
:body "not found"})
(defn json-response [data & [status]]
{:status (or status 200)
:headers {"Content-Type" "application/json"}
:body (json-str data)})
(defn ping [request]
(json-response "pong"))
(defn or-not-found [handler]
(fn [request]
(let [response (handler request)]
(if response
response
(not-found request)))))
(def app (or-not-found (web/wrap-resource (router
[(GET "/api/ping" ping)
(GET "/api/session" json-auth/handle-session)
(POST "/api/session" json-auth/handle-session)
(DELETE "/api/session" json-auth/handle-session)
(GET "/api/login" (fn [request] (redirect "../login.html")))
(GET "/api/user-only-ping" (friend/wrap-authorize ping [::user]))
(GET "/api/admin-only-ping" (friend/wrap-authorize ping [::admin]))]) "/s/")))
(def secure-app
(-> app
(friend/authenticate
{:login-uri "/friend-json-auth/api/session"
:unauthorized-handler json-auth/unauthorized-handler
:workflows [(json-auth/json-login
:login-uri "/friend-json-auth/api/session"
:login-failure-handler json-auth/login-failed
:credential-fn (partial creds/bcrypt-credential-fn users))]})
(ring-session/wrap-session)))
(web/start "/" secure-app)
| null | https://raw.githubusercontent.com/marianoguerra/immutant-recipes/6b05ad77f91826e8613421de5bee337fc1cc65d0/friend-json-auth/src/immutant/init.clj | clojure | (ns immutant.init
(:use
[ring.util.response :only (redirect)]
[cemerick.friend.util :only (gets)]
ring-router.core
[clojure.data.json :only (read-json json-str)])
(:require [cemerick.friend :as friend]
(cemerick.friend [workflows :as workflows]
[credentials :as creds])
[marianoguerra.friend-json-workflow :as json-auth]
[ring.middleware.file :as ring-file]
[ring.middleware.file-info :as ring-file-info]
[ring.middleware.session :as ring-session]
[ring.util.response :as response]
[immutant.web :as web]))
(def users {"root" {:username "root"
:password (creds/hash-bcrypt "admin_password")
:roles #{::admin}}
"jane" {:username "jane"
:password (creds/hash-bcrypt "user_password")
:roles #{::user}}})
(defn not-found [request]
{:status 404
:header {"Content-Type" "text/plain"}
:body "not found"})
(defn json-response [data & [status]]
{:status (or status 200)
:headers {"Content-Type" "application/json"}
:body (json-str data)})
(defn ping [request]
(json-response "pong"))
(defn or-not-found [handler]
(fn [request]
(let [response (handler request)]
(if response
response
(not-found request)))))
(def app (or-not-found (web/wrap-resource (router
[(GET "/api/ping" ping)
(GET "/api/session" json-auth/handle-session)
(POST "/api/session" json-auth/handle-session)
(DELETE "/api/session" json-auth/handle-session)
(GET "/api/login" (fn [request] (redirect "../login.html")))
(GET "/api/user-only-ping" (friend/wrap-authorize ping [::user]))
(GET "/api/admin-only-ping" (friend/wrap-authorize ping [::admin]))]) "/s/")))
(def secure-app
(-> app
(friend/authenticate
{:login-uri "/friend-json-auth/api/session"
:unauthorized-handler json-auth/unauthorized-handler
:workflows [(json-auth/json-login
:login-uri "/friend-json-auth/api/session"
:login-failure-handler json-auth/login-failed
:credential-fn (partial creds/bcrypt-credential-fn users))]})
(ring-session/wrap-session)))
(web/start "/" secure-app)
|
|
e4684520f1fc27e56cf20463cb84d1ec07b1083517ab1b74aa39069c6285fdf3 | jabber-at/ejabberd | mod_bosh_riak.erl | %%%-------------------------------------------------------------------
@author < >
Created : 15 Apr 2017 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2018 ProcessOne
%%%
%%% 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. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%-------------------------------------------------------------------
-module(mod_bosh_riak).
-behaviour(mod_bosh).
%% API
-export([init/0, open_session/2, close_session/1, find_session/1]).
-record(bosh, {sid :: binary(),
pid :: pid()}).
-include("logger.hrl").
%%%===================================================================
%%% API
%%%===================================================================
init() ->
clean_table().
open_session(SID, Pid) ->
ejabberd_riak:put(#bosh{sid = SID, pid = Pid}, bosh_schema()).
close_session(SID) ->
ejabberd_riak:delete(bosh, SID).
find_session(SID) ->
case ejabberd_riak:get(bosh, bosh_schema(), SID) of
{ok, #bosh{pid = Pid}} -> {ok, Pid};
{error, _} = Err -> Err
end.
%%%===================================================================
Internal functions
%%%===================================================================
bosh_schema() ->
{record_info(fields, bosh), #bosh{}}.
clean_table() ->
?DEBUG("Cleaning Riak 'bosh' table...", []),
case ejabberd_riak:get(bosh, bosh_schema()) of
{ok, Rs} ->
lists:foreach(
fun(#bosh{sid = SID, pid = Pid}) when node(Pid) == node() ->
ejabberd_riak:delete(bosh, SID);
(_) ->
ok
end, Rs);
{error, Reason} = Err ->
?ERROR_MSG("failed to clean Riak 'bosh' table: ~p", [Reason]),
Err
end.
| null | https://raw.githubusercontent.com/jabber-at/ejabberd/7bfec36856eaa4df21b26e879d3ba90285bad1aa/src/mod_bosh_riak.erl | erlang | -------------------------------------------------------------------
This program is free software; you can redistribute it and/or
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.
-------------------------------------------------------------------
API
===================================================================
API
===================================================================
===================================================================
=================================================================== | @author < >
Created : 15 Apr 2017 by < >
ejabberd , Copyright ( C ) 2002 - 2018 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
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. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(mod_bosh_riak).
-behaviour(mod_bosh).
-export([init/0, open_session/2, close_session/1, find_session/1]).
-record(bosh, {sid :: binary(),
pid :: pid()}).
-include("logger.hrl").
init() ->
clean_table().
open_session(SID, Pid) ->
ejabberd_riak:put(#bosh{sid = SID, pid = Pid}, bosh_schema()).
close_session(SID) ->
ejabberd_riak:delete(bosh, SID).
find_session(SID) ->
case ejabberd_riak:get(bosh, bosh_schema(), SID) of
{ok, #bosh{pid = Pid}} -> {ok, Pid};
{error, _} = Err -> Err
end.
Internal functions
bosh_schema() ->
{record_info(fields, bosh), #bosh{}}.
clean_table() ->
?DEBUG("Cleaning Riak 'bosh' table...", []),
case ejabberd_riak:get(bosh, bosh_schema()) of
{ok, Rs} ->
lists:foreach(
fun(#bosh{sid = SID, pid = Pid}) when node(Pid) == node() ->
ejabberd_riak:delete(bosh, SID);
(_) ->
ok
end, Rs);
{error, Reason} = Err ->
?ERROR_MSG("failed to clean Riak 'bosh' table: ~p", [Reason]),
Err
end.
|
77f08e817b5a3c0ed42f4f553583099b48322929442da699636155e89b01e9a9 | Bogdanp/racket-crontab | info.rkt | #lang info
(define license 'BSD-3-Clause)
(define version "0.1")
(define collection "crontab")
(define deps '("base"))
| null | https://raw.githubusercontent.com/Bogdanp/racket-crontab/8b940906f10913f37a82845888e72d7dce64c101/crontab-lib/info.rkt | racket | #lang info
(define license 'BSD-3-Clause)
(define version "0.1")
(define collection "crontab")
(define deps '("base"))
|
|
3534acb0db0fa0676301ac19f87446f45f4c6131f475c1bfa490c45f51a0ddbf | TrustInSoft/tis-kernel | LogicSemantics.ml | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(* -------------------------------------------------------------------------- *)
(* --- ACSL Translation --- *)
(* -------------------------------------------------------------------------- *)
open Cil_types
open Cil_datatype
open LogicBuiltins
open Clabels
open Ctypes
open Lang
open Definitions
open Memory
type polarity = [ `Positive | `Negative | `NoPolarity ]
module Make(M : Memory.Model) =
struct
open M
type loc = M.loc
type value = loc Memory.value
type logic = loc Memory.logic
type region = loc sloc list
type sigma = Sigma.t
module L = Cvalues.Logic(M)
module C = LogicCompiler.Make(M)
(* -------------------------------------------------------------------------- *)
(* --- Frames --- *)
(* -------------------------------------------------------------------------- *)
type call = C.call
type frame = C.frame
let pp_frame = C.pp_frame
let get_frame = C.get_frame
let in_frame = C.in_frame
let mem_frame = C.mem_frame
let mem_at_frame = C.mem_at_frame
let mem_at = C.mem_at
let frame = C.frame
let call = C.call
let call_pre = C.call_pre
let call_post = C.call_post
let return = C.return
let result = C.result
let status = C.status
let guards = C.guards
(* -------------------------------------------------------------------------- *)
(* --- Debugging --- *)
(* -------------------------------------------------------------------------- *)
let pp_logic fmt = function
| Vexp e -> F.pp_term fmt e
| Vloc l -> M.pretty fmt l
| Lset _ | Vset _ -> Format.pp_print_string fmt "<set>"
let pp_bound fmt = function None -> () | Some p -> F.pp_term fmt p
let pp_sloc fmt = function
| Sloc l -> M.pretty fmt l
| Sarray(l,_,n) -> Format.fprintf fmt "@[<hov2>%a@,.(..%d)@]"
M.pretty l (n-1)
| Srange(l,_,a,b) -> Format.fprintf fmt "@[<hov2>%a@,.(%a@,..%a)@]"
M.pretty l pp_bound a pp_bound b
| Sdescr(xs,l,p) -> Format.fprintf fmt "@[<hov2>{ %a | %a }@]"
M.pretty l F.pp_pred (F.p_forall xs p)
let pp_region fmt sloc =
List.iter (fun s -> Format.fprintf fmt "@ %a" pp_sloc s) sloc
(* -------------------------------------------------------------------------- *)
--- Translation Environment & Recursion ---
(* -------------------------------------------------------------------------- *)
type env = C.env
let new_env = C.new_env
let move = C.move
let sigma = C.sigma
let call_env s = C.move (C.new_env []) s
let logic_of_value = function
| Val e -> Vexp e
| Loc l -> Vloc l
let loc_of_term env t =
match C.logic env t with
| Vexp e -> M.pointer_loc e
| Vloc l -> l
| _ ->
Warning.error "Non-expected set of locations (%a)" Printer.pp_term t
let val_of_term env t =
match C.logic env t with
| Vexp e -> e
| Vloc l -> M.pointer_val l
| Vset s -> Vset.concretize s
| Lset _ ->
Warning.error "Non-expected set of values (%a)" Printer.pp_term t
let set_of_term env t = L.vset (C.logic env t)
let collection_of_term env t =
let v = C.logic env t in
match v with
| Vexp s when Logic_typing.is_set_type t.term_type ->
let te = Logic_typing.type_of_set_elem t.term_type in
Vset [Vset.Set(tau_of_ltype te,s)]
| w -> w
let term env t =
match C.logic env t with
| Vexp e -> e
| Vloc l -> M.pointer_val l
| s -> Vset.concretize (L.vset s)
(* -------------------------------------------------------------------------- *)
(* --- Accessing an Offset (sub field-index in a compound) --- *)
(* -------------------------------------------------------------------------- *)
let rec access_offset env (v:logic) = function
| TNoOffset -> v
| TModel _ -> Wp_parameters.not_yet_implemented "Model field"
| TField(f,offset) ->
let v_f = L.map (fun r -> Lang.F.e_getfield r (Cfield f)) v in
access_offset env v_f offset
| TIndex(k,offset) ->
let rk = C.logic env k in
let v_k = L.apply Lang.F.e_get v rk in
access_offset env v_k offset
(* -------------------------------------------------------------------------- *)
(* --- Updating an Offset (sub field-index in a compound) --- *)
(* -------------------------------------------------------------------------- *)
let rec update_offset env (r:Lang.F.term) offset (v:Lang.F.term) =
match offset with
| TNoOffset -> v
| TModel _ -> Wp_parameters.not_yet_implemented "Model field"
| TField(f,offset) ->
let r_f = Lang.F.e_getfield r (Cfield f) in
let r_fv = update_offset env r_f offset v in
Lang.F.e_setfield r (Cfield f) r_fv
| TIndex(k,offset) ->
let k = val_of_term env k in
let r_kv = update_offset env (Lang.F.e_get r k) offset v in
Lang.F.e_set r k r_kv
(* -------------------------------------------------------------------------- *)
(* --- Shifting Location of an Offset (pointer shift) --- *)
(* -------------------------------------------------------------------------- *)
typ is logic - type of ( load v )
let rec logic_offset env typ (v:logic) = function
| TNoOffset -> typ , v
| TModel _ -> Wp_parameters.not_yet_implemented "Model field"
| TField(f,offset) ->
logic_offset env f.ftype (L.field v f) offset
| TIndex(k,offset) ->
let te = Cil.typeOf_array_elem typ in
let size = Ctypes.get_array_size (Ctypes.object_of typ) in
let obj = Ctypes.object_of te in
let vloc = L.shift v obj ?size (C.logic env k) in
logic_offset env te vloc offset
(* -------------------------------------------------------------------------- *)
(* --- Logic Variable --- *)
(* -------------------------------------------------------------------------- *)
type lv_value =
| VAL of logic
| VAR of varinfo
let logic_var env lv =
match lv.lv_origin with
| None -> VAL (C.logic_var env lv)
| Some x ->
if x.vformal then match C.formal x with
| Some v -> VAL (logic_of_value v)
| None -> VAR x
else VAR x
(* -------------------------------------------------------------------------- *)
(* --- Term L-Values (this means 'loading' the l-value) --- *)
(* -------------------------------------------------------------------------- *)
let load_loc env typ loc loffset =
let te,lp = logic_offset env typ (Vloc loc) loffset in
L.load (C.sigma env) (Ctypes.object_of te) lp
let term_lval env (lhost,loffset) =
match lhost with
| TResult _ ->
let r = C.result () in
access_offset env (Vexp (Lang.F.e_var r)) loffset
| TMem e ->
let te = Logic_typing.ctype_of_pointed e.term_type in
let te , lp = logic_offset env te (C.logic env e) loffset in
L.load (C.sigma env) (Ctypes.object_of te) lp
| TVar{lv_name="\\exit_status"} ->
assert (loffset = TNoOffset) ; (* int ! *)
Vexp (Lang.F.e_var (C.status ()))
| TVar lv ->
begin
match logic_var env lv with
| VAL v -> access_offset env v loffset
| VAR x -> load_loc env x.vtype (M.cvar x) loffset
end
(* -------------------------------------------------------------------------- *)
(* --- Address of L-Values --- *)
(* -------------------------------------------------------------------------- *)
let addr_lval env (lhost,loffset) =
match lhost with
| TResult _ -> Wp_parameters.abort ~current:true "Address of \\result"
| TMem e ->
let te = Logic_typing.ctype_of_pointed e.term_type in
snd (logic_offset env te (C.logic env e) loffset)
| TVar lv ->
begin
match logic_var env lv with
| VAL v ->
Wp_parameters.abort ~current:true
"Address of logic value (%a)@." pp_logic v
| VAR x ->
snd (logic_offset env x.vtype (Vloc (M.cvar x)) loffset)
end
(* -------------------------------------------------------------------------- *)
--- Unary Operators ---
(* -------------------------------------------------------------------------- *)
(* Only integral *)
let term_unop = function
| Neg -> L.map_opp
| BNot -> L.map Cint.l_not
| LNot -> L.map Lang.F.e_not
(* -------------------------------------------------------------------------- *)
(* --- Equality --- *)
(* -------------------------------------------------------------------------- *)
type eqsort =
| EQ_set
| EQ_loc
| EQ_plain
| EQ_array of Matrix.matrix
| EQ_comp of compinfo
| EQ_incomparable
let eqsort_of_type t =
match Logic_utils.unroll_type t with
| Ltype({lt_name="set"},[_]) -> EQ_set
| Linteger | Lreal | Lvar _ | Larrow _ | Ltype _ -> EQ_plain
| Ctype t ->
match Ctypes.object_of t with
| C_pointer _ -> EQ_loc
| C_int _ | C_float _ -> EQ_plain
| C_comp c -> EQ_comp c
| C_array a -> EQ_array (Matrix.of_array a)
let eqsort_of_comparison a b =
match eqsort_of_type a.term_type , eqsort_of_type b.term_type with
| EQ_set , _ | _ , EQ_set -> EQ_set
| EQ_loc , EQ_loc -> EQ_loc
| EQ_comp c1 , EQ_comp c2 ->
if Compinfo.equal c1 c2 then EQ_comp c1 else EQ_incomparable
| EQ_array (t1,d1) , EQ_array (t2,d2) ->
if Ctypes.equal t1 t2 then
match Matrix.merge d1 d2 with
| Some d -> EQ_array(t1,d)
| None -> EQ_incomparable
else EQ_incomparable
| EQ_plain , EQ_plain -> EQ_plain
| _ -> EQ_incomparable
let use_equal = function
| `Negative -> Wp_parameters.ExtEqual.get ()
| `Positive | `NoPolarity -> false
let term_equal polarity env a b =
match eqsort_of_comparison a b with
| EQ_set ->
let sa = set_of_term env a in
let sb = set_of_term env b in
(* TODO: should be parametric in the equality of elements *)
Vset.equal sa sb
| EQ_loc ->
let la = loc_of_term env a in
let lb = loc_of_term env b in
M.loc_eq la lb
| EQ_comp c ->
let va = val_of_term env a in
let vb = val_of_term env b in
if use_equal polarity
then Lang.F.p_equal va vb
else Cvalues.equal_comp c va vb
| EQ_array m ->
let va = val_of_term env a in
let vb = val_of_term env b in
if use_equal polarity
then Lang.F.p_equal va vb
else Cvalues.equal_array m va vb
| EQ_plain ->
Lang.F.p_equal (val_of_term env a) (val_of_term env b)
| EQ_incomparable ->
(* incomparrable terms *)
Wp_parameters.warning ~current:true
"@[Incomparable terms (comparison is False):@ type %a with@ type %a@]"
Printer.pp_logic_type a.term_type
Printer.pp_logic_type b.term_type ;
Lang.F.p_false
let term_diff polarity env a b =
Lang.F.p_not (term_equal (Cvalues.negate polarity) env a b)
let compare_term env vrel lrel a b =
if Logic_typing.is_pointer_type a.term_type then
lrel (loc_of_term env a) (loc_of_term env b)
else
vrel (val_of_term env a) (val_of_term env b)
(* -------------------------------------------------------------------------- *)
(* --- Term Comparison --- *)
(* -------------------------------------------------------------------------- *)
let exp_equal env a b =
Vexp(Lang.F.e_prop (term_equal `NoPolarity env a b))
let exp_diff env a b =
Vexp(Lang.F.e_prop (term_diff `NoPolarity env a b))
let exp_compare env vrel lrel a b =
Vexp(Lang.F.e_prop (compare_term env vrel lrel a b))
(* -------------------------------------------------------------------------- *)
(* --- Binary Operators --- *)
(* -------------------------------------------------------------------------- *)
let toreal t v =
if t then L.map Cfloat.real_of_int v else v
let arith env fint freal a b =
let va = C.logic env a in
let vb = C.logic env b in
let ta = Logic_typing.is_integral_type a.term_type in
let tb = Logic_typing.is_integral_type b.term_type in
if ta && tb
then fint va vb
else freal (toreal ta va) (toreal tb vb)
let rec fold_assoc bop acc ts =
match ts with
| [] -> acc
| t::others ->
match t.term_node with
| TBinOp(binop,a,b) when bop == binop ->
fold_assoc bop acc (a::b::others)
| _ -> fold_assoc bop (t::acc) others
let term_binop env binop a b =
match binop with
| PlusA -> arith env L.apply_add (L.apply F.e_add) a b
| MinusA -> arith env L.apply_sub (L.apply F.e_sub) a b
| Mult -> arith env (L.apply Lang.F.e_mul) (L.apply F.e_mul) a b
| Div -> arith env (L.apply Lang.F.e_div) (L.apply F.e_div) a b
| Mod -> L.apply Lang.F.e_mod (C.logic env a) (C.logic env b)
| PlusPI | IndexPI ->
let va = C.logic env a in
let vb = C.logic env b in
let te = Logic_typing.ctype_of_pointed a.term_type in
L.shift va (Ctypes.object_of te) vb
| MinusPI ->
let va = C.logic env a in
let vb = C.logic env b in
let te = Logic_typing.ctype_of_pointed a.term_type in
L.shift va (Ctypes.object_of te) (L.map_opp vb)
| MinusPP ->
let te = Logic_typing.ctype_of_pointed a.term_type in
let la = loc_of_term env a in
let lb = loc_of_term env b in
Vexp(M.loc_diff (Ctypes.object_of te) la lb)
| Shiftlt -> L.apply Cint.l_lsl (C.logic env a) (C.logic env b)
| Shiftrt -> L.apply Cint.l_lsr (C.logic env a) (C.logic env b)
| BAnd -> L.apply Cint.l_and (C.logic env a) (C.logic env b)
| BXor -> L.apply Cint.l_xor (C.logic env a) (C.logic env b)
| BOr -> L.apply Cint.l_or (C.logic env a) (C.logic env b)
| LAnd ->
Vexp(Lang.F.e_and (List.map (val_of_term env) (fold_assoc LAnd [] [a;b])))
| LOr ->
Vexp(Lang.F.e_or (List.map (val_of_term env) (fold_assoc LOr [] [a;b])))
| Lt -> exp_compare env Lang.F.p_lt M.loc_lt a b
| Gt -> exp_compare env Lang.F.p_lt M.loc_lt b a
| Le -> exp_compare env Lang.F.p_leq M.loc_leq a b
| Ge -> exp_compare env Lang.F.p_leq M.loc_leq b a
| Eq -> exp_equal env a b
| Ne -> exp_diff env a b
(* -------------------------------------------------------------------------- *)
(* --- Term Cast --- *)
(* -------------------------------------------------------------------------- *)
type cvsort =
| L_bool
| L_real
| L_integer
| L_cint of c_int
| L_cfloat of c_float
| L_pointer of typ
let rec cvsort_of_type t =
match Logic_utils.unroll_type t with
| Ltype({lt_name="set"},[t]) -> cvsort_of_type t
| Ltype _ as b when Logic_const.is_boolean_type b -> L_bool
| Linteger -> L_integer
| Lreal -> L_real
| Ctype c ->
begin
match Ctypes.object_of c with
| C_int i -> L_cint i
| C_float f -> L_cfloat f
| C_pointer te -> L_pointer te
| C_array a -> L_pointer a.arr_element
| obj -> Warning.error "cast from (%a) not implemented yet"
Ctypes.pretty obj
end
| _ -> Warning.error "cast from (%a) not implemented yet"
Printer.pp_logic_type t
let term_cast env typ t =
match Ctypes.object_of typ , cvsort_of_type t.term_type with
| C_int i , L_cint i0 ->
let v = C.logic env t in
if (Ctypes.sub_c_int i0 i) then v
else L.map (Cint.convert i) v
| C_int i , L_integer ->
L.map (Cint.convert i) (C.logic env t)
| C_int i , L_pointer _ ->
L.map_l2t (M.int_of_loc i) (C.logic env t)
| C_int i , (L_cfloat _ | L_real) ->
L.map (Cint.of_real i) (C.logic env t)
| C_float f , (L_cfloat _ | L_real) ->
L.map (Cfloat.convert f) (C.logic env t)
| C_float f , (L_cint _ | L_integer) ->
L.map (Cfloat.float_of_int f) (C.logic env t)
| C_pointer ty , L_pointer t0 ->
let value = C.logic env t in
let o_src = Ctypes.object_of t0 in
let o_dst = Ctypes.object_of ty in
if Ctypes.compare o_src o_dst = 0
then value
else L.map_loc (M.cast { pre=o_src ; post=o_dst }) value
| C_pointer ty , (L_integer | L_cint _) ->
let obj = Ctypes.object_of ty in
L.map_t2l (M.loc_of_int obj) (C.logic env t)
| C_int _ , L_bool ->
L.map Cvalues.bool_val (C.logic env t)
| _ ->
Warning.error "Cast from (%a) to (%a) not implemented yet"
Printer.pp_logic_type t.term_type Printer.pp_typ typ
(* -------------------------------------------------------------------------- *)
(* --- Environment Binding --- *)
(* -------------------------------------------------------------------------- *)
let bind_quantifiers (env:env) qs =
let rec acc xs env hs = function
| [] -> List.rev xs , env , hs
| v::vs ->
let t = Lang.tau_of_ltype v.lv_type in
let x = Lang.freshvar ~basename:v.lv_name t in
let h =
if Wp_parameters.SimplifyForall.get ()
then F.p_true
else Cvalues.has_ltype v.lv_type (Lang.F.e_var x)
in
let e = C.env_let env v (Vexp (Lang.F.e_var x)) in
acc (x::xs) e (h::hs) vs in
acc [] env [] qs
(* -------------------------------------------------------------------------- *)
(* --- Term Nodes --- *)
(* -------------------------------------------------------------------------- *)
let rec term_node (env:env) t =
match t.term_node with
| TConst c -> Vexp (Cvalues.logic_constant c)
| TSizeOf _ | TSizeOfE _ | TSizeOfStr _ | TAlignOf _ | TAlignOfE _ ->
Vexp (Cvalues.constant_term t)
| TLval lval -> term_lval env lval
| TAddrOf lval | TStartOf lval -> addr_lval env lval
| TUnOp(Neg,t) when not (Logic_typing.is_integral_type t.term_type) ->
L.map F.e_opp (C.logic env t)
| TUnOp(unop,t) -> term_unop unop (C.logic env t)
| TBinOp(binop,a,b) -> term_binop env binop a b
| TCastE(ty,t) -> term_cast env ty t
| Tapp(f,ls,ts) ->
begin
match LogicBuiltins.logic f with
| ACSLDEF ->
let es = List.map (val_of_term env) ts in
Vexp( C.call_fun env f ls es )
| LFUN phi ->
let vs = List.map (val_of_term env) ts in
Vexp( Lang.F.e_fun phi vs )
end
| Tlambda _ ->
Warning.error "Lambda-functions not yet implemented"
| TDataCons({ctor_name="\\true"},_) -> Vexp(Lang.F.e_true)
| TDataCons({ctor_name="\\false"},_) -> Vexp(Lang.F.e_false)
| TDataCons(c,ts) ->
let es = List.map (val_of_term env) ts in
begin
match LogicBuiltins.ctor c with
| ACSLDEF -> Vexp( Lang.F.e_fun (CTOR c) es )
| LFUN phi -> Vexp( Lang.F.e_fun phi es )
end
| Tif( cond , a , b ) ->
let c = val_of_term env cond in
let a = val_of_term env a in
let b = val_of_term env b in
Vexp (Lang.F.e_if c a b)
| Tat( t , label ) ->
let clabel = Clabels.c_label label in
C.logic (C.env_at env clabel) t
| Tbase_addr (label,t) ->
ignore label ;
L.map_loc M.base_addr (C.logic env t)
| Toffset (label, _t) ->
ignore label ;
Warning.error "Offset construct not implemented yet"
| Tblock_length (label,t) ->
let obj = object_of (Logic_typing.ctype_of_pointed t.term_type) in
let sigma = C.mem_at env (c_label label) in
L.map_l2t (M.block_length sigma obj) (C.logic env t)
| Tnull ->
Vloc M.null
| TCoerce (_,_)
| TCoerceE (_,_) ->
Wp_parameters.fatal "Jessie constructs"
| TUpdate(a,offset,b) ->
Vexp (update_offset env (val_of_term env a) offset (val_of_term env b))
| Tempty_set -> Vset []
| Tunion ts ->
L.union t.term_type (List.map (collection_of_term env) ts)
| Tinter ts ->
L.inter t.term_type (List.map (collection_of_term env) ts)
| Tcomprehension(t,qs,cond) ->
begin
let xs,env,domain = bind_quantifiers env qs in
let condition = match cond with
| None -> Lang.F.p_conj domain
| Some p ->
let cc = C.pred `NoPolarity env in
let p = Lang.without_assume cc p in
Lang.F.p_conj (p :: domain)
in match C.logic env t with
| Vexp e -> Vset[Vset.Descr(xs,e,condition)]
| Vloc l -> Lset[Sdescr(xs,l,condition)]
| _ -> Wp_parameters.fatal "comprehension set of sets"
end
| Tlet( { l_var_info=v ; l_body=LBterm a } , b ) ->
let va = C.logic env a in
C.logic (C.env_let env v va) b
| Tlet _ ->
Warning.error "Complex let-binding not implemented yet (%a)"
Printer.pp_term t
| Trange(a,b) ->
let bound env = function
| None -> None
| Some x -> Some (val_of_term env x)
in Vset(Vset.range (bound env a) (bound env b))
| Ttypeof _ | Ttype _ ->
Warning.error "Type tag not implemented yet"
| TLogic_coerce(_,t) -> term_node env t
(* -------------------------------------------------------------------------- *)
(* --- Separated --- *)
(* -------------------------------------------------------------------------- *)
let separated_terms env ts =
L.separated
begin
List.map
(fun t ->
let te = Logic_typing.ctype_of_pointed t.term_type in
let obj = Ctypes.object_of te in
obj , L.sloc (C.logic env t)
) ts
end
(* -------------------------------------------------------------------------- *)
(* --- Relations --- *)
(* -------------------------------------------------------------------------- *)
let relation polarity env rel a b =
match rel with
| Rlt -> compare_term env Lang.F.p_lt M.loc_lt a b
| Rgt -> compare_term env Lang.F.p_lt M.loc_lt b a
| Rle -> compare_term env Lang.F.p_leq M.loc_leq a b
| Rge -> compare_term env Lang.F.p_leq M.loc_leq b a
| Req -> term_equal polarity env a b
| Rneq -> term_diff polarity env a b
(* -------------------------------------------------------------------------- *)
(* --- Predicates --- *)
(* -------------------------------------------------------------------------- *)
let valid env acs label t =
let te = Logic_typing.ctype_of_pointed t.term_type in
let sigma = C.mem_at env (Clabels.c_label label) in
let addrs = C.logic env t in
L.valid sigma acs (Ctypes.object_of te) (L.sloc addrs)
let predicate polarity env p =
match p.content with
| Pfalse -> Lang.F.p_false
| Ptrue -> Lang.F.p_true
| Pseparated ts -> separated_terms env ts
| Prel(rel,a,b) -> relation polarity env rel a b
| Pand(a,b) -> Lang.F.p_and (C.pred polarity env a) (C.pred polarity env b)
| Por(a,b) -> Lang.F.p_or (C.pred polarity env a) (C.pred polarity env b)
| Pxor(a,b) ->
Lang.F.p_not
(Lang.F.p_equiv (C.pred `NoPolarity env a) (C.pred `NoPolarity env b))
| Pimplies(a,b) ->
let negated = Cvalues.negate polarity in
Lang.F.p_imply (C.pred negated env a) (C.pred polarity env b)
| Piff(a,b) ->
Lang.F.p_equiv (C.pred `NoPolarity env a) (C.pred `NoPolarity env b)
| Pnot a -> Lang.F.p_not (C.pred (Cvalues.negate polarity) env a)
| Pif(t,a,b) ->
Lang.F.p_if (Lang.F.p_bool (val_of_term env t))
(C.pred polarity env a)
(C.pred polarity env b)
| Papp({l_var_info = {lv_name = "\\subset"}},_,ts) ->
begin match ts with
| [a;b] -> L.subset
a.term_type (C.logic env a)
b.term_type (C.logic env b)
| _ -> Warning.error "\\subset requires 2 arguments"
end
| Papp(f,ls,ts) ->
begin
match C.logic_info env f with
| Some p ->
if ls <> [] || ts <> [] then
Warning.error "Unexpected parameters for named predicate '%a'"
Logic_info.pretty f ; p
| None ->
match LogicBuiltins.logic f with
| ACSLDEF ->
let es = List.map (val_of_term env) ts in
C.call_pred env f ls es
| LFUN phi ->
if ls <> [] then
Warning.error "Unexpected labels for purely logic '%a'"
Logic_info.pretty f ;
let vs = List.map (val_of_term env) ts in
Lang.F.p_call phi vs
end
| Plet( { l_var_info=v ; l_body=LBterm a } , p ) ->
let va = C.logic env a in
C.pred polarity (C.env_let env v va) p
| Plet( { l_var_info=v ; l_body=LBpred q } , p ) ->
let vq = C.pred `NoPolarity env q in
C.pred polarity (C.env_letp env v vq) p
| Plet _ ->
Warning.error "Complex let-inding not implemented yet (%a)"
Printer.pp_predicate_named p
| Pforall(qs,p) ->
let xs,env,hs = bind_quantifiers env qs in
let p = Lang.without_assume (C.pred polarity env) p in
Lang.F.p_forall xs (Lang.F.p_hyps hs p)
| Pexists(qs,p) ->
let xs,env,hs = bind_quantifiers env qs in
let p = Lang.without_assume (C.pred polarity env) p in
Lang.F.p_exists xs (Lang.F.p_conj (p :: hs))
| Pat(p,label) ->
let clabel = Clabels.c_label label in
C.pred polarity (C.env_at env clabel) p
| Pvalid(label,t) -> valid env RW label t
| Pvalid_read(label,t) -> valid env RD label t
| Pvalid_function _t ->
Warning.error
"\\valid_function not yet implemented@\n\
@[<hov 0>(%a)@]" Printer.pp_predicate_named p
| Pallocable _ | Pfreeable _ | Pfresh _ | Pinitialized _ | Pdangling _->
Warning.error
"Allocation, initialization and danglingness not yet implemented@\n\
@[<hov 0>(%a)@]" Printer.pp_predicate_named p
| Psubtype _ ->
Warning.error "Type tags not implemented yet"
(* -------------------------------------------------------------------------- *)
(* --- Set of locations for a term representing a set of l-values --- *)
(* -------------------------------------------------------------------------- *)
let assignable_lval env lv =
match fst lv with
| TResult _ -> [] (* special case ! *)
| _ -> L.sloc (addr_lval env lv)
let assignable env t =
match t.term_node with
| Tempty_set -> []
| TLval lv -> assignable_lval env lv
| Tunion ts -> List.concat (List.map (C.region env) ts)
| Tinter _ -> Warning.error "Intersection in assigns not implemented yet"
| Tcomprehension(t,qs,cond) ->
begin
let xs,env,domain = bind_quantifiers env qs in
let conditions = match cond with
| None -> domain
| Some p -> C.pred `NoPolarity env p :: domain
in
List.map
(function
| Sloc l -> Sdescr(xs,l,Lang.F.p_conj conditions)
| (Sarray _ | Srange _ | Sdescr _) as sloc ->
let ys,l,extend = L.rdescr sloc in
Sdescr(xs@ys,l,Lang.F.p_conj (extend :: conditions))
) (C.region env t)
end
| Tat(t,label) ->
C.region (C.env_at env (Clabels.c_label label)) t
| Tlet( { l_var_info=v ; l_body=LBterm a } , b ) ->
let va = C.logic env a in
C.region (C.env_let env v va) b
| Tlet _ ->
Warning.error "Complex let-binding not implemented yet (%a)"
Printer.pp_term t
| TLogic_coerce(_,t) -> C.region env t
| TBinOp _ | TUnOp _ | Trange _ | TUpdate _ | Tapp _ | Tif _
| TConst _ | Tnull | TDataCons _ | Tlambda _
| Ttype _ | Ttypeof _ | TCastE _
| TAlignOfE _ | TAlignOf _ | TSizeOfStr _ | TSizeOfE _ | TSizeOf _
| Tblock_length _ | Tbase_addr _ | Toffset _ | TAddrOf _ | TStartOf _
-> Wp_parameters.abort ~current:true
"Non-assignable term (%a)" Printer.pp_term t
| TCoerce (_,_)
| TCoerceE (_,_) ->
Wp_parameters.fatal "Jessie constructs"
(* -------------------------------------------------------------------------- *)
(* --- Protection --- *)
(* -------------------------------------------------------------------------- *)
let term_handler t =
let x = Lang.freshvar ~basename:"w" (Lang.tau_of_ltype t.term_type) in
Cvalues.plain t.term_type (Lang.F.e_var x)
let term_protected env t =
Warning.handle
~handler:term_handler
~severe:false
~effect:"Hide sub-term definition"
(term_node env) t
let pred_protected polarity env p =
match polarity with
| `Positive ->
Warning.handle
~effect:"Target turned to False"
~severe:true ~handler:(fun _ -> Lang.F.p_false)
(predicate `Positive env) p
| `Negative ->
Warning.handle
~effect:"Ignored Hypothesis"
~severe:false ~handler:(fun _ -> Lang.F.p_true)
(predicate `Negative env) p
| `NoPolarity ->
predicate `NoPolarity env p
(* -------------------------------------------------------------------------- *)
(* --- Boot Strapping --- *)
(* -------------------------------------------------------------------------- *)
let term_trigger env t =
let v = term_protected env t in
if List.mem "TRIGGER" t.term_name then
begin
match v with
| Vexp e -> C.trigger (Trigger.of_term e)
| Vloc l -> C.trigger (Trigger.of_term (M.pointer_val l))
| _ -> Wp_parameters.warning ~current:true
"Can not trigger on tset"
end ; v
let pred_trigger positive env np =
let p = pred_protected positive env np in
if List.mem "TRIGGER" np.Cil_types.name then
C.trigger (Trigger.of_pred p) ; p
let pred polarity env p =
Context.with_current_loc p.loc (pred_trigger polarity env) p
let logic env t =
Context.with_current_loc t.term_loc (term_trigger env) t
let region env t =
Context.with_current_loc t.term_loc (assignable env) t
let () = C.bootstrap_pred pred
let () = C.bootstrap_term term
let () = C.bootstrap_logic logic
let () = C.bootstrap_region region
let lemma = C.lemma
(* -------------------------------------------------------------------------- *)
(* --- Regions --- *)
(* -------------------------------------------------------------------------- *)
let assigns_from env froms =
List.map
(fun ({it_content=wr},_deps) ->
object_of_logic_type wr.term_type ,
region env wr)
froms
let assigns env = function
| WritesAny -> None
| Writes froms -> Some (assigns_from env froms)
let valid = L.valid
let included = L.included
let separated = L.separated
let occurs_opt x = function None -> false | Some t -> F.occurs x t
let occurs_sloc x = function
| Sloc l -> M.occurs x l
| Sarray(l,_,_) -> M.occurs x l
| Srange(l,_,a,b) -> M.occurs x l || occurs_opt x a || occurs_opt x b
| Sdescr(xs,l,p) ->
if List.exists (Lang.F.Var.equal x) xs then false
else (M.occurs x l || F.occursp x p)
let occurs x = List.exists (occurs_sloc x)
let vars_opt = function None -> Lang.F.Vars.empty | Some t -> F.vars t
let vars_sloc = function
| Sloc l
| Sarray(l,_,_) ->
M.vars l
| Srange(l,_,a,b) ->
Lang.F.Vars.union (M.vars l) (Lang.F.Vars.union (vars_opt a) (vars_opt b))
| Sdescr(xs,l,p) ->
List.fold_left
(fun xs x -> Lang.F.Vars.remove x xs)
(Lang.F.Vars.union (M.vars l) (F.varsp p)) xs
let vars sloc = List.fold_left
(fun xs s -> Lang.F.Vars.union xs (vars_sloc s)) Lang.F.Vars.empty sloc
end
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/wp/LogicSemantics.ml | ocaml | ************************************************************************
************************************************************************
************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
--------------------------------------------------------------------------
--- ACSL Translation ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Frames ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Debugging ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Accessing an Offset (sub field-index in a compound) ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Updating an Offset (sub field-index in a compound) ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Shifting Location of an Offset (pointer shift) ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Logic Variable ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Term L-Values (this means 'loading' the l-value) ---
--------------------------------------------------------------------------
int !
--------------------------------------------------------------------------
--- Address of L-Values ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
Only integral
--------------------------------------------------------------------------
--- Equality ---
--------------------------------------------------------------------------
TODO: should be parametric in the equality of elements
incomparrable terms
--------------------------------------------------------------------------
--- Term Comparison ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Binary Operators ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Term Cast ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Environment Binding ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Term Nodes ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Separated ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Relations ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Predicates ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Set of locations for a term representing a set of l-values ---
--------------------------------------------------------------------------
special case !
--------------------------------------------------------------------------
--- Protection ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Boot Strapping ---
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--- Regions ---
-------------------------------------------------------------------------- | This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Cil_types
open Cil_datatype
open LogicBuiltins
open Clabels
open Ctypes
open Lang
open Definitions
open Memory
type polarity = [ `Positive | `Negative | `NoPolarity ]
module Make(M : Memory.Model) =
struct
open M
type loc = M.loc
type value = loc Memory.value
type logic = loc Memory.logic
type region = loc sloc list
type sigma = Sigma.t
module L = Cvalues.Logic(M)
module C = LogicCompiler.Make(M)
type call = C.call
type frame = C.frame
let pp_frame = C.pp_frame
let get_frame = C.get_frame
let in_frame = C.in_frame
let mem_frame = C.mem_frame
let mem_at_frame = C.mem_at_frame
let mem_at = C.mem_at
let frame = C.frame
let call = C.call
let call_pre = C.call_pre
let call_post = C.call_post
let return = C.return
let result = C.result
let status = C.status
let guards = C.guards
let pp_logic fmt = function
| Vexp e -> F.pp_term fmt e
| Vloc l -> M.pretty fmt l
| Lset _ | Vset _ -> Format.pp_print_string fmt "<set>"
let pp_bound fmt = function None -> () | Some p -> F.pp_term fmt p
let pp_sloc fmt = function
| Sloc l -> M.pretty fmt l
| Sarray(l,_,n) -> Format.fprintf fmt "@[<hov2>%a@,.(..%d)@]"
M.pretty l (n-1)
| Srange(l,_,a,b) -> Format.fprintf fmt "@[<hov2>%a@,.(%a@,..%a)@]"
M.pretty l pp_bound a pp_bound b
| Sdescr(xs,l,p) -> Format.fprintf fmt "@[<hov2>{ %a | %a }@]"
M.pretty l F.pp_pred (F.p_forall xs p)
let pp_region fmt sloc =
List.iter (fun s -> Format.fprintf fmt "@ %a" pp_sloc s) sloc
--- Translation Environment & Recursion ---
type env = C.env
let new_env = C.new_env
let move = C.move
let sigma = C.sigma
let call_env s = C.move (C.new_env []) s
let logic_of_value = function
| Val e -> Vexp e
| Loc l -> Vloc l
let loc_of_term env t =
match C.logic env t with
| Vexp e -> M.pointer_loc e
| Vloc l -> l
| _ ->
Warning.error "Non-expected set of locations (%a)" Printer.pp_term t
let val_of_term env t =
match C.logic env t with
| Vexp e -> e
| Vloc l -> M.pointer_val l
| Vset s -> Vset.concretize s
| Lset _ ->
Warning.error "Non-expected set of values (%a)" Printer.pp_term t
let set_of_term env t = L.vset (C.logic env t)
let collection_of_term env t =
let v = C.logic env t in
match v with
| Vexp s when Logic_typing.is_set_type t.term_type ->
let te = Logic_typing.type_of_set_elem t.term_type in
Vset [Vset.Set(tau_of_ltype te,s)]
| w -> w
let term env t =
match C.logic env t with
| Vexp e -> e
| Vloc l -> M.pointer_val l
| s -> Vset.concretize (L.vset s)
let rec access_offset env (v:logic) = function
| TNoOffset -> v
| TModel _ -> Wp_parameters.not_yet_implemented "Model field"
| TField(f,offset) ->
let v_f = L.map (fun r -> Lang.F.e_getfield r (Cfield f)) v in
access_offset env v_f offset
| TIndex(k,offset) ->
let rk = C.logic env k in
let v_k = L.apply Lang.F.e_get v rk in
access_offset env v_k offset
let rec update_offset env (r:Lang.F.term) offset (v:Lang.F.term) =
match offset with
| TNoOffset -> v
| TModel _ -> Wp_parameters.not_yet_implemented "Model field"
| TField(f,offset) ->
let r_f = Lang.F.e_getfield r (Cfield f) in
let r_fv = update_offset env r_f offset v in
Lang.F.e_setfield r (Cfield f) r_fv
| TIndex(k,offset) ->
let k = val_of_term env k in
let r_kv = update_offset env (Lang.F.e_get r k) offset v in
Lang.F.e_set r k r_kv
typ is logic - type of ( load v )
let rec logic_offset env typ (v:logic) = function
| TNoOffset -> typ , v
| TModel _ -> Wp_parameters.not_yet_implemented "Model field"
| TField(f,offset) ->
logic_offset env f.ftype (L.field v f) offset
| TIndex(k,offset) ->
let te = Cil.typeOf_array_elem typ in
let size = Ctypes.get_array_size (Ctypes.object_of typ) in
let obj = Ctypes.object_of te in
let vloc = L.shift v obj ?size (C.logic env k) in
logic_offset env te vloc offset
type lv_value =
| VAL of logic
| VAR of varinfo
let logic_var env lv =
match lv.lv_origin with
| None -> VAL (C.logic_var env lv)
| Some x ->
if x.vformal then match C.formal x with
| Some v -> VAL (logic_of_value v)
| None -> VAR x
else VAR x
let load_loc env typ loc loffset =
let te,lp = logic_offset env typ (Vloc loc) loffset in
L.load (C.sigma env) (Ctypes.object_of te) lp
let term_lval env (lhost,loffset) =
match lhost with
| TResult _ ->
let r = C.result () in
access_offset env (Vexp (Lang.F.e_var r)) loffset
| TMem e ->
let te = Logic_typing.ctype_of_pointed e.term_type in
let te , lp = logic_offset env te (C.logic env e) loffset in
L.load (C.sigma env) (Ctypes.object_of te) lp
| TVar{lv_name="\\exit_status"} ->
Vexp (Lang.F.e_var (C.status ()))
| TVar lv ->
begin
match logic_var env lv with
| VAL v -> access_offset env v loffset
| VAR x -> load_loc env x.vtype (M.cvar x) loffset
end
let addr_lval env (lhost,loffset) =
match lhost with
| TResult _ -> Wp_parameters.abort ~current:true "Address of \\result"
| TMem e ->
let te = Logic_typing.ctype_of_pointed e.term_type in
snd (logic_offset env te (C.logic env e) loffset)
| TVar lv ->
begin
match logic_var env lv with
| VAL v ->
Wp_parameters.abort ~current:true
"Address of logic value (%a)@." pp_logic v
| VAR x ->
snd (logic_offset env x.vtype (Vloc (M.cvar x)) loffset)
end
--- Unary Operators ---
let term_unop = function
| Neg -> L.map_opp
| BNot -> L.map Cint.l_not
| LNot -> L.map Lang.F.e_not
type eqsort =
| EQ_set
| EQ_loc
| EQ_plain
| EQ_array of Matrix.matrix
| EQ_comp of compinfo
| EQ_incomparable
let eqsort_of_type t =
match Logic_utils.unroll_type t with
| Ltype({lt_name="set"},[_]) -> EQ_set
| Linteger | Lreal | Lvar _ | Larrow _ | Ltype _ -> EQ_plain
| Ctype t ->
match Ctypes.object_of t with
| C_pointer _ -> EQ_loc
| C_int _ | C_float _ -> EQ_plain
| C_comp c -> EQ_comp c
| C_array a -> EQ_array (Matrix.of_array a)
let eqsort_of_comparison a b =
match eqsort_of_type a.term_type , eqsort_of_type b.term_type with
| EQ_set , _ | _ , EQ_set -> EQ_set
| EQ_loc , EQ_loc -> EQ_loc
| EQ_comp c1 , EQ_comp c2 ->
if Compinfo.equal c1 c2 then EQ_comp c1 else EQ_incomparable
| EQ_array (t1,d1) , EQ_array (t2,d2) ->
if Ctypes.equal t1 t2 then
match Matrix.merge d1 d2 with
| Some d -> EQ_array(t1,d)
| None -> EQ_incomparable
else EQ_incomparable
| EQ_plain , EQ_plain -> EQ_plain
| _ -> EQ_incomparable
let use_equal = function
| `Negative -> Wp_parameters.ExtEqual.get ()
| `Positive | `NoPolarity -> false
let term_equal polarity env a b =
match eqsort_of_comparison a b with
| EQ_set ->
let sa = set_of_term env a in
let sb = set_of_term env b in
Vset.equal sa sb
| EQ_loc ->
let la = loc_of_term env a in
let lb = loc_of_term env b in
M.loc_eq la lb
| EQ_comp c ->
let va = val_of_term env a in
let vb = val_of_term env b in
if use_equal polarity
then Lang.F.p_equal va vb
else Cvalues.equal_comp c va vb
| EQ_array m ->
let va = val_of_term env a in
let vb = val_of_term env b in
if use_equal polarity
then Lang.F.p_equal va vb
else Cvalues.equal_array m va vb
| EQ_plain ->
Lang.F.p_equal (val_of_term env a) (val_of_term env b)
| EQ_incomparable ->
Wp_parameters.warning ~current:true
"@[Incomparable terms (comparison is False):@ type %a with@ type %a@]"
Printer.pp_logic_type a.term_type
Printer.pp_logic_type b.term_type ;
Lang.F.p_false
let term_diff polarity env a b =
Lang.F.p_not (term_equal (Cvalues.negate polarity) env a b)
let compare_term env vrel lrel a b =
if Logic_typing.is_pointer_type a.term_type then
lrel (loc_of_term env a) (loc_of_term env b)
else
vrel (val_of_term env a) (val_of_term env b)
let exp_equal env a b =
Vexp(Lang.F.e_prop (term_equal `NoPolarity env a b))
let exp_diff env a b =
Vexp(Lang.F.e_prop (term_diff `NoPolarity env a b))
let exp_compare env vrel lrel a b =
Vexp(Lang.F.e_prop (compare_term env vrel lrel a b))
let toreal t v =
if t then L.map Cfloat.real_of_int v else v
let arith env fint freal a b =
let va = C.logic env a in
let vb = C.logic env b in
let ta = Logic_typing.is_integral_type a.term_type in
let tb = Logic_typing.is_integral_type b.term_type in
if ta && tb
then fint va vb
else freal (toreal ta va) (toreal tb vb)
let rec fold_assoc bop acc ts =
match ts with
| [] -> acc
| t::others ->
match t.term_node with
| TBinOp(binop,a,b) when bop == binop ->
fold_assoc bop acc (a::b::others)
| _ -> fold_assoc bop (t::acc) others
let term_binop env binop a b =
match binop with
| PlusA -> arith env L.apply_add (L.apply F.e_add) a b
| MinusA -> arith env L.apply_sub (L.apply F.e_sub) a b
| Mult -> arith env (L.apply Lang.F.e_mul) (L.apply F.e_mul) a b
| Div -> arith env (L.apply Lang.F.e_div) (L.apply F.e_div) a b
| Mod -> L.apply Lang.F.e_mod (C.logic env a) (C.logic env b)
| PlusPI | IndexPI ->
let va = C.logic env a in
let vb = C.logic env b in
let te = Logic_typing.ctype_of_pointed a.term_type in
L.shift va (Ctypes.object_of te) vb
| MinusPI ->
let va = C.logic env a in
let vb = C.logic env b in
let te = Logic_typing.ctype_of_pointed a.term_type in
L.shift va (Ctypes.object_of te) (L.map_opp vb)
| MinusPP ->
let te = Logic_typing.ctype_of_pointed a.term_type in
let la = loc_of_term env a in
let lb = loc_of_term env b in
Vexp(M.loc_diff (Ctypes.object_of te) la lb)
| Shiftlt -> L.apply Cint.l_lsl (C.logic env a) (C.logic env b)
| Shiftrt -> L.apply Cint.l_lsr (C.logic env a) (C.logic env b)
| BAnd -> L.apply Cint.l_and (C.logic env a) (C.logic env b)
| BXor -> L.apply Cint.l_xor (C.logic env a) (C.logic env b)
| BOr -> L.apply Cint.l_or (C.logic env a) (C.logic env b)
| LAnd ->
Vexp(Lang.F.e_and (List.map (val_of_term env) (fold_assoc LAnd [] [a;b])))
| LOr ->
Vexp(Lang.F.e_or (List.map (val_of_term env) (fold_assoc LOr [] [a;b])))
| Lt -> exp_compare env Lang.F.p_lt M.loc_lt a b
| Gt -> exp_compare env Lang.F.p_lt M.loc_lt b a
| Le -> exp_compare env Lang.F.p_leq M.loc_leq a b
| Ge -> exp_compare env Lang.F.p_leq M.loc_leq b a
| Eq -> exp_equal env a b
| Ne -> exp_diff env a b
type cvsort =
| L_bool
| L_real
| L_integer
| L_cint of c_int
| L_cfloat of c_float
| L_pointer of typ
let rec cvsort_of_type t =
match Logic_utils.unroll_type t with
| Ltype({lt_name="set"},[t]) -> cvsort_of_type t
| Ltype _ as b when Logic_const.is_boolean_type b -> L_bool
| Linteger -> L_integer
| Lreal -> L_real
| Ctype c ->
begin
match Ctypes.object_of c with
| C_int i -> L_cint i
| C_float f -> L_cfloat f
| C_pointer te -> L_pointer te
| C_array a -> L_pointer a.arr_element
| obj -> Warning.error "cast from (%a) not implemented yet"
Ctypes.pretty obj
end
| _ -> Warning.error "cast from (%a) not implemented yet"
Printer.pp_logic_type t
let term_cast env typ t =
match Ctypes.object_of typ , cvsort_of_type t.term_type with
| C_int i , L_cint i0 ->
let v = C.logic env t in
if (Ctypes.sub_c_int i0 i) then v
else L.map (Cint.convert i) v
| C_int i , L_integer ->
L.map (Cint.convert i) (C.logic env t)
| C_int i , L_pointer _ ->
L.map_l2t (M.int_of_loc i) (C.logic env t)
| C_int i , (L_cfloat _ | L_real) ->
L.map (Cint.of_real i) (C.logic env t)
| C_float f , (L_cfloat _ | L_real) ->
L.map (Cfloat.convert f) (C.logic env t)
| C_float f , (L_cint _ | L_integer) ->
L.map (Cfloat.float_of_int f) (C.logic env t)
| C_pointer ty , L_pointer t0 ->
let value = C.logic env t in
let o_src = Ctypes.object_of t0 in
let o_dst = Ctypes.object_of ty in
if Ctypes.compare o_src o_dst = 0
then value
else L.map_loc (M.cast { pre=o_src ; post=o_dst }) value
| C_pointer ty , (L_integer | L_cint _) ->
let obj = Ctypes.object_of ty in
L.map_t2l (M.loc_of_int obj) (C.logic env t)
| C_int _ , L_bool ->
L.map Cvalues.bool_val (C.logic env t)
| _ ->
Warning.error "Cast from (%a) to (%a) not implemented yet"
Printer.pp_logic_type t.term_type Printer.pp_typ typ
let bind_quantifiers (env:env) qs =
let rec acc xs env hs = function
| [] -> List.rev xs , env , hs
| v::vs ->
let t = Lang.tau_of_ltype v.lv_type in
let x = Lang.freshvar ~basename:v.lv_name t in
let h =
if Wp_parameters.SimplifyForall.get ()
then F.p_true
else Cvalues.has_ltype v.lv_type (Lang.F.e_var x)
in
let e = C.env_let env v (Vexp (Lang.F.e_var x)) in
acc (x::xs) e (h::hs) vs in
acc [] env [] qs
let rec term_node (env:env) t =
match t.term_node with
| TConst c -> Vexp (Cvalues.logic_constant c)
| TSizeOf _ | TSizeOfE _ | TSizeOfStr _ | TAlignOf _ | TAlignOfE _ ->
Vexp (Cvalues.constant_term t)
| TLval lval -> term_lval env lval
| TAddrOf lval | TStartOf lval -> addr_lval env lval
| TUnOp(Neg,t) when not (Logic_typing.is_integral_type t.term_type) ->
L.map F.e_opp (C.logic env t)
| TUnOp(unop,t) -> term_unop unop (C.logic env t)
| TBinOp(binop,a,b) -> term_binop env binop a b
| TCastE(ty,t) -> term_cast env ty t
| Tapp(f,ls,ts) ->
begin
match LogicBuiltins.logic f with
| ACSLDEF ->
let es = List.map (val_of_term env) ts in
Vexp( C.call_fun env f ls es )
| LFUN phi ->
let vs = List.map (val_of_term env) ts in
Vexp( Lang.F.e_fun phi vs )
end
| Tlambda _ ->
Warning.error "Lambda-functions not yet implemented"
| TDataCons({ctor_name="\\true"},_) -> Vexp(Lang.F.e_true)
| TDataCons({ctor_name="\\false"},_) -> Vexp(Lang.F.e_false)
| TDataCons(c,ts) ->
let es = List.map (val_of_term env) ts in
begin
match LogicBuiltins.ctor c with
| ACSLDEF -> Vexp( Lang.F.e_fun (CTOR c) es )
| LFUN phi -> Vexp( Lang.F.e_fun phi es )
end
| Tif( cond , a , b ) ->
let c = val_of_term env cond in
let a = val_of_term env a in
let b = val_of_term env b in
Vexp (Lang.F.e_if c a b)
| Tat( t , label ) ->
let clabel = Clabels.c_label label in
C.logic (C.env_at env clabel) t
| Tbase_addr (label,t) ->
ignore label ;
L.map_loc M.base_addr (C.logic env t)
| Toffset (label, _t) ->
ignore label ;
Warning.error "Offset construct not implemented yet"
| Tblock_length (label,t) ->
let obj = object_of (Logic_typing.ctype_of_pointed t.term_type) in
let sigma = C.mem_at env (c_label label) in
L.map_l2t (M.block_length sigma obj) (C.logic env t)
| Tnull ->
Vloc M.null
| TCoerce (_,_)
| TCoerceE (_,_) ->
Wp_parameters.fatal "Jessie constructs"
| TUpdate(a,offset,b) ->
Vexp (update_offset env (val_of_term env a) offset (val_of_term env b))
| Tempty_set -> Vset []
| Tunion ts ->
L.union t.term_type (List.map (collection_of_term env) ts)
| Tinter ts ->
L.inter t.term_type (List.map (collection_of_term env) ts)
| Tcomprehension(t,qs,cond) ->
begin
let xs,env,domain = bind_quantifiers env qs in
let condition = match cond with
| None -> Lang.F.p_conj domain
| Some p ->
let cc = C.pred `NoPolarity env in
let p = Lang.without_assume cc p in
Lang.F.p_conj (p :: domain)
in match C.logic env t with
| Vexp e -> Vset[Vset.Descr(xs,e,condition)]
| Vloc l -> Lset[Sdescr(xs,l,condition)]
| _ -> Wp_parameters.fatal "comprehension set of sets"
end
| Tlet( { l_var_info=v ; l_body=LBterm a } , b ) ->
let va = C.logic env a in
C.logic (C.env_let env v va) b
| Tlet _ ->
Warning.error "Complex let-binding not implemented yet (%a)"
Printer.pp_term t
| Trange(a,b) ->
let bound env = function
| None -> None
| Some x -> Some (val_of_term env x)
in Vset(Vset.range (bound env a) (bound env b))
| Ttypeof _ | Ttype _ ->
Warning.error "Type tag not implemented yet"
| TLogic_coerce(_,t) -> term_node env t
let separated_terms env ts =
L.separated
begin
List.map
(fun t ->
let te = Logic_typing.ctype_of_pointed t.term_type in
let obj = Ctypes.object_of te in
obj , L.sloc (C.logic env t)
) ts
end
let relation polarity env rel a b =
match rel with
| Rlt -> compare_term env Lang.F.p_lt M.loc_lt a b
| Rgt -> compare_term env Lang.F.p_lt M.loc_lt b a
| Rle -> compare_term env Lang.F.p_leq M.loc_leq a b
| Rge -> compare_term env Lang.F.p_leq M.loc_leq b a
| Req -> term_equal polarity env a b
| Rneq -> term_diff polarity env a b
let valid env acs label t =
let te = Logic_typing.ctype_of_pointed t.term_type in
let sigma = C.mem_at env (Clabels.c_label label) in
let addrs = C.logic env t in
L.valid sigma acs (Ctypes.object_of te) (L.sloc addrs)
let predicate polarity env p =
match p.content with
| Pfalse -> Lang.F.p_false
| Ptrue -> Lang.F.p_true
| Pseparated ts -> separated_terms env ts
| Prel(rel,a,b) -> relation polarity env rel a b
| Pand(a,b) -> Lang.F.p_and (C.pred polarity env a) (C.pred polarity env b)
| Por(a,b) -> Lang.F.p_or (C.pred polarity env a) (C.pred polarity env b)
| Pxor(a,b) ->
Lang.F.p_not
(Lang.F.p_equiv (C.pred `NoPolarity env a) (C.pred `NoPolarity env b))
| Pimplies(a,b) ->
let negated = Cvalues.negate polarity in
Lang.F.p_imply (C.pred negated env a) (C.pred polarity env b)
| Piff(a,b) ->
Lang.F.p_equiv (C.pred `NoPolarity env a) (C.pred `NoPolarity env b)
| Pnot a -> Lang.F.p_not (C.pred (Cvalues.negate polarity) env a)
| Pif(t,a,b) ->
Lang.F.p_if (Lang.F.p_bool (val_of_term env t))
(C.pred polarity env a)
(C.pred polarity env b)
| Papp({l_var_info = {lv_name = "\\subset"}},_,ts) ->
begin match ts with
| [a;b] -> L.subset
a.term_type (C.logic env a)
b.term_type (C.logic env b)
| _ -> Warning.error "\\subset requires 2 arguments"
end
| Papp(f,ls,ts) ->
begin
match C.logic_info env f with
| Some p ->
if ls <> [] || ts <> [] then
Warning.error "Unexpected parameters for named predicate '%a'"
Logic_info.pretty f ; p
| None ->
match LogicBuiltins.logic f with
| ACSLDEF ->
let es = List.map (val_of_term env) ts in
C.call_pred env f ls es
| LFUN phi ->
if ls <> [] then
Warning.error "Unexpected labels for purely logic '%a'"
Logic_info.pretty f ;
let vs = List.map (val_of_term env) ts in
Lang.F.p_call phi vs
end
| Plet( { l_var_info=v ; l_body=LBterm a } , p ) ->
let va = C.logic env a in
C.pred polarity (C.env_let env v va) p
| Plet( { l_var_info=v ; l_body=LBpred q } , p ) ->
let vq = C.pred `NoPolarity env q in
C.pred polarity (C.env_letp env v vq) p
| Plet _ ->
Warning.error "Complex let-inding not implemented yet (%a)"
Printer.pp_predicate_named p
| Pforall(qs,p) ->
let xs,env,hs = bind_quantifiers env qs in
let p = Lang.without_assume (C.pred polarity env) p in
Lang.F.p_forall xs (Lang.F.p_hyps hs p)
| Pexists(qs,p) ->
let xs,env,hs = bind_quantifiers env qs in
let p = Lang.without_assume (C.pred polarity env) p in
Lang.F.p_exists xs (Lang.F.p_conj (p :: hs))
| Pat(p,label) ->
let clabel = Clabels.c_label label in
C.pred polarity (C.env_at env clabel) p
| Pvalid(label,t) -> valid env RW label t
| Pvalid_read(label,t) -> valid env RD label t
| Pvalid_function _t ->
Warning.error
"\\valid_function not yet implemented@\n\
@[<hov 0>(%a)@]" Printer.pp_predicate_named p
| Pallocable _ | Pfreeable _ | Pfresh _ | Pinitialized _ | Pdangling _->
Warning.error
"Allocation, initialization and danglingness not yet implemented@\n\
@[<hov 0>(%a)@]" Printer.pp_predicate_named p
| Psubtype _ ->
Warning.error "Type tags not implemented yet"
let assignable_lval env lv =
match fst lv with
| _ -> L.sloc (addr_lval env lv)
let assignable env t =
match t.term_node with
| Tempty_set -> []
| TLval lv -> assignable_lval env lv
| Tunion ts -> List.concat (List.map (C.region env) ts)
| Tinter _ -> Warning.error "Intersection in assigns not implemented yet"
| Tcomprehension(t,qs,cond) ->
begin
let xs,env,domain = bind_quantifiers env qs in
let conditions = match cond with
| None -> domain
| Some p -> C.pred `NoPolarity env p :: domain
in
List.map
(function
| Sloc l -> Sdescr(xs,l,Lang.F.p_conj conditions)
| (Sarray _ | Srange _ | Sdescr _) as sloc ->
let ys,l,extend = L.rdescr sloc in
Sdescr(xs@ys,l,Lang.F.p_conj (extend :: conditions))
) (C.region env t)
end
| Tat(t,label) ->
C.region (C.env_at env (Clabels.c_label label)) t
| Tlet( { l_var_info=v ; l_body=LBterm a } , b ) ->
let va = C.logic env a in
C.region (C.env_let env v va) b
| Tlet _ ->
Warning.error "Complex let-binding not implemented yet (%a)"
Printer.pp_term t
| TLogic_coerce(_,t) -> C.region env t
| TBinOp _ | TUnOp _ | Trange _ | TUpdate _ | Tapp _ | Tif _
| TConst _ | Tnull | TDataCons _ | Tlambda _
| Ttype _ | Ttypeof _ | TCastE _
| TAlignOfE _ | TAlignOf _ | TSizeOfStr _ | TSizeOfE _ | TSizeOf _
| Tblock_length _ | Tbase_addr _ | Toffset _ | TAddrOf _ | TStartOf _
-> Wp_parameters.abort ~current:true
"Non-assignable term (%a)" Printer.pp_term t
| TCoerce (_,_)
| TCoerceE (_,_) ->
Wp_parameters.fatal "Jessie constructs"
let term_handler t =
let x = Lang.freshvar ~basename:"w" (Lang.tau_of_ltype t.term_type) in
Cvalues.plain t.term_type (Lang.F.e_var x)
let term_protected env t =
Warning.handle
~handler:term_handler
~severe:false
~effect:"Hide sub-term definition"
(term_node env) t
let pred_protected polarity env p =
match polarity with
| `Positive ->
Warning.handle
~effect:"Target turned to False"
~severe:true ~handler:(fun _ -> Lang.F.p_false)
(predicate `Positive env) p
| `Negative ->
Warning.handle
~effect:"Ignored Hypothesis"
~severe:false ~handler:(fun _ -> Lang.F.p_true)
(predicate `Negative env) p
| `NoPolarity ->
predicate `NoPolarity env p
let term_trigger env t =
let v = term_protected env t in
if List.mem "TRIGGER" t.term_name then
begin
match v with
| Vexp e -> C.trigger (Trigger.of_term e)
| Vloc l -> C.trigger (Trigger.of_term (M.pointer_val l))
| _ -> Wp_parameters.warning ~current:true
"Can not trigger on tset"
end ; v
let pred_trigger positive env np =
let p = pred_protected positive env np in
if List.mem "TRIGGER" np.Cil_types.name then
C.trigger (Trigger.of_pred p) ; p
let pred polarity env p =
Context.with_current_loc p.loc (pred_trigger polarity env) p
let logic env t =
Context.with_current_loc t.term_loc (term_trigger env) t
let region env t =
Context.with_current_loc t.term_loc (assignable env) t
let () = C.bootstrap_pred pred
let () = C.bootstrap_term term
let () = C.bootstrap_logic logic
let () = C.bootstrap_region region
let lemma = C.lemma
let assigns_from env froms =
List.map
(fun ({it_content=wr},_deps) ->
object_of_logic_type wr.term_type ,
region env wr)
froms
let assigns env = function
| WritesAny -> None
| Writes froms -> Some (assigns_from env froms)
let valid = L.valid
let included = L.included
let separated = L.separated
let occurs_opt x = function None -> false | Some t -> F.occurs x t
let occurs_sloc x = function
| Sloc l -> M.occurs x l
| Sarray(l,_,_) -> M.occurs x l
| Srange(l,_,a,b) -> M.occurs x l || occurs_opt x a || occurs_opt x b
| Sdescr(xs,l,p) ->
if List.exists (Lang.F.Var.equal x) xs then false
else (M.occurs x l || F.occursp x p)
let occurs x = List.exists (occurs_sloc x)
let vars_opt = function None -> Lang.F.Vars.empty | Some t -> F.vars t
let vars_sloc = function
| Sloc l
| Sarray(l,_,_) ->
M.vars l
| Srange(l,_,a,b) ->
Lang.F.Vars.union (M.vars l) (Lang.F.Vars.union (vars_opt a) (vars_opt b))
| Sdescr(xs,l,p) ->
List.fold_left
(fun xs x -> Lang.F.Vars.remove x xs)
(Lang.F.Vars.union (M.vars l) (F.varsp p)) xs
let vars sloc = List.fold_left
(fun xs s -> Lang.F.Vars.union xs (vars_sloc s)) Lang.F.Vars.empty sloc
end
|
c70ec9f2dd64f3f787af788c5e5caf43efed5284ac7a0839a3806fd816f50b6a | racket/draw | hold.rkt | #lang racket/base
(provide with-holding)
(define-syntax-rule (with-holding v expr)
(let ([val v])
(begin0
expr
(done-with val))))
;; Ensure no inline:
(define done-with #f)
(set! done-with void)
| null | https://raw.githubusercontent.com/racket/draw/a6558bdc18438e784c23d452ffd877dac867a7fd/draw-lib/racket/draw/private/hold.rkt | racket | Ensure no inline: | #lang racket/base
(provide with-holding)
(define-syntax-rule (with-holding v expr)
(let ([val v])
(begin0
expr
(done-with val))))
(define done-with #f)
(set! done-with void)
|
da6867bfb259fb8dd82129c20567532d9e1020f473fd759ba5f8b6a53b18fd58 | GNOME/gimp-tiny-fu | beveled-pattern-bullet.scm | ; GIMP - The GNU Image Manipulation Program
Copyright ( C ) 1995 and
;
; Beveled pattern bullet for web pages
Copyright ( C ) 1997
;
;
; 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 </>.
(define (script-fu-beveled-pattern-bullet diameter pattern transparent)
(let* (
(img (car (gimp-image-new diameter diameter RGB)))
(background (car (gimp-layer-new img diameter diameter RGBA-IMAGE _"Bullet" 100 NORMAL-MODE)))
(bumpmap (car (gimp-layer-new img diameter diameter RGBA-IMAGE _"Bumpmap" 100 NORMAL-MODE)))
)
(gimp-context-push)
(gimp-context-set-defaults)
(gimp-image-undo-disable img)
(gimp-image-insert-layer img background 0 -1)
(gimp-image-insert-layer img bumpmap 0 -1)
; Create pattern layer
(gimp-context-set-background '(0 0 0))
(gimp-edit-fill background BACKGROUND-FILL)
(gimp-context-set-pattern pattern)
(gimp-edit-bucket-fill background PATTERN-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0)
; Create bumpmap layer
(gimp-edit-fill bumpmap BACKGROUND-FILL)
(gimp-context-set-background '(127 127 127))
(gimp-image-select-ellipse img CHANNEL-OP-REPLACE 1 1 (- diameter 2) (- diameter 2))
(gimp-edit-fill bumpmap BACKGROUND-FILL)
(gimp-context-set-background '(255 255 255))
(gimp-image-select-ellipse img CHANNEL-OP-REPLACE 2 2 (- diameter 4) (- diameter 4))
(gimp-edit-fill bumpmap BACKGROUND-FILL)
(gimp-selection-none img)
; Bumpmap
(plug-in-bump-map RUN-NONINTERACTIVE img background bumpmap 135 45 2 0 0 0 0 TRUE FALSE 0)
; Background
(gimp-context-set-background '(0 0 0))
(gimp-image-select-ellipse img CHANNEL-OP-REPLACE 0 0 diameter diameter)
(gimp-selection-invert img)
(gimp-edit-clear background)
(gimp-selection-none img)
(gimp-image-set-active-layer img background)
(gimp-image-remove-layer img bumpmap)
(if (= transparent FALSE)
(gimp-image-flatten img))
(gimp-image-undo-enable img)
(gimp-display-new img)
(gimp-context-pop)
)
)
(script-fu-register "script-fu-beveled-pattern-bullet"
_"_Bullet..."
_"Create a beveled pattern bullet for webpages"
"Federico Mena Quintero"
"Federico Mena Quintero"
"July 1997"
""
SF-ADJUSTMENT _"Diameter" '(16 1 150 1 10 0 1)
SF-PATTERN _"Pattern" "Wood"
SF-TOGGLE _"Transparent background" FALSE
)
(script-fu-menu-register "script-fu-beveled-pattern-bullet"
"<Image>/File/Create/Web Page Themes/Beveled Pattern")
| null | https://raw.githubusercontent.com/GNOME/gimp-tiny-fu/a64d85eec23b997e535488d67f55b44395ba3f2e/scripts/beveled-pattern-bullet.scm | scheme | GIMP - The GNU Image Manipulation Program
Beveled pattern bullet for web pages
This program is free software: you can redistribute it and/or modify
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.
along with this program. If not, see </>.
Create pattern layer
Create bumpmap layer
Bumpmap
Background | Copyright ( C ) 1995 and
Copyright ( C ) 1997
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
(define (script-fu-beveled-pattern-bullet diameter pattern transparent)
(let* (
(img (car (gimp-image-new diameter diameter RGB)))
(background (car (gimp-layer-new img diameter diameter RGBA-IMAGE _"Bullet" 100 NORMAL-MODE)))
(bumpmap (car (gimp-layer-new img diameter diameter RGBA-IMAGE _"Bumpmap" 100 NORMAL-MODE)))
)
(gimp-context-push)
(gimp-context-set-defaults)
(gimp-image-undo-disable img)
(gimp-image-insert-layer img background 0 -1)
(gimp-image-insert-layer img bumpmap 0 -1)
(gimp-context-set-background '(0 0 0))
(gimp-edit-fill background BACKGROUND-FILL)
(gimp-context-set-pattern pattern)
(gimp-edit-bucket-fill background PATTERN-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0)
(gimp-edit-fill bumpmap BACKGROUND-FILL)
(gimp-context-set-background '(127 127 127))
(gimp-image-select-ellipse img CHANNEL-OP-REPLACE 1 1 (- diameter 2) (- diameter 2))
(gimp-edit-fill bumpmap BACKGROUND-FILL)
(gimp-context-set-background '(255 255 255))
(gimp-image-select-ellipse img CHANNEL-OP-REPLACE 2 2 (- diameter 4) (- diameter 4))
(gimp-edit-fill bumpmap BACKGROUND-FILL)
(gimp-selection-none img)
(plug-in-bump-map RUN-NONINTERACTIVE img background bumpmap 135 45 2 0 0 0 0 TRUE FALSE 0)
(gimp-context-set-background '(0 0 0))
(gimp-image-select-ellipse img CHANNEL-OP-REPLACE 0 0 diameter diameter)
(gimp-selection-invert img)
(gimp-edit-clear background)
(gimp-selection-none img)
(gimp-image-set-active-layer img background)
(gimp-image-remove-layer img bumpmap)
(if (= transparent FALSE)
(gimp-image-flatten img))
(gimp-image-undo-enable img)
(gimp-display-new img)
(gimp-context-pop)
)
)
(script-fu-register "script-fu-beveled-pattern-bullet"
_"_Bullet..."
_"Create a beveled pattern bullet for webpages"
"Federico Mena Quintero"
"Federico Mena Quintero"
"July 1997"
""
SF-ADJUSTMENT _"Diameter" '(16 1 150 1 10 0 1)
SF-PATTERN _"Pattern" "Wood"
SF-TOGGLE _"Transparent background" FALSE
)
(script-fu-menu-register "script-fu-beveled-pattern-bullet"
"<Image>/File/Create/Web Page Themes/Beveled Pattern")
|
f65ec7bb854d6748ba8ae0daf74369669e92fb1591710e13788906fe0b975646 | MarcKaufmann/congame | identity.rkt | #lang racket/base
(require congame-web/components/auth
congame-web/components/user
congame/components/export
(only-in congame/components/study
current-study-instance-id
current-study-stack)
db
koyo/url
(prefix-in http: net/http-easy)
racket/contract
racket/format)
(provide
put/identity)
(define-logger identity)
(define/contract (put/identity key value)
(-> symbol? any/c void?)
(define u (current-user))
(cond
[(and (not (sql-null? (user-identity-service-url u)))
(not (sql-null? (user-identity-service-key u))))
(define url
(~a (user-identity-service-url u)
(format "/api/v1/study-instances/~a/data?key=~a"
(current-study-instance-id)
(user-identity-service-key u))))
(define data
(hasheq
'congame-url (->jsexpr (make-application-url))
'key (->jsexpr key)
'stack (->jsexpr (current-study-stack))
'value (->jsexpr value)))
; FIXME: do authorization check based on an api user for congame server. use congame_servers table rather than users.
(define res
(http:put url #:json data))
(log-identity-debug "put/identity~n url: ~a~n data: ~e" url data)
(unless (= (http:response-status-code res) 201)
(error 'put/identity "request failed~n response: ~a" (http:response-body res)))]
[else
; TODO: Is it a feature or a bug that non-identity users trigger this?
(log-identity-warning "failed to put/identity~n current user is not an identity user~n username: ~a~n key: ~a" (user-username u) key)]))
| null | https://raw.githubusercontent.com/MarcKaufmann/congame/ba0d4e4dc4208b4dddbbd602e9093b77bbdb7d1d/congame-web/components/identity.rkt | racket | FIXME: do authorization check based on an api user for congame server. use congame_servers table rather than users.
TODO: Is it a feature or a bug that non-identity users trigger this? | #lang racket/base
(require congame-web/components/auth
congame-web/components/user
congame/components/export
(only-in congame/components/study
current-study-instance-id
current-study-stack)
db
koyo/url
(prefix-in http: net/http-easy)
racket/contract
racket/format)
(provide
put/identity)
(define-logger identity)
(define/contract (put/identity key value)
(-> symbol? any/c void?)
(define u (current-user))
(cond
[(and (not (sql-null? (user-identity-service-url u)))
(not (sql-null? (user-identity-service-key u))))
(define url
(~a (user-identity-service-url u)
(format "/api/v1/study-instances/~a/data?key=~a"
(current-study-instance-id)
(user-identity-service-key u))))
(define data
(hasheq
'congame-url (->jsexpr (make-application-url))
'key (->jsexpr key)
'stack (->jsexpr (current-study-stack))
'value (->jsexpr value)))
(define res
(http:put url #:json data))
(log-identity-debug "put/identity~n url: ~a~n data: ~e" url data)
(unless (= (http:response-status-code res) 201)
(error 'put/identity "request failed~n response: ~a" (http:response-body res)))]
[else
(log-identity-warning "failed to put/identity~n current user is not an identity user~n username: ~a~n key: ~a" (user-username u) key)]))
|
1154057b4c2d18d0439416c3b4996db74eed175528edbede0c9bca9e4578c079 | lep/jassbot | Signature.hs | # LANGUAGE DeriveGeneric #
module Jassbot.Signature
( Native(..)
, Signature(..)
, parameters
, fnname
, returnType
, sloppySignatureParser
, pretty
) where
import GHC.Generics
import Data.Binary
import Data.List (intercalate)
import Data.Functor
import Control.Applicative
import Text.Megaparsec (Parsec)
import Text.Megaparsec ( option, sepBy, try, lookAhead, choice, eof)
import Data.Void
import Jass.Parser as Jass
import qualified Jass.Ast as Jass
data Native = Native | Function
deriving (Show, Generic)
instance Binary Native
type Name = Jass.Name
data Signature = Sig Jass.Constant Native Name [(Jass.Type, Name)] Jass.Type
deriving (Show, Generic)
instance Binary Signature
parameters :: Signature -> [Jass.Type]
parameters (Sig _ _ _ p _) = map fst p
fnname :: Signature -> Name
fnname (Sig _ _ n _ _) = n
returnType :: Signature -> Jass.Type
returnType (Sig _ _ _ _ r) = r
sloppySignatureParser :: Parsec Void String (Maybe String, Maybe [String], Maybe String)
sloppySignatureParser =
justName <|> fullSig <|> nameRet <|> paramRet
where
fullSig = try $ do
--traceM "fullsig"
name <- Just <$> Jass.identifier
Jass.reserved "takes"
args <- (Jass.reserved "nothing" $> ["nothing"]) <|> (Jass.identifier `sepBy` optional (symbol ","))
ret <- option "" $ do
Jass.reserved "returns"
option "" ((Jass.reserved "nothing" $> "nothing") <|> Jass.identifier)
return $ case args of
["nothing"] -> (name, Just [], empty2Maybe ret)
_ -> (name, empty2Maybe args, empty2Maybe ret)
nameRet = try $ do
--traceM "nameRet"
name <- Just <$> Jass.identifier
Jass.reserved "returns"
ret <- option "" ((Jass.reserved "nothing" $> "nothing") <|> Jass.identifier)
return (name, Nothing, empty2Maybe ret)
paramRet = try $ do
--traceM "paramRet"
optional $ Jass.reserved "takes"
args <- (Jass.reserved "nothing" $> ["nothing"]) <|> (Jass.identifier `sepBy` optional (symbol ","))
ret <- option "" $ do
Jass.reserved "returns"
option "" ((Jass.reserved "nothing" $> "nothing") <|> Jass.identifier)
return $ case args of
["nothing"] -> (Nothing, Just [], empty2Maybe ret)
_ -> (Nothing, empty2Maybe args, empty2Maybe ret)
justName = try $ do
--traceM "justname"
name <- Jass.identifier <* eof
return (Just name, Nothing, Nothing)
empty2Maybe x
| x == mempty = Nothing
| otherwise = Just x
pretty s =
unwords [ ppconst s ++ ppfn s
, fnname s, "takes"
, ppargs $ parameters s
, "returns", pptype $ returnType s ]
where
ppargs [] = "nothing"
ppargs _ = intercalate ", " $ map pparg (parameters' s)
pparg (t, n) = unwords [pptype t, n]
pptype = id
ppconst (Sig Jass.Const _ _ _ _) = "constant "
ppconst (Sig Jass.Normal _ _ _ _) = ""
ppfn (Sig _ Native _ _ _) = "native"
ppfn (Sig _ Function _ _ _) = "function"
parameters' (Sig _ _ _ args _) = args
| null | https://raw.githubusercontent.com/lep/jassbot/d02402b2f058bca4c77a9014dff24dccab82eb34/Jassbot/Signature.hs | haskell | traceM "fullsig"
traceM "nameRet"
traceM "paramRet"
traceM "justname" | # LANGUAGE DeriveGeneric #
module Jassbot.Signature
( Native(..)
, Signature(..)
, parameters
, fnname
, returnType
, sloppySignatureParser
, pretty
) where
import GHC.Generics
import Data.Binary
import Data.List (intercalate)
import Data.Functor
import Control.Applicative
import Text.Megaparsec (Parsec)
import Text.Megaparsec ( option, sepBy, try, lookAhead, choice, eof)
import Data.Void
import Jass.Parser as Jass
import qualified Jass.Ast as Jass
data Native = Native | Function
deriving (Show, Generic)
instance Binary Native
type Name = Jass.Name
data Signature = Sig Jass.Constant Native Name [(Jass.Type, Name)] Jass.Type
deriving (Show, Generic)
instance Binary Signature
parameters :: Signature -> [Jass.Type]
parameters (Sig _ _ _ p _) = map fst p
fnname :: Signature -> Name
fnname (Sig _ _ n _ _) = n
returnType :: Signature -> Jass.Type
returnType (Sig _ _ _ _ r) = r
sloppySignatureParser :: Parsec Void String (Maybe String, Maybe [String], Maybe String)
sloppySignatureParser =
justName <|> fullSig <|> nameRet <|> paramRet
where
fullSig = try $ do
name <- Just <$> Jass.identifier
Jass.reserved "takes"
args <- (Jass.reserved "nothing" $> ["nothing"]) <|> (Jass.identifier `sepBy` optional (symbol ","))
ret <- option "" $ do
Jass.reserved "returns"
option "" ((Jass.reserved "nothing" $> "nothing") <|> Jass.identifier)
return $ case args of
["nothing"] -> (name, Just [], empty2Maybe ret)
_ -> (name, empty2Maybe args, empty2Maybe ret)
nameRet = try $ do
name <- Just <$> Jass.identifier
Jass.reserved "returns"
ret <- option "" ((Jass.reserved "nothing" $> "nothing") <|> Jass.identifier)
return (name, Nothing, empty2Maybe ret)
paramRet = try $ do
optional $ Jass.reserved "takes"
args <- (Jass.reserved "nothing" $> ["nothing"]) <|> (Jass.identifier `sepBy` optional (symbol ","))
ret <- option "" $ do
Jass.reserved "returns"
option "" ((Jass.reserved "nothing" $> "nothing") <|> Jass.identifier)
return $ case args of
["nothing"] -> (Nothing, Just [], empty2Maybe ret)
_ -> (Nothing, empty2Maybe args, empty2Maybe ret)
justName = try $ do
name <- Jass.identifier <* eof
return (Just name, Nothing, Nothing)
empty2Maybe x
| x == mempty = Nothing
| otherwise = Just x
pretty s =
unwords [ ppconst s ++ ppfn s
, fnname s, "takes"
, ppargs $ parameters s
, "returns", pptype $ returnType s ]
where
ppargs [] = "nothing"
ppargs _ = intercalate ", " $ map pparg (parameters' s)
pparg (t, n) = unwords [pptype t, n]
pptype = id
ppconst (Sig Jass.Const _ _ _ _) = "constant "
ppconst (Sig Jass.Normal _ _ _ _) = ""
ppfn (Sig _ Native _ _ _) = "native"
ppfn (Sig _ Function _ _ _) = "function"
parameters' (Sig _ _ _ args _) = args
|
c37c3e209bf263c910b770da626615b4a6a3d7bcfd7071edc6c73442ca5b1dcc | gothinkster/clojurescript-keechma-realworld-example-app | register_form.cljs | (ns app.controllers.guest.register-form
(:require [keechma.next.controller :as ctrl]
[keechma.next.controllers.pipelines :as pipelines]
[keechma.pipelines.core :as pp :refer-macros [pipeline!]]
[app.api :as api]
[promesa.core :as p]
[keechma.next.controllers.form :as form]
[app.validators :as v]
[promesa.core :as p]
[keechma.next.controllers.router :as router]))
(derive :guest/register-form ::pipelines/controller)
(def pipelines
{:keechma.form/submit-data
(pipeline!
[value {:keys [meta-state*], :as ctrl}]
(pp/swap! meta-state* dissoc :submit-errors)
(api/register value)
(ctrl/broadcast ctrl :guest/login value)
(router/redirect! ctrl :router {:page "home", :subpage "personal"})
(rescue! [error] (pp/swap! meta-state* assoc :submit-errors error)))})
(defmethod ctrl/prep :guest/register-form
[ctrl]
(pipelines/register
ctrl
(form/wrap pipelines
(v/to-validator {:username [:not-empty],
:email [:email :not-empty],
:password [:not-empty :ok-password]}))))
| null | https://raw.githubusercontent.com/gothinkster/clojurescript-keechma-realworld-example-app/f6d32f8eea5439b0b33df1afb89da6d27b7da66b/src/app/controllers/guest/register_form.cljs | clojure | (ns app.controllers.guest.register-form
(:require [keechma.next.controller :as ctrl]
[keechma.next.controllers.pipelines :as pipelines]
[keechma.pipelines.core :as pp :refer-macros [pipeline!]]
[app.api :as api]
[promesa.core :as p]
[keechma.next.controllers.form :as form]
[app.validators :as v]
[promesa.core :as p]
[keechma.next.controllers.router :as router]))
(derive :guest/register-form ::pipelines/controller)
(def pipelines
{:keechma.form/submit-data
(pipeline!
[value {:keys [meta-state*], :as ctrl}]
(pp/swap! meta-state* dissoc :submit-errors)
(api/register value)
(ctrl/broadcast ctrl :guest/login value)
(router/redirect! ctrl :router {:page "home", :subpage "personal"})
(rescue! [error] (pp/swap! meta-state* assoc :submit-errors error)))})
(defmethod ctrl/prep :guest/register-form
[ctrl]
(pipelines/register
ctrl
(form/wrap pipelines
(v/to-validator {:username [:not-empty],
:email [:email :not-empty],
:password [:not-empty :ok-password]}))))
|
|
510b49a073cd5fae157fdb6087d1b029c8d12a80fd27796ff1794531f92b7962 | uwplse/synapse | specs.rkt | #lang s-exp rosette
(require "../../opsyn/engine/util.rkt")
(provide (all-defined-out))
; Utility procedures for defining pre conditions
; on inputs and (relaxed) correctness constraints
; on outputs.
; Returns a procedure that takes as input a list of
; numbers and asserts that all of them are between
; low and high, inclusive.
(define (range low high)
(procedure-rename
(lambda (xs)
(for ([x xs])
(let ([x (finitize x)])
(assert (<= (finitize low) x))
(assert (<= x (finitize high))))))
'range))
Asserts the correctness constraint
(define (exact p s)
(assert (= (finitize p) (finitize s))))
; Returns a procedure that asserts a relaxed
correctness constraint on p and s , which constrains p
to be p within |s| > > e of s.
(define (relaxed e)
(if (= e 32)
exact
(procedure-rename
(lambda (p s)
(let* ([s (finitize s)]
[p (finitize p)]
[e (finitize e)]
[diff (finitize (abs (finitize (- s p))))])
(assert (>= diff 0))
(assert (<= diff (finitize (>> (finitize (abs s)) e))))))
'relaxed)))
| null | https://raw.githubusercontent.com/uwplse/synapse/10f605f8f1fff6dade90607f516550b961a10169/benchmarks/parrot/specs.rkt | racket | Utility procedures for defining pre conditions
on inputs and (relaxed) correctness constraints
on outputs.
Returns a procedure that takes as input a list of
numbers and asserts that all of them are between
low and high, inclusive.
Returns a procedure that asserts a relaxed | #lang s-exp rosette
(require "../../opsyn/engine/util.rkt")
(provide (all-defined-out))
(define (range low high)
(procedure-rename
(lambda (xs)
(for ([x xs])
(let ([x (finitize x)])
(assert (<= (finitize low) x))
(assert (<= x (finitize high))))))
'range))
Asserts the correctness constraint
(define (exact p s)
(assert (= (finitize p) (finitize s))))
correctness constraint on p and s , which constrains p
to be p within |s| > > e of s.
(define (relaxed e)
(if (= e 32)
exact
(procedure-rename
(lambda (p s)
(let* ([s (finitize s)]
[p (finitize p)]
[e (finitize e)]
[diff (finitize (abs (finitize (- s p))))])
(assert (>= diff 0))
(assert (<= diff (finitize (>> (finitize (abs s)) e))))))
'relaxed)))
|
67446b2c41695636f4eecee8da330975ea6bee0e5cd811ef84cacf1425255129 | mmcgrana/clj-stacktrace | core.clj | (ns clj-stacktrace.core
(:require [clojure.string :as string]))
(defn- clojure-code?
"Returns true if the filename is non-null and indicates a clj source file."
[class-name file]
(or (re-find #"^user" class-name)
(= file "NO_SOURCE_FILE")
(and file (re-find #"\.clj$" file))))
(defn- clojure-ns
"Returns the clojure namespace name implied by the bytecode class name."
[class-name]
(string/replace (or (get (re-find #"([^$]+)\$" class-name) 1)
(get (re-find #"(.+)\.[^.]+$" class-name) 1))
#"_" "-"))
;; drop everything before and including the first $
drop everything after and including and the second $
;; drop any __xyz suffixes
;; sub _PLACEHOLDER_ for the corresponding char
(def clojure-fn-subs
[[#"^[^$]*\$" ""]
[#"\$.*" ""]
[#"__\d+.*" ""]
[#"_QMARK_" "?"]
[#"_BANG_" "!"]
[#"_PLUS_" "+"]
[#"_GT_" ">"]
[#"_LT_" "<"]
[#"_EQ_" "="]
[#"_STAR_" "*"]
[#"_SLASH_" "/"]
[#"_" "-"]])
(defn- clojure-fn
"Returns the clojure function name implied by the bytecode class name."
[class-name]
(reduce
(fn [base-name [pattern sub]] (string/replace base-name pattern sub))
class-name
clojure-fn-subs))
(defn- clojure-anon-fn?
"Returns true if the bytecode class name implies an anonymous inner fn."
[class-name]
(boolean (re-find #"\$.*\$" class-name)))
(defn parse-trace-elem
"Returns a map of information about the java trace element.
All returned maps have the keys:
:file String of source file name.
:line Number of source line number of the enclosing form.
Additionally for elements from Java code:
:java true, to indicate a Java elem.
:class String of the name of the class to which the method belongs.
Additionally for elements from Clojure code:
:clojure true, to inidcate a Clojure elem.
:ns String representing the namespace of the function.
:fn String representing the name of the enclosing var for the function.
:anon-fn true iff the function is an anonymous inner fn."
[^StackTraceElement elem]
(let [class-name (.getClassName elem)
file (.getFileName elem)
line (let [l (.getLineNumber elem)] (if (pos? l) l))
parsed {:file file :line line}]
(if (clojure-code? class-name file)
(assoc parsed
:clojure true
:ns (clojure-ns class-name)
:fn (clojure-fn class-name)
:anon-fn (clojure-anon-fn? class-name))
(assoc parsed
:java true
:class class-name
:method (.getMethodName elem)))))
(defn parse-trace-elems
"Returns a seq of maps providing usefull information about the java stack
trace elements. See parse-trace-elem."
[elems]
(map parse-trace-elem elems))
(defn- trim-redundant
"Returns the portion of the tail of causer-elems that is not duplicated in
the tail of caused-elems. This corresponds to the \"...26 more\" that you
see at the bottom of regular trace dumps."
[causer-parsed-elems caused-parsed-elems]
(loop [rcauser-parsed-elems (reverse causer-parsed-elems)
rcaused-parsed-elems (reverse caused-parsed-elems)]
(if-let [rcauser-bottom (first rcauser-parsed-elems)]
(if (= rcauser-bottom (first rcaused-parsed-elems))
(recur (next rcauser-parsed-elems) (next rcaused-parsed-elems))
(reverse rcauser-parsed-elems)))))
(defn- parse-cause-exception
"Like parse-exception, but for causing exceptions. The returned map has all
of the same keys as the map returned by parse-exception, and one added one:
:trimmed-elems A subset of :trace-elems representing the portion of the
top of the stacktrace not shared with that of the caused
exception."
[^Throwable causer-e caused-parsed-elems]
(let [parsed-elems (parse-trace-elems (.getStackTrace causer-e))
base {:class (class causer-e)
:message (.getMessage causer-e)
:trace-elems parsed-elems
:trimmed-elems (trim-redundant parsed-elems caused-parsed-elems)}]
(if-let [cause (.getCause causer-e)]
(assoc base :cause (parse-cause-exception cause parsed-elems))
base)))
(defn parse-exception
"Returns a Clojure map providing usefull informaiton about the exception.
The map has keys
:class Class of the exception.
:message Regular exception message string.
:trace-elems Parsed stack trace elems, see parse-trace-elem.
:cause See parse-cause-exception."
[^Throwable e]
(let [parsed-elems (parse-trace-elems (.getStackTrace e))
base {:class (class e)
:message (.getMessage e)
:trace-elems parsed-elems}]
(if-let [cause (.getCause e)]
(assoc base :cause (parse-cause-exception cause parsed-elems))
base)))
| null | https://raw.githubusercontent.com/mmcgrana/clj-stacktrace/94dc2dd748710e79800e94b713e167e5dc525717/src/clj_stacktrace/core.clj | clojure | drop everything before and including the first $
drop any __xyz suffixes
sub _PLACEHOLDER_ for the corresponding char | (ns clj-stacktrace.core
(:require [clojure.string :as string]))
(defn- clojure-code?
"Returns true if the filename is non-null and indicates a clj source file."
[class-name file]
(or (re-find #"^user" class-name)
(= file "NO_SOURCE_FILE")
(and file (re-find #"\.clj$" file))))
(defn- clojure-ns
"Returns the clojure namespace name implied by the bytecode class name."
[class-name]
(string/replace (or (get (re-find #"([^$]+)\$" class-name) 1)
(get (re-find #"(.+)\.[^.]+$" class-name) 1))
#"_" "-"))
drop everything after and including and the second $
(def clojure-fn-subs
[[#"^[^$]*\$" ""]
[#"\$.*" ""]
[#"__\d+.*" ""]
[#"_QMARK_" "?"]
[#"_BANG_" "!"]
[#"_PLUS_" "+"]
[#"_GT_" ">"]
[#"_LT_" "<"]
[#"_EQ_" "="]
[#"_STAR_" "*"]
[#"_SLASH_" "/"]
[#"_" "-"]])
(defn- clojure-fn
"Returns the clojure function name implied by the bytecode class name."
[class-name]
(reduce
(fn [base-name [pattern sub]] (string/replace base-name pattern sub))
class-name
clojure-fn-subs))
(defn- clojure-anon-fn?
"Returns true if the bytecode class name implies an anonymous inner fn."
[class-name]
(boolean (re-find #"\$.*\$" class-name)))
(defn parse-trace-elem
"Returns a map of information about the java trace element.
All returned maps have the keys:
:file String of source file name.
:line Number of source line number of the enclosing form.
Additionally for elements from Java code:
:java true, to indicate a Java elem.
:class String of the name of the class to which the method belongs.
Additionally for elements from Clojure code:
:clojure true, to inidcate a Clojure elem.
:ns String representing the namespace of the function.
:fn String representing the name of the enclosing var for the function.
:anon-fn true iff the function is an anonymous inner fn."
[^StackTraceElement elem]
(let [class-name (.getClassName elem)
file (.getFileName elem)
line (let [l (.getLineNumber elem)] (if (pos? l) l))
parsed {:file file :line line}]
(if (clojure-code? class-name file)
(assoc parsed
:clojure true
:ns (clojure-ns class-name)
:fn (clojure-fn class-name)
:anon-fn (clojure-anon-fn? class-name))
(assoc parsed
:java true
:class class-name
:method (.getMethodName elem)))))
(defn parse-trace-elems
"Returns a seq of maps providing usefull information about the java stack
trace elements. See parse-trace-elem."
[elems]
(map parse-trace-elem elems))
(defn- trim-redundant
"Returns the portion of the tail of causer-elems that is not duplicated in
the tail of caused-elems. This corresponds to the \"...26 more\" that you
see at the bottom of regular trace dumps."
[causer-parsed-elems caused-parsed-elems]
(loop [rcauser-parsed-elems (reverse causer-parsed-elems)
rcaused-parsed-elems (reverse caused-parsed-elems)]
(if-let [rcauser-bottom (first rcauser-parsed-elems)]
(if (= rcauser-bottom (first rcaused-parsed-elems))
(recur (next rcauser-parsed-elems) (next rcaused-parsed-elems))
(reverse rcauser-parsed-elems)))))
(defn- parse-cause-exception
"Like parse-exception, but for causing exceptions. The returned map has all
of the same keys as the map returned by parse-exception, and one added one:
:trimmed-elems A subset of :trace-elems representing the portion of the
top of the stacktrace not shared with that of the caused
exception."
[^Throwable causer-e caused-parsed-elems]
(let [parsed-elems (parse-trace-elems (.getStackTrace causer-e))
base {:class (class causer-e)
:message (.getMessage causer-e)
:trace-elems parsed-elems
:trimmed-elems (trim-redundant parsed-elems caused-parsed-elems)}]
(if-let [cause (.getCause causer-e)]
(assoc base :cause (parse-cause-exception cause parsed-elems))
base)))
(defn parse-exception
"Returns a Clojure map providing usefull informaiton about the exception.
The map has keys
:class Class of the exception.
:message Regular exception message string.
:trace-elems Parsed stack trace elems, see parse-trace-elem.
:cause See parse-cause-exception."
[^Throwable e]
(let [parsed-elems (parse-trace-elems (.getStackTrace e))
base {:class (class e)
:message (.getMessage e)
:trace-elems parsed-elems}]
(if-let [cause (.getCause e)]
(assoc base :cause (parse-cause-exception cause parsed-elems))
base)))
|
6293e3716f5ecac352c877b419a7cc9c0af476f906e9ba07a3d885db451b35cd | tek/polysemy-hasql | Input.hs | module Polysemy.Hasql.Queue.Input where
import Control.Concurrent (threadWaitRead)
import qualified Control.Concurrent.Async as Concurrent
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TBMQueue (TBMQueue, closeTBMQueue, newTBMQueueIO, readTBMQueue, writeTBMQueue)
import Control.Monad.Trans.Maybe (MaybeT (MaybeT), runMaybeT)
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.UUID as UUID
import Data.UUID (UUID)
import qualified Database.PostgreSQL.LibPQ as LibPQ
import Exon (exon)
import Hasql.Connection (Connection, withLibPQConnection)
import qualified Polysemy.Async as Async
import qualified Polysemy.Conc as Monitor
import Polysemy.Conc (
ClockSkewConfig,
Monitor,
Restart,
RestartingMonitor,
interpretAtomic,
interpretMonitorRestart,
monitorClockSkew,
)
import qualified Polysemy.Db.Data.DbConnectionError as DbConnectionError
import qualified Polysemy.Db.Data.DbError as DbError
import Polysemy.Db.Data.DbError (DbError)
import qualified Polysemy.Db.Data.Store as Store
import Polysemy.Db.Data.Store (Store)
import qualified Polysemy.Db.Data.Uid as Uid
import Polysemy.Db.Data.Uid (Uuid)
import Polysemy.Db.SOP.Constraint (symbolText)
import Polysemy.Final (withWeavingToFinal)
import Polysemy.Input (Input (Input))
import qualified Polysemy.Log as Log
import qualified Polysemy.Time as Time
import Prelude hiding (Queue, group, listen)
import Torsor (Torsor)
import qualified Polysemy.Hasql.Data.Database as Database
import Polysemy.Hasql.Data.Database (Database, InitDb (InitDb))
import Polysemy.Hasql.Data.SqlCode (SqlCode (SqlCode))
import qualified Polysemy.Hasql.Database as Database (retryingSqlDef)
import Polysemy.Hasql.Database (interpretDatabase)
import Polysemy.Hasql.Queue.Data.Queue (InputQueueConnection, Queue)
import Polysemy.Hasql.Queue.Data.Queued (Queued, QueuedRep)
import qualified Polysemy.Hasql.Queue.Data.Queued as Queued (Queued (..))
import Polysemy.Hasql.Store (interpretStoreDbFullNoUpdateGen)
tryDequeueSem ::
Members [Monitor Restart, Embed IO] r =>
LibPQ.Connection ->
Sem r (Either Text (Maybe UUID))
tryDequeueSem connection =
embed (LibPQ.notifies connection) >>= \case
Just (LibPQ.Notify _ _ payload) ->
case UUID.fromASCIIBytes payload of
Just d ->
pure (Right (Just d))
Nothing ->
pure (Left [exon|invalid UUID payload: #{decodeUtf8 payload}|])
Nothing ->
embed (LibPQ.socket connection) >>= \case
Just fd -> do
Monitor.monitor (embed (threadWaitRead fd))
Right Nothing <$ embed (LibPQ.consumeInput connection)
Nothing ->
pure (Left "couldn't connect with LibPQ.socket")
listen ::
∀ (queue :: Symbol) r .
KnownSymbol queue =>
Members [Database, Log, Embed IO] r =>
Sem r ()
listen = do
Log.debug [exon|executing `listen` for queue #{symbolText @queue}|]
Database.retryingSqlDef [exon|listen "#{SqlCode (symbolText @queue)}"|]
unlisten ::
∀ (queue :: Symbol) e r .
KnownSymbol queue =>
Members [Database !! e, Log] r =>
Sem r ()
unlisten = do
Log.debug [exon|executing `unlisten` for queue `#{symbolText @queue}`|]
resume_ (Database.retryingSqlDef [exon|unlisten "#{SqlCode (symbolText @queue)}"|])
processMessages ::
Ord t =>
NonEmpty (Uuid (Queued t d)) ->
NonEmpty d
processMessages =
fmap (Queued.queue_payload . Uid._payload) . NonEmpty.sortWith (Queued.queue_created . Uid._payload)
initQueue ::
∀ (queue :: Symbol) e d t r .
Ord t =>
KnownSymbol queue =>
Members [Store UUID (Queued t d) !! e, Database, Log, Embed IO] r =>
(d -> Sem r ()) ->
Sem r ()
initQueue write = do
waiting <- resumeAs Nothing Store.deleteAll
traverse_ (traverse_ write . processMessages) waiting
listen @queue
withPqConn ::
Member (Final IO) r =>
Connection ->
(LibPQ.Connection -> Sem r a) ->
Sem r (Either Text a)
withPqConn connection use =
errorToIOFinal $ fromExceptionSemVia @SomeException show $ withWeavingToFinal \ s lower _ -> do
withLibPQConnection connection \ c -> lower (raise (use c) <$ s)
dequeueAndProcess ::
∀ d t dt r .
Ord t =>
Members [Monitor Restart, Final IO] r =>
Members [Store UUID (Queued t d) !! DbError, Database !! DbError, Time t dt, Stop DbError, Log, Embed IO] r =>
TBMQueue d ->
Connection ->
Sem r ()
dequeueAndProcess queue connection = do
result <- join <$> withPqConn connection tryDequeueSem
void $ runMaybeT do
id' <- MaybeT (stopEitherWith (DbError.Connection . DbConnectionError.Acquire) result)
messages <- MaybeT (restop (Store.delete id'))
liftIO (traverse_ (atomically . writeTBMQueue queue) (processMessages messages))
dequeue ::
∀ (queue :: Symbol) d t dt r .
Ord t =>
KnownSymbol queue =>
Members [Monitor Restart, Final IO] r =>
Members [Store UUID (Queued t d) !! DbError, Database !! DbError, Stop DbError, Time t dt, Log, Embed IO] r =>
TBMQueue d ->
Sem r ()
dequeue queue =
restop @_ @Database (Database.withInit initDb (Database.connect (dequeueAndProcess queue)))
where
initDb =
InitDb [exon|dequeue-#{name}|] \ _ ->
initQueue @queue (embed . atomically . writeTBMQueue queue)
name =
symbolText @queue
dequeueLoop ::
∀ (queue :: Symbol) d t dt u r .
Ord t =>
TimeUnit u =>
KnownSymbol queue =>
Member RestartingMonitor r =>
Members [Store UUID (Queued t d) !! DbError, Database !! DbError, Time t dt, Log, Embed IO, Final IO] r =>
u ->
(DbError -> Sem r Bool) ->
TBMQueue d ->
Sem r ()
dequeueLoop errorDelay errorHandler queue =
Monitor.restart spin
where
spin =
either (result <=< raise . errorHandler) (const spin) =<< runStop (dequeue @queue queue)
result = \case
True -> disconnect *> Time.sleep errorDelay *> spin
False -> embed (atomically (closeTBMQueue queue))
disconnect =
unlisten @queue *> resume_ Database.disconnect
interpretInputDbQueue ::
∀ d r .
Member (Embed IO) r =>
TBMQueue d ->
InterpreterFor (Input (Maybe d)) r
interpretInputDbQueue queue =
interpret \case
Input ->
embed (atomically (readTBMQueue queue))
dequeueThread ::
∀ (queue :: Symbol) d t dt u r .
Ord t =>
TimeUnit u =>
KnownSymbol queue =>
Member RestartingMonitor r =>
Members [Store UUID (Queued t d) !! DbError, Database !! DbError, Time t dt, Log, Async, Embed IO, Final IO] r =>
u ->
(DbError -> Sem r Bool) ->
Sem r (Concurrent.Async (Maybe ()), TBMQueue d)
dequeueThread errorDelay errorHandler = do
queue <- embed (newTBMQueueIO 64)
handle <- async (dequeueLoop @queue errorDelay errorHandler queue)
pure (handle, queue)
releaseInputQueue ::
∀ (queue :: Symbol) d e r .
KnownSymbol queue =>
Members [Database !! e, Log, Async, Embed IO] r =>
Concurrent.Async (Maybe ()) ->
TBMQueue d ->
Sem r ()
releaseInputQueue handle _ = do
Log.debug [exon|executing `unlisten` for queue `#{symbolText @queue}`|]
Async.cancel handle
resume_ (Database.retryingSqlDef [exon|unlisten "#{SqlCode (symbolText @queue)}"|])
interpretInputDbQueueListen ::
∀ (queue :: Symbol) d t dt u r .
Ord t =>
TimeUnit u =>
KnownSymbol queue =>
Members [RestartingMonitor, Final IO] r =>
Members [Store UUID (Queued t d) !! DbError, Database !! DbError, Time t dt, Log, Resource, Async, Embed IO] r =>
u ->
(DbError -> Sem r Bool) ->
InterpreterFor (Input (Maybe d)) r
interpretInputDbQueueListen errorDelay errorHandler sem =
bracket acquire (uncurry (releaseInputQueue @queue)) \ (_, queue) ->
interpretInputDbQueue queue sem
where
acquire =
dequeueThread @queue errorDelay errorHandler
interpretInputDbQueueFull ::
∀ (queue :: Symbol) d t diff dt u r .
Ord t =>
TimeUnit u =>
TimeUnit diff =>
Torsor t diff =>
KnownSymbol queue =>
Members [InputQueueConnection queue, Store UUID (Queued t d) !! DbError, Time t dt, Log, Race, Resource, Async] r =>
Members [Embed IO, Final IO] r =>
u ->
ClockSkewConfig ->
(DbError -> Sem r Bool) ->
InterpreterFor (Input (Maybe d)) r
interpretInputDbQueueFull errorDelay csConfig errorHandler =
tag .
interpretDatabase .
interpretAtomic Nothing .
interpretMonitorRestart (monitorClockSkew csConfig) .
raiseUnder .
interpretInputDbQueueListen @queue errorDelay (raise . raise . raise . errorHandler) .
raiseUnder3
interpretInputDbQueueFullGen ::
∀ (queue :: Symbol) d t diff dt u r .
TimeUnit u =>
TimeUnit diff =>
Torsor t diff =>
Queue queue t d =>
Members [InputQueueConnection queue, Database !! DbError, Time t dt, Log, Resource, Async, Embed IO, Final IO] r =>
Member Race r =>
u ->
ClockSkewConfig ->
(DbError -> Sem r Bool) ->
InterpreterFor (Input (Maybe d)) r
interpretInputDbQueueFullGen errorDelay csConfig errorHandler =
interpretStoreDbFullNoUpdateGen @QueuedRep .
raiseUnder2 .
interpretInputDbQueueFull @queue errorDelay csConfig (raise . errorHandler) .
raiseUnder
| null | https://raw.githubusercontent.com/tek/polysemy-hasql/59897996f780231c74001a9c605094f74f13c88c/packages/hasql/lib/Polysemy/Hasql/Queue/Input.hs | haskell | module Polysemy.Hasql.Queue.Input where
import Control.Concurrent (threadWaitRead)
import qualified Control.Concurrent.Async as Concurrent
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TBMQueue (TBMQueue, closeTBMQueue, newTBMQueueIO, readTBMQueue, writeTBMQueue)
import Control.Monad.Trans.Maybe (MaybeT (MaybeT), runMaybeT)
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.UUID as UUID
import Data.UUID (UUID)
import qualified Database.PostgreSQL.LibPQ as LibPQ
import Exon (exon)
import Hasql.Connection (Connection, withLibPQConnection)
import qualified Polysemy.Async as Async
import qualified Polysemy.Conc as Monitor
import Polysemy.Conc (
ClockSkewConfig,
Monitor,
Restart,
RestartingMonitor,
interpretAtomic,
interpretMonitorRestart,
monitorClockSkew,
)
import qualified Polysemy.Db.Data.DbConnectionError as DbConnectionError
import qualified Polysemy.Db.Data.DbError as DbError
import Polysemy.Db.Data.DbError (DbError)
import qualified Polysemy.Db.Data.Store as Store
import Polysemy.Db.Data.Store (Store)
import qualified Polysemy.Db.Data.Uid as Uid
import Polysemy.Db.Data.Uid (Uuid)
import Polysemy.Db.SOP.Constraint (symbolText)
import Polysemy.Final (withWeavingToFinal)
import Polysemy.Input (Input (Input))
import qualified Polysemy.Log as Log
import qualified Polysemy.Time as Time
import Prelude hiding (Queue, group, listen)
import Torsor (Torsor)
import qualified Polysemy.Hasql.Data.Database as Database
import Polysemy.Hasql.Data.Database (Database, InitDb (InitDb))
import Polysemy.Hasql.Data.SqlCode (SqlCode (SqlCode))
import qualified Polysemy.Hasql.Database as Database (retryingSqlDef)
import Polysemy.Hasql.Database (interpretDatabase)
import Polysemy.Hasql.Queue.Data.Queue (InputQueueConnection, Queue)
import Polysemy.Hasql.Queue.Data.Queued (Queued, QueuedRep)
import qualified Polysemy.Hasql.Queue.Data.Queued as Queued (Queued (..))
import Polysemy.Hasql.Store (interpretStoreDbFullNoUpdateGen)
tryDequeueSem ::
Members [Monitor Restart, Embed IO] r =>
LibPQ.Connection ->
Sem r (Either Text (Maybe UUID))
tryDequeueSem connection =
embed (LibPQ.notifies connection) >>= \case
Just (LibPQ.Notify _ _ payload) ->
case UUID.fromASCIIBytes payload of
Just d ->
pure (Right (Just d))
Nothing ->
pure (Left [exon|invalid UUID payload: #{decodeUtf8 payload}|])
Nothing ->
embed (LibPQ.socket connection) >>= \case
Just fd -> do
Monitor.monitor (embed (threadWaitRead fd))
Right Nothing <$ embed (LibPQ.consumeInput connection)
Nothing ->
pure (Left "couldn't connect with LibPQ.socket")
listen ::
∀ (queue :: Symbol) r .
KnownSymbol queue =>
Members [Database, Log, Embed IO] r =>
Sem r ()
listen = do
Log.debug [exon|executing `listen` for queue #{symbolText @queue}|]
Database.retryingSqlDef [exon|listen "#{SqlCode (symbolText @queue)}"|]
unlisten ::
∀ (queue :: Symbol) e r .
KnownSymbol queue =>
Members [Database !! e, Log] r =>
Sem r ()
unlisten = do
Log.debug [exon|executing `unlisten` for queue `#{symbolText @queue}`|]
resume_ (Database.retryingSqlDef [exon|unlisten "#{SqlCode (symbolText @queue)}"|])
processMessages ::
Ord t =>
NonEmpty (Uuid (Queued t d)) ->
NonEmpty d
processMessages =
fmap (Queued.queue_payload . Uid._payload) . NonEmpty.sortWith (Queued.queue_created . Uid._payload)
initQueue ::
∀ (queue :: Symbol) e d t r .
Ord t =>
KnownSymbol queue =>
Members [Store UUID (Queued t d) !! e, Database, Log, Embed IO] r =>
(d -> Sem r ()) ->
Sem r ()
initQueue write = do
waiting <- resumeAs Nothing Store.deleteAll
traverse_ (traverse_ write . processMessages) waiting
listen @queue
withPqConn ::
Member (Final IO) r =>
Connection ->
(LibPQ.Connection -> Sem r a) ->
Sem r (Either Text a)
withPqConn connection use =
errorToIOFinal $ fromExceptionSemVia @SomeException show $ withWeavingToFinal \ s lower _ -> do
withLibPQConnection connection \ c -> lower (raise (use c) <$ s)
dequeueAndProcess ::
∀ d t dt r .
Ord t =>
Members [Monitor Restart, Final IO] r =>
Members [Store UUID (Queued t d) !! DbError, Database !! DbError, Time t dt, Stop DbError, Log, Embed IO] r =>
TBMQueue d ->
Connection ->
Sem r ()
dequeueAndProcess queue connection = do
result <- join <$> withPqConn connection tryDequeueSem
void $ runMaybeT do
id' <- MaybeT (stopEitherWith (DbError.Connection . DbConnectionError.Acquire) result)
messages <- MaybeT (restop (Store.delete id'))
liftIO (traverse_ (atomically . writeTBMQueue queue) (processMessages messages))
dequeue ::
∀ (queue :: Symbol) d t dt r .
Ord t =>
KnownSymbol queue =>
Members [Monitor Restart, Final IO] r =>
Members [Store UUID (Queued t d) !! DbError, Database !! DbError, Stop DbError, Time t dt, Log, Embed IO] r =>
TBMQueue d ->
Sem r ()
dequeue queue =
restop @_ @Database (Database.withInit initDb (Database.connect (dequeueAndProcess queue)))
where
initDb =
InitDb [exon|dequeue-#{name}|] \ _ ->
initQueue @queue (embed . atomically . writeTBMQueue queue)
name =
symbolText @queue
dequeueLoop ::
∀ (queue :: Symbol) d t dt u r .
Ord t =>
TimeUnit u =>
KnownSymbol queue =>
Member RestartingMonitor r =>
Members [Store UUID (Queued t d) !! DbError, Database !! DbError, Time t dt, Log, Embed IO, Final IO] r =>
u ->
(DbError -> Sem r Bool) ->
TBMQueue d ->
Sem r ()
dequeueLoop errorDelay errorHandler queue =
Monitor.restart spin
where
spin =
either (result <=< raise . errorHandler) (const spin) =<< runStop (dequeue @queue queue)
result = \case
True -> disconnect *> Time.sleep errorDelay *> spin
False -> embed (atomically (closeTBMQueue queue))
disconnect =
unlisten @queue *> resume_ Database.disconnect
interpretInputDbQueue ::
∀ d r .
Member (Embed IO) r =>
TBMQueue d ->
InterpreterFor (Input (Maybe d)) r
interpretInputDbQueue queue =
interpret \case
Input ->
embed (atomically (readTBMQueue queue))
dequeueThread ::
∀ (queue :: Symbol) d t dt u r .
Ord t =>
TimeUnit u =>
KnownSymbol queue =>
Member RestartingMonitor r =>
Members [Store UUID (Queued t d) !! DbError, Database !! DbError, Time t dt, Log, Async, Embed IO, Final IO] r =>
u ->
(DbError -> Sem r Bool) ->
Sem r (Concurrent.Async (Maybe ()), TBMQueue d)
dequeueThread errorDelay errorHandler = do
queue <- embed (newTBMQueueIO 64)
handle <- async (dequeueLoop @queue errorDelay errorHandler queue)
pure (handle, queue)
releaseInputQueue ::
∀ (queue :: Symbol) d e r .
KnownSymbol queue =>
Members [Database !! e, Log, Async, Embed IO] r =>
Concurrent.Async (Maybe ()) ->
TBMQueue d ->
Sem r ()
releaseInputQueue handle _ = do
Log.debug [exon|executing `unlisten` for queue `#{symbolText @queue}`|]
Async.cancel handle
resume_ (Database.retryingSqlDef [exon|unlisten "#{SqlCode (symbolText @queue)}"|])
interpretInputDbQueueListen ::
∀ (queue :: Symbol) d t dt u r .
Ord t =>
TimeUnit u =>
KnownSymbol queue =>
Members [RestartingMonitor, Final IO] r =>
Members [Store UUID (Queued t d) !! DbError, Database !! DbError, Time t dt, Log, Resource, Async, Embed IO] r =>
u ->
(DbError -> Sem r Bool) ->
InterpreterFor (Input (Maybe d)) r
interpretInputDbQueueListen errorDelay errorHandler sem =
bracket acquire (uncurry (releaseInputQueue @queue)) \ (_, queue) ->
interpretInputDbQueue queue sem
where
acquire =
dequeueThread @queue errorDelay errorHandler
interpretInputDbQueueFull ::
∀ (queue :: Symbol) d t diff dt u r .
Ord t =>
TimeUnit u =>
TimeUnit diff =>
Torsor t diff =>
KnownSymbol queue =>
Members [InputQueueConnection queue, Store UUID (Queued t d) !! DbError, Time t dt, Log, Race, Resource, Async] r =>
Members [Embed IO, Final IO] r =>
u ->
ClockSkewConfig ->
(DbError -> Sem r Bool) ->
InterpreterFor (Input (Maybe d)) r
interpretInputDbQueueFull errorDelay csConfig errorHandler =
tag .
interpretDatabase .
interpretAtomic Nothing .
interpretMonitorRestart (monitorClockSkew csConfig) .
raiseUnder .
interpretInputDbQueueListen @queue errorDelay (raise . raise . raise . errorHandler) .
raiseUnder3
interpretInputDbQueueFullGen ::
∀ (queue :: Symbol) d t diff dt u r .
TimeUnit u =>
TimeUnit diff =>
Torsor t diff =>
Queue queue t d =>
Members [InputQueueConnection queue, Database !! DbError, Time t dt, Log, Resource, Async, Embed IO, Final IO] r =>
Member Race r =>
u ->
ClockSkewConfig ->
(DbError -> Sem r Bool) ->
InterpreterFor (Input (Maybe d)) r
interpretInputDbQueueFullGen errorDelay csConfig errorHandler =
interpretStoreDbFullNoUpdateGen @QueuedRep .
raiseUnder2 .
interpretInputDbQueueFull @queue errorDelay csConfig (raise . errorHandler) .
raiseUnder
|
|
8452d350f9473b61beec404b16c88423b559387d03fbb47181f8788597be4eaf | ocamllabs/ocaml-modular-implicits | includemod.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
(* Inclusion checks for the module language *)
open Misc
open Path
open Typedtree
open Types
type symptom =
Missing_field of Ident.t * Location.t * string (* kind *)
| Implicit_flags of Ident.t * Location.t * Location.t
| Value_descriptions of Ident.t * value_description * value_description
| Type_declarations of Ident.t * type_declaration
* type_declaration * Includecore.type_mismatch list
| Extension_constructors of
Ident.t * extension_constructor * extension_constructor
| Module_types of module_type * module_type
| Modtype_infos of Ident.t * modtype_declaration * modtype_declaration
| Modtype_permutation
| Interface_mismatch of string * string
| Class_type_declarations of
Ident.t * class_type_declaration * class_type_declaration *
Ctype.class_match_failure list
| Class_declarations of
Ident.t * class_declaration * class_declaration *
Ctype.class_match_failure list
| Unbound_modtype_path of Path.t
| Unbound_module_path of Path.t
| Invalid_module_alias of Path.t
type pos =
| Module of Ident.t
| Modtype of Ident.t
| Param of pos_param
| Body of pos_param
and pos_param =
| Generative
| Applicative of Ident.t
| Implicit of Ident.t
type error = pos list * Env.t * symptom
exception Error of error list
(* All functions "blah env x1 x2" check that x1 is included in x2,
i.e. that x1 is the type of an implementation that fulfills the
specification x2. If not, Error is raised with a backtrace of the error. *)
(* Inclusion between implicit flags *)
let implicit_flags env cxt id f1 l1 f2 l2 =
match f1, f2 with
| Asttypes.Implicit, Asttypes.Implicit -> ()
| Asttypes.Implicit, Asttypes.Nonimplicit -> ()
| Asttypes.Nonimplicit, Asttypes.Nonimplicit -> ()
| _ -> raise(Error[cxt, env, Implicit_flags(id, l1, l2)])
(* Inclusion between value descriptions *)
let value_descriptions env cxt subst id vd1 vd2 =
Cmt_format.record_value_dependency vd1 vd2;
Env.mark_value_used env (Ident.name id) vd1;
let vd2 = Subst.value_description subst vd2 in
try
Includecore.value_descriptions env vd1 vd2
with Includecore.Dont_match ->
raise(Error[cxt, env, Value_descriptions(id, vd1, vd2)])
(* Inclusion between type declarations *)
let type_declarations env cxt subst id decl1 decl2 =
Env.mark_type_used env (Ident.name id) decl1;
let decl2 = Subst.type_declaration subst decl2 in
let err = Includecore.type_declarations env (Ident.name id) decl1 id decl2 in
if err <> [] then
raise(Error[cxt, env, Type_declarations(id, decl1, decl2, err)])
(* Inclusion between extension constructors *)
let extension_constructors env cxt subst id ext1 ext2 =
let ext2 = Subst.extension_constructor subst ext2 in
if Includecore.extension_constructors env id ext1 ext2
then ()
else raise(Error[cxt, env, Extension_constructors(id, ext1, ext2)])
(* Inclusion between class declarations *)
let class_type_declarations env cxt subst id decl1 decl2 =
let decl2 = Subst.cltype_declaration subst decl2 in
match Includeclass.class_type_declarations env decl1 decl2 with
[] -> ()
| reason ->
raise(Error[cxt, env, Class_type_declarations(id, decl1, decl2, reason)])
let class_declarations env cxt subst id decl1 decl2 =
let decl2 = Subst.class_declaration subst decl2 in
match Includeclass.class_declarations env decl1 decl2 with
[] -> ()
| reason ->
raise(Error[cxt, env, Class_declarations(id, decl1, decl2, reason)])
(* Expand a module type identifier when possible *)
exception Dont_match
let may_expand_module_path env path =
try ignore (Env.find_modtype_expansion path env); true
with Not_found -> false
let expand_module_path env cxt path =
try
Env.find_modtype_expansion path env
with Not_found ->
raise(Error[cxt, env, Unbound_modtype_path path])
let expand_module_alias env cxt path =
try (Env.find_module path env).md_type
with Not_found ->
raise(Error[cxt, env, Unbound_module_path path])
let rec normalize_module_path env cxt path =
match expand_module_alias env cxt path with
Mty_alias path ' - > normalize_module_path env cxt path '
| _ - > path
let rec normalize_module_path env cxt path =
match expand_module_alias env cxt path with
Mty_alias path' -> normalize_module_path env cxt path'
| _ -> path
*)
(* Extract name, kind and ident from a signature item *)
type field_desc =
Field_value of string
| Field_type of string
| Field_typext of string
| Field_module of string
| Field_modtype of string
| Field_class of string
| Field_classtype of string
let kind_of_field_desc = function
| Field_value _ -> "value"
| Field_type _ -> "type"
| Field_typext _ -> "extension constructor"
| Field_module _ -> "module"
| Field_modtype _ -> "module type"
| Field_class _ -> "class"
| Field_classtype _ -> "class type"
let item_ident_name = function
Sig_value(id, d) -> (id, d.val_loc, Field_value(Ident.name id))
| Sig_type(id, d, _) -> (id, d.type_loc, Field_type(Ident.name id))
| Sig_typext(id, d, _) -> (id, d.ext_loc, Field_typext(Ident.name id))
| Sig_module(id, d, _) -> (id, d.md_loc, Field_module(Ident.name id))
| Sig_modtype(id, d) -> (id, d.mtd_loc, Field_modtype(Ident.name id))
| Sig_class(id, d, _) -> (id, d.cty_loc, Field_class(Ident.name id))
| Sig_class_type(id, d, _) -> (id, d.clty_loc, Field_classtype(Ident.name id))
let is_runtime_component = function
| Sig_value(_,{val_kind = Val_prim _})
| Sig_type(_,_,_)
| Sig_modtype(_,_)
| Sig_class_type(_,_,_) -> false
| Sig_value(_,_)
| Sig_typext(_,_,_)
| Sig_module(_,_,_)
| Sig_class(_, _,_) -> true
(* Print a coercion *)
let rec print_list pr ppf = function
[] -> ()
| [a] -> pr ppf a
| a :: l -> pr ppf a; Format.fprintf ppf ";@ "; print_list pr ppf l
let print_list pr ppf l =
Format.fprintf ppf "[@[%a@]]" (print_list pr) l
let rec print_coercion ppf c =
let pr fmt = Format.fprintf ppf fmt in
match c with
Tcoerce_none -> pr "id"
| Tcoerce_structure (fl, nl) ->
pr "@[<2>struct@ %a@ %a@]"
(print_list print_coercion2) fl
(print_list print_coercion3) nl
| Tcoerce_functor (inp, out) ->
pr "@[<2>functor@ (%a)@ (%a)@]"
print_coercion inp
print_coercion out
| Tcoerce_primitive pd ->
pr "prim %s" pd.Primitive.prim_name
| Tcoerce_alias (p, c) ->
pr "@[<2>alias %a@ (%a)@]"
Printtyp.path p
print_coercion c
and print_coercion2 ppf (n, c) =
Format.fprintf ppf "@[%d,@ %a@]" n print_coercion c
and print_coercion3 ppf (i, n, c) =
Format.fprintf ppf "@[%s, %d,@ %a@]"
(Ident.unique_name i) n print_coercion c
(* Simplify a structure coercion *)
let simplify_structure_coercion cc id_pos_list =
let rec is_identity_coercion pos = function
| [] ->
true
| (n, c) :: rem ->
n = pos && c = Tcoerce_none && is_identity_coercion (pos + 1) rem in
if is_identity_coercion 0 cc
then Tcoerce_none
else Tcoerce_structure (cc, id_pos_list)
(* Inclusion between module types.
Return the restriction that transforms a value of the smaller type
into a value of the bigger type. *)
let rec modtypes env cxt subst mty1 mty2 =
try
try_modtypes env cxt subst mty1 mty2
with
Dont_match ->
raise(Error[cxt, env, Module_types(mty1, Subst.modtype subst mty2)])
| Error reasons as err ->
match mty1, mty2 with
Mty_alias _, _
| _, Mty_alias _ -> raise err
| _ ->
raise(Error((cxt, env, Module_types(mty1, Subst.modtype subst mty2))
:: reasons))
and try_modtypes env cxt subst mty1 mty2 =
match (mty1, mty2) with
| (Mty_alias p1, Mty_alias p2) ->
if Env.is_functor_arg p2 env then
raise (Error[cxt, env, Invalid_module_alias p2]);
if Path.same p1 p2 then Tcoerce_none else
let p1 = Env.normalize_path None env p1
and p2 = Env.normalize_path None env (Subst.module_path subst p2) in
(* Should actually be Tcoerce_ignore, if it existed *)
if Path.same p1 p2 then Tcoerce_none else raise Dont_match
| (Mty_alias p1, _) ->
let p1 = try
Env.normalize_path (Some Location.none) env p1
with Env.Error (Env.Missing_module (_, _, path)) ->
raise (Error[cxt, env, Unbound_module_path path])
in
let mty1 = Mtype.strengthen env (expand_module_alias env cxt p1) p1 in
Tcoerce_alias (p1, modtypes env cxt subst mty1 mty2)
| (Mty_ident p1, _) when may_expand_module_path env p1 ->
try_modtypes env cxt subst (expand_module_path env cxt p1) mty2
| (_, Mty_ident p2) ->
try_modtypes2 env cxt mty1 (Subst.modtype subst mty2)
| (Mty_signature sig1, Mty_signature sig2) ->
signatures env cxt subst sig1 sig2
| (Mty_functor(param1, res1), Mty_functor(param2, res2)) -> begin
match param1, param2 with
| Mpar_generative, Mpar_generative -> begin
match modtypes env (Body Generative::cxt) subst res1 res2 with
| Tcoerce_none -> Tcoerce_none
| cc -> Tcoerce_functor (Tcoerce_none, cc)
end
| Mpar_applicative(id1, arg1), Mpar_applicative(id2, arg2) -> begin
let arg2' = Subst.modtype subst arg2 in
let cc_arg =
modtypes env (Param (Applicative id1)::cxt) Subst.identity arg2' arg1
in
let cc_res =
modtypes (Env.add_module id1 arg2' env) (Body (Applicative id1)::cxt)
(Subst.add_module id2 (Pident id1) subst) res1 res2
in
match (cc_arg, cc_res) with
(Tcoerce_none, Tcoerce_none) -> Tcoerce_none
| _ -> Tcoerce_functor(cc_arg, cc_res)
end
| Mpar_implicit(id1, arg1), Mpar_implicit(id2, arg2) -> begin
let arg2' = Subst.modtype subst arg2 in
let cc_arg =
modtypes env (Param (Implicit id1)::cxt) Subst.identity arg2' arg1
in
let cc_res =
modtypes (Env.add_module id1 arg2' env) (Body (Implicit id1)::cxt)
(Subst.add_module id2 (Pident id1) subst) res1 res2
in
match (cc_arg, cc_res) with
(Tcoerce_none, Tcoerce_none) -> Tcoerce_none
| _ -> Tcoerce_functor(cc_arg, cc_res)
end
| (_, _) -> raise Dont_match
end
| (_, _) ->
raise Dont_match
and try_modtypes2 env cxt mty1 mty2 =
(* mty2 is an identifier *)
match (mty1, mty2) with
(Mty_ident p1, Mty_ident p2) when Path.same p1 p2 ->
Tcoerce_none
| (_, Mty_ident p2) ->
try_modtypes env cxt Subst.identity mty1 (expand_module_path env cxt p2)
| (_, _) ->
assert false
(* Inclusion between signatures *)
and signatures env cxt subst sig1 sig2 =
(* Environment used to check inclusion of components *)
let new_env =
Env.add_signature sig1 (Env.in_signature env) in
(* Keep ids for module aliases *)
let (id_pos_list,_) =
List.fold_left
(fun (l,pos) -> function
Sig_module (id, _, _) ->
((id,pos,Tcoerce_none)::l , pos+1)
| item -> (l, if is_runtime_component item then pos+1 else pos))
([], 0) sig1 in
Build a table of the components of , along with their positions .
The table is indexed by kind and name of component
The table is indexed by kind and name of component *)
let rec build_component_table pos tbl = function
[] -> pos, tbl
| item :: rem ->
let (id, _loc, name) = item_ident_name item in
let nextpos = if is_runtime_component item then pos + 1 else pos in
build_component_table nextpos
(Tbl.add name (id, item, pos) tbl) rem in
let len1, comps1 =
build_component_table 0 Tbl.empty sig1 in
let len2 =
List.fold_left
(fun n i -> if is_runtime_component i then n + 1 else n)
0
sig2
in
Pair each component of sig2 with a component of ,
identifying the names along the way .
Return a coercion list indicating , for all run - time components
of sig2 , the position of the matching run - time components of sig1
and the coercion to be applied to it .
identifying the names along the way.
Return a coercion list indicating, for all run-time components
of sig2, the position of the matching run-time components of sig1
and the coercion to be applied to it. *)
let rec pair_components subst paired unpaired = function
[] ->
begin match unpaired with
[] ->
let cc =
signature_components new_env cxt subst (List.rev paired)
in
see PR#5098
simplify_structure_coercion cc id_pos_list
else
Tcoerce_structure (cc, id_pos_list)
| _ -> raise(Error unpaired)
end
| item2 :: rem ->
let (id2, loc, name2) = item_ident_name item2 in
let name2, report =
match item2, name2 with
Sig_type (_, {type_manifest=None}, _), Field_type s
when let l = String.length s in
l >= 4 && String.sub s (l-4) 4 = "#row" ->
(* Do not report in case of failure,
as the main type will generate an error *)
Field_type (String.sub s 0 (String.length s - 4)), false
| _ -> name2, true
in
begin try
let (id1, item1, pos1) = Tbl.find name2 comps1 in
let new_subst =
match item2 with
Sig_type _ ->
Subst.add_type id2 (Pident id1) subst
| Sig_module _ ->
Subst.add_module id2 (Pident id1) subst
| Sig_modtype _ ->
Subst.add_modtype id2 (Mty_ident (Pident id1)) subst
| Sig_value _ | Sig_typext _
| Sig_class _ | Sig_class_type _ ->
subst
in
pair_components new_subst
((item1, item2, pos1) :: paired) unpaired rem
with Not_found ->
let unpaired =
if report then
(cxt, env, Missing_field (id2, loc, kind_of_field_desc name2)) ::
unpaired
else unpaired in
pair_components subst paired unpaired rem
end in
(* Do the pairing and checking, and return the final coercion *)
pair_components subst [] [] sig2
(* Inclusion between signature components *)
and signature_components env cxt subst = function
[] -> []
| (Sig_value(id1, valdecl1), Sig_value(id2, valdecl2), pos) :: rem ->
let cc = value_descriptions env cxt subst id1 valdecl1 valdecl2 in
begin match valdecl2.val_kind with
Val_prim p -> signature_components env cxt subst rem
| _ -> (pos, cc) :: signature_components env cxt subst rem
end
| (Sig_type(id1, tydecl1, _), Sig_type(id2, tydecl2, _), pos) :: rem ->
type_declarations env cxt subst id1 tydecl1 tydecl2;
signature_components env cxt subst rem
| (Sig_typext(id1, ext1, _), Sig_typext(id2, ext2, _), pos)
:: rem ->
extension_constructors env cxt subst id1 ext1 ext2;
(pos, Tcoerce_none) :: signature_components env cxt subst rem
| (Sig_module(id1, mty1, _), Sig_module(id2, mty2, _), pos) :: rem ->
let cc =
modtypes env (Module id1::cxt) subst
(Mtype.strengthen env mty1.md_type (Pident id1)) mty2.md_type in
implicit_flags env cxt id1
mty1.md_implicit mty1.md_loc
mty2.md_implicit mty2.md_loc;
(pos, cc) :: signature_components env cxt subst rem
| (Sig_modtype(id1, info1), Sig_modtype(id2, info2), pos) :: rem ->
modtype_infos env cxt subst id1 info1 info2;
signature_components env cxt subst rem
| (Sig_class(id1, decl1, _), Sig_class(id2, decl2, _), pos) :: rem ->
class_declarations env cxt subst id1 decl1 decl2;
(pos, Tcoerce_none) :: signature_components env cxt subst rem
| (Sig_class_type(id1, info1, _),
Sig_class_type(id2, info2, _), pos) :: rem ->
class_type_declarations env cxt subst id1 info1 info2;
signature_components env cxt subst rem
| _ -> assert false
(* Inclusion between module type specifications *)
and modtype_infos env cxt subst id info1 info2 =
let info2 = Subst.modtype_declaration subst info2 in
let cxt' = Modtype id :: cxt in
try
match (info1.mtd_type, info2.mtd_type) with
(None, None) -> ()
| (Some mty1, None) -> ()
| (Some mty1, Some mty2) ->
check_modtype_equiv env cxt' mty1 mty2
| (None, Some mty2) ->
check_modtype_equiv env cxt' (Mty_ident(Pident id)) mty2
with Error reasons ->
raise(Error((cxt, env, Modtype_infos(id, info1, info2)) :: reasons))
and check_modtype_equiv env cxt mty1 mty2 =
match
(modtypes env cxt Subst.identity mty1 mty2,
modtypes env cxt Subst.identity mty2 mty1)
with
(Tcoerce_none, Tcoerce_none) -> ()
| (_, _) -> raise(Error [cxt, env, Modtype_permutation])
(* Simplified inclusion check between module types (for Env) *)
let check_modtype_inclusion env mty1 path1 mty2 =
try
ignore(modtypes env [] Subst.identity
(Mtype.strengthen env mty1 path1) mty2)
with Error reasons ->
raise Not_found
let _ = Env.check_modtype_inclusion := check_modtype_inclusion
(* Check that an implementation of a compilation unit meets its
interface. *)
let compunit env impl_name impl_sig intf_name intf_sig =
try
signatures env [] Subst.identity impl_sig intf_sig
with Error reasons ->
raise(Error(([], Env.empty,Interface_mismatch(impl_name, intf_name))
:: reasons))
(* Hide the context and substitution parameters to the outside world *)
let modtypes env mty1 mty2 = modtypes env [] Subst.identity mty1 mty2
let signatures env sig1 sig2 = signatures env [] Subst.identity sig1 sig2
let type_declarations env id decl1 decl2 =
type_declarations env [] Subst.identity id decl1 decl2
let modtypes env =
let c = modtypes env in
Format.eprintf " @[<2 > modtypes@ % a@ % a = @ % a@]@. "
Printtyp.modtype m2
print_coercion c ;
c
let modtypes env m1 m2 =
let c = modtypes env m1 m2 in
Format.eprintf "@[<2>modtypes@ %a@ %a =@ %a@]@."
Printtyp.modtype m1 Printtyp.modtype m2
print_coercion c;
c
*)
(* Error report *)
open Format
open Printtyp
let show_loc msg ppf loc =
let pos = loc.Location.loc_start in
if List.mem pos.Lexing.pos_fname [""; "_none_"; "//toplevel//"] then ()
else fprintf ppf "@\n@[<2>%a:@ %s@]" Location.print_loc loc msg
let show_locs ppf (loc1, loc2) =
show_loc "Expected declaration" ppf loc2;
show_loc "Actual declaration" ppf loc1
let include_err ppf = function
| Missing_field (id, loc, kind) ->
fprintf ppf "The %s `%a' is required but not provided" kind ident id;
show_loc "Expected declaration" ppf loc
| Implicit_flags (id, l1, l2) ->
fprintf ppf "Implicit annotations of %a do not match" ident id;
show_locs ppf (l1, l2)
| Value_descriptions(id, d1, d2) ->
fprintf ppf
"@[<hv 2>Values do not match:@ %a@;<1 -2>is not included in@ %a@]"
(value_description id) d1 (value_description id) d2;
show_locs ppf (d1.val_loc, d2.val_loc);
| Type_declarations(id, d1, d2, errs) ->
fprintf ppf "@[<v>@[<hv>%s:@;<1 2>%a@ %s@;<1 2>%a@]%a%a@]"
"Type declarations do not match"
(type_declaration id) d1
"is not included in"
(type_declaration id) d2
show_locs (d1.type_loc, d2.type_loc)
(Includecore.report_type_mismatch
"the first" "the second" "declaration") errs
| Extension_constructors(id, x1, x2) ->
fprintf ppf
"@[<hv 2>Extension declarations do not match:@ \
%a@;<1 -2>is not included in@ %a@]"
(extension_constructor id) x1
(extension_constructor id) x2;
show_locs ppf (x1.ext_loc, x2.ext_loc)
| Module_types(mty1, mty2)->
fprintf ppf
"@[<hv 2>Modules do not match:@ \
%a@;<1 -2>is not included in@ %a@]"
modtype mty1
modtype mty2
| Modtype_infos(id, d1, d2) ->
fprintf ppf
"@[<hv 2>Module type declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]"
(modtype_declaration id) d1
(modtype_declaration id) d2
| Modtype_permutation ->
fprintf ppf "Illegal permutation of structure fields"
| Interface_mismatch(impl_name, intf_name) ->
fprintf ppf "@[The implementation %s@ does not match the interface %s:"
impl_name intf_name
| Class_type_declarations(id, d1, d2, reason) ->
fprintf ppf
"@[<hv 2>Class type declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]@ %a"
(Printtyp.cltype_declaration id) d1
(Printtyp.cltype_declaration id) d2
Includeclass.report_error reason
| Class_declarations(id, d1, d2, reason) ->
fprintf ppf
"@[<hv 2>Class declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]@ %a"
(Printtyp.class_declaration id) d1
(Printtyp.class_declaration id) d2
Includeclass.report_error reason
| Unbound_modtype_path path ->
fprintf ppf "Unbound module type %a" Printtyp.path path
| Unbound_module_path path ->
fprintf ppf "Unbound module %a" Printtyp.path path
| Invalid_module_alias path ->
fprintf ppf "Module %a cannot be aliased" Printtyp.path path
let rec context ppf = function
Module id :: rem ->
fprintf ppf "@[<2>module %a%a@]" ident id params rem
| Modtype id :: rem ->
fprintf ppf "@[<2>module type %a =@ %a@]" ident id context_mty rem
| Body p :: rem -> begin
match p with
| Generative ->
fprintf ppf "functor () ->@ %a" context_mty rem
| Applicative x ->
fprintf ppf "functor (%a) ->@ %a" ident x context_mty rem
| Implicit x ->
fprintf ppf "functor {%a} ->@ %a" ident x context_mty rem
end
| Param p :: rem -> begin
match p with
| Generative -> assert false
| Applicative x ->
fprintf ppf "functor (%a : %a) -> ..." ident x context_mty rem
| Implicit x ->
fprintf ppf "functor {%a : %a} -> ..." ident x context_mty rem
end
| [] ->
fprintf ppf "<here>"
and context_mty ppf = function
(Module _ | Modtype _) :: _ as rem ->
fprintf ppf "@[<2>sig@ %a@;<1 -2>end@]" context rem
| cxt -> context ppf cxt
and params ppf = function
Body p :: rem -> begin
match p with
| Generative ->
fprintf ppf "()%a" params rem
| Applicative x ->
fprintf ppf "(%a)%a" ident x params rem
| Implicit x ->
fprintf ppf "{%a}%a" ident x params rem
end
| Param p :: rem -> begin
match p with
| Generative -> assert false
| Applicative x ->
fprintf ppf "(%a :@ %a) : ..." ident x context_mty rem
| Implicit x ->
fprintf ppf "{%a :@ %a} : ..." ident x context_mty rem
end
| cxt ->
fprintf ppf " :@ %a" context_mty cxt
let path_of_context = function
Module id :: rem ->
let rec subm path = function
[] -> path
| Module id :: rem -> subm (Pdot (path, Ident.name id, -1)) rem
| _ -> assert false
in subm (Pident id) rem
| _ -> assert false
let context ppf cxt =
if cxt = [] then () else
if List.for_all (function Module _ -> true | _ -> false) cxt then
fprintf ppf "In module %a:@ " path (path_of_context cxt)
else
fprintf ppf "@[<hv 2>At position@ %a@]@ " context cxt
let include_err ppf (cxt, env, err) =
Printtyp.wrap_printing_env env (fun () ->
fprintf ppf "@[<v>%a%a@]" context (List.rev cxt) include_err err)
let buffer = ref Bytes.empty
let is_big obj =
let size = !Clflags.error_size in
size > 0 &&
begin
if Bytes.length !buffer < size then buffer := Bytes.create size;
try ignore (Marshal.to_buffer !buffer 0 size obj []); false
with _ -> true
end
let report_error ppf errs =
if errs = [] then () else
let (errs , err) = split_last errs in
let pe = ref true in
let include_err' ppf (_,_,obj as err) =
if not (is_big obj) then fprintf ppf "%a@ " include_err err
else if !pe then (fprintf ppf "...@ "; pe := false)
in
let print_errs ppf = List.iter (include_err' ppf) in
fprintf ppf "@[<v>%a%a@]" print_errs errs include_err err
(* We could do a better job to split the individual error items
as sub-messages of the main interface mismatch on the whole unit. *)
let () =
Location.register_error_of_exn
(function
| Error err -> Some (Location.error_of_printer_file report_error err)
| _ -> None
)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/typing/includemod.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
Inclusion checks for the module language
kind
All functions "blah env x1 x2" check that x1 is included in x2,
i.e. that x1 is the type of an implementation that fulfills the
specification x2. If not, Error is raised with a backtrace of the error.
Inclusion between implicit flags
Inclusion between value descriptions
Inclusion between type declarations
Inclusion between extension constructors
Inclusion between class declarations
Expand a module type identifier when possible
Extract name, kind and ident from a signature item
Print a coercion
Simplify a structure coercion
Inclusion between module types.
Return the restriction that transforms a value of the smaller type
into a value of the bigger type.
Should actually be Tcoerce_ignore, if it existed
mty2 is an identifier
Inclusion between signatures
Environment used to check inclusion of components
Keep ids for module aliases
Do not report in case of failure,
as the main type will generate an error
Do the pairing and checking, and return the final coercion
Inclusion between signature components
Inclusion between module type specifications
Simplified inclusion check between module types (for Env)
Check that an implementation of a compilation unit meets its
interface.
Hide the context and substitution parameters to the outside world
Error report
We could do a better job to split the individual error items
as sub-messages of the main interface mismatch on the whole unit. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
open Misc
open Path
open Typedtree
open Types
type symptom =
| Implicit_flags of Ident.t * Location.t * Location.t
| Value_descriptions of Ident.t * value_description * value_description
| Type_declarations of Ident.t * type_declaration
* type_declaration * Includecore.type_mismatch list
| Extension_constructors of
Ident.t * extension_constructor * extension_constructor
| Module_types of module_type * module_type
| Modtype_infos of Ident.t * modtype_declaration * modtype_declaration
| Modtype_permutation
| Interface_mismatch of string * string
| Class_type_declarations of
Ident.t * class_type_declaration * class_type_declaration *
Ctype.class_match_failure list
| Class_declarations of
Ident.t * class_declaration * class_declaration *
Ctype.class_match_failure list
| Unbound_modtype_path of Path.t
| Unbound_module_path of Path.t
| Invalid_module_alias of Path.t
type pos =
| Module of Ident.t
| Modtype of Ident.t
| Param of pos_param
| Body of pos_param
and pos_param =
| Generative
| Applicative of Ident.t
| Implicit of Ident.t
type error = pos list * Env.t * symptom
exception Error of error list
let implicit_flags env cxt id f1 l1 f2 l2 =
match f1, f2 with
| Asttypes.Implicit, Asttypes.Implicit -> ()
| Asttypes.Implicit, Asttypes.Nonimplicit -> ()
| Asttypes.Nonimplicit, Asttypes.Nonimplicit -> ()
| _ -> raise(Error[cxt, env, Implicit_flags(id, l1, l2)])
let value_descriptions env cxt subst id vd1 vd2 =
Cmt_format.record_value_dependency vd1 vd2;
Env.mark_value_used env (Ident.name id) vd1;
let vd2 = Subst.value_description subst vd2 in
try
Includecore.value_descriptions env vd1 vd2
with Includecore.Dont_match ->
raise(Error[cxt, env, Value_descriptions(id, vd1, vd2)])
let type_declarations env cxt subst id decl1 decl2 =
Env.mark_type_used env (Ident.name id) decl1;
let decl2 = Subst.type_declaration subst decl2 in
let err = Includecore.type_declarations env (Ident.name id) decl1 id decl2 in
if err <> [] then
raise(Error[cxt, env, Type_declarations(id, decl1, decl2, err)])
let extension_constructors env cxt subst id ext1 ext2 =
let ext2 = Subst.extension_constructor subst ext2 in
if Includecore.extension_constructors env id ext1 ext2
then ()
else raise(Error[cxt, env, Extension_constructors(id, ext1, ext2)])
let class_type_declarations env cxt subst id decl1 decl2 =
let decl2 = Subst.cltype_declaration subst decl2 in
match Includeclass.class_type_declarations env decl1 decl2 with
[] -> ()
| reason ->
raise(Error[cxt, env, Class_type_declarations(id, decl1, decl2, reason)])
let class_declarations env cxt subst id decl1 decl2 =
let decl2 = Subst.class_declaration subst decl2 in
match Includeclass.class_declarations env decl1 decl2 with
[] -> ()
| reason ->
raise(Error[cxt, env, Class_declarations(id, decl1, decl2, reason)])
exception Dont_match
let may_expand_module_path env path =
try ignore (Env.find_modtype_expansion path env); true
with Not_found -> false
let expand_module_path env cxt path =
try
Env.find_modtype_expansion path env
with Not_found ->
raise(Error[cxt, env, Unbound_modtype_path path])
let expand_module_alias env cxt path =
try (Env.find_module path env).md_type
with Not_found ->
raise(Error[cxt, env, Unbound_module_path path])
let rec normalize_module_path env cxt path =
match expand_module_alias env cxt path with
Mty_alias path ' - > normalize_module_path env cxt path '
| _ - > path
let rec normalize_module_path env cxt path =
match expand_module_alias env cxt path with
Mty_alias path' -> normalize_module_path env cxt path'
| _ -> path
*)
type field_desc =
Field_value of string
| Field_type of string
| Field_typext of string
| Field_module of string
| Field_modtype of string
| Field_class of string
| Field_classtype of string
let kind_of_field_desc = function
| Field_value _ -> "value"
| Field_type _ -> "type"
| Field_typext _ -> "extension constructor"
| Field_module _ -> "module"
| Field_modtype _ -> "module type"
| Field_class _ -> "class"
| Field_classtype _ -> "class type"
let item_ident_name = function
Sig_value(id, d) -> (id, d.val_loc, Field_value(Ident.name id))
| Sig_type(id, d, _) -> (id, d.type_loc, Field_type(Ident.name id))
| Sig_typext(id, d, _) -> (id, d.ext_loc, Field_typext(Ident.name id))
| Sig_module(id, d, _) -> (id, d.md_loc, Field_module(Ident.name id))
| Sig_modtype(id, d) -> (id, d.mtd_loc, Field_modtype(Ident.name id))
| Sig_class(id, d, _) -> (id, d.cty_loc, Field_class(Ident.name id))
| Sig_class_type(id, d, _) -> (id, d.clty_loc, Field_classtype(Ident.name id))
let is_runtime_component = function
| Sig_value(_,{val_kind = Val_prim _})
| Sig_type(_,_,_)
| Sig_modtype(_,_)
| Sig_class_type(_,_,_) -> false
| Sig_value(_,_)
| Sig_typext(_,_,_)
| Sig_module(_,_,_)
| Sig_class(_, _,_) -> true
let rec print_list pr ppf = function
[] -> ()
| [a] -> pr ppf a
| a :: l -> pr ppf a; Format.fprintf ppf ";@ "; print_list pr ppf l
let print_list pr ppf l =
Format.fprintf ppf "[@[%a@]]" (print_list pr) l
let rec print_coercion ppf c =
let pr fmt = Format.fprintf ppf fmt in
match c with
Tcoerce_none -> pr "id"
| Tcoerce_structure (fl, nl) ->
pr "@[<2>struct@ %a@ %a@]"
(print_list print_coercion2) fl
(print_list print_coercion3) nl
| Tcoerce_functor (inp, out) ->
pr "@[<2>functor@ (%a)@ (%a)@]"
print_coercion inp
print_coercion out
| Tcoerce_primitive pd ->
pr "prim %s" pd.Primitive.prim_name
| Tcoerce_alias (p, c) ->
pr "@[<2>alias %a@ (%a)@]"
Printtyp.path p
print_coercion c
and print_coercion2 ppf (n, c) =
Format.fprintf ppf "@[%d,@ %a@]" n print_coercion c
and print_coercion3 ppf (i, n, c) =
Format.fprintf ppf "@[%s, %d,@ %a@]"
(Ident.unique_name i) n print_coercion c
let simplify_structure_coercion cc id_pos_list =
let rec is_identity_coercion pos = function
| [] ->
true
| (n, c) :: rem ->
n = pos && c = Tcoerce_none && is_identity_coercion (pos + 1) rem in
if is_identity_coercion 0 cc
then Tcoerce_none
else Tcoerce_structure (cc, id_pos_list)
let rec modtypes env cxt subst mty1 mty2 =
try
try_modtypes env cxt subst mty1 mty2
with
Dont_match ->
raise(Error[cxt, env, Module_types(mty1, Subst.modtype subst mty2)])
| Error reasons as err ->
match mty1, mty2 with
Mty_alias _, _
| _, Mty_alias _ -> raise err
| _ ->
raise(Error((cxt, env, Module_types(mty1, Subst.modtype subst mty2))
:: reasons))
and try_modtypes env cxt subst mty1 mty2 =
match (mty1, mty2) with
| (Mty_alias p1, Mty_alias p2) ->
if Env.is_functor_arg p2 env then
raise (Error[cxt, env, Invalid_module_alias p2]);
if Path.same p1 p2 then Tcoerce_none else
let p1 = Env.normalize_path None env p1
and p2 = Env.normalize_path None env (Subst.module_path subst p2) in
if Path.same p1 p2 then Tcoerce_none else raise Dont_match
| (Mty_alias p1, _) ->
let p1 = try
Env.normalize_path (Some Location.none) env p1
with Env.Error (Env.Missing_module (_, _, path)) ->
raise (Error[cxt, env, Unbound_module_path path])
in
let mty1 = Mtype.strengthen env (expand_module_alias env cxt p1) p1 in
Tcoerce_alias (p1, modtypes env cxt subst mty1 mty2)
| (Mty_ident p1, _) when may_expand_module_path env p1 ->
try_modtypes env cxt subst (expand_module_path env cxt p1) mty2
| (_, Mty_ident p2) ->
try_modtypes2 env cxt mty1 (Subst.modtype subst mty2)
| (Mty_signature sig1, Mty_signature sig2) ->
signatures env cxt subst sig1 sig2
| (Mty_functor(param1, res1), Mty_functor(param2, res2)) -> begin
match param1, param2 with
| Mpar_generative, Mpar_generative -> begin
match modtypes env (Body Generative::cxt) subst res1 res2 with
| Tcoerce_none -> Tcoerce_none
| cc -> Tcoerce_functor (Tcoerce_none, cc)
end
| Mpar_applicative(id1, arg1), Mpar_applicative(id2, arg2) -> begin
let arg2' = Subst.modtype subst arg2 in
let cc_arg =
modtypes env (Param (Applicative id1)::cxt) Subst.identity arg2' arg1
in
let cc_res =
modtypes (Env.add_module id1 arg2' env) (Body (Applicative id1)::cxt)
(Subst.add_module id2 (Pident id1) subst) res1 res2
in
match (cc_arg, cc_res) with
(Tcoerce_none, Tcoerce_none) -> Tcoerce_none
| _ -> Tcoerce_functor(cc_arg, cc_res)
end
| Mpar_implicit(id1, arg1), Mpar_implicit(id2, arg2) -> begin
let arg2' = Subst.modtype subst arg2 in
let cc_arg =
modtypes env (Param (Implicit id1)::cxt) Subst.identity arg2' arg1
in
let cc_res =
modtypes (Env.add_module id1 arg2' env) (Body (Implicit id1)::cxt)
(Subst.add_module id2 (Pident id1) subst) res1 res2
in
match (cc_arg, cc_res) with
(Tcoerce_none, Tcoerce_none) -> Tcoerce_none
| _ -> Tcoerce_functor(cc_arg, cc_res)
end
| (_, _) -> raise Dont_match
end
| (_, _) ->
raise Dont_match
and try_modtypes2 env cxt mty1 mty2 =
match (mty1, mty2) with
(Mty_ident p1, Mty_ident p2) when Path.same p1 p2 ->
Tcoerce_none
| (_, Mty_ident p2) ->
try_modtypes env cxt Subst.identity mty1 (expand_module_path env cxt p2)
| (_, _) ->
assert false
and signatures env cxt subst sig1 sig2 =
let new_env =
Env.add_signature sig1 (Env.in_signature env) in
let (id_pos_list,_) =
List.fold_left
(fun (l,pos) -> function
Sig_module (id, _, _) ->
((id,pos,Tcoerce_none)::l , pos+1)
| item -> (l, if is_runtime_component item then pos+1 else pos))
([], 0) sig1 in
Build a table of the components of , along with their positions .
The table is indexed by kind and name of component
The table is indexed by kind and name of component *)
let rec build_component_table pos tbl = function
[] -> pos, tbl
| item :: rem ->
let (id, _loc, name) = item_ident_name item in
let nextpos = if is_runtime_component item then pos + 1 else pos in
build_component_table nextpos
(Tbl.add name (id, item, pos) tbl) rem in
let len1, comps1 =
build_component_table 0 Tbl.empty sig1 in
let len2 =
List.fold_left
(fun n i -> if is_runtime_component i then n + 1 else n)
0
sig2
in
Pair each component of sig2 with a component of ,
identifying the names along the way .
Return a coercion list indicating , for all run - time components
of sig2 , the position of the matching run - time components of sig1
and the coercion to be applied to it .
identifying the names along the way.
Return a coercion list indicating, for all run-time components
of sig2, the position of the matching run-time components of sig1
and the coercion to be applied to it. *)
let rec pair_components subst paired unpaired = function
[] ->
begin match unpaired with
[] ->
let cc =
signature_components new_env cxt subst (List.rev paired)
in
see PR#5098
simplify_structure_coercion cc id_pos_list
else
Tcoerce_structure (cc, id_pos_list)
| _ -> raise(Error unpaired)
end
| item2 :: rem ->
let (id2, loc, name2) = item_ident_name item2 in
let name2, report =
match item2, name2 with
Sig_type (_, {type_manifest=None}, _), Field_type s
when let l = String.length s in
l >= 4 && String.sub s (l-4) 4 = "#row" ->
Field_type (String.sub s 0 (String.length s - 4)), false
| _ -> name2, true
in
begin try
let (id1, item1, pos1) = Tbl.find name2 comps1 in
let new_subst =
match item2 with
Sig_type _ ->
Subst.add_type id2 (Pident id1) subst
| Sig_module _ ->
Subst.add_module id2 (Pident id1) subst
| Sig_modtype _ ->
Subst.add_modtype id2 (Mty_ident (Pident id1)) subst
| Sig_value _ | Sig_typext _
| Sig_class _ | Sig_class_type _ ->
subst
in
pair_components new_subst
((item1, item2, pos1) :: paired) unpaired rem
with Not_found ->
let unpaired =
if report then
(cxt, env, Missing_field (id2, loc, kind_of_field_desc name2)) ::
unpaired
else unpaired in
pair_components subst paired unpaired rem
end in
pair_components subst [] [] sig2
and signature_components env cxt subst = function
[] -> []
| (Sig_value(id1, valdecl1), Sig_value(id2, valdecl2), pos) :: rem ->
let cc = value_descriptions env cxt subst id1 valdecl1 valdecl2 in
begin match valdecl2.val_kind with
Val_prim p -> signature_components env cxt subst rem
| _ -> (pos, cc) :: signature_components env cxt subst rem
end
| (Sig_type(id1, tydecl1, _), Sig_type(id2, tydecl2, _), pos) :: rem ->
type_declarations env cxt subst id1 tydecl1 tydecl2;
signature_components env cxt subst rem
| (Sig_typext(id1, ext1, _), Sig_typext(id2, ext2, _), pos)
:: rem ->
extension_constructors env cxt subst id1 ext1 ext2;
(pos, Tcoerce_none) :: signature_components env cxt subst rem
| (Sig_module(id1, mty1, _), Sig_module(id2, mty2, _), pos) :: rem ->
let cc =
modtypes env (Module id1::cxt) subst
(Mtype.strengthen env mty1.md_type (Pident id1)) mty2.md_type in
implicit_flags env cxt id1
mty1.md_implicit mty1.md_loc
mty2.md_implicit mty2.md_loc;
(pos, cc) :: signature_components env cxt subst rem
| (Sig_modtype(id1, info1), Sig_modtype(id2, info2), pos) :: rem ->
modtype_infos env cxt subst id1 info1 info2;
signature_components env cxt subst rem
| (Sig_class(id1, decl1, _), Sig_class(id2, decl2, _), pos) :: rem ->
class_declarations env cxt subst id1 decl1 decl2;
(pos, Tcoerce_none) :: signature_components env cxt subst rem
| (Sig_class_type(id1, info1, _),
Sig_class_type(id2, info2, _), pos) :: rem ->
class_type_declarations env cxt subst id1 info1 info2;
signature_components env cxt subst rem
| _ -> assert false
and modtype_infos env cxt subst id info1 info2 =
let info2 = Subst.modtype_declaration subst info2 in
let cxt' = Modtype id :: cxt in
try
match (info1.mtd_type, info2.mtd_type) with
(None, None) -> ()
| (Some mty1, None) -> ()
| (Some mty1, Some mty2) ->
check_modtype_equiv env cxt' mty1 mty2
| (None, Some mty2) ->
check_modtype_equiv env cxt' (Mty_ident(Pident id)) mty2
with Error reasons ->
raise(Error((cxt, env, Modtype_infos(id, info1, info2)) :: reasons))
and check_modtype_equiv env cxt mty1 mty2 =
match
(modtypes env cxt Subst.identity mty1 mty2,
modtypes env cxt Subst.identity mty2 mty1)
with
(Tcoerce_none, Tcoerce_none) -> ()
| (_, _) -> raise(Error [cxt, env, Modtype_permutation])
let check_modtype_inclusion env mty1 path1 mty2 =
try
ignore(modtypes env [] Subst.identity
(Mtype.strengthen env mty1 path1) mty2)
with Error reasons ->
raise Not_found
let _ = Env.check_modtype_inclusion := check_modtype_inclusion
let compunit env impl_name impl_sig intf_name intf_sig =
try
signatures env [] Subst.identity impl_sig intf_sig
with Error reasons ->
raise(Error(([], Env.empty,Interface_mismatch(impl_name, intf_name))
:: reasons))
let modtypes env mty1 mty2 = modtypes env [] Subst.identity mty1 mty2
let signatures env sig1 sig2 = signatures env [] Subst.identity sig1 sig2
let type_declarations env id decl1 decl2 =
type_declarations env [] Subst.identity id decl1 decl2
let modtypes env =
let c = modtypes env in
Format.eprintf " @[<2 > modtypes@ % a@ % a = @ % a@]@. "
Printtyp.modtype m2
print_coercion c ;
c
let modtypes env m1 m2 =
let c = modtypes env m1 m2 in
Format.eprintf "@[<2>modtypes@ %a@ %a =@ %a@]@."
Printtyp.modtype m1 Printtyp.modtype m2
print_coercion c;
c
*)
open Format
open Printtyp
let show_loc msg ppf loc =
let pos = loc.Location.loc_start in
if List.mem pos.Lexing.pos_fname [""; "_none_"; "//toplevel//"] then ()
else fprintf ppf "@\n@[<2>%a:@ %s@]" Location.print_loc loc msg
let show_locs ppf (loc1, loc2) =
show_loc "Expected declaration" ppf loc2;
show_loc "Actual declaration" ppf loc1
let include_err ppf = function
| Missing_field (id, loc, kind) ->
fprintf ppf "The %s `%a' is required but not provided" kind ident id;
show_loc "Expected declaration" ppf loc
| Implicit_flags (id, l1, l2) ->
fprintf ppf "Implicit annotations of %a do not match" ident id;
show_locs ppf (l1, l2)
| Value_descriptions(id, d1, d2) ->
fprintf ppf
"@[<hv 2>Values do not match:@ %a@;<1 -2>is not included in@ %a@]"
(value_description id) d1 (value_description id) d2;
show_locs ppf (d1.val_loc, d2.val_loc);
| Type_declarations(id, d1, d2, errs) ->
fprintf ppf "@[<v>@[<hv>%s:@;<1 2>%a@ %s@;<1 2>%a@]%a%a@]"
"Type declarations do not match"
(type_declaration id) d1
"is not included in"
(type_declaration id) d2
show_locs (d1.type_loc, d2.type_loc)
(Includecore.report_type_mismatch
"the first" "the second" "declaration") errs
| Extension_constructors(id, x1, x2) ->
fprintf ppf
"@[<hv 2>Extension declarations do not match:@ \
%a@;<1 -2>is not included in@ %a@]"
(extension_constructor id) x1
(extension_constructor id) x2;
show_locs ppf (x1.ext_loc, x2.ext_loc)
| Module_types(mty1, mty2)->
fprintf ppf
"@[<hv 2>Modules do not match:@ \
%a@;<1 -2>is not included in@ %a@]"
modtype mty1
modtype mty2
| Modtype_infos(id, d1, d2) ->
fprintf ppf
"@[<hv 2>Module type declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]"
(modtype_declaration id) d1
(modtype_declaration id) d2
| Modtype_permutation ->
fprintf ppf "Illegal permutation of structure fields"
| Interface_mismatch(impl_name, intf_name) ->
fprintf ppf "@[The implementation %s@ does not match the interface %s:"
impl_name intf_name
| Class_type_declarations(id, d1, d2, reason) ->
fprintf ppf
"@[<hv 2>Class type declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]@ %a"
(Printtyp.cltype_declaration id) d1
(Printtyp.cltype_declaration id) d2
Includeclass.report_error reason
| Class_declarations(id, d1, d2, reason) ->
fprintf ppf
"@[<hv 2>Class declarations do not match:@ \
%a@;<1 -2>does not match@ %a@]@ %a"
(Printtyp.class_declaration id) d1
(Printtyp.class_declaration id) d2
Includeclass.report_error reason
| Unbound_modtype_path path ->
fprintf ppf "Unbound module type %a" Printtyp.path path
| Unbound_module_path path ->
fprintf ppf "Unbound module %a" Printtyp.path path
| Invalid_module_alias path ->
fprintf ppf "Module %a cannot be aliased" Printtyp.path path
let rec context ppf = function
Module id :: rem ->
fprintf ppf "@[<2>module %a%a@]" ident id params rem
| Modtype id :: rem ->
fprintf ppf "@[<2>module type %a =@ %a@]" ident id context_mty rem
| Body p :: rem -> begin
match p with
| Generative ->
fprintf ppf "functor () ->@ %a" context_mty rem
| Applicative x ->
fprintf ppf "functor (%a) ->@ %a" ident x context_mty rem
| Implicit x ->
fprintf ppf "functor {%a} ->@ %a" ident x context_mty rem
end
| Param p :: rem -> begin
match p with
| Generative -> assert false
| Applicative x ->
fprintf ppf "functor (%a : %a) -> ..." ident x context_mty rem
| Implicit x ->
fprintf ppf "functor {%a : %a} -> ..." ident x context_mty rem
end
| [] ->
fprintf ppf "<here>"
and context_mty ppf = function
(Module _ | Modtype _) :: _ as rem ->
fprintf ppf "@[<2>sig@ %a@;<1 -2>end@]" context rem
| cxt -> context ppf cxt
and params ppf = function
Body p :: rem -> begin
match p with
| Generative ->
fprintf ppf "()%a" params rem
| Applicative x ->
fprintf ppf "(%a)%a" ident x params rem
| Implicit x ->
fprintf ppf "{%a}%a" ident x params rem
end
| Param p :: rem -> begin
match p with
| Generative -> assert false
| Applicative x ->
fprintf ppf "(%a :@ %a) : ..." ident x context_mty rem
| Implicit x ->
fprintf ppf "{%a :@ %a} : ..." ident x context_mty rem
end
| cxt ->
fprintf ppf " :@ %a" context_mty cxt
let path_of_context = function
Module id :: rem ->
let rec subm path = function
[] -> path
| Module id :: rem -> subm (Pdot (path, Ident.name id, -1)) rem
| _ -> assert false
in subm (Pident id) rem
| _ -> assert false
let context ppf cxt =
if cxt = [] then () else
if List.for_all (function Module _ -> true | _ -> false) cxt then
fprintf ppf "In module %a:@ " path (path_of_context cxt)
else
fprintf ppf "@[<hv 2>At position@ %a@]@ " context cxt
let include_err ppf (cxt, env, err) =
Printtyp.wrap_printing_env env (fun () ->
fprintf ppf "@[<v>%a%a@]" context (List.rev cxt) include_err err)
let buffer = ref Bytes.empty
let is_big obj =
let size = !Clflags.error_size in
size > 0 &&
begin
if Bytes.length !buffer < size then buffer := Bytes.create size;
try ignore (Marshal.to_buffer !buffer 0 size obj []); false
with _ -> true
end
let report_error ppf errs =
if errs = [] then () else
let (errs , err) = split_last errs in
let pe = ref true in
let include_err' ppf (_,_,obj as err) =
if not (is_big obj) then fprintf ppf "%a@ " include_err err
else if !pe then (fprintf ppf "...@ "; pe := false)
in
let print_errs ppf = List.iter (include_err' ppf) in
fprintf ppf "@[<v>%a%a@]" print_errs errs include_err err
let () =
Location.register_error_of_exn
(function
| Error err -> Some (Location.error_of_printer_file report_error err)
| _ -> None
)
|
712a641284e64a9542277df7b0e1cf3cb366dc7ff5db03faa61a3d4bd7b96b12 | yetibot/yetibot | jira.clj | (ns yetibot.commands.jira
(:require
[clojure.tools.cli :refer [parse-opts]]
[yetibot.core.util :refer [filter-nil-vals ]]
[taoensso.timbre :refer [info debug]]
[clojure.string :refer [split join trim blank?]]
[yetibot.core.hooks :refer [cmd-hook]]
[clojure.data.json :as json]
[yetibot.api.jira :as api :refer [channel-projects]]))
(defn success? [res]
(re-find #"^2" (str (:status res) "2")))
(defn format-error [{:keys [status body]}]
(info "jira api error" status body)
{:result/error
(cond
(= 403 status) (str "403 Forbidden. Verify your JIRA credentials?")
(= 401 status) (str "401 Unauthorized. Check your JIRA credentials?")
body (join " "
(or
try to figure out which one of JIRA 's many weirdo
;; responses we're dealing with here
(-> body :errorMessages seq)
(map
(fn [[k v]] (str (name k) ": " v))
(-> body :errors))))
;; ¯\_(ツ)_/¯
:else (str status " JIRA API error"))})
(defn report-if-error
"Checks the stauts of the HTTP response for 2xx, and if not, looks in the body
for :errorMessages or :errors. To use this, make sure to use the
`:throw-exceptions false`, `:content-type :json` and, `:coerce :always`
options in the HTTP request."
[req-fn succ-fn]
(try
(let [{:keys [body status] :as res} (req-fn)]
sometimes JIRA 200s even when there are errors so check if there are
;; errors in the json response
(info "jira succ" status (pr-str body))
(if (or (:errorMessages body)
(:errors body))
(format-error res)
(succ-fn res)))
(catch Exception e
(let [{:keys [status body] :as error} (ex-data e)
json-body (try (json/read-str body :key-fn keyword)
(catch Exception e nil))]
(debug "jira error" (pr-str e))
(format-error (assoc error :body json-body))))))
(defn configured-projects-cmd
"jira configured-projects # list configured projects (⭐️ indicates global default; ⚡️ indicates channel default; channel default overrides global default)"
{:yb/cat #{:issue}}
[{:keys [settings]}]
(let [projects-for-chan (set (channel-projects settings))]
(remove
nil?
(into
(vec (for [pk (api/project-keys)]
(when-not (projects-for-chan pk)
(str
(when (= pk (api/default-project-key)) "⭐️ ")
(api/url-from-key pk)))))
(map (fn [pk] (str "⚡️ " (api/url-from-key pk)))
projects-for-chan)))))
(defn project-users-cmd
"jira project-users # list the users channel project or default project
jira project-users <project> # list the users for the configured project(s)"
{:yb/cat #{:issue}}
[{:keys [settings] [_ project-key] :match}]
(let [project (or project-key
(first (channel-projects settings))
(api/default-project-key))]
(report-if-error
#(api/get-users project)
(fn [{:keys [body] :as res}]
{:result/data body
:result/value (map :displayName body)}))))
(defn users-cmd
"jira users <query> # search for users matching <query>"
{:yb/cat #{:issue}}
[{[_ query] :match}]
(report-if-error
#(api/search-users query)
(fn [{:keys [body] :as res}]
{:result/data body
:result/value (map :displayName body)})))
(defn resolve-cmd
"jira resolve <issue> <comment> # resolve an issue and set its resolution to fixed"
{:yb/cat #{:issue}}
[{[_ iss comment] :match user :user settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(let [comment (format "%s: %s" (:name user) comment)]
(if-let [issue-data (:body (api/get-issue iss))]
(report-if-error
#(api/resolve-issue iss comment)
(fn [res]
(if res
{:result/value (api/fetch-and-format-issue-short iss)
:result/data res}
{:result/error (str "Issue `" iss "` is already resolved")})))
{:result/error (str "Unable to find any issue `" iss "`")}))))
(defn priorities-cmd
"jira pri # list the priorities for this JIRA instance"
{:yb/cat #{:issue}}
[_]
(report-if-error
#(api/priorities)
(fn [{priorities :body :as res}]
{:result/value (->> priorities
(map (fn [{:keys [statusColor name description]}]
[name (str description " " statusColor)]))
flatten
(apply sorted-map))
:result/data priorities})))
(def issue-opts
[["-j" "--project-key PROJECT KEY"
"Project key (use `channel set jira-project PROJECT1` to set a channel-specific default)"]
["-c" "--component COMPONENT" "Component"]
["-i" "--issue-type ISSUE TYPE" "Issue type"]
["-s" "--summary SUMMARY" "Summary"]
["-a" "--assignee ASSIGNEE" "Assignee"]
["-e" "--reporter REPORTER" "Reporter"]
["-f" "--fix-version FIX VERSION" "Fix version"]
["-d" "--desc DESCRIPTION" "Description"]
["-t" "--time TIME ESTIAMTED" "Time estimated"]
["-r" "--remaining REMAINING TIME ESTIAMTED" "Remaining time estimated"]
["-p" "--parent PARENT ISSUE KEY" "Parent issue key; creates a sub-task if specified"]
["-y" "--priority PRIORITY" "Priority of the issue"]])
(defn parse-issue-opts
"Parse opts using issue-opts and trim all the values of the keys in options"
[opts]
(let [parsed (parse-opts
(map trim (split opts #"(?=\s-\w)|(?<=\s-\w)")) issue-opts)]
(update-in parsed [:options]
(fn [options]
(into {} (map (fn [[k v]] [k (trim v)]) options))))))
(meta #'parse-issue-opts)
(def foo
^{:doc "wat"}
(fn [] 1))
(defn bar
"sends x to any taps. Will not block. Returns true if there was room in the queue,
false if not (dropped)."
{:added "1.10"
:doc (str "override" 1)}
[x]
"bar")
[ -c < component > ] [ -j project - key ( use ` channel set jira - project PROJECT1
;; to set a channel-specific default)] [-i issue-type] [-e reporter] [-a
;; <assignee>] [-d <description>] [-f <fix-version>] [-t <time estimated>]
;; [-p <parent-issue-key> (creates a sub-task if specified)]
(defn create-cmd
{:doc
(str
\newline
"jira create <summary> [options] # creates a new JIRA issue.
Whether `options` are optional or not depend on your JIRA Project
configuration. For example, sometimes `description` is required.
Options are:"
\newline
\newline
(join
\newline
(map
(fn [[short-key long-key desc]]
(format "%s, %s %s %s"
short-key
long-key
(str \newline (join (map (constantly " ") (range 4))))
desc))
issue-opts))
\newline)
:yb/cat #{:issue}}
[{[_ opts-str] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(let [parsed (parse-issue-opts opts-str)
summary (->> parsed :arguments (join " "))
{:keys [priority] :as opts} (:options parsed)
issue-type (when-let [issue-type (:issue-type opts)]
(let [parsed-it (read-string issue-type)]
(if (number? parsed-it)
;; they provided an id so use that but in string form
issue-type
;; they provided a string so match by name and grab
the first one
(let [its (api/issue-types)
pattern (re-pattern
(str "(?i)" (:issue-type opts)))]
(:id (first (filter #(re-find pattern (:name %))
its)))))))
component-ids (when (:component opts)
(map :id
(api/find-component-like (:component opts))))]
(if (or
(:project-key opts)
(api/default-project-key)
(seq api/*jira-projects*))
(report-if-error
#(api/create-issue
(filter-nil-vals
(merge
{:summary summary}
(when priority {:priority-key priority})
(when issue-type {:issue-type-id issue-type})
(when component-ids {:component-ids component-ids})
(select-keys opts [:fix-version :project-key :parent
:desc :reporter :assignee])
(when (:time opts)
{:timetracking {:originalEstimate (:time opts)
:remainingEstimate (:time opts)}}))))
(fn [res]
(info "create command" (pr-str res))
(let [iss-key (-> res :body :key)]
{:result/value (api/fetch-and-format-issue-short iss-key)
:result/data (select-keys
res [:body :status :request-time])})))
{:result/error
"No project specified. Either specify it directly with `-j project-key` or set channel jira project(s) with `channel set jira-project PROJECT1,PROJECT2`"}))))
(defn update-cmd
"jira update <issue-key> [-s <summary>] [-c <component>] [-a <assignee>] [-d <description>] [-f <fix-version>] [-t <time estimated>] [-r <remaining time estimated>]"
{:doc
(str
\newline
"jira update <issue-key> [options] # update an existing JIRA issue
Available `options` are:"
\newline
\newline
(join
\newline
(map
(fn [[short-key long-key desc]]
(format "%s, %s %s %s"
short-key
long-key
(str \newline (join (map (constantly " ") (range 4))))
desc))
issue-opts))
\newline)
:yb/cat #{:issue}}
[{[_ issue-key opts-str] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(let [parsed (parse-issue-opts opts-str)
{:keys [priority] :as opts} (:options parsed)]
(clojure.pprint/pprint parsed)
(let [component-ids (when (:component opts)
(map :id (api/find-component-like
(:component opts))))]
(report-if-error
#(api/update-issue
issue-key
(filter-nil-vals
(merge
{:component-ids component-ids}
(when priority {:priority-key priority})
(select-keys opts [:fix-version :summary :desc :reporter :assignee])
(when (or (:remaining opts) (:time opts))
{:timetracking
(merge (when (:remaining opts)
{:remainingEstimate (:remaining opts)})
(when (:time opts)
{:originalEstimate (:time opts)}))}))))
(fn [res]
(info "updated" res)
(let [iss-key (-> res :body :key)]
{:result/value (str "Updated: "
(api/fetch-and-format-issue-short
issue-key))
:result/data (:body res)})))))))
(defn- short-jira-list [res]
(if (success? res)
(map api/format-issue-short
(->> res :body :issues (take 15)))
(-> res :body :errorMessages)))
(defn assign-cmd
"jira assign <issue> <assignee> # assign <issue> to <assignee>"
{:yb/cat #{:issue}}
[{[_ iss-key assignee] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(report-if-error
#(let [user-to-assign (api/resolve-user-by-query assignee)]
(if user-to-assign
(api/update-issue iss-key {:assignee assignee})
{:result/error (format "Couldn't find user for `%s`" assignee)}))
(fn [res]
(if res
{:result/value
(-> iss-key api/get-issue :body api/format-issue-short)
:result/data (:body res)}
{:result/error (format "Unable to assign %s to %s"
iss-key assignee)})))))
(defn comment-cmd
"jira comment <issue> <comment> # comment on <issue>"
{:yb/cat #{:issue}}
[{[_ iss-key body] :match user :user settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(let [body (format "%s: %s" (:name user) body)]
(report-if-error
#(api/post-comment iss-key body)
(fn [res]
{:result/value
(-> iss-key api/get-issue :body api/format-issue-long)
:result/data (:body res)})))))
(defn recent-cmd
"jira recent # show the 15 most recent issues from default project(s)
jira recent <project> # show the 15 most recent issues for <project>"
{:yb/cat #{:issue}}
[{[_ project] :match :keys [settings] :as cmd-opts}]
(info "recent opts" (pr-str cmd-opts))
(info "recent for project:" project)
(binding [api/*jira-project* project
api/*jira-projects* (channel-projects settings)]
(info "recent" (pr-str (api/default-project-key)))
(if (api/default-project-key)
(report-if-error
#(api/recent project)
(fn [res]
{:result/value (short-jira-list res)
:result/data (-> res :body :issues)}))
{:result/error
"You don't have any JIRA projects configured for this channel. Use `channel set jira-project PROJECT1,PROJECT2` to configure 1 or more."
})))
(defn search-cmd
"jira search <query> # return up to 15 issues matching <query> across all configured projects"
{:yb/cat #{:issue}}
[{[_ query] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(report-if-error
#(api/search-by-query query)
(fn [res]
{:result/value (short-jira-list res)
:result/data res}))))
(defn jql-cmd
"jira jql <jql> # return up to 15 issues matching <jql> query across all configured projects"
{:yb/cat #{:issue}}
[{[_ jql] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(report-if-error
#(api/search jql)
(fn [res]
{:result/value (short-jira-list res)
:result/data (-> res :body :issues)}))))
(defn components-cmd
"jira components # list components and their leads by project"
{:yb/cat #{:issue}}
[{:keys [settings]}]
(binding [api/*jira-projects* (channel-projects settings)]
(info "components projects" (channel-projects settings))
TODO this needs error handling but our current err handling structure
does n't work so well for composite results from multiple API calls
;; unless we figured out a way to report multiple results
(let [data (mapcat (comp :body api/components) (api/project-keys))]
{:result/data data
:result/value (map
(fn [{component-name :name
:keys [project lead description]}]
(str
"[" project "] "
"[" (-> lead :displayName) "] "
component-name
" — "
description))
data)})))
(defn priorities-cmd
"jira priorities # list JIRA priorities"
{:yb/cat #{:issue}}
[{:keys [settings]}]
(let [{:keys [body]} (api/priorities)]
{:result/value (map
(fn [{:keys [statusColor description]
pri-name :name}]
(format "%s %s: %s" statusColor pri-name description))
body)
:result/data body}))
(defn format-version [v]
(str
(when-let [rd (:releaseDate v)] (str " [release date " rd "]"))
(when (:archived v) " [archived]")
(when (:released v) " [released]")
" " (:name v) " - " (:description v)))
(defn versions-cmd
"jira versions <project-key> # list versions for <project-key>
jira versions # Lists versions for all configured project-keys"
{:yb/cat #{:issue}}
[{[_ project-key] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(let [project-keys (if project-key [project-key] (api/project-keys))
TODO needs error handling
data (mapcat
#(->> (api/versions %)
:body
(map (fn [v] (assoc v :project %))))
project-keys)]
{:result/data data
:result/value (map (fn [version]
(str "[" (:project version) "]"
(format-version version)))
data)})))
(defn parse-cmd
"jira parse <text> # parse the issue key out of a jira issue URL"
{:yb/cat #{:issue}}
[{[_ text] :match}]
(second (re-find #"browse\/([^\/]+)" text)))
(defn show-cmd
"jira show <issue> # show the full details of an issue"
{:yb/cat #{:issue}}
[{[_ issue-key] :match}]
(report-if-error
#(api/get-issue issue-key)
(fn [{:keys [body]}]
(info "!!! show-cmd" (pr-str body))
{:result/value (api/format-issue-long body)
:result/data body})))
(defn delete-cmd
"jira delete <issue> # delete the issue"
{:yb/cat #{:issue}}
[{[_ issue-key] :match}]
(report-if-error
#(api/delete-issue issue-key)
(fn [res]
(info "deleted jira issue" issue-key res)
{:result/value (str "Deleted " issue-key)
:result/data (:body res)})))
(defn worklog-cmd
"jira worklog <issue> <time-spent> <work-description> # log work on <issue>"
[{[_ issue-key time-spent work-description] :match}]
(if-let [issue-data (:body (api/get-issue issue-key))]
(report-if-error
#(api/add-worklog-item issue-key time-spent work-description)
(fn [res]
(info "worklog-response" (pr-str res))
(if res
{:result/value (-> issue-key
api/get-issue
:body
api/format-issue-long)
:result/data res})))
{:result/error (str "Unable to find any issue `" issue-key "`")}))
(defn issue-types-cmd
"jira issue-types [<name to match>] # return issue types, optionally filtering on <name to match>"
[{[_ issue-types-filter] :match}]
(info "issue-types-cmd" issue-types-filter)
(let [its (api/issue-types)
;; optionally filter the issue types if the user provided a pattern
filtered (if (blank? issue-types-filter)
its
(let [pattern (re-pattern
(str "(?i)" issue-types-filter))]
(filter #(re-find pattern (:name %)) its)))]
{:result/value (map (fn [{issue-type-name :name
:keys [id description]}]
(format "[%s] %s: %s" id issue-type-name description))
filtered)
:result/data filtered}))
(defn projects-cmd
"jira projects [<query>] - list projects, optionally matching <query>"
[{[_ query] :match}]
(report-if-error
#(api/get-projects query)
(fn [{:keys [body]}]
{:result/value (map api/format-project (:values body))
:result/collection-path [:values]
:result/data body})))
(comment
(-> "YETIBOT-1"
api/get-issue
:body
api/format-issue-long))
(defn transitions-cmd
"jira transitions <issue> # list the available transitions for <issue>"
{:yb/cat #{:issue}}
[{[_ issue-key] :match}]
(let [{{transitions :transitions} :body} (api/get-transitions issue-key)]
{:result/data transitions
:result/value (map :name transitions)}))
(defn transition-cmd
"jira transition <issue> <transition> # Move <issue> through <transition>"
{:yb/cat #{:issue}}
[{[_ issue-key transition-name] :match}]
(let [transition (api/find-transition issue-key transition-name)]
(if transition
(report-if-error
#(api/transition-issue issue-key (:id transition))
(fn [res]
(info "transition result" (pr-str res))
(if res
{:result/value (api/fetch-and-format-issue-short issue-key)
:result/data res})))
{:result/error (format "Couldn't find transition `%s` for issue `%s`"
issue-key transition-name)})))
(cmd-hook
#"jira"
#"transition\s+(\S+)\s+(\S+)" transition-cmd
#"transitions\s+(\S+)" transitions-cmd
#"^issue-types\s*(.*)" issue-types-cmd
#"^configured-projects" configured-projects-cmd
#"^projects\s*(\S+)*" projects-cmd
#"^parse\s+(.+)" parse-cmd
#"^show\s+(\S+)" show-cmd
#"^delete\s+(\S+)" delete-cmd
#"^worklog\s+(\S+)\s+(\S+)\s+(.+)" worklog-cmd
#"^components" components-cmd
#"^priorities" priorities-cmd
#"^versions\s*(\S+)*" versions-cmd
#"^recent\s*(\S+)*" recent-cmd
#"^pri" priorities-cmd
#"^project-users\s*(\S.+)*" project-users-cmd
#"^users\s+(\S+)" users-cmd
#"^assign\s+(\S+)\s+(\S+)" assign-cmd
#"^comment\s+(\S+)\s+(.+)" comment-cmd
#"^search\s+(.+)" search-cmd
#"^jql\s+(.+)" jql-cmd
#"^create\s+(.+)" create-cmd
#"^update\s+(\S+)\s+(.+)" update-cmd
#"^resolve\s+([\w\-]+)\s+(.+)" resolve-cmd)
| null | https://raw.githubusercontent.com/yetibot/yetibot/2fb5c1182b1a53ab0e433d6bab2775ebd43367de/src/yetibot/commands/jira.clj | clojure | responses we're dealing with here
¯\_(ツ)_/¯
errors in the json response
to set a channel-specific default)] [-i issue-type] [-e reporter] [-a
<assignee>] [-d <description>] [-f <fix-version>] [-t <time estimated>]
[-p <parent-issue-key> (creates a sub-task if specified)]
they provided an id so use that but in string form
they provided a string so match by name and grab
unless we figured out a way to report multiple results
optionally filter the issue types if the user provided a pattern | (ns yetibot.commands.jira
(:require
[clojure.tools.cli :refer [parse-opts]]
[yetibot.core.util :refer [filter-nil-vals ]]
[taoensso.timbre :refer [info debug]]
[clojure.string :refer [split join trim blank?]]
[yetibot.core.hooks :refer [cmd-hook]]
[clojure.data.json :as json]
[yetibot.api.jira :as api :refer [channel-projects]]))
(defn success? [res]
(re-find #"^2" (str (:status res) "2")))
(defn format-error [{:keys [status body]}]
(info "jira api error" status body)
{:result/error
(cond
(= 403 status) (str "403 Forbidden. Verify your JIRA credentials?")
(= 401 status) (str "401 Unauthorized. Check your JIRA credentials?")
body (join " "
(or
try to figure out which one of JIRA 's many weirdo
(-> body :errorMessages seq)
(map
(fn [[k v]] (str (name k) ": " v))
(-> body :errors))))
:else (str status " JIRA API error"))})
(defn report-if-error
"Checks the stauts of the HTTP response for 2xx, and if not, looks in the body
for :errorMessages or :errors. To use this, make sure to use the
`:throw-exceptions false`, `:content-type :json` and, `:coerce :always`
options in the HTTP request."
[req-fn succ-fn]
(try
(let [{:keys [body status] :as res} (req-fn)]
sometimes JIRA 200s even when there are errors so check if there are
(info "jira succ" status (pr-str body))
(if (or (:errorMessages body)
(:errors body))
(format-error res)
(succ-fn res)))
(catch Exception e
(let [{:keys [status body] :as error} (ex-data e)
json-body (try (json/read-str body :key-fn keyword)
(catch Exception e nil))]
(debug "jira error" (pr-str e))
(format-error (assoc error :body json-body))))))
(defn configured-projects-cmd
"jira configured-projects # list configured projects (⭐️ indicates global default; ⚡️ indicates channel default; channel default overrides global default)"
{:yb/cat #{:issue}}
[{:keys [settings]}]
(let [projects-for-chan (set (channel-projects settings))]
(remove
nil?
(into
(vec (for [pk (api/project-keys)]
(when-not (projects-for-chan pk)
(str
(when (= pk (api/default-project-key)) "⭐️ ")
(api/url-from-key pk)))))
(map (fn [pk] (str "⚡️ " (api/url-from-key pk)))
projects-for-chan)))))
(defn project-users-cmd
"jira project-users # list the users channel project or default project
jira project-users <project> # list the users for the configured project(s)"
{:yb/cat #{:issue}}
[{:keys [settings] [_ project-key] :match}]
(let [project (or project-key
(first (channel-projects settings))
(api/default-project-key))]
(report-if-error
#(api/get-users project)
(fn [{:keys [body] :as res}]
{:result/data body
:result/value (map :displayName body)}))))
(defn users-cmd
"jira users <query> # search for users matching <query>"
{:yb/cat #{:issue}}
[{[_ query] :match}]
(report-if-error
#(api/search-users query)
(fn [{:keys [body] :as res}]
{:result/data body
:result/value (map :displayName body)})))
(defn resolve-cmd
"jira resolve <issue> <comment> # resolve an issue and set its resolution to fixed"
{:yb/cat #{:issue}}
[{[_ iss comment] :match user :user settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(let [comment (format "%s: %s" (:name user) comment)]
(if-let [issue-data (:body (api/get-issue iss))]
(report-if-error
#(api/resolve-issue iss comment)
(fn [res]
(if res
{:result/value (api/fetch-and-format-issue-short iss)
:result/data res}
{:result/error (str "Issue `" iss "` is already resolved")})))
{:result/error (str "Unable to find any issue `" iss "`")}))))
(defn priorities-cmd
"jira pri # list the priorities for this JIRA instance"
{:yb/cat #{:issue}}
[_]
(report-if-error
#(api/priorities)
(fn [{priorities :body :as res}]
{:result/value (->> priorities
(map (fn [{:keys [statusColor name description]}]
[name (str description " " statusColor)]))
flatten
(apply sorted-map))
:result/data priorities})))
(def issue-opts
[["-j" "--project-key PROJECT KEY"
"Project key (use `channel set jira-project PROJECT1` to set a channel-specific default)"]
["-c" "--component COMPONENT" "Component"]
["-i" "--issue-type ISSUE TYPE" "Issue type"]
["-s" "--summary SUMMARY" "Summary"]
["-a" "--assignee ASSIGNEE" "Assignee"]
["-e" "--reporter REPORTER" "Reporter"]
["-f" "--fix-version FIX VERSION" "Fix version"]
["-d" "--desc DESCRIPTION" "Description"]
["-t" "--time TIME ESTIAMTED" "Time estimated"]
["-r" "--remaining REMAINING TIME ESTIAMTED" "Remaining time estimated"]
["-p" "--parent PARENT ISSUE KEY" "Parent issue key; creates a sub-task if specified"]
["-y" "--priority PRIORITY" "Priority of the issue"]])
(defn parse-issue-opts
"Parse opts using issue-opts and trim all the values of the keys in options"
[opts]
(let [parsed (parse-opts
(map trim (split opts #"(?=\s-\w)|(?<=\s-\w)")) issue-opts)]
(update-in parsed [:options]
(fn [options]
(into {} (map (fn [[k v]] [k (trim v)]) options))))))
(meta #'parse-issue-opts)
(def foo
^{:doc "wat"}
(fn [] 1))
(defn bar
"sends x to any taps. Will not block. Returns true if there was room in the queue,
false if not (dropped)."
{:added "1.10"
:doc (str "override" 1)}
[x]
"bar")
[ -c < component > ] [ -j project - key ( use ` channel set jira - project PROJECT1
(defn create-cmd
{:doc
(str
\newline
"jira create <summary> [options] # creates a new JIRA issue.
Whether `options` are optional or not depend on your JIRA Project
configuration. For example, sometimes `description` is required.
Options are:"
\newline
\newline
(join
\newline
(map
(fn [[short-key long-key desc]]
(format "%s, %s %s %s"
short-key
long-key
(str \newline (join (map (constantly " ") (range 4))))
desc))
issue-opts))
\newline)
:yb/cat #{:issue}}
[{[_ opts-str] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(let [parsed (parse-issue-opts opts-str)
summary (->> parsed :arguments (join " "))
{:keys [priority] :as opts} (:options parsed)
issue-type (when-let [issue-type (:issue-type opts)]
(let [parsed-it (read-string issue-type)]
(if (number? parsed-it)
issue-type
the first one
(let [its (api/issue-types)
pattern (re-pattern
(str "(?i)" (:issue-type opts)))]
(:id (first (filter #(re-find pattern (:name %))
its)))))))
component-ids (when (:component opts)
(map :id
(api/find-component-like (:component opts))))]
(if (or
(:project-key opts)
(api/default-project-key)
(seq api/*jira-projects*))
(report-if-error
#(api/create-issue
(filter-nil-vals
(merge
{:summary summary}
(when priority {:priority-key priority})
(when issue-type {:issue-type-id issue-type})
(when component-ids {:component-ids component-ids})
(select-keys opts [:fix-version :project-key :parent
:desc :reporter :assignee])
(when (:time opts)
{:timetracking {:originalEstimate (:time opts)
:remainingEstimate (:time opts)}}))))
(fn [res]
(info "create command" (pr-str res))
(let [iss-key (-> res :body :key)]
{:result/value (api/fetch-and-format-issue-short iss-key)
:result/data (select-keys
res [:body :status :request-time])})))
{:result/error
"No project specified. Either specify it directly with `-j project-key` or set channel jira project(s) with `channel set jira-project PROJECT1,PROJECT2`"}))))
(defn update-cmd
"jira update <issue-key> [-s <summary>] [-c <component>] [-a <assignee>] [-d <description>] [-f <fix-version>] [-t <time estimated>] [-r <remaining time estimated>]"
{:doc
(str
\newline
"jira update <issue-key> [options] # update an existing JIRA issue
Available `options` are:"
\newline
\newline
(join
\newline
(map
(fn [[short-key long-key desc]]
(format "%s, %s %s %s"
short-key
long-key
(str \newline (join (map (constantly " ") (range 4))))
desc))
issue-opts))
\newline)
:yb/cat #{:issue}}
[{[_ issue-key opts-str] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(let [parsed (parse-issue-opts opts-str)
{:keys [priority] :as opts} (:options parsed)]
(clojure.pprint/pprint parsed)
(let [component-ids (when (:component opts)
(map :id (api/find-component-like
(:component opts))))]
(report-if-error
#(api/update-issue
issue-key
(filter-nil-vals
(merge
{:component-ids component-ids}
(when priority {:priority-key priority})
(select-keys opts [:fix-version :summary :desc :reporter :assignee])
(when (or (:remaining opts) (:time opts))
{:timetracking
(merge (when (:remaining opts)
{:remainingEstimate (:remaining opts)})
(when (:time opts)
{:originalEstimate (:time opts)}))}))))
(fn [res]
(info "updated" res)
(let [iss-key (-> res :body :key)]
{:result/value (str "Updated: "
(api/fetch-and-format-issue-short
issue-key))
:result/data (:body res)})))))))
(defn- short-jira-list [res]
(if (success? res)
(map api/format-issue-short
(->> res :body :issues (take 15)))
(-> res :body :errorMessages)))
(defn assign-cmd
"jira assign <issue> <assignee> # assign <issue> to <assignee>"
{:yb/cat #{:issue}}
[{[_ iss-key assignee] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(report-if-error
#(let [user-to-assign (api/resolve-user-by-query assignee)]
(if user-to-assign
(api/update-issue iss-key {:assignee assignee})
{:result/error (format "Couldn't find user for `%s`" assignee)}))
(fn [res]
(if res
{:result/value
(-> iss-key api/get-issue :body api/format-issue-short)
:result/data (:body res)}
{:result/error (format "Unable to assign %s to %s"
iss-key assignee)})))))
(defn comment-cmd
"jira comment <issue> <comment> # comment on <issue>"
{:yb/cat #{:issue}}
[{[_ iss-key body] :match user :user settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(let [body (format "%s: %s" (:name user) body)]
(report-if-error
#(api/post-comment iss-key body)
(fn [res]
{:result/value
(-> iss-key api/get-issue :body api/format-issue-long)
:result/data (:body res)})))))
(defn recent-cmd
"jira recent # show the 15 most recent issues from default project(s)
jira recent <project> # show the 15 most recent issues for <project>"
{:yb/cat #{:issue}}
[{[_ project] :match :keys [settings] :as cmd-opts}]
(info "recent opts" (pr-str cmd-opts))
(info "recent for project:" project)
(binding [api/*jira-project* project
api/*jira-projects* (channel-projects settings)]
(info "recent" (pr-str (api/default-project-key)))
(if (api/default-project-key)
(report-if-error
#(api/recent project)
(fn [res]
{:result/value (short-jira-list res)
:result/data (-> res :body :issues)}))
{:result/error
"You don't have any JIRA projects configured for this channel. Use `channel set jira-project PROJECT1,PROJECT2` to configure 1 or more."
})))
(defn search-cmd
"jira search <query> # return up to 15 issues matching <query> across all configured projects"
{:yb/cat #{:issue}}
[{[_ query] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(report-if-error
#(api/search-by-query query)
(fn [res]
{:result/value (short-jira-list res)
:result/data res}))))
(defn jql-cmd
"jira jql <jql> # return up to 15 issues matching <jql> query across all configured projects"
{:yb/cat #{:issue}}
[{[_ jql] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(report-if-error
#(api/search jql)
(fn [res]
{:result/value (short-jira-list res)
:result/data (-> res :body :issues)}))))
(defn components-cmd
"jira components # list components and their leads by project"
{:yb/cat #{:issue}}
[{:keys [settings]}]
(binding [api/*jira-projects* (channel-projects settings)]
(info "components projects" (channel-projects settings))
TODO this needs error handling but our current err handling structure
does n't work so well for composite results from multiple API calls
(let [data (mapcat (comp :body api/components) (api/project-keys))]
{:result/data data
:result/value (map
(fn [{component-name :name
:keys [project lead description]}]
(str
"[" project "] "
"[" (-> lead :displayName) "] "
component-name
" — "
description))
data)})))
(defn priorities-cmd
"jira priorities # list JIRA priorities"
{:yb/cat #{:issue}}
[{:keys [settings]}]
(let [{:keys [body]} (api/priorities)]
{:result/value (map
(fn [{:keys [statusColor description]
pri-name :name}]
(format "%s %s: %s" statusColor pri-name description))
body)
:result/data body}))
(defn format-version [v]
(str
(when-let [rd (:releaseDate v)] (str " [release date " rd "]"))
(when (:archived v) " [archived]")
(when (:released v) " [released]")
" " (:name v) " - " (:description v)))
(defn versions-cmd
"jira versions <project-key> # list versions for <project-key>
jira versions # Lists versions for all configured project-keys"
{:yb/cat #{:issue}}
[{[_ project-key] :match settings :settings}]
(binding [api/*jira-projects* (channel-projects settings)]
(let [project-keys (if project-key [project-key] (api/project-keys))
TODO needs error handling
data (mapcat
#(->> (api/versions %)
:body
(map (fn [v] (assoc v :project %))))
project-keys)]
{:result/data data
:result/value (map (fn [version]
(str "[" (:project version) "]"
(format-version version)))
data)})))
(defn parse-cmd
"jira parse <text> # parse the issue key out of a jira issue URL"
{:yb/cat #{:issue}}
[{[_ text] :match}]
(second (re-find #"browse\/([^\/]+)" text)))
(defn show-cmd
"jira show <issue> # show the full details of an issue"
{:yb/cat #{:issue}}
[{[_ issue-key] :match}]
(report-if-error
#(api/get-issue issue-key)
(fn [{:keys [body]}]
(info "!!! show-cmd" (pr-str body))
{:result/value (api/format-issue-long body)
:result/data body})))
(defn delete-cmd
"jira delete <issue> # delete the issue"
{:yb/cat #{:issue}}
[{[_ issue-key] :match}]
(report-if-error
#(api/delete-issue issue-key)
(fn [res]
(info "deleted jira issue" issue-key res)
{:result/value (str "Deleted " issue-key)
:result/data (:body res)})))
(defn worklog-cmd
"jira worklog <issue> <time-spent> <work-description> # log work on <issue>"
[{[_ issue-key time-spent work-description] :match}]
(if-let [issue-data (:body (api/get-issue issue-key))]
(report-if-error
#(api/add-worklog-item issue-key time-spent work-description)
(fn [res]
(info "worklog-response" (pr-str res))
(if res
{:result/value (-> issue-key
api/get-issue
:body
api/format-issue-long)
:result/data res})))
{:result/error (str "Unable to find any issue `" issue-key "`")}))
(defn issue-types-cmd
"jira issue-types [<name to match>] # return issue types, optionally filtering on <name to match>"
[{[_ issue-types-filter] :match}]
(info "issue-types-cmd" issue-types-filter)
(let [its (api/issue-types)
filtered (if (blank? issue-types-filter)
its
(let [pattern (re-pattern
(str "(?i)" issue-types-filter))]
(filter #(re-find pattern (:name %)) its)))]
{:result/value (map (fn [{issue-type-name :name
:keys [id description]}]
(format "[%s] %s: %s" id issue-type-name description))
filtered)
:result/data filtered}))
(defn projects-cmd
"jira projects [<query>] - list projects, optionally matching <query>"
[{[_ query] :match}]
(report-if-error
#(api/get-projects query)
(fn [{:keys [body]}]
{:result/value (map api/format-project (:values body))
:result/collection-path [:values]
:result/data body})))
(comment
(-> "YETIBOT-1"
api/get-issue
:body
api/format-issue-long))
(defn transitions-cmd
"jira transitions <issue> # list the available transitions for <issue>"
{:yb/cat #{:issue}}
[{[_ issue-key] :match}]
(let [{{transitions :transitions} :body} (api/get-transitions issue-key)]
{:result/data transitions
:result/value (map :name transitions)}))
(defn transition-cmd
"jira transition <issue> <transition> # Move <issue> through <transition>"
{:yb/cat #{:issue}}
[{[_ issue-key transition-name] :match}]
(let [transition (api/find-transition issue-key transition-name)]
(if transition
(report-if-error
#(api/transition-issue issue-key (:id transition))
(fn [res]
(info "transition result" (pr-str res))
(if res
{:result/value (api/fetch-and-format-issue-short issue-key)
:result/data res})))
{:result/error (format "Couldn't find transition `%s` for issue `%s`"
issue-key transition-name)})))
(cmd-hook
#"jira"
#"transition\s+(\S+)\s+(\S+)" transition-cmd
#"transitions\s+(\S+)" transitions-cmd
#"^issue-types\s*(.*)" issue-types-cmd
#"^configured-projects" configured-projects-cmd
#"^projects\s*(\S+)*" projects-cmd
#"^parse\s+(.+)" parse-cmd
#"^show\s+(\S+)" show-cmd
#"^delete\s+(\S+)" delete-cmd
#"^worklog\s+(\S+)\s+(\S+)\s+(.+)" worklog-cmd
#"^components" components-cmd
#"^priorities" priorities-cmd
#"^versions\s*(\S+)*" versions-cmd
#"^recent\s*(\S+)*" recent-cmd
#"^pri" priorities-cmd
#"^project-users\s*(\S.+)*" project-users-cmd
#"^users\s+(\S+)" users-cmd
#"^assign\s+(\S+)\s+(\S+)" assign-cmd
#"^comment\s+(\S+)\s+(.+)" comment-cmd
#"^search\s+(.+)" search-cmd
#"^jql\s+(.+)" jql-cmd
#"^create\s+(.+)" create-cmd
#"^update\s+(\S+)\s+(.+)" update-cmd
#"^resolve\s+([\w\-]+)\s+(.+)" resolve-cmd)
|
10062c1f994eadc323cd06c73939a4316d1034701e3b846134fffa7177625ee3 | sdiehl/bulletproofs | Internal.hs | # LANGUAGE DeriveGeneric , , ViewPatterns #
module Bulletproofs.RangeProof.Internal where
import Protolude
import Numeric (showIntAtBase)
import Data.Char (intToDigit, digitToInt)
import Control.Monad.Random (MonadRandom)
import Data.Field.Galois (PrimeField(..))
import Data.Curve.Weierstrass.SECP256K1 (PA, Fr, mul, inv, gen)
import Bulletproofs.Utils
import Bulletproofs.InnerProductProof.Internal
data RangeProof f p
= RangeProof
{ tBlinding :: f
-- ^ Blinding factor of the T1 and T2 commitments,
-- combined into the form required to make the committed version of the x-polynomial add up
, mu :: f
-- ^ Blinding factor required for the Verifier to verify commitments A, S
, t :: f
-- ^ Dot product of vectors l and r that prove knowledge of the value in range
-- t = t(x) = l(x) · r(x)
, aCommit :: p
^ Commitment to aL and aR , where aL and aR are vectors of bits
such that aL · 2^n = v and aR = aL − 1^n .
-- A = α · H + aL · G + aR · H
, sCommit :: p
-- ^ Commitment to new vectors sL, sR, created at random by the Prover
, t1Commit :: p
^ commitment to coefficient t1
, t2Commit :: p
^ commitment to coefficient t2
, productProof :: InnerProductProof f p
-- ^ Inner product argument to prove that a commitment P
-- has vectors l, r ∈ Z^n for which P = l · G + r · H + ( l, r ) · U
} deriving (Show, Eq, Generic, NFData)
data RangeProofError f
= UpperBoundTooLarge Integer -- ^ The upper bound of the range is too large
| ValueNotInRange f -- ^ Value is not within the range required
| ValuesNotInRange [f] -- ^ Values are not within the range required
^ Dimension n is required to be a power of 2
deriving (Show, Eq, Generic, NFData)
-----------------------------
-- Polynomials
-----------------------------
data LRPolys f
= LRPolys
{ l0 :: [f]
, l1 :: [f]
, r0 :: [f]
, r1 :: [f]
}
data TPoly f
= TPoly
{ t0 :: f
, t1 :: f
, t2 :: f
}
-----------------------------
Internal functions
-----------------------------
-- | Encode the value v into a bit representation. Let aL be a vector
of bits such that < aL , 2^n > = v ( put more simply , the components of a L are the
-- binary digits of v).
encodeBit :: Integer -> Fr -> [Fr]
encodeBit n v = fillWithZeros n $ fromIntegral . digitToInt <$> showIntAtBase 2 intToDigit (fromP v) ""
-- | Bits of v reversed.
v = < a , 2^n > = a_0 * 2 ^ 0 + ... + a_n-1 * 2^(n-1 )
reversedEncodeBit :: Integer -> Fr -> [Fr]
reversedEncodeBit n = reverse . encodeBit n
reversedEncodeBitMulti :: Integer -> [Fr] -> [Fr]
reversedEncodeBitMulti n = foldl' (\acc v -> acc ++ reversedEncodeBit n v) []
| In order to prove that v is in range , each element of aL is either 0 or 1 .
-- We construct a “complementary” vector aR = aL − 1^n and require that
aL ◦ aR = 0 hold .
complementaryVector :: Num a => [a] -> [a]
complementaryVector aL = (\vi -> vi - 1) <$> aL
| Add non - relevant zeros to a vector to match the size
-- of the other vectors used in the protocol
fillWithZeros :: Num f => Integer -> [f] -> [f]
fillWithZeros n aL = zeros ++ aL
where
zeros = replicate (fromInteger n - length aL) 0
| Obfuscate encoded bits with challenges y and
z^2 * < aL , 2^n > + z * < aL − 1^n − aR , y^n > + < aL , aR · y^n > = ( z^2 ) * v
The property holds because < aL − 1^n − aR , y^n > = 0 and < aL · aR , y^n > = 0
obfuscateEncodedBits :: Integer -> [Fr] -> [Fr] -> Fr -> Fr -> Fr
obfuscateEncodedBits n aL aR y z
= ((z ^ 2) * dot aL (powerVector 2 n))
+ (z * dot ((aL ^-^ powerVector 1 n) ^-^ aR) yN)
+ dot (hadamard aL aR) yN
where
yN = powerVector y n
Convert obfuscateEncodedBits into a single inner product .
-- We can afford for this factorization to leave terms “dangling”, but
-- what’s important is that the aL , aR terms be kept inside
-- (since they can’t be shared with the Verifier):
< aL − z * 1^n , y^n ◦ ( aR + z * 1^n ) + z^2 * 2^n > = z 2 v + δ(y , z )
obfuscateEncodedBitsSingle :: Integer -> [Fr] -> [Fr] -> Fr -> Fr -> Fr
obfuscateEncodedBitsSingle n aL aR y z
= dot
(aL ^-^ z1n)
(hadamard (powerVector y n) (aR ^+^ z1n) ^+^ ((*) (z ^ 2) <$> powerVector 2 n))
where
z1n = (*) z <$> powerVector 1 n
| We need to blind the vectors aL , aR to make the proof zero knowledge .
The Prover creates randomly vectors sL and sR. On creating these , the
-- Prover can send commitments to these vectors;
these are properly blinded vector commitments :
commitBitVectors
:: (MonadRandom m)
=> Fr
-> Fr
-> [Fr]
-> [Fr]
-> [Fr]
-> [Fr]
-> m (PA, PA)
commitBitVectors aBlinding sBlinding aL aR sL sR = do
let aLG = sumExps aL gs
aRH = sumExps aR hs
sLG = sumExps sL gs
sRH = sumExps sR hs
aBlindingH = mul h aBlinding
sBlindingH = mul h sBlinding
Commitment to aL and aR
let aCommit = aBlindingH <> aLG <> aRH
-- Commitment to sL and sR
let sCommit = sBlindingH <> sLG <> sRH
pure (aCommit, sCommit)
-- | (z − z^2) * <1^n, y^n> − z^3 * <1^n, 2^n>
delta :: Integer -> Integer -> Fr -> Fr -> Fr
delta n m y z
= ((z - (z ^ 2)) * dot (powerVector 1 nm) (powerVector y nm))
- foldl' (\acc j -> acc + ((z ^ (j + 2)) * dot (powerVector 1 n) (powerVector 2 n))) 0 [1..m]
where
nm = n * m
-- | Check that a value is in a specific range
checkRange :: Integer -> Fr -> Bool
checkRange n (fromP -> v) = v >= 0 && v < 2 ^ n
-- | Check that a value is in a specific range
checkRanges :: Integer -> [Fr] -> Bool
checkRanges n vs = and $ fmap (\(fromP -> v) -> v >= 0 && v < 2 ^ n) vs
| Compute commitment of linear vector polynomials l and r
P = A + xS − zG + ( z*y^n + z^2 * 2^n ) * hs '
computeLRCommitment
:: Integer
-> Integer
-> PA
-> PA
-> Fr
-> Fr
-> Fr
-> Fr
-> Fr
-> Fr
-> [PA]
-> PA
computeLRCommitment n m aCommit sCommit t tBlinding mu x y z hs'
= aCommit -- A
<>
(sCommit `mul` x) -- xS
<>
(inv (gsSum `mul` z)) -- (- zG)
<>
( )
<>
foldl'
(\acc j -> acc <> sumExps (hExp' j) (sliceHs' j))
mempty
[1..m]
<>
(inv (h `mul` mu))
<>
(u `mul` t)
where
gsSum = foldl' (<>) mempty (take (fromIntegral nm) gs)
hExp = (*) z <$> powerVector y nm
hExp' j = (*) (z ^ (j+1)) <$> powerVector 2 n
sliceHs' j = slice n j hs'
uChallenge = shamirU tBlinding mu t
u = gen `mul` uChallenge
nm = n * m
| null | https://raw.githubusercontent.com/sdiehl/bulletproofs/6cb356a2ad44dea139abb81214f1babab8456b91/Bulletproofs/RangeProof/Internal.hs | haskell | ^ Blinding factor of the T1 and T2 commitments,
combined into the form required to make the committed version of the x-polynomial add up
^ Blinding factor required for the Verifier to verify commitments A, S
^ Dot product of vectors l and r that prove knowledge of the value in range
t = t(x) = l(x) · r(x)
A = α · H + aL · G + aR · H
^ Commitment to new vectors sL, sR, created at random by the Prover
^ Inner product argument to prove that a commitment P
has vectors l, r ∈ Z^n for which P = l · G + r · H + ( l, r ) · U
^ The upper bound of the range is too large
^ Value is not within the range required
^ Values are not within the range required
---------------------------
Polynomials
---------------------------
---------------------------
---------------------------
| Encode the value v into a bit representation. Let aL be a vector
binary digits of v).
| Bits of v reversed.
We construct a “complementary” vector aR = aL − 1^n and require that
of the other vectors used in the protocol
We can afford for this factorization to leave terms “dangling”, but
what’s important is that the aL , aR terms be kept inside
(since they can’t be shared with the Verifier):
Prover can send commitments to these vectors;
Commitment to sL and sR
| (z − z^2) * <1^n, y^n> − z^3 * <1^n, 2^n>
| Check that a value is in a specific range
| Check that a value is in a specific range
A
xS
(- zG) | # LANGUAGE DeriveGeneric , , ViewPatterns #
module Bulletproofs.RangeProof.Internal where
import Protolude
import Numeric (showIntAtBase)
import Data.Char (intToDigit, digitToInt)
import Control.Monad.Random (MonadRandom)
import Data.Field.Galois (PrimeField(..))
import Data.Curve.Weierstrass.SECP256K1 (PA, Fr, mul, inv, gen)
import Bulletproofs.Utils
import Bulletproofs.InnerProductProof.Internal
data RangeProof f p
= RangeProof
{ tBlinding :: f
, mu :: f
, t :: f
, aCommit :: p
^ Commitment to aL and aR , where aL and aR are vectors of bits
such that aL · 2^n = v and aR = aL − 1^n .
, sCommit :: p
, t1Commit :: p
^ commitment to coefficient t1
, t2Commit :: p
^ commitment to coefficient t2
, productProof :: InnerProductProof f p
} deriving (Show, Eq, Generic, NFData)
data RangeProofError f
^ Dimension n is required to be a power of 2
deriving (Show, Eq, Generic, NFData)
data LRPolys f
= LRPolys
{ l0 :: [f]
, l1 :: [f]
, r0 :: [f]
, r1 :: [f]
}
data TPoly f
= TPoly
{ t0 :: f
, t1 :: f
, t2 :: f
}
Internal functions
of bits such that < aL , 2^n > = v ( put more simply , the components of a L are the
encodeBit :: Integer -> Fr -> [Fr]
encodeBit n v = fillWithZeros n $ fromIntegral . digitToInt <$> showIntAtBase 2 intToDigit (fromP v) ""
v = < a , 2^n > = a_0 * 2 ^ 0 + ... + a_n-1 * 2^(n-1 )
reversedEncodeBit :: Integer -> Fr -> [Fr]
reversedEncodeBit n = reverse . encodeBit n
reversedEncodeBitMulti :: Integer -> [Fr] -> [Fr]
reversedEncodeBitMulti n = foldl' (\acc v -> acc ++ reversedEncodeBit n v) []
| In order to prove that v is in range , each element of aL is either 0 or 1 .
aL ◦ aR = 0 hold .
complementaryVector :: Num a => [a] -> [a]
complementaryVector aL = (\vi -> vi - 1) <$> aL
| Add non - relevant zeros to a vector to match the size
fillWithZeros :: Num f => Integer -> [f] -> [f]
fillWithZeros n aL = zeros ++ aL
where
zeros = replicate (fromInteger n - length aL) 0
| Obfuscate encoded bits with challenges y and
z^2 * < aL , 2^n > + z * < aL − 1^n − aR , y^n > + < aL , aR · y^n > = ( z^2 ) * v
The property holds because < aL − 1^n − aR , y^n > = 0 and < aL · aR , y^n > = 0
obfuscateEncodedBits :: Integer -> [Fr] -> [Fr] -> Fr -> Fr -> Fr
obfuscateEncodedBits n aL aR y z
= ((z ^ 2) * dot aL (powerVector 2 n))
+ (z * dot ((aL ^-^ powerVector 1 n) ^-^ aR) yN)
+ dot (hadamard aL aR) yN
where
yN = powerVector y n
Convert obfuscateEncodedBits into a single inner product .
< aL − z * 1^n , y^n ◦ ( aR + z * 1^n ) + z^2 * 2^n > = z 2 v + δ(y , z )
obfuscateEncodedBitsSingle :: Integer -> [Fr] -> [Fr] -> Fr -> Fr -> Fr
obfuscateEncodedBitsSingle n aL aR y z
= dot
(aL ^-^ z1n)
(hadamard (powerVector y n) (aR ^+^ z1n) ^+^ ((*) (z ^ 2) <$> powerVector 2 n))
where
z1n = (*) z <$> powerVector 1 n
| We need to blind the vectors aL , aR to make the proof zero knowledge .
The Prover creates randomly vectors sL and sR. On creating these , the
these are properly blinded vector commitments :
commitBitVectors
:: (MonadRandom m)
=> Fr
-> Fr
-> [Fr]
-> [Fr]
-> [Fr]
-> [Fr]
-> m (PA, PA)
commitBitVectors aBlinding sBlinding aL aR sL sR = do
let aLG = sumExps aL gs
aRH = sumExps aR hs
sLG = sumExps sL gs
sRH = sumExps sR hs
aBlindingH = mul h aBlinding
sBlindingH = mul h sBlinding
Commitment to aL and aR
let aCommit = aBlindingH <> aLG <> aRH
let sCommit = sBlindingH <> sLG <> sRH
pure (aCommit, sCommit)
delta :: Integer -> Integer -> Fr -> Fr -> Fr
delta n m y z
= ((z - (z ^ 2)) * dot (powerVector 1 nm) (powerVector y nm))
- foldl' (\acc j -> acc + ((z ^ (j + 2)) * dot (powerVector 1 n) (powerVector 2 n))) 0 [1..m]
where
nm = n * m
checkRange :: Integer -> Fr -> Bool
checkRange n (fromP -> v) = v >= 0 && v < 2 ^ n
checkRanges :: Integer -> [Fr] -> Bool
checkRanges n vs = and $ fmap (\(fromP -> v) -> v >= 0 && v < 2 ^ n) vs
| Compute commitment of linear vector polynomials l and r
P = A + xS − zG + ( z*y^n + z^2 * 2^n ) * hs '
computeLRCommitment
:: Integer
-> Integer
-> PA
-> PA
-> Fr
-> Fr
-> Fr
-> Fr
-> Fr
-> Fr
-> [PA]
-> PA
computeLRCommitment n m aCommit sCommit t tBlinding mu x y z hs'
<>
<>
<>
( )
<>
foldl'
(\acc j -> acc <> sumExps (hExp' j) (sliceHs' j))
mempty
[1..m]
<>
(inv (h `mul` mu))
<>
(u `mul` t)
where
gsSum = foldl' (<>) mempty (take (fromIntegral nm) gs)
hExp = (*) z <$> powerVector y nm
hExp' j = (*) (z ^ (j+1)) <$> powerVector 2 n
sliceHs' j = slice n j hs'
uChallenge = shamirU tBlinding mu t
u = gen `mul` uChallenge
nm = n * m
|
7850fd07508921bb8c0d5f03c15b65585e680539d8578e99b6ee8bc7336f2c0b | simonstl/introducing-erlang-2nd | combined.erl | -module(combined).
-export([height_to_mph/1]).
height_to_mph(Meters) -> convert:mps_to_mph(drop:fall_velocity(Meters)). | null | https://raw.githubusercontent.com/simonstl/introducing-erlang-2nd/607e9c85fb767cf5519d331ef6ed549aee51fe61/ch02/ex3-combined/combined.erl | erlang | -module(combined).
-export([height_to_mph/1]).
height_to_mph(Meters) -> convert:mps_to_mph(drop:fall_velocity(Meters)). |
|
d4f553d3ddee712a209f8a1f109edcab69d86e485daf7bf4f0342931d9bef0be | digital-asset/ghc | Main.hs | module Main(main) where
import M1 ()
main :: IO ()
main = return ()
| null | https://raw.githubusercontent.com/digital-asset/ghc/323dc6fcb127f77c08423873efc0a088c071440a/testsuite/tests/warnings/should_compile/T13727/src-exe/Main.hs | haskell | module Main(main) where
import M1 ()
main :: IO ()
main = return ()
|
|
f08f4842f5a912b615011e0dbd34196f9c9cbb066d151fea0b980b0fa3451479 | exercism/babashka | minesweeper_test.clj | (ns minesweeper-test
(:require [clojure.test :refer [deftest is]]
[clojure.string :refer [join]]
[minesweeper :refer [draw]]))
(def line-separator (System/getProperty "line.separator"))
(deftest zero-size-board
(is (= (draw "") "")))
(deftest empty-board
(is (= (draw (join line-separator [" "
" "
" "]))
(join line-separator [" "
" "
" "]))))
(deftest surrounded
(is (= (draw (join line-separator ["***"
"* *"
"***"]))
(join line-separator ["***"
"*8*"
"***"]))))
(deftest board-full-of-mines
(is (= (draw (join line-separator ["***"
"***"
"***"]))
(join line-separator ["***"
"***"
"***"]))))
(deftest horizontal-line
(is (= (draw " * * ")
"1*2*1")))
(deftest vertical-line
(is (= (draw (join line-separator [" "
"*"
" "
"*"
" "]))
(join line-separator ["1"
"*"
"2"
"*"
"1"]))))
(deftest cross
(is (= (draw (join line-separator [" * "
" * "
"*****"
" * "
" * "]))
(join line-separator [" 2*2 "
"25*52"
"*****"
"25*52"
" 2*2 "]))))
| null | https://raw.githubusercontent.com/exercism/babashka/7375f1938ff95b242320313eaeedb8eca31a1b5b/exercises/practice/minesweeper/test/minesweeper_test.clj | clojure | (ns minesweeper-test
(:require [clojure.test :refer [deftest is]]
[clojure.string :refer [join]]
[minesweeper :refer [draw]]))
(def line-separator (System/getProperty "line.separator"))
(deftest zero-size-board
(is (= (draw "") "")))
(deftest empty-board
(is (= (draw (join line-separator [" "
" "
" "]))
(join line-separator [" "
" "
" "]))))
(deftest surrounded
(is (= (draw (join line-separator ["***"
"* *"
"***"]))
(join line-separator ["***"
"*8*"
"***"]))))
(deftest board-full-of-mines
(is (= (draw (join line-separator ["***"
"***"
"***"]))
(join line-separator ["***"
"***"
"***"]))))
(deftest horizontal-line
(is (= (draw " * * ")
"1*2*1")))
(deftest vertical-line
(is (= (draw (join line-separator [" "
"*"
" "
"*"
" "]))
(join line-separator ["1"
"*"
"2"
"*"
"1"]))))
(deftest cross
(is (= (draw (join line-separator [" * "
" * "
"*****"
" * "
" * "]))
(join line-separator [" 2*2 "
"25*52"
"*****"
"25*52"
" 2*2 "]))))
|
|
d1addbe047625c6bc89bcd3a22ea7e4b0dbff51a36d70aa0fa624bfa92e8be2d | rabbitmq/rabbitmq-web-dispatch | rabbit_web_dispatch_SUITE.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_web_dispatch_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
all() ->
[
{group, non_parallel_tests}
].
groups() ->
[
{non_parallel_tests, [], [
query_static_resource_test,
add_idempotence_test,
log_source_address_test,
parse_ip_test
]}
].
%% -------------------------------------------------------------------
%% Test suite setup/teardown.
%% -------------------------------------------------------------------
init_per_suite(Config) ->
rabbit_ct_helpers:log_environment(),
Config1 = rabbit_ct_helpers:set_config(Config, [
{rmq_nodename_suffix, ?MODULE},
{rmq_extra_tcp_ports, [tcp_port_http_extra]}
]),
rabbit_ct_helpers:run_setup_steps(Config1,
rabbit_ct_broker_helpers:setup_steps()).
end_per_suite(Config) ->
rabbit_ct_helpers:run_teardown_steps(Config,
rabbit_ct_broker_helpers:teardown_steps()).
init_per_group(_, Config) ->
Config.
end_per_group(_, Config) ->
Config.
init_per_testcase(Testcase, Config) ->
rabbit_ct_helpers:testcase_started(Config, Testcase).
end_per_testcase(Testcase, Config) ->
rabbit_ct_helpers:testcase_finished(Config, Testcase).
%% -------------------------------------------------------------------
%% Test cases.
%% -------------------------------------------------------------------
query_static_resource_test(Config) ->
Host = rabbit_ct_helpers:get_config(Config, rmq_hostname),
Port = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_http_extra),
rabbit_ct_broker_helpers:rpc(Config, 0, ?MODULE, query_static_resource_test1, [Host, Port]).
query_static_resource_test1(Host, Port) ->
inets:start(),
TODO this is a fairly rubbish test , but not as bad as it was
rabbit_web_dispatch:register_static_context(test, [{port, Port}],
"rabbit_web_dispatch_test",
?MODULE, "test/priv/www", "Test"),
inets:start(),
{ok, {_Status, _Headers, Body}} =
httpc:request(format("http://~s:~w/rabbit_web_dispatch_test/index.html", [Host, Port])),
?assert(string:str(Body, "RabbitMQ HTTP Server Test Page") /= 0),
passed.
add_idempotence_test(Config) ->
Port = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_http_extra),
rabbit_ct_broker_helpers:rpc(Config, 0, ?MODULE, add_idempotence_test1, [Port]).
add_idempotence_test1(Port) ->
inets:start(),
F = fun(_Req) -> ok end,
L = {"/foo", "Foo"},
rabbit_web_dispatch_registry:add(foo, [{port, Port}], F, F, L),
rabbit_web_dispatch_registry:add(foo, [{port, Port}], F, F, L),
?assertEqual(
1, length([ok || {"/foo", _, _} <-
rabbit_web_dispatch_registry:list_all()])),
passed.
parse_ip_test(Config) ->
Port = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_http_extra),
I have to Port + 1 here to have a free port not used by a listener .
rabbit_ct_broker_helpers:rpc(Config, 0, ?MODULE, parse_ip_test1, [Port + 1]).
parse_ip_test1(Port) ->
F = fun(_Req) -> ok end,
L = {"/parse_ip", "ParseIP"},
rabbit_web_dispatch_registry:add(parse_ip, [{port, Port}, {ip, "127.0.0.1"}], F, F, L),
?assertEqual(
1, length([ok || {"/parse_ip", _, _} <-
rabbit_web_dispatch_registry:list_all()])),
passed.
log_source_address_test(Config) ->
Port = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_http_extra),
rabbit_ct_broker_helpers:rpc(Config, 0, ?MODULE, log_source_address_test1, [Port]).
log_source_address_test1(Port) ->
inets:start(),
%% Given: everything in place to issue AND log an HTTP response.
{ok, _} = rabbit_web_dispatch:register_context_handler(log_response_test,
[{port, Port}], path(), table(), description()),
ok = webmachine_log:add_handler(webmachine_log_handler, [log_directory()]),
%% When: when a client makes a request.
{ok, _Response} = httpc:request(get, {":" ++
string(Port) ++ "/" ++ string(path()), []}, [],
[{ip, string(source())}]),
%% Then: log written WITH source IP address AND path.
true = logged(source()),
true = logged(path ()),
true = logged(binary(status())),
passed.
%% Ancillary procedures for log test
%% Resource for testing with.
path() -> <<"wonderland">>.
%% HTTP server port.
port() -> 4096.
%% Log files will be written here.
log_directory() ->
os:getenv("RABBITMQ_LOG_BASE") ++ "/".
%% Source IP address of request.
source() -> <<"127.0.0.1">>.
description() -> "Test that source IP address is logged upon HTTP response.".
status() -> 500.
reason() -> <<"Testing, testing... 1, 2, 3.">>.
%% HTTP server forwarding table.
table() ->
cowboy_router:compile([{source(), [{"/" ++ string(path()), ?MODULE, []}]}]).
%% Cowboy handler callbacks.
init(Req, State) ->
cowboy_req:reply(
status(), #{<<"content-type">> => <<"text/plain">>}, reason(), Req),
{ok, Req, State}.
terminate(_, _, _) ->
ok.
%% Predicate: the given `Text` is read from file.
logged(Text) ->
{ok, Handle} = file:open(log_directory() ++
"access.log" ++ webmachine_log:suffix(webmachine_log:datehour()),
[read, binary]),
logged(Handle, Text).
logged(Handle, Text) ->
case io:get_line(Handle, "") of
eof ->
file:close(Handle),
false;
Line when is_binary(Line) ->
case binary:matches(Line, Text) of
[] ->
logged(Handle, Text);
[{N,_}] when is_integer(N), N >= 0 ->
true
end
end.
%% Convenience procedures.
string(N) when is_integer(N) ->
erlang:integer_to_list(N);
string(B) when is_binary(B) ->
erlang:binary_to_list(B).
binary(N) when is_integer(N) ->
erlang:integer_to_binary(N).
format(Fmt, Val) ->
lists:flatten(io_lib:format(Fmt, Val)).
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-web-dispatch/3fc4f8471bf1afad24bbb07ecad8853d5b3a05a7/test/rabbit_web_dispatch_SUITE.erl | erlang |
-------------------------------------------------------------------
Test suite setup/teardown.
-------------------------------------------------------------------
-------------------------------------------------------------------
Test cases.
-------------------------------------------------------------------
Given: everything in place to issue AND log an HTTP response.
When: when a client makes a request.
Then: log written WITH source IP address AND path.
Ancillary procedures for log test
Resource for testing with.
HTTP server port.
Log files will be written here.
Source IP address of request.
HTTP server forwarding table.
Cowboy handler callbacks.
Predicate: the given `Text` is read from file.
Convenience procedures. | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2020 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_web_dispatch_SUITE).
-compile(export_all).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
all() ->
[
{group, non_parallel_tests}
].
groups() ->
[
{non_parallel_tests, [], [
query_static_resource_test,
add_idempotence_test,
log_source_address_test,
parse_ip_test
]}
].
init_per_suite(Config) ->
rabbit_ct_helpers:log_environment(),
Config1 = rabbit_ct_helpers:set_config(Config, [
{rmq_nodename_suffix, ?MODULE},
{rmq_extra_tcp_ports, [tcp_port_http_extra]}
]),
rabbit_ct_helpers:run_setup_steps(Config1,
rabbit_ct_broker_helpers:setup_steps()).
end_per_suite(Config) ->
rabbit_ct_helpers:run_teardown_steps(Config,
rabbit_ct_broker_helpers:teardown_steps()).
init_per_group(_, Config) ->
Config.
end_per_group(_, Config) ->
Config.
init_per_testcase(Testcase, Config) ->
rabbit_ct_helpers:testcase_started(Config, Testcase).
end_per_testcase(Testcase, Config) ->
rabbit_ct_helpers:testcase_finished(Config, Testcase).
query_static_resource_test(Config) ->
Host = rabbit_ct_helpers:get_config(Config, rmq_hostname),
Port = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_http_extra),
rabbit_ct_broker_helpers:rpc(Config, 0, ?MODULE, query_static_resource_test1, [Host, Port]).
query_static_resource_test1(Host, Port) ->
inets:start(),
TODO this is a fairly rubbish test , but not as bad as it was
rabbit_web_dispatch:register_static_context(test, [{port, Port}],
"rabbit_web_dispatch_test",
?MODULE, "test/priv/www", "Test"),
inets:start(),
{ok, {_Status, _Headers, Body}} =
httpc:request(format("http://~s:~w/rabbit_web_dispatch_test/index.html", [Host, Port])),
?assert(string:str(Body, "RabbitMQ HTTP Server Test Page") /= 0),
passed.
add_idempotence_test(Config) ->
Port = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_http_extra),
rabbit_ct_broker_helpers:rpc(Config, 0, ?MODULE, add_idempotence_test1, [Port]).
add_idempotence_test1(Port) ->
inets:start(),
F = fun(_Req) -> ok end,
L = {"/foo", "Foo"},
rabbit_web_dispatch_registry:add(foo, [{port, Port}], F, F, L),
rabbit_web_dispatch_registry:add(foo, [{port, Port}], F, F, L),
?assertEqual(
1, length([ok || {"/foo", _, _} <-
rabbit_web_dispatch_registry:list_all()])),
passed.
parse_ip_test(Config) ->
Port = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_http_extra),
I have to Port + 1 here to have a free port not used by a listener .
rabbit_ct_broker_helpers:rpc(Config, 0, ?MODULE, parse_ip_test1, [Port + 1]).
parse_ip_test1(Port) ->
F = fun(_Req) -> ok end,
L = {"/parse_ip", "ParseIP"},
rabbit_web_dispatch_registry:add(parse_ip, [{port, Port}, {ip, "127.0.0.1"}], F, F, L),
?assertEqual(
1, length([ok || {"/parse_ip", _, _} <-
rabbit_web_dispatch_registry:list_all()])),
passed.
log_source_address_test(Config) ->
Port = rabbit_ct_broker_helpers:get_node_config(Config, 0, tcp_port_http_extra),
rabbit_ct_broker_helpers:rpc(Config, 0, ?MODULE, log_source_address_test1, [Port]).
log_source_address_test1(Port) ->
inets:start(),
{ok, _} = rabbit_web_dispatch:register_context_handler(log_response_test,
[{port, Port}], path(), table(), description()),
ok = webmachine_log:add_handler(webmachine_log_handler, [log_directory()]),
{ok, _Response} = httpc:request(get, {":" ++
string(Port) ++ "/" ++ string(path()), []}, [],
[{ip, string(source())}]),
true = logged(source()),
true = logged(path ()),
true = logged(binary(status())),
passed.
path() -> <<"wonderland">>.
port() -> 4096.
log_directory() ->
os:getenv("RABBITMQ_LOG_BASE") ++ "/".
source() -> <<"127.0.0.1">>.
description() -> "Test that source IP address is logged upon HTTP response.".
status() -> 500.
reason() -> <<"Testing, testing... 1, 2, 3.">>.
table() ->
cowboy_router:compile([{source(), [{"/" ++ string(path()), ?MODULE, []}]}]).
init(Req, State) ->
cowboy_req:reply(
status(), #{<<"content-type">> => <<"text/plain">>}, reason(), Req),
{ok, Req, State}.
terminate(_, _, _) ->
ok.
logged(Text) ->
{ok, Handle} = file:open(log_directory() ++
"access.log" ++ webmachine_log:suffix(webmachine_log:datehour()),
[read, binary]),
logged(Handle, Text).
logged(Handle, Text) ->
case io:get_line(Handle, "") of
eof ->
file:close(Handle),
false;
Line when is_binary(Line) ->
case binary:matches(Line, Text) of
[] ->
logged(Handle, Text);
[{N,_}] when is_integer(N), N >= 0 ->
true
end
end.
string(N) when is_integer(N) ->
erlang:integer_to_list(N);
string(B) when is_binary(B) ->
erlang:binary_to_list(B).
binary(N) when is_integer(N) ->
erlang:integer_to_binary(N).
format(Fmt, Val) ->
lists:flatten(io_lib:format(Fmt, Val)).
|
c7ca362144191a5aeebcb2533ed68845c34989b8fe0f263581a8796a4a1683a4 | srid/ema | Check.hs | module Ema.Route.Prism.Check (
checkRoutePrismGivenFilePath,
checkRoutePrismGivenRoute,
) where
import Control.Monad.Writer (Writer, runWriter, tell)
import Data.Text qualified as T
import Ema.Route.Prism.Type (Prism_, fromPrism_)
import Optics.Core (Prism', preview, review)
import System.FilePath ((</>))
checkRoutePrismGivenRoute ::
(HasCallStack, Eq r, Show r) =>
(a -> Prism_ FilePath r) ->
a ->
r ->
Either Text ()
checkRoutePrismGivenRoute enc a r =
let s = review (fromPrism_ $ enc a) r
in checkRoutePrism enc a r s
checkRoutePrismGivenFilePath ::
(HasCallStack, Eq r, Show r) =>
(a -> Prism_ FilePath r) ->
a ->
FilePath ->
Either (r, [(FilePath, Text)]) (Maybe r)
checkRoutePrismGivenFilePath enc a s = do
We should treat /foo , /foo.html and / index.html as equivalent .
let candidates = [s, s <> ".html", s </> "index.html"]
rp = fromPrism_ $ enc a
case asum (preview rp <$> candidates) of
Nothing -> pure Nothing
Just r -> do
All candidates must be checked , and if even one passes - we let this
-- route go through.
let (failed, passed) =
partitionEithers $
candidates <&> \candidate ->
case checkRoutePrism enc a r candidate of
Left err -> Left (candidate, err)
Right () -> Right ()
if null passed
then Left (r, failed)
else Right (Just r)
checkRoutePrism :: (Eq r, Show r) => (a -> Prism_ FilePath r) -> a -> r -> FilePath -> Either Text ()
checkRoutePrism p a r s =
let (valid, checkLog) =
runWriter $ routePrismIsLawfulFor p a r s
in if valid
then Right ()
else Left $ "Unlawful route prism for route value '" <> show r <> "'\n- " <> T.intercalate "\n- " checkLog
{- | Check if the route @Prism_@ is lawful.
A route @Prism_@ is lawful if its conversions both the ways form an
isomorphism for a given value.
Returns a Writer reporting logs.
-}
routePrismIsLawfulFor ::
forall ctx a.
(Eq a, Show a) =>
(ctx -> Prism_ FilePath a) ->
ctx ->
a ->
FilePath ->
Writer [Text] Bool
routePrismIsLawfulFor enc =
prismIsLawfulFor . fromPrism_ . enc
prismIsLawfulFor ::
forall s a.
(Eq a, Eq s, Show a, ToText s) =>
Prism' s a ->
a ->
s ->
Writer [Text] Bool
prismIsLawfulFor p a s = do
-- TODO: The logging here could be improved.
-- log $ "Testing Partial ISO law for " <> show a <> " and " <> toText s
let s' :: s = review p a
-- log $ "Prism actual encoding: " <> toText s'
let ma' :: Maybe a = preview p s'
log $ " Decoding of that encoding : " < > show '
unless (s == s') $
log $
toText s <> " /= " <> toText s' <> " (encoding of '" <> show a <> "')"
unless (Just a == ma') $
log $
show (Just a) <> " /= " <> show ma' <> " (decoding of " <> toText s <> ")"
pure $ (s == s') && (Just a == ma')
where
log = tell . one
| null | https://raw.githubusercontent.com/srid/ema/61faae56aa0f3c6ca815f344684cc566f6341662/ema/src/Ema/Route/Prism/Check.hs | haskell | route go through.
| Check if the route @Prism_@ is lawful.
A route @Prism_@ is lawful if its conversions both the ways form an
isomorphism for a given value.
Returns a Writer reporting logs.
TODO: The logging here could be improved.
log $ "Testing Partial ISO law for " <> show a <> " and " <> toText s
log $ "Prism actual encoding: " <> toText s' | module Ema.Route.Prism.Check (
checkRoutePrismGivenFilePath,
checkRoutePrismGivenRoute,
) where
import Control.Monad.Writer (Writer, runWriter, tell)
import Data.Text qualified as T
import Ema.Route.Prism.Type (Prism_, fromPrism_)
import Optics.Core (Prism', preview, review)
import System.FilePath ((</>))
checkRoutePrismGivenRoute ::
(HasCallStack, Eq r, Show r) =>
(a -> Prism_ FilePath r) ->
a ->
r ->
Either Text ()
checkRoutePrismGivenRoute enc a r =
let s = review (fromPrism_ $ enc a) r
in checkRoutePrism enc a r s
checkRoutePrismGivenFilePath ::
(HasCallStack, Eq r, Show r) =>
(a -> Prism_ FilePath r) ->
a ->
FilePath ->
Either (r, [(FilePath, Text)]) (Maybe r)
checkRoutePrismGivenFilePath enc a s = do
We should treat /foo , /foo.html and / index.html as equivalent .
let candidates = [s, s <> ".html", s </> "index.html"]
rp = fromPrism_ $ enc a
case asum (preview rp <$> candidates) of
Nothing -> pure Nothing
Just r -> do
All candidates must be checked , and if even one passes - we let this
let (failed, passed) =
partitionEithers $
candidates <&> \candidate ->
case checkRoutePrism enc a r candidate of
Left err -> Left (candidate, err)
Right () -> Right ()
if null passed
then Left (r, failed)
else Right (Just r)
checkRoutePrism :: (Eq r, Show r) => (a -> Prism_ FilePath r) -> a -> r -> FilePath -> Either Text ()
checkRoutePrism p a r s =
let (valid, checkLog) =
runWriter $ routePrismIsLawfulFor p a r s
in if valid
then Right ()
else Left $ "Unlawful route prism for route value '" <> show r <> "'\n- " <> T.intercalate "\n- " checkLog
routePrismIsLawfulFor ::
forall ctx a.
(Eq a, Show a) =>
(ctx -> Prism_ FilePath a) ->
ctx ->
a ->
FilePath ->
Writer [Text] Bool
routePrismIsLawfulFor enc =
prismIsLawfulFor . fromPrism_ . enc
prismIsLawfulFor ::
forall s a.
(Eq a, Eq s, Show a, ToText s) =>
Prism' s a ->
a ->
s ->
Writer [Text] Bool
prismIsLawfulFor p a s = do
let s' :: s = review p a
let ma' :: Maybe a = preview p s'
log $ " Decoding of that encoding : " < > show '
unless (s == s') $
log $
toText s <> " /= " <> toText s' <> " (encoding of '" <> show a <> "')"
unless (Just a == ma') $
log $
show (Just a) <> " /= " <> show ma' <> " (decoding of " <> toText s <> ")"
pure $ (s == s') && (Just a == ma')
where
log = tell . one
|
63420f4553b92e6694ba2fb93f98df5657076253778181565ca5ccbe1068380a | show-matz/CL-STL | cl-stl-functional.lisp |
(in-package :cl-stl)
(declaim (inline not1
not2
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) bind1st
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) bind2nd
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) ptr_fun1
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) ptr_fun2
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) mem_fun
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) mem_fun_ref
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) mem_fun1
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) mem_fun1_ref
#-cl-stl-0x98 is_placeholder
#-cl-stl-0x98 is_bind_expression
#-cl-stl-0x98 target))
;-------------------------------------------------------------------------------
;
; functor basis
;
;-------------------------------------------------------------------------------
(defclass functor (clonable)
((closure :type cl:function
:initform nil
:initarg :closure
:accessor __functor-closure)))
deprecated in 0x11 or later
deprecated in 0x11 or later
;-------------------------------------------------------------------------------
;
; default methods for functor
;
;-------------------------------------------------------------------------------
(labels ((empty-fnc (&rest args)
(declare (ignore args))
(error 'bad_function_call :what "empty function.")))
(defmethod initialize-instance :after ((fnctr functor) &key)
(let ((closure (__functor-closure fnctr)))
(if (null closure)
(setf (__functor-closure fnctr) #'empty-fnc)
(closer-mop:set-funcallable-instance-function fnctr closure))))
(defmethod (setf __functor-closure) :after (closure (fnctr functor))
(if (null closure)
(setf (__functor-closure fnctr) #'empty-fnc)
(closer-mop:set-funcallable-instance-function fnctr closure))))
(defmethod functor_function ((func cl:function))
func)
(defmethod functor_function ((func functor))
(__functor-closure func))
(defmethod operator_clone ((func cl:function))
func)
(defmethod operator_clone ((func functor))
(make-instance (type-of func)
:closure (__functor-closure func)))
(defmacro define-functor (name (&rest superclasses) (&rest slot-specifiers) &rest class-options)
`(defclass ,name (,@superclasses closer-mop:funcallable-standard-object)
,slot-specifiers
(:metaclass closer-mop:funcallable-standard-class)
,@class-options))
;-------------------------------------------------------------------------------
;
20.3.2 , arithmetic operations :
;
;-------------------------------------------------------------------------------
;------------------------------------------------------------
; class plus
;------------------------------------------------------------
(define-functor plus (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor plus (0))
(labels ((__plus (arg1 arg2) (+ arg1 arg2)))
(define-constructor plus ()
(make-instance 'plus :closure #'__plus)))
;------------------------------------------------------------
; class minus
;------------------------------------------------------------
(define-functor minus (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor minus (0))
(labels ((__minus (arg1 arg2) (- arg1 arg2)))
(define-constructor minus ()
(make-instance 'minus :closure #'__minus)))
;------------------------------------------------------------
; class multiplies
;------------------------------------------------------------
(define-functor multiplies (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor multiplies (0))
(labels ((__multiplies (arg1 arg2) (* arg1 arg2)))
(define-constructor multiplies ()
(make-instance 'multiplies :closure #'__multiplies)))
;------------------------------------------------------------
; class divides
;------------------------------------------------------------
(define-functor divides (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor divides (0))
(labels ((__divides (arg1 arg2) (/ arg1 arg2)))
(define-constructor divides ()
(make-instance 'divides :closure #'__divides)))
;------------------------------------------------------------
; class modulus
;------------------------------------------------------------
(define-functor modulus (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor modulus (0))
(labels ((__modulus (arg1 arg2) (mod arg1 arg2)))
(define-constructor modulus ()
(make-instance 'modulus :closure #'__modulus)))
;------------------------------------------------------------
; class negate
;------------------------------------------------------------
(define-functor negate (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function) ())
(declare-constructor negate (0))
(labels ((__negate (arg) (* -1 arg)))
(define-constructor negate ()
(make-instance 'negate :closure #'__negate)))
;-------------------------------------------------------------------------------
;
; 20.3.3, comparisons:
;
;-------------------------------------------------------------------------------
;------------------------------------------------------------
class equal_to
;------------------------------------------------------------
(define-functor equal_to (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor equal_to-operator)))
(declare-constructor equal_to (0 1))
(labels ((__equal_to-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'equal_to
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor equal_to ()
(__equal_to-ctor #'operator_==))
#-cl-stl-noextra
(define-constructor equal_to (op)
(__equal_to-ctor op))
(defmethod operator_clone ((func equal_to))
(__equal_to-ctor (equal_to-operator func))))
;------------------------------------------------------------
; class not_equal_to
;------------------------------------------------------------
(define-functor not_equal_to (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor not_equal_to-operator)))
(declare-constructor not_equal_to (0 1))
(labels ((__not_equal_to-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'not_equal_to
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor not_equal_to ()
(__not_equal_to-ctor #'operator_/=))
#-cl-stl-noextra
(define-constructor not_equal_to (op)
(__not_equal_to-ctor op))
(defmethod operator_clone ((func not_equal_to))
(__not_equal_to-ctor (not_equal_to-operator func))))
;------------------------------------------------------------
; class greater
;------------------------------------------------------------
(define-functor greater (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor greater-operator)))
(declare-constructor greater (0 1))
(labels ((__greater-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'greater
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor greater ()
(__greater-ctor #'operator_>))
#-cl-stl-noextra
(define-constructor greater (op)
(__greater-ctor op))
(defmethod operator_clone ((func greater))
(__greater-ctor (greater-operator func))))
;------------------------------------------------------------
; class less
;------------------------------------------------------------
(define-functor less (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor less-operator)))
(declare-constructor less (0 1))
(labels ((__less-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'less
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor less ()
(__less-ctor #'operator_<))
#-cl-stl-noextra
(define-constructor less (op)
(__less-ctor op))
(defmethod operator_clone ((func less))
(__less-ctor (less-operator func))))
;------------------------------------------------------------
class greater_equal
;------------------------------------------------------------
(define-functor greater_equal (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor greater_equal-operator)))
(declare-constructor greater_equal (0 1))
(labels ((__greater_equal-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'greater_equal
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor greater_equal ()
(__greater_equal-ctor #'operator_>=))
#-cl-stl-noextra
(define-constructor greater_equal (op)
(__greater_equal-ctor op))
(defmethod operator_clone ((func greater_equal))
(__greater_equal-ctor (greater_equal-operator func))))
;------------------------------------------------------------
; class less_equal
;------------------------------------------------------------
(define-functor less_equal (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor less_equal-operator)))
(declare-constructor less_equal (0 1))
(labels ((__less_equal-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'less_equal
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor less_equal ()
(__less_equal-ctor #'operator_<=))
#-cl-stl-noextra
(define-constructor less_equal (op)
(__less_equal-ctor op))
(defmethod operator_clone ((func less_equal))
(__less_equal-ctor (less_equal-operator func))))
;-------------------------------------------------------------------------------
;
20.3.4 , logical operations :
;
;-------------------------------------------------------------------------------
;------------------------------------------------------------
; class logical_and
;------------------------------------------------------------
(define-functor logical_and (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor logical_and (0))
(labels ((__logical_and (arg1 arg2)
(and arg1 arg2)))
(define-constructor logical_and ()
(make-instance 'logical_and :closure #'__logical_and)))
;------------------------------------------------------------
class logical_or
;------------------------------------------------------------
(define-functor logical_or (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor logical_or (0))
(labels ((__logical_or (arg1 arg2)
(or arg1 arg2)))
(define-constructor logical_or ()
(make-instance 'logical_or :closure #'__logical_or)))
;------------------------------------------------------------
; class logical_not
;------------------------------------------------------------
(define-functor logical_not (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function) ())
(declare-constructor logical_not (0))
(labels ((__logical_not (arg)
(not arg)))
(define-constructor logical_not ()
(make-instance 'logical_not :closure #'__logical_not)))
;-------------------------------------------------------------------------------
;
; 20.3.5, negators:
;
;-------------------------------------------------------------------------------
;------------------------------------------------------------
class unary_negate & function not1
;------------------------------------------------------------
(define-functor unary_negate (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :initform nil
:initarg :operator
:accessor unary_negate-operator)))
(declare-constructor unary_negate (1))
(define-constructor unary_negate (op)
#+cl-stl-warn-deprecated
(progn
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(warn "unary_negate is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'unary_negate
:operator op
:closure (lambda (arg)
(not (funcall fnc arg))))))
(defun not1 (op)
#+cl-stl-warn-deprecated
(progn
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(warn "not1 is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'unary_negate
:operator op
:closure (lambda (arg)
(not (funcall fnc arg))))))
(defmethod operator_clone ((func unary_negate))
(let* ((op (clone (unary_negate-operator func)))
(fnc (functor_function op)))
(make-instance 'unary_negate
:operator op
:closure (lambda (arg)
(not (funcall fnc arg))))))
;------------------------------------------------------------
; class binary_negate & function not2
;------------------------------------------------------------
(define-functor binary_negate (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor binary_negate-operator)))
(declare-constructor binary_negate (1))
(define-constructor binary_negate (op)
#+cl-stl-warn-deprecated
(progn
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(warn "binary_negate is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'binary_negate
:operator op
:closure (lambda (arg1 arg2)
(not (funcall fnc arg1 arg2))))))
(defun not2 (op)
#+cl-stl-warn-deprecated
(progn
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(warn "not2 is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'binary_negate
:operator op
:closure (lambda (arg1 arg2)
(not (funcall fnc arg1 arg2))))))
(defmethod operator_clone ((func binary_negate))
(let* ((op (clone (binary_negate-operator func)))
(fnc (functor_function op)))
(make-instance 'binary_negate
:operator op
:closure (lambda (arg1 arg2)
(not (funcall fnc arg1 arg2))))))
;-------------------------------------------------------------------------------
;
20.3.6 , binders :
;
;-------------------------------------------------------------------------------
;------------------------------------------------------------
class binder1st & function bind1st
;------------------------------------------------------------
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor binder1st (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :initform nil
:initarg :operator
:accessor binder1st-operator)
(arg :initform nil
:initarg :arg
:accessor binder1st-arg)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor binder1st (2))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor binder1st (op arg1)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "binder1st is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'binder1st
:operator op
:arg arg1
:closure (lambda (arg2)
(funcall fnc arg1 arg2)))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun bind1st (functor arg)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "bind1st is deprecated."))
(let* ((op (clone functor))
(fnc (functor_function op)))
(make-instance 'binder1st
:operator op
:arg arg
:closure (lambda (arg2)
(funcall fnc arg arg2)))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func binder1st))
(let* ((op (clone (binder1st-operator func)))
(arg1 (binder1st-arg func))
(fnc (functor_function op)))
(make-instance 'binder1st
:operator op
:arg arg1
:closure (lambda (arg2)
(funcall fnc arg1 arg2)))))
;------------------------------------------------------------
class binder2nd & function bind2nd
;------------------------------------------------------------
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor binder2nd (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :initform nil
:initarg :operator
:accessor binder2nd-operator)
(arg :initform nil
:initarg :arg
:accessor binder2nd-arg)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor binder2nd (2))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor binder2nd (op arg2)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "binder2nd is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'binder2nd
:operator op
:arg arg2
:closure (lambda (arg1)
(funcall fnc arg1 arg2)))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun bind2nd (functor arg)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "bind2nd is deprecated."))
(let* ((op (clone functor))
(fnc (functor_function op)))
(make-instance 'binder2nd
:operator op
:arg arg
:closure (lambda (arg1)
(funcall fnc arg1 arg)))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func binder2nd))
(let* ((op (clone (binder2nd-operator func)))
(arg2 (binder2nd-arg func))
(fnc (functor_function op)))
(make-instance 'binder2nd
:operator op
:arg arg2
:closure (lambda (arg1)
(funcall fnc arg1 arg2)))))
;-------------------------------------------------------------------------------
;
20.3.7 , adaptors :
;
;-------------------------------------------------------------------------------
;------------------------------------------------------------
class pointer_to_unary_function & function ptr_fun1
( NONSENSE in CL - STL )
;------------------------------------------------------------
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor pointer_to_unary_function (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :type cl:function
:initform nil
:initarg :operator
:accessor pointer_to_unary_function-operator)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor pointer_to_unary_function (1))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor pointer_to_unary_function (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "pointer_to_unary_function is deprecated."))
(make-instance 'pointer_to_unary_function
:operator func
:closure (lambda (arg)
(funcall func arg))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun ptr_fun1 (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "ptr_fun1 is deprecated."))
(make-instance 'pointer_to_unary_function
:operator func
:closure (lambda (arg)
(funcall func arg))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func pointer_to_unary_function))
(let ((func (pointer_to_unary_function-operator func)))
(make-instance 'pointer_to_unary_function
:operator func
:closure (lambda (arg)
(funcall func arg)))))
;------------------------------------------------------------
; class pointer_to_binary_function & function ptr_fun2
( NONSENSE in CL - STL )
;------------------------------------------------------------
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor pointer_to_binary_function (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :type cl:function
:initform nil
:initarg :operator
:accessor pointer_to_binary_function-operator)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor pointer_to_binary_function (1))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor pointer_to_binary_function (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "pointer_to_binary_function is deprecated."))
(make-instance 'pointer_to_binary_function
:operator func
:closure (lambda (arg1 arg2)
(funcall func arg1 arg2))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun ptr_fun2 (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "ptr_fun2 is deprecated."))
(make-instance 'pointer_to_binary_function
:operator func
:closure (lambda (arg1 arg2)
(funcall func arg1 arg2))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func pointer_to_binary_function))
(let ((func (pointer_to_binary_function-operator func)))
(make-instance 'pointer_to_binary_function
:operator func
:closure (lambda (arg1 arg2)
(funcall func arg1 arg2)))))
;-------------------------------------------------------------------------------
;
20.3.8 , adaptors :
;
;-------------------------------------------------------------------------------
;------------------------------------------------------------
class & function mem_fun etc .
( NONSENSE in CL - STL )
;------------------------------------------------------------
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor mem_fun_t (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :type cl:function
:initform nil
:initarg :operator
:accessor mem_fun_t-operator)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor mem_fun_t (1))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor mem_fun_t (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun_t is deprecated."))
(make-instance 'mem_fun_t
:operator func
:closure (lambda (obj)
(funcall func obj))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun mem_fun (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun is deprecated."))
(make-instance 'mem_fun_t
:operator func
:closure (lambda (obj)
(funcall func obj))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun mem_fun_ref (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun_ref is deprecated."))
(make-instance 'mem_fun_t
:operator func
:closure (lambda (obj)
(funcall func obj))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func mem_fun_t))
(let ((func (mem_fun_t-operator func)))
(make-instance 'mem_fun_t
:operator func
:closure (lambda (obj)
(funcall func obj)))))
;------------------------------------------------------------
class mem_fun1_t & function mem_fun1 etc .
( NONSENSE in CL - STL )
;------------------------------------------------------------
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor mem_fun1_t (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :type cl:function
:initform nil
:initarg :operator
:accessor mem_fun1_t-operator)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor mem_fun1_t (1))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor mem_fun1_t (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun1_t is deprecated."))
(make-instance 'mem_fun1_t
:operator func
:closure (lambda (obj arg)
(funcall func obj arg))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun mem_fun1 (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun1 is deprecated."))
(make-instance 'mem_fun1_t
:operator func
:closure (lambda (obj arg)
(funcall func obj arg))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun mem_fun1_ref (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun1_ref is deprecated."))
(make-instance 'mem_fun1_t
:operator func
:closure (lambda (obj arg)
(funcall func obj arg))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func mem_fun1_t))
(let ((func (mem_fun1_t-operator func)))
(make-instance 'mem_fun1_t
:operator func
:closure (lambda (obj arg)
(funcall func obj arg)))))
;------------------------------------------------------------
; class mem_fun_ref-t;
;------------------------------------------------------------
-- > use instead .
;------------------------------------------------------------
; class mem_fun1_ref-t;
;------------------------------------------------------------
; --> use mem_fun1_t instead.
;-------------------------------------------------------------------------------
;
; 0x11
;
;-------------------------------------------------------------------------------
#-cl-stl-0x98
(defun is_placeholder (arg)
(if (not (keywordp arg))
0
(handler-case (values (parse-integer (symbol-name arg)))
(error () 0))))
#-cl-stl-0x98
(defun is_bind_expression (arg)
(eq (type-of arg) '__binded-expr))
;------------------------------------------------------------
; class __binded-expr
;------------------------------------------------------------
#-cl-stl-0x98
(define-functor __binded-expr (functor)
((bindee :initarg :bindee
:accessor __binded-expr-bindee)
(params :type cl:vector
:initarg :params
:accessor __binded-expr-params)
(cloner :type cl:function
:initarg :cloner
:accessor __binded-expr-cloner)))
#-cl-stl-0x98
(defmethod operator_clone ((func __binded-expr))
(funcall (__binded-expr-cloner func) func))
;------------------------------------------------------------
; bind macro
;------------------------------------------------------------
#-cl-stl-0x98
(defmacro bind (func &rest args)
(let ((max-arg 0)
(arg-hash (make-hash-table)))
(labels ((get-argsym (idx)
(let ((is-new nil)
(ret (gethash idx arg-hash)))
(unless ret
(setf ret (gensym (format nil "ARG~A-" idx)))
(setf (gethash idx arg-hash) ret)
(setf is-new t)
(when (< max-arg idx)
(setf max-arg idx)))
(values ret is-new)))
(make-lambda-list (idx lambda-list ignore-list)
(if (< max-arg idx)
(values (nreverse lambda-list)
(nreverse ignore-list))
(multiple-value-bind (sym is-new) (get-argsym idx)
(cl:push sym lambda-list)
(when is-new
(cl:push sym ignore-list))
(make-lambda-list (1+ idx) lambda-list ignore-list))))
(imp (args acc1 acc2 prm-sym &optional (idx 0))
(if (null args)
(values (nreverse acc1)
(nreverse acc2))
(let* ((item (car args))
(ret (is_placeholder item)))
(if (< 0 ret)
(cl:push (get-argsym ret) acc2)
(progn
(cl:push `(aref ,prm-sym ,idx) acc2)
(cl:push `(_= (aref ,prm-sym ,idx) ,(car args)) acc1)
(incf idx)))
(imp (cdr args) acc1 acc2 prm-sym idx)))))
(let ((g-imp (gensym "IMP"))
(g-fnc (gensym "FNC"))
(g-bindee (gensym "BINDEE"))
(g-bd-fnc (gensym "BD-FNC"))
(g-params (gensym "PARAMS"))
(g-cloner (gensym "CLONER")))
(multiple-value-bind (arg-lst prm-lst) (imp args nil nil g-params)
(multiple-value-bind (lambda-list ignore-list) (make-lambda-list 1 nil nil)
`(labels ((,g-imp (,g-bindee ,g-params ,g-cloner)
(declare (type cl:vector ,g-params))
(let ((,g-bd-fnc (functor_function ,g-bindee)))
(declare (type cl:function ,g-bd-fnc))
(make-instance '__binded-expr
:bindee ,g-bindee :params ,g-params :cloner ,g-cloner
:closure (lambda (,@lambda-list)
,(when ignore-list
`(declare (ignore ,@ignore-list)))
(funcall ,g-bd-fnc ,@prm-lst))))))
(let* ((,g-bindee (clone ,func))
(,g-params (make-array ,(length arg-lst) :initial-element nil))
(,g-cloner (lambda (,g-fnc)
(,g-imp (clone (__binded-expr-bindee ,g-fnc))
(clone (__binded-expr-params ,g-fnc))
(__binded-expr-cloner ,g-fnc)))))
,@arg-lst
(,g-imp ,g-bindee ,g-params ,g-cloner)))))))))
;------------------------------------------------------------
; class function
;------------------------------------------------------------
#-cl-stl-0x98
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-functor function (functor)
((target :initform nil
:initarg :target
:accessor __function-target))))
#-cl-stl-0x98
(declare-constructor function (0 1))
#-cl-stl-0x98
(labels ((__function-ctor (op)
(if (null op)
(make-instance 'function :target nil :closure nil)
(let* ((target (clone op)))
(make-instance 'function
:target target
:closure (functor_function target))))))
(define-constructor function ()
(__function-ctor nil))
(define-constructor function ((op (eql nil)))
(__function-ctor nil))
(define-constructor function ((op cl:function))
(__function-ctor op))
(define-constructor function ((op functor))
(__function-ctor op))
(define-constructor function ((fn function))
(__function-ctor (__function-target fn)))
(defmethod operator_clone ((fn function))
(__function-ctor (__function-target fn))))
#-cl-stl-0x98
(define-constructor function ((rm& remove-reference))
(with-reference (rm)
(let ((fnctr rm))
(__check-type-of-move-constructor fnctr function)
(let ((target (__function-target fnctr))
(closure (__functor-closure fnctr)))
(setf (__function-target fnctr) nil)
(setf (__functor-closure fnctr) nil)
(make-instance 'function :target target :closure closure)))))
#-cl-stl-0x98
(defmethod operator_cast ((fn function) (typename (eql 'boolean)))
(if (__function-target fn) t nil))
#-cl-stl-0x98
(locally (declare (optimize speed))
(labels ((__assign (fnc op)
(declare (type function fnc))
(if (null op)
(progn
(setf (__function-target fnc) nil)
(setf (__functor-closure fnc) nil))
(let* ((target (clone op))
(closure (functor_function op)))
(setf (__function-target fnc) target)
(setf (__functor-closure fnc) closure)))))
(declare (inline __assign))
(defmethod operator_= ((lhs function) rhs)
(error 'type-mismatch :what (format nil "Can't convert ~A to stl:function." rhs))
lhs)
(defmethod operator_= ((lhs function) (rhs function))
(__assign lhs (__function-target rhs))
lhs)
(defmethod operator_= ((lhs function) (rhs (eql nil)))
(setf (__function-target lhs) nil)
(setf (__functor-closure lhs) nil)
lhs)
(defmethod-overload assign ((this function) (fnc function))
(__assign this (__function-target fnc))
nil)
(defmethod-overload assign ((this function) (fnc (eql nil)))
(setf (__function-target this) nil)
(setf (__functor-closure this) nil)
nil)))
#-cl-stl-0x98
(defmethod operator_move ((lhs function) (rhs function))
(unless (eq lhs rhs)
(setf (__function-target lhs) (__function-target rhs))
(setf (__functor-closure lhs) (__functor-closure rhs))
(setf (__function-target rhs) nil)
(setf (__functor-closure rhs) nil))
(values lhs rhs))
#-cl-stl-0x98
(defmethod-overload swap ((fn1 function) (fn2 function))
(let ((op (__function-target fn1))
(fn (__functor-closure fn1)))
(setf (__function-target fn1) (__function-target fn2))
(setf (__functor-closure fn1) (__functor-closure fn2))
(setf (__function-target fn2) op)
(setf (__functor-closure fn2) fn))
(values fn1 fn2))
#-cl-stl-0x98
(defun target (fn)
(__function-target fn))
#-cl-stl-0x98
(locally (declare (optimize speed))
(labels ((__empty (fn)
(declare (type function fn))
(if (__function-target fn) nil t)))
(declare (inline __empty))
(defmethod operator_== ((fn function) (rhs (eql nil))) (__empty fn))
(defmethod operator_== ((lhs (eql nil)) (fn function)) (__empty fn))
(defmethod operator_/= ((fn function) (rhs (eql nil))) (not (__empty fn)))
(defmethod operator_/= ((lhs (eql nil)) (fn function)) (not (__empty fn)))))
;------------------------------------------------------------
; class bit_and
;------------------------------------------------------------
#-cl-stl-0x98
(define-functor bit_and (functor) ())
#-cl-stl-0x98
(declare-constructor bit_and (0))
#-cl-stl-0x98
(labels ((__bit_and (arg1 arg2) (logand arg1 arg2)))
(define-constructor bit_and ()
(make-instance 'bit_and :closure #'__bit_and)))
;------------------------------------------------------------
; class bit_or
;------------------------------------------------------------
#-cl-stl-0x98
(define-functor bit_or (functor) ())
#-cl-stl-0x98
(declare-constructor bit_or (0))
#-cl-stl-0x98
(labels ((__bit_or (arg1 arg2) (logior arg1 arg2)))
(define-constructor bit_or ()
(make-instance 'bit_or :closure #'__bit_or)))
;------------------------------------------------------------
; class bit_xor
;------------------------------------------------------------
#-cl-stl-0x98
(define-functor bit_xor (functor) ())
#-cl-stl-0x98
(declare-constructor bit_xor (0))
#-cl-stl-0x98
(labels ((__bit_xor (arg1 arg2) (logxor arg1 arg2)))
(define-constructor bit_xor ()
(make-instance 'bit_xor :closure #'__bit_xor)))
;;------------------------------------------------------------
;; class mem_fn
;;------------------------------------------------------------
#-cl-stl-0x98
(define-functor mem_fn (functor)
((method :type cl:function
:initform nil
:initarg :method
:accessor mem_fn-method)))
#-cl-stl-0x98
(declare-constructor mem_fn (1))
#-cl-stl-0x98
(labels ((__mem_fn-ctor (method)
(make-instance 'mem_fn
:method method
:closure (lambda (&rest args)
(cl:apply method args)))))
(define-constructor mem_fn (method)
(__mem_fn-ctor method))
(defmethod operator_clone ((func mem_fn))
(__mem_fn-ctor (mem_fn-method func))))
;;------------------------------------------------------------
;; function apply
;;------------------------------------------------------------
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(locally (declare (optimize speed))
(defun apply (fnc tpl)
(let ((arr (__inner-array tpl)))
(declare (type simple-vector arr))
(let ((cnt (length arr)))
(declare (type fixnum cnt))
(case cnt
(2 (locally (declare (type (simple-vector 2) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1))))
(3 (locally (declare (type (simple-vector 3) arr))
(cl:funcall fnc (svref arr 0)
(svref arr 1) (svref arr 2))))
(4 (locally (declare (type (simple-vector 4) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3))))
(5 (locally (declare (type (simple-vector 5) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3) (svref arr 4))))
(6 (locally (declare (type (simple-vector 6) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3)
(svref arr 4) (svref arr 5))))
(7 (locally (declare (type (simple-vector 7) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3)
(svref arr 4) (svref arr 5) (svref arr 6))))
(8 (locally (declare (type (simple-vector 8) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3)
(svref arr 4) (svref arr 5)
(svref arr 6) (svref arr 7))))
(9 (locally (declare (type (simple-vector 9) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3)
(svref arr 4) (svref arr 5)
(svref arr 6) (svref arr 7) (svref arr 8))))
(t (cl:apply fnc (coerce arr 'cl:list))))))))
;;------------------------------------------------------------
;; function not_fn
;;------------------------------------------------------------
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor __not_fn (functor)
((op :initform nil
:initarg :operator
:accessor __not_fn-operator)))
;;#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
( declare - constructor _ _ not_fn ( 2 ) )
;;
;;#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
;;(define-constructor __not_fn (op)
;; (let* ((op (clone op))
( fnc ( functor_function op ) ) )
;; (make-instance '__not_fn
;; :operator op
;; :closure (lambda (&rest params)
( _ ! ( cl : apply ) ) ) ) ) )
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun not_fn (functor)
(let* ((op (clone functor))
(fnc (functor_function op)))
(make-instance '__not_fn
:operator op
:closure (lambda (&rest params)
(_! (cl:apply fnc params))))))
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func __not_fn))
(let* ((op (clone (__not_fn-operator func)))
(fnc (functor_function op)))
(make-instance '__not_fn
:operator op
:closure (lambda (&rest params)
(_! (cl:apply fnc params))))))
| null | https://raw.githubusercontent.com/show-matz/CL-STL/c6ffeac2815fa933121bc4c8b331d9c3516dff88/src/cl-stl-functional.lisp | lisp | -------------------------------------------------------------------------------
functor basis
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
default methods for functor
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
------------------------------------------------------------
class plus
------------------------------------------------------------
------------------------------------------------------------
class minus
------------------------------------------------------------
------------------------------------------------------------
class multiplies
------------------------------------------------------------
------------------------------------------------------------
class divides
------------------------------------------------------------
------------------------------------------------------------
class modulus
------------------------------------------------------------
------------------------------------------------------------
class negate
------------------------------------------------------------
-------------------------------------------------------------------------------
20.3.3, comparisons:
-------------------------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
class not_equal_to
------------------------------------------------------------
------------------------------------------------------------
class greater
------------------------------------------------------------
------------------------------------------------------------
class less
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
class less_equal
------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
------------------------------------------------------------
class logical_and
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
class logical_not
------------------------------------------------------------
-------------------------------------------------------------------------------
20.3.5, negators:
-------------------------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
class binary_negate & function not2
------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
class pointer_to_binary_function & function ptr_fun2
------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
class mem_fun_ref-t;
------------------------------------------------------------
------------------------------------------------------------
class mem_fun1_ref-t;
------------------------------------------------------------
--> use mem_fun1_t instead.
-------------------------------------------------------------------------------
0x11
-------------------------------------------------------------------------------
------------------------------------------------------------
class __binded-expr
------------------------------------------------------------
------------------------------------------------------------
bind macro
------------------------------------------------------------
------------------------------------------------------------
class function
------------------------------------------------------------
------------------------------------------------------------
class bit_and
------------------------------------------------------------
------------------------------------------------------------
class bit_or
------------------------------------------------------------
------------------------------------------------------------
class bit_xor
------------------------------------------------------------
------------------------------------------------------------
class mem_fn
------------------------------------------------------------
------------------------------------------------------------
function apply
------------------------------------------------------------
------------------------------------------------------------
function not_fn
------------------------------------------------------------
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor __not_fn (op)
(let* ((op (clone op))
(make-instance '__not_fn
:operator op
:closure (lambda (&rest params) |
(in-package :cl-stl)
(declaim (inline not1
not2
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) bind1st
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) bind2nd
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) ptr_fun1
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) ptr_fun2
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) mem_fun
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) mem_fun_ref
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) mem_fun1
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14) mem_fun1_ref
#-cl-stl-0x98 is_placeholder
#-cl-stl-0x98 is_bind_expression
#-cl-stl-0x98 target))
(defclass functor (clonable)
((closure :type cl:function
:initform nil
:initarg :closure
:accessor __functor-closure)))
deprecated in 0x11 or later
deprecated in 0x11 or later
(labels ((empty-fnc (&rest args)
(declare (ignore args))
(error 'bad_function_call :what "empty function.")))
(defmethod initialize-instance :after ((fnctr functor) &key)
(let ((closure (__functor-closure fnctr)))
(if (null closure)
(setf (__functor-closure fnctr) #'empty-fnc)
(closer-mop:set-funcallable-instance-function fnctr closure))))
(defmethod (setf __functor-closure) :after (closure (fnctr functor))
(if (null closure)
(setf (__functor-closure fnctr) #'empty-fnc)
(closer-mop:set-funcallable-instance-function fnctr closure))))
(defmethod functor_function ((func cl:function))
func)
(defmethod functor_function ((func functor))
(__functor-closure func))
(defmethod operator_clone ((func cl:function))
func)
(defmethod operator_clone ((func functor))
(make-instance (type-of func)
:closure (__functor-closure func)))
(defmacro define-functor (name (&rest superclasses) (&rest slot-specifiers) &rest class-options)
`(defclass ,name (,@superclasses closer-mop:funcallable-standard-object)
,slot-specifiers
(:metaclass closer-mop:funcallable-standard-class)
,@class-options))
20.3.2 , arithmetic operations :
(define-functor plus (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor plus (0))
(labels ((__plus (arg1 arg2) (+ arg1 arg2)))
(define-constructor plus ()
(make-instance 'plus :closure #'__plus)))
(define-functor minus (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor minus (0))
(labels ((__minus (arg1 arg2) (- arg1 arg2)))
(define-constructor minus ()
(make-instance 'minus :closure #'__minus)))
(define-functor multiplies (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor multiplies (0))
(labels ((__multiplies (arg1 arg2) (* arg1 arg2)))
(define-constructor multiplies ()
(make-instance 'multiplies :closure #'__multiplies)))
(define-functor divides (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor divides (0))
(labels ((__divides (arg1 arg2) (/ arg1 arg2)))
(define-constructor divides ()
(make-instance 'divides :closure #'__divides)))
(define-functor modulus (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor modulus (0))
(labels ((__modulus (arg1 arg2) (mod arg1 arg2)))
(define-constructor modulus ()
(make-instance 'modulus :closure #'__modulus)))
(define-functor negate (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function) ())
(declare-constructor negate (0))
(labels ((__negate (arg) (* -1 arg)))
(define-constructor negate ()
(make-instance 'negate :closure #'__negate)))
class equal_to
(define-functor equal_to (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor equal_to-operator)))
(declare-constructor equal_to (0 1))
(labels ((__equal_to-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'equal_to
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor equal_to ()
(__equal_to-ctor #'operator_==))
#-cl-stl-noextra
(define-constructor equal_to (op)
(__equal_to-ctor op))
(defmethod operator_clone ((func equal_to))
(__equal_to-ctor (equal_to-operator func))))
(define-functor not_equal_to (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor not_equal_to-operator)))
(declare-constructor not_equal_to (0 1))
(labels ((__not_equal_to-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'not_equal_to
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor not_equal_to ()
(__not_equal_to-ctor #'operator_/=))
#-cl-stl-noextra
(define-constructor not_equal_to (op)
(__not_equal_to-ctor op))
(defmethod operator_clone ((func not_equal_to))
(__not_equal_to-ctor (not_equal_to-operator func))))
(define-functor greater (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor greater-operator)))
(declare-constructor greater (0 1))
(labels ((__greater-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'greater
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor greater ()
(__greater-ctor #'operator_>))
#-cl-stl-noextra
(define-constructor greater (op)
(__greater-ctor op))
(defmethod operator_clone ((func greater))
(__greater-ctor (greater-operator func))))
(define-functor less (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor less-operator)))
(declare-constructor less (0 1))
(labels ((__less-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'less
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor less ()
(__less-ctor #'operator_<))
#-cl-stl-noextra
(define-constructor less (op)
(__less-ctor op))
(defmethod operator_clone ((func less))
(__less-ctor (less-operator func))))
class greater_equal
(define-functor greater_equal (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor greater_equal-operator)))
(declare-constructor greater_equal (0 1))
(labels ((__greater_equal-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'greater_equal
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor greater_equal ()
(__greater_equal-ctor #'operator_>=))
#-cl-stl-noextra
(define-constructor greater_equal (op)
(__greater_equal-ctor op))
(defmethod operator_clone ((func greater_equal))
(__greater_equal-ctor (greater_equal-operator func))))
(define-functor less_equal (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor less_equal-operator)))
(declare-constructor less_equal (0 1))
(labels ((__less_equal-ctor (op)
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'less_equal
:operator op
:closure (lambda (arg1 arg2)
(funcall fnc arg1 arg2))))))
(define-constructor less_equal ()
(__less_equal-ctor #'operator_<=))
#-cl-stl-noextra
(define-constructor less_equal (op)
(__less_equal-ctor op))
(defmethod operator_clone ((func less_equal))
(__less_equal-ctor (less_equal-operator func))))
20.3.4 , logical operations :
(define-functor logical_and (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor logical_and (0))
(labels ((__logical_and (arg1 arg2)
(and arg1 arg2)))
(define-constructor logical_and ()
(make-instance 'logical_and :closure #'__logical_and)))
class logical_or
(define-functor logical_or (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function) ())
(declare-constructor logical_or (0))
(labels ((__logical_or (arg1 arg2)
(or arg1 arg2)))
(define-constructor logical_or ()
(make-instance 'logical_or :closure #'__logical_or)))
(define-functor logical_not (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function) ())
(declare-constructor logical_not (0))
(labels ((__logical_not (arg)
(not arg)))
(define-constructor logical_not ()
(make-instance 'logical_not :closure #'__logical_not)))
class unary_negate & function not1
(define-functor unary_negate (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :initform nil
:initarg :operator
:accessor unary_negate-operator)))
(declare-constructor unary_negate (1))
(define-constructor unary_negate (op)
#+cl-stl-warn-deprecated
(progn
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(warn "unary_negate is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'unary_negate
:operator op
:closure (lambda (arg)
(not (funcall fnc arg))))))
(defun not1 (op)
#+cl-stl-warn-deprecated
(progn
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(warn "not1 is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'unary_negate
:operator op
:closure (lambda (arg)
(not (funcall fnc arg))))))
(defmethod operator_clone ((func unary_negate))
(let* ((op (clone (unary_negate-operator func)))
(fnc (functor_function op)))
(make-instance 'unary_negate
:operator op
:closure (lambda (arg)
(not (funcall fnc arg))))))
(define-functor binary_negate (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :initform nil
:initarg :operator
:accessor binary_negate-operator)))
(declare-constructor binary_negate (1))
(define-constructor binary_negate (op)
#+cl-stl-warn-deprecated
(progn
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(warn "binary_negate is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'binary_negate
:operator op
:closure (lambda (arg1 arg2)
(not (funcall fnc arg1 arg2))))))
(defun not2 (op)
#+cl-stl-warn-deprecated
(progn
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(warn "not2 is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'binary_negate
:operator op
:closure (lambda (arg1 arg2)
(not (funcall fnc arg1 arg2))))))
(defmethod operator_clone ((func binary_negate))
(let* ((op (clone (binary_negate-operator func)))
(fnc (functor_function op)))
(make-instance 'binary_negate
:operator op
:closure (lambda (arg1 arg2)
(not (funcall fnc arg1 arg2))))))
20.3.6 , binders :
class binder1st & function bind1st
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor binder1st (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :initform nil
:initarg :operator
:accessor binder1st-operator)
(arg :initform nil
:initarg :arg
:accessor binder1st-arg)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor binder1st (2))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor binder1st (op arg1)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "binder1st is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'binder1st
:operator op
:arg arg1
:closure (lambda (arg2)
(funcall fnc arg1 arg2)))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun bind1st (functor arg)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "bind1st is deprecated."))
(let* ((op (clone functor))
(fnc (functor_function op)))
(make-instance 'binder1st
:operator op
:arg arg
:closure (lambda (arg2)
(funcall fnc arg arg2)))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func binder1st))
(let* ((op (clone (binder1st-operator func)))
(arg1 (binder1st-arg func))
(fnc (functor_function op)))
(make-instance 'binder1st
:operator op
:arg arg1
:closure (lambda (arg2)
(funcall fnc arg1 arg2)))))
class binder2nd & function bind2nd
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor binder2nd (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :initform nil
:initarg :operator
:accessor binder2nd-operator)
(arg :initform nil
:initarg :arg
:accessor binder2nd-arg)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor binder2nd (2))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor binder2nd (op arg2)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "binder2nd is deprecated."))
(let* ((op (clone op))
(fnc (functor_function op)))
(make-instance 'binder2nd
:operator op
:arg arg2
:closure (lambda (arg1)
(funcall fnc arg1 arg2)))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun bind2nd (functor arg)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "bind2nd is deprecated."))
(let* ((op (clone functor))
(fnc (functor_function op)))
(make-instance 'binder2nd
:operator op
:arg arg
:closure (lambda (arg1)
(funcall fnc arg1 arg)))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func binder2nd))
(let* ((op (clone (binder2nd-operator func)))
(arg2 (binder2nd-arg func))
(fnc (functor_function op)))
(make-instance 'binder2nd
:operator op
:arg arg2
:closure (lambda (arg1)
(funcall fnc arg1 arg2)))))
20.3.7 , adaptors :
class pointer_to_unary_function & function ptr_fun1
( NONSENSE in CL - STL )
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor pointer_to_unary_function (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :type cl:function
:initform nil
:initarg :operator
:accessor pointer_to_unary_function-operator)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor pointer_to_unary_function (1))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor pointer_to_unary_function (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "pointer_to_unary_function is deprecated."))
(make-instance 'pointer_to_unary_function
:operator func
:closure (lambda (arg)
(funcall func arg))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun ptr_fun1 (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "ptr_fun1 is deprecated."))
(make-instance 'pointer_to_unary_function
:operator func
:closure (lambda (arg)
(funcall func arg))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func pointer_to_unary_function))
(let ((func (pointer_to_unary_function-operator func)))
(make-instance 'pointer_to_unary_function
:operator func
:closure (lambda (arg)
(funcall func arg)))))
( NONSENSE in CL - STL )
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor pointer_to_binary_function (#-cl-stl-0x98 functor
#+cl-stl-0x98 binary_function)
((op :type cl:function
:initform nil
:initarg :operator
:accessor pointer_to_binary_function-operator)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor pointer_to_binary_function (1))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor pointer_to_binary_function (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "pointer_to_binary_function is deprecated."))
(make-instance 'pointer_to_binary_function
:operator func
:closure (lambda (arg1 arg2)
(funcall func arg1 arg2))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun ptr_fun2 (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "ptr_fun2 is deprecated."))
(make-instance 'pointer_to_binary_function
:operator func
:closure (lambda (arg1 arg2)
(funcall func arg1 arg2))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func pointer_to_binary_function))
(let ((func (pointer_to_binary_function-operator func)))
(make-instance 'pointer_to_binary_function
:operator func
:closure (lambda (arg1 arg2)
(funcall func arg1 arg2)))))
20.3.8 , adaptors :
class & function mem_fun etc .
( NONSENSE in CL - STL )
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor mem_fun_t (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :type cl:function
:initform nil
:initarg :operator
:accessor mem_fun_t-operator)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor mem_fun_t (1))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor mem_fun_t (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun_t is deprecated."))
(make-instance 'mem_fun_t
:operator func
:closure (lambda (obj)
(funcall func obj))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun mem_fun (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun is deprecated."))
(make-instance 'mem_fun_t
:operator func
:closure (lambda (obj)
(funcall func obj))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun mem_fun_ref (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun_ref is deprecated."))
(make-instance 'mem_fun_t
:operator func
:closure (lambda (obj)
(funcall func obj))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func mem_fun_t))
(let ((func (mem_fun_t-operator func)))
(make-instance 'mem_fun_t
:operator func
:closure (lambda (obj)
(funcall func obj)))))
class mem_fun1_t & function mem_fun1 etc .
( NONSENSE in CL - STL )
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor mem_fun1_t (#-cl-stl-0x98 functor
#+cl-stl-0x98 unary_function)
((op :type cl:function
:initform nil
:initarg :operator
:accessor mem_fun1_t-operator)))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(declare-constructor mem_fun1_t (1))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-constructor mem_fun1_t (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun1_t is deprecated."))
(make-instance 'mem_fun1_t
:operator func
:closure (lambda (obj arg)
(funcall func obj arg))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun mem_fun1 (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun1 is deprecated."))
(make-instance 'mem_fun1_t
:operator func
:closure (lambda (obj arg)
(funcall func obj arg))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun mem_fun1_ref (func)
#+cl-stl-warn-deprecated
(progn
#-cl-stl-0x98 (warn "mem_fun1_ref is deprecated."))
(make-instance 'mem_fun1_t
:operator func
:closure (lambda (obj arg)
(funcall func obj arg))))
#+(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func mem_fun1_t))
(let ((func (mem_fun1_t-operator func)))
(make-instance 'mem_fun1_t
:operator func
:closure (lambda (obj arg)
(funcall func obj arg)))))
-- > use instead .
#-cl-stl-0x98
(defun is_placeholder (arg)
(if (not (keywordp arg))
0
(handler-case (values (parse-integer (symbol-name arg)))
(error () 0))))
#-cl-stl-0x98
(defun is_bind_expression (arg)
(eq (type-of arg) '__binded-expr))
#-cl-stl-0x98
(define-functor __binded-expr (functor)
((bindee :initarg :bindee
:accessor __binded-expr-bindee)
(params :type cl:vector
:initarg :params
:accessor __binded-expr-params)
(cloner :type cl:function
:initarg :cloner
:accessor __binded-expr-cloner)))
#-cl-stl-0x98
(defmethod operator_clone ((func __binded-expr))
(funcall (__binded-expr-cloner func) func))
#-cl-stl-0x98
(defmacro bind (func &rest args)
(let ((max-arg 0)
(arg-hash (make-hash-table)))
(labels ((get-argsym (idx)
(let ((is-new nil)
(ret (gethash idx arg-hash)))
(unless ret
(setf ret (gensym (format nil "ARG~A-" idx)))
(setf (gethash idx arg-hash) ret)
(setf is-new t)
(when (< max-arg idx)
(setf max-arg idx)))
(values ret is-new)))
(make-lambda-list (idx lambda-list ignore-list)
(if (< max-arg idx)
(values (nreverse lambda-list)
(nreverse ignore-list))
(multiple-value-bind (sym is-new) (get-argsym idx)
(cl:push sym lambda-list)
(when is-new
(cl:push sym ignore-list))
(make-lambda-list (1+ idx) lambda-list ignore-list))))
(imp (args acc1 acc2 prm-sym &optional (idx 0))
(if (null args)
(values (nreverse acc1)
(nreverse acc2))
(let* ((item (car args))
(ret (is_placeholder item)))
(if (< 0 ret)
(cl:push (get-argsym ret) acc2)
(progn
(cl:push `(aref ,prm-sym ,idx) acc2)
(cl:push `(_= (aref ,prm-sym ,idx) ,(car args)) acc1)
(incf idx)))
(imp (cdr args) acc1 acc2 prm-sym idx)))))
(let ((g-imp (gensym "IMP"))
(g-fnc (gensym "FNC"))
(g-bindee (gensym "BINDEE"))
(g-bd-fnc (gensym "BD-FNC"))
(g-params (gensym "PARAMS"))
(g-cloner (gensym "CLONER")))
(multiple-value-bind (arg-lst prm-lst) (imp args nil nil g-params)
(multiple-value-bind (lambda-list ignore-list) (make-lambda-list 1 nil nil)
`(labels ((,g-imp (,g-bindee ,g-params ,g-cloner)
(declare (type cl:vector ,g-params))
(let ((,g-bd-fnc (functor_function ,g-bindee)))
(declare (type cl:function ,g-bd-fnc))
(make-instance '__binded-expr
:bindee ,g-bindee :params ,g-params :cloner ,g-cloner
:closure (lambda (,@lambda-list)
,(when ignore-list
`(declare (ignore ,@ignore-list)))
(funcall ,g-bd-fnc ,@prm-lst))))))
(let* ((,g-bindee (clone ,func))
(,g-params (make-array ,(length arg-lst) :initial-element nil))
(,g-cloner (lambda (,g-fnc)
(,g-imp (clone (__binded-expr-bindee ,g-fnc))
(clone (__binded-expr-params ,g-fnc))
(__binded-expr-cloner ,g-fnc)))))
,@arg-lst
(,g-imp ,g-bindee ,g-params ,g-cloner)))))))))
#-cl-stl-0x98
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-functor function (functor)
((target :initform nil
:initarg :target
:accessor __function-target))))
#-cl-stl-0x98
(declare-constructor function (0 1))
#-cl-stl-0x98
(labels ((__function-ctor (op)
(if (null op)
(make-instance 'function :target nil :closure nil)
(let* ((target (clone op)))
(make-instance 'function
:target target
:closure (functor_function target))))))
(define-constructor function ()
(__function-ctor nil))
(define-constructor function ((op (eql nil)))
(__function-ctor nil))
(define-constructor function ((op cl:function))
(__function-ctor op))
(define-constructor function ((op functor))
(__function-ctor op))
(define-constructor function ((fn function))
(__function-ctor (__function-target fn)))
(defmethod operator_clone ((fn function))
(__function-ctor (__function-target fn))))
#-cl-stl-0x98
(define-constructor function ((rm& remove-reference))
(with-reference (rm)
(let ((fnctr rm))
(__check-type-of-move-constructor fnctr function)
(let ((target (__function-target fnctr))
(closure (__functor-closure fnctr)))
(setf (__function-target fnctr) nil)
(setf (__functor-closure fnctr) nil)
(make-instance 'function :target target :closure closure)))))
#-cl-stl-0x98
(defmethod operator_cast ((fn function) (typename (eql 'boolean)))
(if (__function-target fn) t nil))
#-cl-stl-0x98
(locally (declare (optimize speed))
(labels ((__assign (fnc op)
(declare (type function fnc))
(if (null op)
(progn
(setf (__function-target fnc) nil)
(setf (__functor-closure fnc) nil))
(let* ((target (clone op))
(closure (functor_function op)))
(setf (__function-target fnc) target)
(setf (__functor-closure fnc) closure)))))
(declare (inline __assign))
(defmethod operator_= ((lhs function) rhs)
(error 'type-mismatch :what (format nil "Can't convert ~A to stl:function." rhs))
lhs)
(defmethod operator_= ((lhs function) (rhs function))
(__assign lhs (__function-target rhs))
lhs)
(defmethod operator_= ((lhs function) (rhs (eql nil)))
(setf (__function-target lhs) nil)
(setf (__functor-closure lhs) nil)
lhs)
(defmethod-overload assign ((this function) (fnc function))
(__assign this (__function-target fnc))
nil)
(defmethod-overload assign ((this function) (fnc (eql nil)))
(setf (__function-target this) nil)
(setf (__functor-closure this) nil)
nil)))
#-cl-stl-0x98
(defmethod operator_move ((lhs function) (rhs function))
(unless (eq lhs rhs)
(setf (__function-target lhs) (__function-target rhs))
(setf (__functor-closure lhs) (__functor-closure rhs))
(setf (__function-target rhs) nil)
(setf (__functor-closure rhs) nil))
(values lhs rhs))
#-cl-stl-0x98
(defmethod-overload swap ((fn1 function) (fn2 function))
(let ((op (__function-target fn1))
(fn (__functor-closure fn1)))
(setf (__function-target fn1) (__function-target fn2))
(setf (__functor-closure fn1) (__functor-closure fn2))
(setf (__function-target fn2) op)
(setf (__functor-closure fn2) fn))
(values fn1 fn2))
#-cl-stl-0x98
(defun target (fn)
(__function-target fn))
#-cl-stl-0x98
(locally (declare (optimize speed))
(labels ((__empty (fn)
(declare (type function fn))
(if (__function-target fn) nil t)))
(declare (inline __empty))
(defmethod operator_== ((fn function) (rhs (eql nil))) (__empty fn))
(defmethod operator_== ((lhs (eql nil)) (fn function)) (__empty fn))
(defmethod operator_/= ((fn function) (rhs (eql nil))) (not (__empty fn)))
(defmethod operator_/= ((lhs (eql nil)) (fn function)) (not (__empty fn)))))
#-cl-stl-0x98
(define-functor bit_and (functor) ())
#-cl-stl-0x98
(declare-constructor bit_and (0))
#-cl-stl-0x98
(labels ((__bit_and (arg1 arg2) (logand arg1 arg2)))
(define-constructor bit_and ()
(make-instance 'bit_and :closure #'__bit_and)))
#-cl-stl-0x98
(define-functor bit_or (functor) ())
#-cl-stl-0x98
(declare-constructor bit_or (0))
#-cl-stl-0x98
(labels ((__bit_or (arg1 arg2) (logior arg1 arg2)))
(define-constructor bit_or ()
(make-instance 'bit_or :closure #'__bit_or)))
#-cl-stl-0x98
(define-functor bit_xor (functor) ())
#-cl-stl-0x98
(declare-constructor bit_xor (0))
#-cl-stl-0x98
(labels ((__bit_xor (arg1 arg2) (logxor arg1 arg2)))
(define-constructor bit_xor ()
(make-instance 'bit_xor :closure #'__bit_xor)))
#-cl-stl-0x98
(define-functor mem_fn (functor)
((method :type cl:function
:initform nil
:initarg :method
:accessor mem_fn-method)))
#-cl-stl-0x98
(declare-constructor mem_fn (1))
#-cl-stl-0x98
(labels ((__mem_fn-ctor (method)
(make-instance 'mem_fn
:method method
:closure (lambda (&rest args)
(cl:apply method args)))))
(define-constructor mem_fn (method)
(__mem_fn-ctor method))
(defmethod operator_clone ((func mem_fn))
(__mem_fn-ctor (mem_fn-method func))))
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(locally (declare (optimize speed))
(defun apply (fnc tpl)
(let ((arr (__inner-array tpl)))
(declare (type simple-vector arr))
(let ((cnt (length arr)))
(declare (type fixnum cnt))
(case cnt
(2 (locally (declare (type (simple-vector 2) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1))))
(3 (locally (declare (type (simple-vector 3) arr))
(cl:funcall fnc (svref arr 0)
(svref arr 1) (svref arr 2))))
(4 (locally (declare (type (simple-vector 4) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3))))
(5 (locally (declare (type (simple-vector 5) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3) (svref arr 4))))
(6 (locally (declare (type (simple-vector 6) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3)
(svref arr 4) (svref arr 5))))
(7 (locally (declare (type (simple-vector 7) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3)
(svref arr 4) (svref arr 5) (svref arr 6))))
(8 (locally (declare (type (simple-vector 8) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3)
(svref arr 4) (svref arr 5)
(svref arr 6) (svref arr 7))))
(9 (locally (declare (type (simple-vector 9) arr))
(cl:funcall fnc (svref arr 0) (svref arr 1)
(svref arr 2) (svref arr 3)
(svref arr 4) (svref arr 5)
(svref arr 6) (svref arr 7) (svref arr 8))))
(t (cl:apply fnc (coerce arr 'cl:list))))))))
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(define-functor __not_fn (functor)
((op :initform nil
:initarg :operator
:accessor __not_fn-operator)))
( declare - constructor _ _ not_fn ( 2 ) )
( fnc ( functor_function op ) ) )
( _ ! ( cl : apply ) ) ) ) ) )
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defun not_fn (functor)
(let* ((op (clone functor))
(fnc (functor_function op)))
(make-instance '__not_fn
:operator op
:closure (lambda (&rest params)
(_! (cl:apply fnc params))))))
#-(or cl-stl-0x98 cl-stl-0x11 cl-stl-0x14)
(defmethod operator_clone ((func __not_fn))
(let* ((op (clone (__not_fn-operator func)))
(fnc (functor_function op)))
(make-instance '__not_fn
:operator op
:closure (lambda (&rest params)
(_! (cl:apply fnc params))))))
|
19f3015bc60a87267d85e40017a3898af9330973072fb2d24f4c640ef454d8b3 | erlyvideo/publisher | rtsp_inbound.erl | @author < > [ ]
2010 - 2011
%%% @doc RTSP socket module
%%%
%%%
1 . connect
2 . describe
3 . each setup
4 . play , possible Rtp - Sync
5 . get each packet
6 . decode
%%%
%%%
%%% @end
@reference See < a href=" / rtsp " target="_top"></a > for common information .
%%% @end
%%%
This file is part of erlang - rtsp .
%%%
%%% erlang-rtsp 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.
%%%
%%% erlang-rtsp 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 erlang - rtsp . If not , see < / > .
%%%
%%%---------------------------------------------------------------------------------------
-module(rtsp_inbound).
-author('Max Lapshin <>').
-include("log.hrl").
-include_lib("erlmedia/include/video_frame.hrl").
-include_lib("erlmedia/include/media_info.hrl").
-include_lib("erlmedia/include/sdp.hrl").
-include("rtsp.hrl").
-export([handle_call/3, sync_rtp/2, handle_announce_request/4, handle_receive_setup/4]).
-export([handle_pause/4]).
-export([dump_io/2]).
dump_io(#rtsp_socket{dump_traffic = false}, _) -> ok;
dump_io(_, Call) -> io:format(">>>>>> RTSP OUT (~p:~p) >>>>>~n~s~n", [?MODULE, ?LINE, Call]).
handle_call({connect, URL, Options}, _From, RTSP) ->
RTSP1 = case proplists:get_value(consumer, Options) of
undefined -> RTSP;
Consumer ->
Ref = erlang:monitor(process, Consumer),
RTSP#rtsp_socket{media = Consumer, rtp_ref = Ref}
end,
Timeout = proplists:get_value(timeout, Options, ?DEFAULT_TIMEOUT),
{rtsp, UserInfo, Host, Port, _Path, _Query} = http_uri2:parse(URL),
Transport = proplists:get_value(transport, Options, tcp),
{Auth, AuthType} = case UserInfo of
[] -> {fun(_Req, _Url) -> "" end, undefined};
_ -> {fun(_Req, _Url) -> "Authorization: Basic "++binary_to_list(base64:encode(UserInfo))++"\r\n" end, basic}
end,
RTSP2 = RTSP1#rtsp_socket{url = URL, content_base = URL, options = Options,
auth = Auth, auth_type = AuthType, auth_info = UserInfo, timeout = Timeout, transport = Transport},
ConnectOptions = [binary, {packet, raw}, {active, once}, {keepalive, true}, {send_timeout, Timeout}, {send_timeout_close, true}],
case gen_tcp:connect(Host, Port, ConnectOptions, Timeout) of
{ok, Socket} ->
?D({"RTSP Connected", URL}),
{reply, ok, RTSP2#rtsp_socket{socket = Socket}, Timeout};
Else ->
{stop, normal, Else, RTSP2}
end;
handle_call({consume, Consumer}, _From, #rtsp_socket{rtp_ref = OldRef, timeout = Timeout} = RTSP) ->
(catch erlang:demonitor(OldRef)),
Ref = erlang:monitor(process, Consumer),
{reply, ok, RTSP#rtsp_socket{rtp = Consumer, rtp_ref = Ref}, Timeout};
handle_call({request, options}, From, #rtsp_socket{socket = Socket, url = URL, auth = Auth, seq = Seq, timeout = Timeout} = RTSP) ->
Call = io_lib:format("OPTIONS ~s RTSP/1.0\r\nCSeq: ~p\r\n"++Auth("OPTIONS", URL)++"\r\n", [URL, Seq+1]),
gen_tcp:send(Socket, Call),
dump_io(RTSP, Call),
{noreply, RTSP#rtsp_socket{pending = From, state = options, seq = Seq+1}, Timeout};
handle_call({request, describe}, From, #rtsp_socket{socket = Socket, url = URL, auth = Auth, seq = Seq, timeout = Timeout} = RTSP) ->
Call = io_lib:format("DESCRIBE ~s RTSP/1.0\r\nCSeq: ~p\r\nAccept: application/sdp\r\n"++Auth("DESCRIBE", URL)++"\r\n", [URL, Seq+1]),
gen_tcp:send(Socket, Call),
dump_io(RTSP, Call),
{noreply, RTSP#rtsp_socket{pending = From, state = describe, seq = Seq+1}, Timeout};
handle_call({request, setup, Num}, From,
#rtsp_socket{socket = Socket, rtp = RTP, rtp_streams = Streams, seq = Seq, auth = Auth, timeout = Timeout, transport = Transport,
session = Session, content_base = ContentBase} = RTSP) ->
? D({"Setup " , , Streams } ) ,
_Stream = #stream_info{options = Options} = element(Num, Streams),
Control = proplists:get_value(control, Options),
{ok, RTP1, Reply} = rtp:setup_channel(RTP, Num, [{proto,Transport},{tcp_socket,Socket}]),
TransportHeader = case Transport of
tcp -> io_lib:format("Transport: RTP/AVP/TCP;unicast;interleaved=~p-~p\r\n", [Num*2 - 2, Num*2-1]);
udp ->
Port1 = proplists:get_value(local_rtp_port, Reply),
Port2 = proplists:get_value(local_rtcp_port, Reply),
io_lib:format("Transport: RTP/AVP;unicast;client_port=~p-~p\r\n", [Port1, Port2])
end,
SetupURL = append_trackid(ContentBase, Control),
Call = io_lib:format("SETUP ~s RTSP/1.0\r\nCSeq: ~p\r\n"++Session++TransportHeader++Auth("SETUP", SetupURL)++"\r\n",
[SetupURL, Seq + 1]),
gen_tcp:send(Socket, Call),
dump_io(RTSP, Call),
{noreply, RTSP#rtsp_socket{pending = From, state = {setup, Num}, rtp = RTP1, seq = Seq+1}, Timeout};
handle_call({request, play}, From, #rtsp_socket{socket = Socket, url = URL, seq = Seq, session = Session, auth = Auth, timeout = Timeout} = RTSP) ->
Call = io_lib:format("PLAY ~s RTSP/1.0\r\nCSeq: ~p\r\n"++Auth("PLAY", URL)++Session++"\r\n", [URL, Seq + 1]),
gen_tcp:send(Socket, Call),
dump_io(RTSP, Call),
{noreply, RTSP#rtsp_socket{pending = From, state = play, seq = Seq + 1}, Timeout}.
sync_rtp(#rtsp_socket{rtp = RTP, control_map = ControlMap, url = URL} = Socket, RtpHeaders) ->
case proplists:get_value('Rtp-Info', RtpHeaders) of
undefined ->
Socket;
RtpInfo ->
RTP1 = lists:foldl(fun(Headers, RTP_) ->
case extract_control(proplists:get_value(url, Headers), URL, ControlMap) of
undefined -> ?D({unsynced, Headers}), RTP_;
StreamNum -> rtp:sync(RTP_, StreamNum, Headers)
end
end, RTP, RtpInfo),
Socket#rtsp_socket{rtp = RTP1}
end.
handle_announce_request(#rtsp_socket{callback = Callback} = Socket, URL, Headers, Body) ->
Socket1 = #rtsp_socket{pending_reply = {ok, MediaInfo, _}} = rtsp_socket:handle_sdp(Socket, Headers, Body),
case Callback:announce(URL, Headers, MediaInfo) of
{ok, Media} ->
?D({"Announced to", Media}),
erlang:monitor(process, Media),
rtsp_socket:reply(Socket1#rtsp_socket{session = rtsp_socket:generate_session(), rtp = rtp:init(local,MediaInfo),
media = Media, direction = in}, "200 OK", [{'Cseq', seq(Headers)}]);
{error, authentication} ->
rtsp_socket:reply(Socket1, "401 Unauthorized", [{"WWW-Authenticate", "Basic realm=\"Erlyvideo Streaming Server\""}, {'Cseq', seq(Headers)}])
end.
handle_receive_setup(#rtsp_socket{socket = Sock, rtp = RTP} = Socket, URL, Headers, _Body) ->
{match, [Control]} = re:run(URL, "/([^/]+)$", [{capture, all_but_first, list}]),
StreamId = proplists:get_value(Control, Socket#rtsp_socket.control_map),
Transport = proplists:get_value('Transport', Headers),
{ok, RTP1, _Reply} = rtp:setup_channel(RTP, StreamId, [{tcp_socket,Sock}|Transport]),
rtsp_socket:reply(Socket#rtsp_socket{rtp = RTP1}, "200 OK", [{'Cseq', seq(Headers)}, {'Transport', proplists:get_value('Transport', Headers)}]).
handle_pause(#rtsp_socket{} = Socket, _URL, Headers, _Body) ->
rtsp_socket:reply(Socket, "200 OK", [{'Cseq', seq(Headers)}]).
seq(Headers) ->
proplists:get_value('Cseq', Headers, 1).
append_trackid(_URL, ("rtsp://"++ _) = TrackID) ->
TrackID;
append_trackid(URL, TrackID) ->
case string:tokens(URL, "?") of
[URL1, URL2] -> clean_dslash(URL1 ++ "/" ++ TrackID ++ "?" ++ URL2);
[URL] -> clean_dslash(URL ++ "/" ++ TrackID)
end.
clean_dslash("rtsp://"++URL) ->
"rtsp://"++re:replace(URL, "//", "/", [global,{return,list}]).
lookup_in_control_map(_ControlUrl, []) -> undefined;
lookup_in_control_map(ControlUrl, [{Track,Number}|ControlMap]) ->
Postfix = string:substr(ControlUrl, length(ControlUrl) - length(Track) + 1),
if
Postfix == Track -> Number;
true -> lookup_in_control_map(ControlUrl, ControlMap)
end.
extract_control(ControlUrl, _URL, ControlMap) ->
lookup_in_control_map(ControlUrl, ControlMap).
%%
%% Tests
%%
-include_lib("eunit/include/eunit.hrl").
append_trackid_test_() ->
[?_assertEqual("rtsp:554/h264.sdp/trackID=1", append_trackid("rtsp:554/h264.sdp", "trackID=1")),
?_assertEqual("rtsp:554/h264.sdp/trackID=1?res=half&x0=0", append_trackid("rtsp:554/h264.sdp?res=half&x0=0", "trackID=1")),
?_assertEqual("rtsp:554/h264.sdp/track1?res=half&x0=0", append_trackid("rtsp:554/h264.sdp?res=half&x0=0", "track1")),
?_assertEqual("rtsp:554/h264.sdp/track1?res=half&x0=0", append_trackid("rtsp:554/h264.sdp?res=half&x0=0", "rtsp:554/h264.sdp/track1?res=half&x0=0"))
].
extract_control_test_() ->
[
?_assertEqual(1, extract_control("track1", "rtsp:554/h264", [{"track1",1}])),
?_assertEqual(1, extract_control("track1", "rtsp", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp:554/h264/track1", "rtsp:554/h264", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp:554/h264/track1", "rtsp:554/h264/", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp", "rtsp:554/h264", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp", "rtsp:554/h264/", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp:554/h264/track1", "rtsp", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp:554/h264/track1", "rtsp/", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp", "rtsp:[email protected]/554/h264", [{"track1",1}]))
].
| null | https://raw.githubusercontent.com/erlyvideo/publisher/5bb2dfa6477c46160dc5fafcc030fc3f5340ec80/apps/rtsp/src/rtsp_inbound.erl | erlang | @doc RTSP socket module
@end
@end
erlang-rtsp is free software: you can redistribute it and/or modify
(at your option) any later version.
erlang-rtsp 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.
---------------------------------------------------------------------------------------
Tests
| @author < > [ ]
2010 - 2011
1 . connect
2 . describe
3 . each setup
4 . play , possible Rtp - Sync
5 . get each packet
6 . decode
@reference See < a href=" / rtsp " target="_top"></a > for common information .
This file is part of erlang - rtsp .
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
along with erlang - rtsp . If not , see < / > .
-module(rtsp_inbound).
-author('Max Lapshin <>').
-include("log.hrl").
-include_lib("erlmedia/include/video_frame.hrl").
-include_lib("erlmedia/include/media_info.hrl").
-include_lib("erlmedia/include/sdp.hrl").
-include("rtsp.hrl").
-export([handle_call/3, sync_rtp/2, handle_announce_request/4, handle_receive_setup/4]).
-export([handle_pause/4]).
-export([dump_io/2]).
dump_io(#rtsp_socket{dump_traffic = false}, _) -> ok;
dump_io(_, Call) -> io:format(">>>>>> RTSP OUT (~p:~p) >>>>>~n~s~n", [?MODULE, ?LINE, Call]).
handle_call({connect, URL, Options}, _From, RTSP) ->
RTSP1 = case proplists:get_value(consumer, Options) of
undefined -> RTSP;
Consumer ->
Ref = erlang:monitor(process, Consumer),
RTSP#rtsp_socket{media = Consumer, rtp_ref = Ref}
end,
Timeout = proplists:get_value(timeout, Options, ?DEFAULT_TIMEOUT),
{rtsp, UserInfo, Host, Port, _Path, _Query} = http_uri2:parse(URL),
Transport = proplists:get_value(transport, Options, tcp),
{Auth, AuthType} = case UserInfo of
[] -> {fun(_Req, _Url) -> "" end, undefined};
_ -> {fun(_Req, _Url) -> "Authorization: Basic "++binary_to_list(base64:encode(UserInfo))++"\r\n" end, basic}
end,
RTSP2 = RTSP1#rtsp_socket{url = URL, content_base = URL, options = Options,
auth = Auth, auth_type = AuthType, auth_info = UserInfo, timeout = Timeout, transport = Transport},
ConnectOptions = [binary, {packet, raw}, {active, once}, {keepalive, true}, {send_timeout, Timeout}, {send_timeout_close, true}],
case gen_tcp:connect(Host, Port, ConnectOptions, Timeout) of
{ok, Socket} ->
?D({"RTSP Connected", URL}),
{reply, ok, RTSP2#rtsp_socket{socket = Socket}, Timeout};
Else ->
{stop, normal, Else, RTSP2}
end;
handle_call({consume, Consumer}, _From, #rtsp_socket{rtp_ref = OldRef, timeout = Timeout} = RTSP) ->
(catch erlang:demonitor(OldRef)),
Ref = erlang:monitor(process, Consumer),
{reply, ok, RTSP#rtsp_socket{rtp = Consumer, rtp_ref = Ref}, Timeout};
handle_call({request, options}, From, #rtsp_socket{socket = Socket, url = URL, auth = Auth, seq = Seq, timeout = Timeout} = RTSP) ->
Call = io_lib:format("OPTIONS ~s RTSP/1.0\r\nCSeq: ~p\r\n"++Auth("OPTIONS", URL)++"\r\n", [URL, Seq+1]),
gen_tcp:send(Socket, Call),
dump_io(RTSP, Call),
{noreply, RTSP#rtsp_socket{pending = From, state = options, seq = Seq+1}, Timeout};
handle_call({request, describe}, From, #rtsp_socket{socket = Socket, url = URL, auth = Auth, seq = Seq, timeout = Timeout} = RTSP) ->
Call = io_lib:format("DESCRIBE ~s RTSP/1.0\r\nCSeq: ~p\r\nAccept: application/sdp\r\n"++Auth("DESCRIBE", URL)++"\r\n", [URL, Seq+1]),
gen_tcp:send(Socket, Call),
dump_io(RTSP, Call),
{noreply, RTSP#rtsp_socket{pending = From, state = describe, seq = Seq+1}, Timeout};
handle_call({request, setup, Num}, From,
#rtsp_socket{socket = Socket, rtp = RTP, rtp_streams = Streams, seq = Seq, auth = Auth, timeout = Timeout, transport = Transport,
session = Session, content_base = ContentBase} = RTSP) ->
? D({"Setup " , , Streams } ) ,
_Stream = #stream_info{options = Options} = element(Num, Streams),
Control = proplists:get_value(control, Options),
{ok, RTP1, Reply} = rtp:setup_channel(RTP, Num, [{proto,Transport},{tcp_socket,Socket}]),
TransportHeader = case Transport of
tcp -> io_lib:format("Transport: RTP/AVP/TCP;unicast;interleaved=~p-~p\r\n", [Num*2 - 2, Num*2-1]);
udp ->
Port1 = proplists:get_value(local_rtp_port, Reply),
Port2 = proplists:get_value(local_rtcp_port, Reply),
io_lib:format("Transport: RTP/AVP;unicast;client_port=~p-~p\r\n", [Port1, Port2])
end,
SetupURL = append_trackid(ContentBase, Control),
Call = io_lib:format("SETUP ~s RTSP/1.0\r\nCSeq: ~p\r\n"++Session++TransportHeader++Auth("SETUP", SetupURL)++"\r\n",
[SetupURL, Seq + 1]),
gen_tcp:send(Socket, Call),
dump_io(RTSP, Call),
{noreply, RTSP#rtsp_socket{pending = From, state = {setup, Num}, rtp = RTP1, seq = Seq+1}, Timeout};
handle_call({request, play}, From, #rtsp_socket{socket = Socket, url = URL, seq = Seq, session = Session, auth = Auth, timeout = Timeout} = RTSP) ->
Call = io_lib:format("PLAY ~s RTSP/1.0\r\nCSeq: ~p\r\n"++Auth("PLAY", URL)++Session++"\r\n", [URL, Seq + 1]),
gen_tcp:send(Socket, Call),
dump_io(RTSP, Call),
{noreply, RTSP#rtsp_socket{pending = From, state = play, seq = Seq + 1}, Timeout}.
sync_rtp(#rtsp_socket{rtp = RTP, control_map = ControlMap, url = URL} = Socket, RtpHeaders) ->
case proplists:get_value('Rtp-Info', RtpHeaders) of
undefined ->
Socket;
RtpInfo ->
RTP1 = lists:foldl(fun(Headers, RTP_) ->
case extract_control(proplists:get_value(url, Headers), URL, ControlMap) of
undefined -> ?D({unsynced, Headers}), RTP_;
StreamNum -> rtp:sync(RTP_, StreamNum, Headers)
end
end, RTP, RtpInfo),
Socket#rtsp_socket{rtp = RTP1}
end.
handle_announce_request(#rtsp_socket{callback = Callback} = Socket, URL, Headers, Body) ->
Socket1 = #rtsp_socket{pending_reply = {ok, MediaInfo, _}} = rtsp_socket:handle_sdp(Socket, Headers, Body),
case Callback:announce(URL, Headers, MediaInfo) of
{ok, Media} ->
?D({"Announced to", Media}),
erlang:monitor(process, Media),
rtsp_socket:reply(Socket1#rtsp_socket{session = rtsp_socket:generate_session(), rtp = rtp:init(local,MediaInfo),
media = Media, direction = in}, "200 OK", [{'Cseq', seq(Headers)}]);
{error, authentication} ->
rtsp_socket:reply(Socket1, "401 Unauthorized", [{"WWW-Authenticate", "Basic realm=\"Erlyvideo Streaming Server\""}, {'Cseq', seq(Headers)}])
end.
handle_receive_setup(#rtsp_socket{socket = Sock, rtp = RTP} = Socket, URL, Headers, _Body) ->
{match, [Control]} = re:run(URL, "/([^/]+)$", [{capture, all_but_first, list}]),
StreamId = proplists:get_value(Control, Socket#rtsp_socket.control_map),
Transport = proplists:get_value('Transport', Headers),
{ok, RTP1, _Reply} = rtp:setup_channel(RTP, StreamId, [{tcp_socket,Sock}|Transport]),
rtsp_socket:reply(Socket#rtsp_socket{rtp = RTP1}, "200 OK", [{'Cseq', seq(Headers)}, {'Transport', proplists:get_value('Transport', Headers)}]).
handle_pause(#rtsp_socket{} = Socket, _URL, Headers, _Body) ->
rtsp_socket:reply(Socket, "200 OK", [{'Cseq', seq(Headers)}]).
seq(Headers) ->
proplists:get_value('Cseq', Headers, 1).
append_trackid(_URL, ("rtsp://"++ _) = TrackID) ->
TrackID;
append_trackid(URL, TrackID) ->
case string:tokens(URL, "?") of
[URL1, URL2] -> clean_dslash(URL1 ++ "/" ++ TrackID ++ "?" ++ URL2);
[URL] -> clean_dslash(URL ++ "/" ++ TrackID)
end.
clean_dslash("rtsp://"++URL) ->
"rtsp://"++re:replace(URL, "//", "/", [global,{return,list}]).
lookup_in_control_map(_ControlUrl, []) -> undefined;
lookup_in_control_map(ControlUrl, [{Track,Number}|ControlMap]) ->
Postfix = string:substr(ControlUrl, length(ControlUrl) - length(Track) + 1),
if
Postfix == Track -> Number;
true -> lookup_in_control_map(ControlUrl, ControlMap)
end.
extract_control(ControlUrl, _URL, ControlMap) ->
lookup_in_control_map(ControlUrl, ControlMap).
-include_lib("eunit/include/eunit.hrl").
append_trackid_test_() ->
[?_assertEqual("rtsp:554/h264.sdp/trackID=1", append_trackid("rtsp:554/h264.sdp", "trackID=1")),
?_assertEqual("rtsp:554/h264.sdp/trackID=1?res=half&x0=0", append_trackid("rtsp:554/h264.sdp?res=half&x0=0", "trackID=1")),
?_assertEqual("rtsp:554/h264.sdp/track1?res=half&x0=0", append_trackid("rtsp:554/h264.sdp?res=half&x0=0", "track1")),
?_assertEqual("rtsp:554/h264.sdp/track1?res=half&x0=0", append_trackid("rtsp:554/h264.sdp?res=half&x0=0", "rtsp:554/h264.sdp/track1?res=half&x0=0"))
].
extract_control_test_() ->
[
?_assertEqual(1, extract_control("track1", "rtsp:554/h264", [{"track1",1}])),
?_assertEqual(1, extract_control("track1", "rtsp", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp:554/h264/track1", "rtsp:554/h264", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp:554/h264/track1", "rtsp:554/h264/", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp", "rtsp:554/h264", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp", "rtsp:554/h264/", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp:554/h264/track1", "rtsp", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp:554/h264/track1", "rtsp/", [{"track1",1}])),
?_assertEqual(1, extract_control("rtsp", "rtsp:[email protected]/554/h264", [{"track1",1}]))
].
|
b1df13cf0a9f71143fd3cb0d5eb636bb4421b3e50b7c4d001b69a4bb442cb84c | patrickgombert/erlang-koans | about_lists.erl | -module(about_lists).
-export([lists_are_not_homogeneous/0,
we_can_add/0,
we_can_also_take_away/0,
lists_define_delete/0,
just_how_many_are_deleted/0,
lists_have_heads/0,
lists_also_have_tails/0,
constructing_with_cons/0,
length_is_as_simple_as_it_seems/0,
lists_of_tuples_can_be_found_by_key/0
]).
lists_are_not_homogeneous() ->
NotJustFruits = [apple, banana, __, mango],
Element = lists:nth(3, NotJustFruits),
(Element < 2) and (Element > 0).
we_can_add() ->
[apple, banana] ++ __.
we_can_also_take_away() ->
[apple, banana] -- [__].
lists_define_delete() ->
lists:delete(__, [apple, banana]).
just_how_many_are_deleted() ->
__ =:= lists:delete(apple, [apple, banana, apple]).
lists_have_heads() ->
[Head | Tail] = [apple, banana, mango],
__ =:= Head.
lists_also_have_tails() ->
[Head | Tail] = [apple, banana, mango],
__ =:= Tail.
constructing_with_cons() ->
__ =:= [apple | [banana | [mango | [pear | []]]]].
length_is_as_simple_as_it_seems() ->
__ =:= length([1, 2, 3]).
lists_of_tuples_can_be_found_by_key() ->
Meals = [{breakfast, eggs}, {lunch, pasta}, {dinner, burrito}],
{lunch, _} = lists:keyfind(__, 2, Meals).
| null | https://raw.githubusercontent.com/patrickgombert/erlang-koans/d80032d99b6ee3537e585ea02b743fe681fad8cf/src/about_lists.erl | erlang | -module(about_lists).
-export([lists_are_not_homogeneous/0,
we_can_add/0,
we_can_also_take_away/0,
lists_define_delete/0,
just_how_many_are_deleted/0,
lists_have_heads/0,
lists_also_have_tails/0,
constructing_with_cons/0,
length_is_as_simple_as_it_seems/0,
lists_of_tuples_can_be_found_by_key/0
]).
lists_are_not_homogeneous() ->
NotJustFruits = [apple, banana, __, mango],
Element = lists:nth(3, NotJustFruits),
(Element < 2) and (Element > 0).
we_can_add() ->
[apple, banana] ++ __.
we_can_also_take_away() ->
[apple, banana] -- [__].
lists_define_delete() ->
lists:delete(__, [apple, banana]).
just_how_many_are_deleted() ->
__ =:= lists:delete(apple, [apple, banana, apple]).
lists_have_heads() ->
[Head | Tail] = [apple, banana, mango],
__ =:= Head.
lists_also_have_tails() ->
[Head | Tail] = [apple, banana, mango],
__ =:= Tail.
constructing_with_cons() ->
__ =:= [apple | [banana | [mango | [pear | []]]]].
length_is_as_simple_as_it_seems() ->
__ =:= length([1, 2, 3]).
lists_of_tuples_can_be_found_by_key() ->
Meals = [{breakfast, eggs}, {lunch, pasta}, {dinner, burrito}],
{lunch, _} = lists:keyfind(__, 2, Meals).
|
|
06745f29da45b948266cc141d7aa9ed80fe8fd35043273b6b1c8b0cfbd4e6dd8 | Kappa-Dev/KappaTools | kfiles.ml | (******************************************************************************)
(* _ __ * The Kappa Language *)
| |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF
(* | ' / *********************************************************************)
(* | . \ * This file is distributed under the terms of the *)
(* |_|\_\ * GNU Lesser General Public License Version 3 *)
(******************************************************************************)
open Lwt.Infix
type item = {
rank : int;
content : string;
}
type catalog = {
elements : (string,item) Hashtbl.t;
index : string option Mods.DynArray.t;
ast : Ast.parsing_compil option ref;
}
type catalog_item = {
position : int;
id : string;
}
let write_catalog_item ob { position; id } =
let () = Buffer.add_char ob '{' in
let () = JsonUtil.write_field "id" Yojson.Basic.write_string ob id in
let () = JsonUtil.write_comma ob in
let () = JsonUtil.write_field "position" Yojson.Basic.write_int ob position in
Buffer.add_char ob '}'
let read_catalog_item p lb =
let (position,id,count) =
Yojson.Basic.read_fields
(fun (pos,i,c) key p lb ->
if key = "position" then (Yojson.Basic.read_int p lb,i,succ c)
else let () = assert (key = "id") in
(pos,Yojson.Basic.read_string p lb,succ c))
(-1,"",0) p lb in
let () = assert (count = 2) in { position; id }
let create () = {
elements = Hashtbl.create 1;
index = Mods.DynArray.create 1 None;
ast = ref None;
}
let put ~position:(rank) ~id ~content catalog =
let () = Hashtbl.replace catalog.elements id {rank; content} in
match Mods.DynArray.get catalog.index rank with
| None ->
let () = Mods.DynArray.set catalog.index rank (Some id) in
let () = catalog.ast := None in
Result.Ok ()
| Some aie ->
Result.Error
("Slot "^string_of_int rank^" is not available. There is already "^aie)
let file_create ~position ~id ~content catalog =
if Hashtbl.mem catalog.elements id then
Result.Error ("A file called \""^id^"\" is already present in the catalog")
else
put ~position ~id ~content catalog
let file_move ~position ~id catalog =
match Hashtbl.find_all catalog.elements id with
| [] -> Result.Error ("Missing file \""^id^"\" in the catalog")
| _ :: _ :: _ -> Result.Error "File catalog has serious problems"
| [ { rank; content } ] ->
let () = Mods.DynArray.set catalog.index rank None in
put ~position ~id ~content catalog
let file_patch ~id content catalog =
match Hashtbl.find_all catalog.elements id with
| [] -> Result.Error ("Unknown file \""^id^"\"")
| _ :: _ :: _ -> Result.Error "Serious problems in file catalog"
| [ { rank; _ } ] ->
let () = Hashtbl.replace catalog.elements id { rank; content } in
let () = catalog.ast := None in
Result.Ok ()
let file_delete ~id catalog =
match Hashtbl.find_all catalog.elements id with
| [] -> Result.Error ("No file \""^id^"\"")
| _ :: _ :: _ -> failwith "Big troubles in file catalog"
| [ { rank; _ } ] ->
let () = Mods.DynArray.set catalog.index rank None in
let () = Hashtbl.remove catalog.elements id in
let () = catalog.ast := None in
Result.Ok ()
let file_get ~id catalog =
match Hashtbl.find_all catalog.elements id with
| [] -> Result.Error ("File \""^id^"\" does not exist")
| _ :: _ :: _ -> Result.Error "Corrupted file catalog"
| [ { rank; content } ] ->
Result.Ok (content,rank)
let catalog catalog =
Mods.DynArray.fold_righti
(fun position x acc -> match x with
| None -> acc
| Some id -> { position; id }::acc)
catalog.index []
let parse yield catalog =
match !(catalog.ast) with
| Some compile -> Lwt.return (Result_util.ok compile)
| None ->
Mods.DynArray.fold_righti
(fun _ x acc -> match x with
| None -> acc
| Some x ->
let file = Hashtbl.find catalog.elements x in
let lexbuf = Lexing.from_string file.content in
let () = lexbuf.Lexing.lex_curr_p <-
{ lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = x } in
acc >>= fun (compile,err) ->
let compile =
{ compile with Ast.filenames = x :: compile.Ast.filenames } in
Lwt.catch
(fun () ->
(Lwt.wrap1 Klexer4.model lexbuf) >>=
(fun (insts,err') ->
(yield ()) >>=
(fun () ->
Lwt.return
(Cst.append_to_ast_compil insts compile,err'@err))))
(function
| ExceptionDefn.Syntax_Error (message,range)
| ExceptionDefn.Malformed_Decl (message,range)
| ExceptionDefn.Internal_Error (message,range) ->
Lwt.return (compile,(message,range)::err)
| Invalid_argument error ->
Lwt.return
(compile,
(Locality.dummy_annot ("Runtime error "^ error))::err)
| exn ->
let message = Printexc.to_string exn in
Lwt.return (compile,(Locality.dummy_annot message)::err))
) catalog.index (Lwt.return (Ast.empty_compil,[])) >>= function
| compile, [] ->
let () = catalog.ast := Some compile in
Lwt.return (Result_util.ok compile)
| _, err ->
let err = List.map
(fun (text,p as x) ->
let range =
if Locality.has_dummy_annot x then None else Some p in
{Result_util.severity = Logs.Error; range; text})
err in
Lwt.return (Result_util.error err)
let overwrite filename ast catalog =
let content = Format.asprintf "%a" Ast.print_parsing_compil_kappa ast in
let it = { rank = 0; content } in
let () = Hashtbl.reset catalog.elements in
let () = Hashtbl.add catalog.elements filename it in
let () =
Mods.DynArray.iteri
(fun i _ -> Mods.DynArray.set catalog.index i None)
catalog.index in
let () = Mods.DynArray.set catalog.index 0 (Some filename) in
catalog.ast := Some ast
| null | https://raw.githubusercontent.com/Kappa-Dev/KappaTools/777835b82f449d3d379713df76ff25fd5926b762/core/grammar/kfiles.ml | ocaml | ****************************************************************************
_ __ * The Kappa Language
| ' / ********************************************************************
| . \ * This file is distributed under the terms of the
|_|\_\ * GNU Lesser General Public License Version 3
**************************************************************************** | | |/ / * Copyright 2010 - 2020 CNRS - Harvard Medical School - INRIA - IRIF
open Lwt.Infix
type item = {
rank : int;
content : string;
}
type catalog = {
elements : (string,item) Hashtbl.t;
index : string option Mods.DynArray.t;
ast : Ast.parsing_compil option ref;
}
type catalog_item = {
position : int;
id : string;
}
let write_catalog_item ob { position; id } =
let () = Buffer.add_char ob '{' in
let () = JsonUtil.write_field "id" Yojson.Basic.write_string ob id in
let () = JsonUtil.write_comma ob in
let () = JsonUtil.write_field "position" Yojson.Basic.write_int ob position in
Buffer.add_char ob '}'
let read_catalog_item p lb =
let (position,id,count) =
Yojson.Basic.read_fields
(fun (pos,i,c) key p lb ->
if key = "position" then (Yojson.Basic.read_int p lb,i,succ c)
else let () = assert (key = "id") in
(pos,Yojson.Basic.read_string p lb,succ c))
(-1,"",0) p lb in
let () = assert (count = 2) in { position; id }
let create () = {
elements = Hashtbl.create 1;
index = Mods.DynArray.create 1 None;
ast = ref None;
}
let put ~position:(rank) ~id ~content catalog =
let () = Hashtbl.replace catalog.elements id {rank; content} in
match Mods.DynArray.get catalog.index rank with
| None ->
let () = Mods.DynArray.set catalog.index rank (Some id) in
let () = catalog.ast := None in
Result.Ok ()
| Some aie ->
Result.Error
("Slot "^string_of_int rank^" is not available. There is already "^aie)
let file_create ~position ~id ~content catalog =
if Hashtbl.mem catalog.elements id then
Result.Error ("A file called \""^id^"\" is already present in the catalog")
else
put ~position ~id ~content catalog
let file_move ~position ~id catalog =
match Hashtbl.find_all catalog.elements id with
| [] -> Result.Error ("Missing file \""^id^"\" in the catalog")
| _ :: _ :: _ -> Result.Error "File catalog has serious problems"
| [ { rank; content } ] ->
let () = Mods.DynArray.set catalog.index rank None in
put ~position ~id ~content catalog
let file_patch ~id content catalog =
match Hashtbl.find_all catalog.elements id with
| [] -> Result.Error ("Unknown file \""^id^"\"")
| _ :: _ :: _ -> Result.Error "Serious problems in file catalog"
| [ { rank; _ } ] ->
let () = Hashtbl.replace catalog.elements id { rank; content } in
let () = catalog.ast := None in
Result.Ok ()
let file_delete ~id catalog =
match Hashtbl.find_all catalog.elements id with
| [] -> Result.Error ("No file \""^id^"\"")
| _ :: _ :: _ -> failwith "Big troubles in file catalog"
| [ { rank; _ } ] ->
let () = Mods.DynArray.set catalog.index rank None in
let () = Hashtbl.remove catalog.elements id in
let () = catalog.ast := None in
Result.Ok ()
let file_get ~id catalog =
match Hashtbl.find_all catalog.elements id with
| [] -> Result.Error ("File \""^id^"\" does not exist")
| _ :: _ :: _ -> Result.Error "Corrupted file catalog"
| [ { rank; content } ] ->
Result.Ok (content,rank)
let catalog catalog =
Mods.DynArray.fold_righti
(fun position x acc -> match x with
| None -> acc
| Some id -> { position; id }::acc)
catalog.index []
let parse yield catalog =
match !(catalog.ast) with
| Some compile -> Lwt.return (Result_util.ok compile)
| None ->
Mods.DynArray.fold_righti
(fun _ x acc -> match x with
| None -> acc
| Some x ->
let file = Hashtbl.find catalog.elements x in
let lexbuf = Lexing.from_string file.content in
let () = lexbuf.Lexing.lex_curr_p <-
{ lexbuf.Lexing.lex_curr_p with Lexing.pos_fname = x } in
acc >>= fun (compile,err) ->
let compile =
{ compile with Ast.filenames = x :: compile.Ast.filenames } in
Lwt.catch
(fun () ->
(Lwt.wrap1 Klexer4.model lexbuf) >>=
(fun (insts,err') ->
(yield ()) >>=
(fun () ->
Lwt.return
(Cst.append_to_ast_compil insts compile,err'@err))))
(function
| ExceptionDefn.Syntax_Error (message,range)
| ExceptionDefn.Malformed_Decl (message,range)
| ExceptionDefn.Internal_Error (message,range) ->
Lwt.return (compile,(message,range)::err)
| Invalid_argument error ->
Lwt.return
(compile,
(Locality.dummy_annot ("Runtime error "^ error))::err)
| exn ->
let message = Printexc.to_string exn in
Lwt.return (compile,(Locality.dummy_annot message)::err))
) catalog.index (Lwt.return (Ast.empty_compil,[])) >>= function
| compile, [] ->
let () = catalog.ast := Some compile in
Lwt.return (Result_util.ok compile)
| _, err ->
let err = List.map
(fun (text,p as x) ->
let range =
if Locality.has_dummy_annot x then None else Some p in
{Result_util.severity = Logs.Error; range; text})
err in
Lwt.return (Result_util.error err)
let overwrite filename ast catalog =
let content = Format.asprintf "%a" Ast.print_parsing_compil_kappa ast in
let it = { rank = 0; content } in
let () = Hashtbl.reset catalog.elements in
let () = Hashtbl.add catalog.elements filename it in
let () =
Mods.DynArray.iteri
(fun i _ -> Mods.DynArray.set catalog.index i None)
catalog.index in
let () = Mods.DynArray.set catalog.index 0 (Some filename) in
catalog.ast := Some ast
|
20b0d1f6260e3cf639e2945b69b4ab356cc0774c34986dbf8c57df1da4a8fcbc | conscell/hugs-android | Eliza.hs | -- Eliza: an implementation of the classic pseudo-psychoanalyst ---------------
--
Gofer version by , January 12 1992 .
Modified for Hugs 1.3 , August 1996 .
--
-- Adapted from a pascal implementation provided as part of an experimental
package from ( ) , Univ . of KY . with original
pascal code apparently provided by ( ) .
-------------------------------------------------------------------------------
module Eliza where
import Interact
import Char(toUpper)
eliza = interact (writeStr hi $ session initial [])
where hi = "\n\
\Hi! I'm Eliza. I am your personal therapy computer.\n\
\Please tell me your problem.\n\
\\n"
-- Read a line at a time, and produce some kind of response -------------------
session rs prev
= readLine "> " (\l ->
let ws = words (trim l)
(response,rs') = if prev==ws then repeated rs else answer rs ws
in writeStr (response ++ "\n\n") $ session rs' ws)
trim :: String -> String -- strip punctuation characters
trim = foldr cons "" . dropWhile (`elem` punct)
where x `cons` xs | x `elem` punct && null xs = []
| otherwise = x : xs
punct = [' ', '.', '!', '?', ',']
answer :: State -> Words -> (String, State)
answer st l = (response, newKeyTab kt st)
where (response, kt) = ans (keyTabOf st)
e `cons` (r, es) = (r, e:es)
ans (e:es) | null rs = e `cons` ans es
| otherwise = (makeResponse a (head rs), (key,as):es)
where rs = replies key l
(key,(a:as)) = e
-- Find all possible replies (without leading string for given key ------------
replies :: Words -> Words -> [String]
replies key l = ( map (conjug l . drop (length key))
. filter (prefix key . map ucase)
. netails) l
prefix :: Eq a => [a] -> [a] -> Bool
[] `prefix` xs = True
(x:xs) `prefix` [] = False
(x:xs) `prefix` (y:ys) = x==y && (xs `prefix` ys)
netails :: [a] -> [[a]] -- non-empty tails of list
netails [] = []
netails xs = xs : netails (tail xs)
ucase :: String -> String -- map string to upper case
ucase = map toUpper
-- Replace keywords in a list of words with appropriate conjugations ----------
conjug :: Words -> Words -> String
conjug d = unwords . trailingI . map conj . maybe d -- d is default input
where maybe d xs = if null xs then d else xs
conj w = head ([m | (w',m)<-conjugates, uw==w'] ++ [w])
where uw = ucase w
trailingI = foldr cons []
where x `cons` xs | x=="I" && null xs = ["me"]
| otherwise = x:xs
conjugates :: [(String, String)]
conjugates = prepare (oneways ++ concat [[(x,y), (y,x)] | (x,y) <- bothways])
where oneways = [ ("me", "you") ]
bothways = [ ("are", "am"), ("we're", "was"),
("you", "I"), ("your", "my"),
("I've", "you've"), ("I'm", "you're") ]
prepare = map (\(w,r) -> (ucase w, r))
-- Response data --------------------------------------------------------------
type Words = [String]
type KeyTable = [(Key, Replies)]
type Replies = [String]
type State = (KeyTable, Replies)
type Key = Words
repeated :: State -> (String, State)
repeated (kt, (r:rp)) = (r, (kt, rp))
newKeyTab :: KeyTable -> State -> State
newKeyTab kt' (kt, rp) = (kt', rp)
keyTabOf :: State -> KeyTable
keyTabOf (kt, rp) = kt
makeResponse :: String -> String -> String
makeResponse ('?':cs) us = cs ++ " " ++ us ++ "?"
makeResponse ('.':cs) us = cs ++ " " ++ us ++ "."
makeResponse cs us = cs
initial :: State
initial = ([(words k, cycle rs) | (k,rs) <-respMsgs], cycle repeatMsgs)
repeatMsgs = [ "Why did you repeat yourself?",
"Do you expect a different answer by repeating yourself?",
"Come, come, elucidate your thoughts.",
"Please don't repeat yourself!" ]
respMsgs = [ ("CAN YOU", canYou),
("CAN I", canI),
("YOU ARE", youAre),
("YOU'RE", youAre),
("I DON'T", iDont),
("I FEEL", iFeel),
("WHY DON'T YOU", whyDont),
("WHY CAN'T I", whyCant),
("ARE YOU", areYou),
("I CAN'T", iCant),
("I AM", iAm),
("I'M", iAm),
("YOU", you),
("YES", yes),
("NO", no),
("COMPUTER", computer),
("COMPUTERS", computer),
("I WANT", iWant),
("WHAT", question),
("HOW", question),
("WHO", question),
("WHERE", question),
("WHEN", question),
("WHY", question),
("NAME", name),
("BECAUSE", because),
("CAUSE", because),
("SORRY", sorry),
("DREAM", dream),
("DREAMS", dream),
("HI", hello),
("HELLO", hello),
("MAYBE", maybe),
("YOUR", your),
("ALWAYS", always),
("THINK", think),
("ALIKE", alike),
("FRIEND", friend),
("FRIENDS", friend),
("", nokeyMsgs) ]
where
canYou = [ "?Don't you believe that I can",
"?Perhaps you would like to be able to",
"?You want me to be able to" ]
canI = [ "?Perhaps you don't want to",
"?Do you want to be able to" ]
youAre = [ "?What makes you think I am",
"?Does it please you to believe I am",
"?Perhaps you would like to be",
"?Do you sometimes wish you were" ]
iDont = [ "?Don't you really",
"?Why don't you",
"?Do you wish to be able to",
"Does that trouble you?" ]
iFeel = [ "Tell me more about such feelings.",
"?Do you often feel",
"?Do you enjoy feeling" ]
whyDont = [ "?Do you really believe I don't",
".Perhaps in good time I will",
"?Do you want me to" ]
whyCant = [ "?Do you think you should be able to",
"?Why can't you" ]
areYou = [ "?Why are you interested in whether or not I am",
"?Would you prefer if I were not",
"?Perhaps in your fantasies I am" ]
iCant = [ "?How do you know you can't",
"Have you tried?",
"?Perhaps you can now" ]
iAm = [ "?Did you come to me because you are",
"?How long have you been",
"?Do you believe it is normal to be",
"?Do you enjoy being" ]
you = [ "We were discussing you --not me.",
"?Oh,",
"You're not really talking about me, are you?" ]
yes = [ "You seem quite positive.",
"Are you Sure?",
"I see.",
"I understand." ]
no = [ "Are you saying no just to be negative?",
"You are being a bit negative.",
"Why not?",
"Are you sure?",
"Why no?" ]
computer = [ "Do computers worry you?",
"Are you talking about me in particular?",
"Are you frightened by machines?",
"Why do you mention computers?",
"What do you think machines have to do with your problems?",
"Don't you think computers can help people?",
"What is it about machines that worries you?" ]
iWant = [ "?Why do you want",
"?What would it mean to you if you got",
"?Suppose you got",
"?What if you never got",
".I sometimes also want" ]
question = [ "Why do you ask?",
"Does that question interest you?",
"What answer would please you the most?",
"What do you think?",
"Are such questions on your mind often?",
"What is it that you really want to know?",
"Have you asked anyone else?",
"Have you asked such questions before?",
"What else comes to mind when you ask that?" ]
name = [ "Names don't interest me.",
"I don't care about names --please go on." ]
because = [ "Is that the real reason?",
"Don't any other reasons come to mind?",
"Does that reason explain anything else?",
"What other reasons might there be?" ]
sorry = [ "Please don't apologise!",
"Apologies are not necessary.",
"What feelings do you have when you apologise?",
"Don't be so defensive!" ]
dream = [ "What does that dream suggest to you?",
"Do you dream often?",
"What persons appear in your dreams?",
"Are you disturbed by your dreams?" ]
hello = [ "How do you...please state your problem." ]
maybe = [ "You don't seem quite certain.",
"Why the uncertain tone?",
"Can't you be more positive?",
"You aren't sure?",
"Don't you know?" ]
your = [ "?Why are you concerned about my",
"?What about your own" ]
always = [ "Can you think of a specific example?",
"When?",
"What are you thinking of?",
"Really, always?" ]
think = [ "Do you really think so?",
"?But you are not sure you",
"?Do you doubt you" ]
alike = [ "In what way?",
"What resemblence do you see?",
"What does the similarity suggest to you?",
"What other connections do you see?",
"Cound there really be some connection?",
"How?" ]
friend = [ "Why do you bring up the topic of friends?",
"Do your friends worry you?",
"Do your friends pick on you?",
"Are you sure you have any friends?",
"Do you impose on your friends?",
"Perhaps your love for friends worries you." ]
nokeyMsgs = [ "I'm not sure I understand you fully.",
"What does that suggest to you?",
"I see.",
"Can you elaborate on that?",
"Say, do you have any psychological problems?" ]
-------------------------------------------------------------------------------
| null | https://raw.githubusercontent.com/conscell/hugs-android/31e5861bc1a1dd9931e6b2471a9f45c14e3c6c7e/hugs/lib/hugs/demos/Eliza.hs | haskell | Eliza: an implementation of the classic pseudo-psychoanalyst ---------------
Adapted from a pascal implementation provided as part of an experimental
-----------------------------------------------------------------------------
Read a line at a time, and produce some kind of response -------------------
strip punctuation characters
Find all possible replies (without leading string for given key ------------
non-empty tails of list
map string to upper case
Replace keywords in a list of words with appropriate conjugations ----------
d is default input
Response data --------------------------------------------------------------
----------------------------------------------------------------------------- | Gofer version by , January 12 1992 .
Modified for Hugs 1.3 , August 1996 .
package from ( ) , Univ . of KY . with original
pascal code apparently provided by ( ) .
module Eliza where
import Interact
import Char(toUpper)
eliza = interact (writeStr hi $ session initial [])
where hi = "\n\
\Hi! I'm Eliza. I am your personal therapy computer.\n\
\Please tell me your problem.\n\
\\n"
session rs prev
= readLine "> " (\l ->
let ws = words (trim l)
(response,rs') = if prev==ws then repeated rs else answer rs ws
in writeStr (response ++ "\n\n") $ session rs' ws)
trim = foldr cons "" . dropWhile (`elem` punct)
where x `cons` xs | x `elem` punct && null xs = []
| otherwise = x : xs
punct = [' ', '.', '!', '?', ',']
answer :: State -> Words -> (String, State)
answer st l = (response, newKeyTab kt st)
where (response, kt) = ans (keyTabOf st)
e `cons` (r, es) = (r, e:es)
ans (e:es) | null rs = e `cons` ans es
| otherwise = (makeResponse a (head rs), (key,as):es)
where rs = replies key l
(key,(a:as)) = e
replies :: Words -> Words -> [String]
replies key l = ( map (conjug l . drop (length key))
. filter (prefix key . map ucase)
. netails) l
prefix :: Eq a => [a] -> [a] -> Bool
[] `prefix` xs = True
(x:xs) `prefix` [] = False
(x:xs) `prefix` (y:ys) = x==y && (xs `prefix` ys)
netails [] = []
netails xs = xs : netails (tail xs)
ucase = map toUpper
conjug :: Words -> Words -> String
where maybe d xs = if null xs then d else xs
conj w = head ([m | (w',m)<-conjugates, uw==w'] ++ [w])
where uw = ucase w
trailingI = foldr cons []
where x `cons` xs | x=="I" && null xs = ["me"]
| otherwise = x:xs
conjugates :: [(String, String)]
conjugates = prepare (oneways ++ concat [[(x,y), (y,x)] | (x,y) <- bothways])
where oneways = [ ("me", "you") ]
bothways = [ ("are", "am"), ("we're", "was"),
("you", "I"), ("your", "my"),
("I've", "you've"), ("I'm", "you're") ]
prepare = map (\(w,r) -> (ucase w, r))
type Words = [String]
type KeyTable = [(Key, Replies)]
type Replies = [String]
type State = (KeyTable, Replies)
type Key = Words
repeated :: State -> (String, State)
repeated (kt, (r:rp)) = (r, (kt, rp))
newKeyTab :: KeyTable -> State -> State
newKeyTab kt' (kt, rp) = (kt', rp)
keyTabOf :: State -> KeyTable
keyTabOf (kt, rp) = kt
makeResponse :: String -> String -> String
makeResponse ('?':cs) us = cs ++ " " ++ us ++ "?"
makeResponse ('.':cs) us = cs ++ " " ++ us ++ "."
makeResponse cs us = cs
initial :: State
initial = ([(words k, cycle rs) | (k,rs) <-respMsgs], cycle repeatMsgs)
repeatMsgs = [ "Why did you repeat yourself?",
"Do you expect a different answer by repeating yourself?",
"Come, come, elucidate your thoughts.",
"Please don't repeat yourself!" ]
respMsgs = [ ("CAN YOU", canYou),
("CAN I", canI),
("YOU ARE", youAre),
("YOU'RE", youAre),
("I DON'T", iDont),
("I FEEL", iFeel),
("WHY DON'T YOU", whyDont),
("WHY CAN'T I", whyCant),
("ARE YOU", areYou),
("I CAN'T", iCant),
("I AM", iAm),
("I'M", iAm),
("YOU", you),
("YES", yes),
("NO", no),
("COMPUTER", computer),
("COMPUTERS", computer),
("I WANT", iWant),
("WHAT", question),
("HOW", question),
("WHO", question),
("WHERE", question),
("WHEN", question),
("WHY", question),
("NAME", name),
("BECAUSE", because),
("CAUSE", because),
("SORRY", sorry),
("DREAM", dream),
("DREAMS", dream),
("HI", hello),
("HELLO", hello),
("MAYBE", maybe),
("YOUR", your),
("ALWAYS", always),
("THINK", think),
("ALIKE", alike),
("FRIEND", friend),
("FRIENDS", friend),
("", nokeyMsgs) ]
where
canYou = [ "?Don't you believe that I can",
"?Perhaps you would like to be able to",
"?You want me to be able to" ]
canI = [ "?Perhaps you don't want to",
"?Do you want to be able to" ]
youAre = [ "?What makes you think I am",
"?Does it please you to believe I am",
"?Perhaps you would like to be",
"?Do you sometimes wish you were" ]
iDont = [ "?Don't you really",
"?Why don't you",
"?Do you wish to be able to",
"Does that trouble you?" ]
iFeel = [ "Tell me more about such feelings.",
"?Do you often feel",
"?Do you enjoy feeling" ]
whyDont = [ "?Do you really believe I don't",
".Perhaps in good time I will",
"?Do you want me to" ]
whyCant = [ "?Do you think you should be able to",
"?Why can't you" ]
areYou = [ "?Why are you interested in whether or not I am",
"?Would you prefer if I were not",
"?Perhaps in your fantasies I am" ]
iCant = [ "?How do you know you can't",
"Have you tried?",
"?Perhaps you can now" ]
iAm = [ "?Did you come to me because you are",
"?How long have you been",
"?Do you believe it is normal to be",
"?Do you enjoy being" ]
you = [ "We were discussing you --not me.",
"?Oh,",
"You're not really talking about me, are you?" ]
yes = [ "You seem quite positive.",
"Are you Sure?",
"I see.",
"I understand." ]
no = [ "Are you saying no just to be negative?",
"You are being a bit negative.",
"Why not?",
"Are you sure?",
"Why no?" ]
computer = [ "Do computers worry you?",
"Are you talking about me in particular?",
"Are you frightened by machines?",
"Why do you mention computers?",
"What do you think machines have to do with your problems?",
"Don't you think computers can help people?",
"What is it about machines that worries you?" ]
iWant = [ "?Why do you want",
"?What would it mean to you if you got",
"?Suppose you got",
"?What if you never got",
".I sometimes also want" ]
question = [ "Why do you ask?",
"Does that question interest you?",
"What answer would please you the most?",
"What do you think?",
"Are such questions on your mind often?",
"What is it that you really want to know?",
"Have you asked anyone else?",
"Have you asked such questions before?",
"What else comes to mind when you ask that?" ]
name = [ "Names don't interest me.",
"I don't care about names --please go on." ]
because = [ "Is that the real reason?",
"Don't any other reasons come to mind?",
"Does that reason explain anything else?",
"What other reasons might there be?" ]
sorry = [ "Please don't apologise!",
"Apologies are not necessary.",
"What feelings do you have when you apologise?",
"Don't be so defensive!" ]
dream = [ "What does that dream suggest to you?",
"Do you dream often?",
"What persons appear in your dreams?",
"Are you disturbed by your dreams?" ]
hello = [ "How do you...please state your problem." ]
maybe = [ "You don't seem quite certain.",
"Why the uncertain tone?",
"Can't you be more positive?",
"You aren't sure?",
"Don't you know?" ]
your = [ "?Why are you concerned about my",
"?What about your own" ]
always = [ "Can you think of a specific example?",
"When?",
"What are you thinking of?",
"Really, always?" ]
think = [ "Do you really think so?",
"?But you are not sure you",
"?Do you doubt you" ]
alike = [ "In what way?",
"What resemblence do you see?",
"What does the similarity suggest to you?",
"What other connections do you see?",
"Cound there really be some connection?",
"How?" ]
friend = [ "Why do you bring up the topic of friends?",
"Do your friends worry you?",
"Do your friends pick on you?",
"Are you sure you have any friends?",
"Do you impose on your friends?",
"Perhaps your love for friends worries you." ]
nokeyMsgs = [ "I'm not sure I understand you fully.",
"What does that suggest to you?",
"I see.",
"Can you elaborate on that?",
"Say, do you have any psychological problems?" ]
|
fa41e131665c8c840e12ba3d49246754933cf743303da997108c5f1bf4e90910 | HaskellForCats/HaskellForCats | findAvPrimes2.hs | module FindAvTruPrimes where
{- taking a list of primes and then finding the average of that list that is itself a prime
-}
- let lX = ( sum findAvTruPrimes 101 ) ` div ` ( length ( findAvTruPrimes 101 ) )
* FindAvTruPrimes > ( prime ( average ( findAvTruPrimes 101 ) ) )
True
- let lX = (sum findAvTruPrimes 101) `div` (length (findAvTruPrimes 101))
*FindAvTruPrimes> (prime (average (findAvTruPrimes 101)))
True
-}
factors n = [x| x <- [1..n], n `mod` x == 0]
prime n = factors n == [1,n]
primes n = [x | x <- [2..n], prime x]
average ns = sum ns `div` length ns
avPrime n = prime (average (primes n))
find k t = [v | (k', v) <- t, k == k']
odds n = map (\x -> x * 2 + 1) [0..n -1]
prime_tups n = zip (primes n) [prime x | x <- primes n]
prime_Tups n = zip [prime x | x <- primes n] (primes n)
findPrimeTups n = find True (prime_Tups n)
primeTups n = zip [avPrime x | x <- primes n] (primes n)
findAvTruPrimes n = find True (primeTups n)
| null | https://raw.githubusercontent.com/HaskellForCats/HaskellForCats/2d7a15c0cdaa262c157bbf37af6e72067bc279bc/findAvPrimes2.hs | haskell | taking a list of primes and then finding the average of that list that is itself a prime
| module FindAvTruPrimes where
- let lX = ( sum findAvTruPrimes 101 ) ` div ` ( length ( findAvTruPrimes 101 ) )
* FindAvTruPrimes > ( prime ( average ( findAvTruPrimes 101 ) ) )
True
- let lX = (sum findAvTruPrimes 101) `div` (length (findAvTruPrimes 101))
*FindAvTruPrimes> (prime (average (findAvTruPrimes 101)))
True
-}
factors n = [x| x <- [1..n], n `mod` x == 0]
prime n = factors n == [1,n]
primes n = [x | x <- [2..n], prime x]
average ns = sum ns `div` length ns
avPrime n = prime (average (primes n))
find k t = [v | (k', v) <- t, k == k']
odds n = map (\x -> x * 2 + 1) [0..n -1]
prime_tups n = zip (primes n) [prime x | x <- primes n]
prime_Tups n = zip [prime x | x <- primes n] (primes n)
findPrimeTups n = find True (prime_Tups n)
primeTups n = zip [avPrime x | x <- primes n] (primes n)
findAvTruPrimes n = find True (primeTups n)
|
2df03e5ca16de081b53ad48fbae78b97677609cf9741f09f267a58d7e7f6c9ba | samanthadoran/effective-guacamole | console.lisp | (defpackage #:psx-console
(:nicknames #:psx)
(:use :cl :psx-cpu :memory)
(:export #:make-psx #:load-rom-from-file #:console-on #:make-console
#:setup-and-run))
(in-package :psx-console)
(declaim (optimize (speed 3) (safety 1)))
(defstruct psx
"A model psx"
(scheduler (psx-scheduler:make-scheduler) :type psx-scheduler:scheduler)
(cpu (make-cpu) :type cpu)
(irq (psx-irq:make-irq) :type psx-irq:irq)
(timers (psx-timers:make-timers) :type psx-timers:timers)
(cdrom (psx-cdrom:make-cdrom) :type psx-cdrom:cdrom)
(joypads (psx-joypads:make-joypads) :type psx-joypads:joypads)
(gpu (psx-gpu:make-gpu) :type psx-gpu:gpu)
(spu (psx-spu:make-spu) :type psx-spu:spu)
; TODO(Samantha): I'm not convinced this is going to work out cleanly.
(dma (psx-dma:make-dma) :type psx-dma:dma)
(bios-rom
(make-array #x80000 :element-type '(unsigned-byte 8) :initial-element 0)
:type (simple-array (unsigned-byte 8) (#x80000)))
; The #x200000s here are indicative of the non-mirrored ram size of the psx.
; We already have a constant for this size, but using it here makes the
; macroexpander cry.
(ram
(make-array +ram-size-non-mirrored+ :element-type '(unsigned-byte 8) :initial-element 0)
:type (simple-array (unsigned-byte 8) (#.+ram-size-non-mirrored+)))
(data-cache
(make-array +data-cache-size+ :element-type '(unsigned-byte 8) :initial-element 0)
:type (simple-array (unsigned-byte 8) (#.+data-cache-size+))))
(defun load-rom-from-file (filepath)
(with-open-file (stream filepath :element-type '(unsigned-byte 8))
(let ((rom (make-array (file-length stream)
:element-type '(unsigned-byte 8))))
(read-sequence rom stream)
rom)))
(declaim (ftype (function (psx pathname &optional pathname)) console-on))
(defun console-on (psx bios-rom-path &optional iso-path)
(when iso-path
(setf (psx-cdrom:cdrom-image (psx-cdrom psx))
(load-rom-from-file iso-path)))
(setf (psx-bios-rom psx) (load-rom-from-file bios-rom-path))
(map-memory psx)
(psx-cpu:power-on (psx-cpu psx))
(psx-gpu:power-on (psx-gpu psx))
(setf (psx-scheduler:component-sync-callback
(aref (psx-scheduler:scheduler-components (psx-scheduler psx)) 0))
(lambda (epoch) (psx-gpu:sync (psx-gpu psx) epoch)))
(setf (psx-scheduler:component-sync-callback
(aref (psx-scheduler:scheduler-components (psx-scheduler psx)) 1))
(lambda (epoch)
(declare (ignore epoch))
(psx-timers:sync-timers (psx-timers psx))))
(setf (psx-scheduler:component-sync-callback
(aref (psx-scheduler:scheduler-components (psx-scheduler psx)) 2))
(lambda (epoch)
(psx-joypads:sync (psx-joypads psx) epoch)))
(setf (psx-scheduler:component-sync-callback
(aref (psx-scheduler:scheduler-components (psx-scheduler psx)) 3))
(lambda (epoch)
(psx-cdrom:sync (psx-cdrom psx) epoch)))
(setf (psx-timers::timers-system-clock-callback (psx-timers psx))
(lambda () (psx-scheduler:scheduler-master-clock (psx-scheduler psx))))
(setf (psx-cdrom::cdrom-system-clock-callback (psx-cdrom psx))
(lambda () (psx-scheduler:scheduler-master-clock (psx-scheduler psx))))
(psx-timers:init-timers (psx-timers psx))
(values))
; TODO(Samantha): Rename this to something more descriptive
; (declaim (ftype (function (pathname) psx) make-console))
(defun make-console (bios-rom-path &key iso-path)
(let ((my-psx (make-psx)))
(console-on my-psx bios-rom-path iso-path)
my-psx))
; TODO(Samantha): Figure out the type specifier for this.
(defun exe-should-be-loaded (psx exe-path)
(and
(= (psx-cpu::cpu-program-counter (psx-cpu psx)) #x80030000)
exe-path))
(declaim (ftype (function (psx pathname))
load-exe))
(defun load-exe (psx exe-path)
"Loads a psx-exe at the location specified by path."
(let* ((exe (load-rom-from-file exe-path))
(pc (read-word-from-byte-array exe #x10))
(r28 (read-word-from-byte-array exe #x14))
(r29 (read-word-from-byte-array exe #x30))
(r30 (+ r29 (read-word-from-byte-array exe #x34)))
(base-in-ram (read-word-from-byte-array exe #x18))
(exe-size (- (array-dimension exe 0) #x800)))
(setf (aref (psx-cpu::cpu-registers (psx-cpu psx)) 28)
r28)
(setf (aref (psx-cpu::cpu-registers (psx-cpu psx)) 29)
r29)
(setf (aref (psx-cpu::cpu-registers (psx-cpu psx)) 30)
r30)
(setf (psx-cpu::cpu-program-counter (psx-cpu psx))
pc)
(setf (psx-cpu::cpu-next-program-counter (psx-cpu psx))
(+ pc 4))
(loop for i from 0 to (1- exe-size)
do (write-byte* psx (+ i base-in-ram) (aref exe (+ i #x800))))
(values)))
(declaim (ftype (function (pathname &optional pathname)
(unsigned-byte 32))
setup-and-run))
(defun setup-and-run (bios-rom-path &key exe-path iso-path)
(psx-renderer:initialize)
(psx-input:init-pads)
(let ((psx (make-console bios-rom-path :iso-path iso-path)))
(loop for cpu-clocks = (step-cpu (psx-cpu psx))
do (when (exe-should-be-loaded psx exe-path)
(load-exe psx exe-path))
do (psx-scheduler:sync-components (psx-scheduler psx) cpu-clocks)))
0)
| null | https://raw.githubusercontent.com/samanthadoran/effective-guacamole/89fa1a8c0527e519e4a1a0b8f85b041843b99099/console.lisp | lisp | TODO(Samantha): I'm not convinced this is going to work out cleanly.
The #x200000s here are indicative of the non-mirrored ram size of the psx.
We already have a constant for this size, but using it here makes the
macroexpander cry.
TODO(Samantha): Rename this to something more descriptive
(declaim (ftype (function (pathname) psx) make-console))
TODO(Samantha): Figure out the type specifier for this. | (defpackage #:psx-console
(:nicknames #:psx)
(:use :cl :psx-cpu :memory)
(:export #:make-psx #:load-rom-from-file #:console-on #:make-console
#:setup-and-run))
(in-package :psx-console)
(declaim (optimize (speed 3) (safety 1)))
(defstruct psx
"A model psx"
(scheduler (psx-scheduler:make-scheduler) :type psx-scheduler:scheduler)
(cpu (make-cpu) :type cpu)
(irq (psx-irq:make-irq) :type psx-irq:irq)
(timers (psx-timers:make-timers) :type psx-timers:timers)
(cdrom (psx-cdrom:make-cdrom) :type psx-cdrom:cdrom)
(joypads (psx-joypads:make-joypads) :type psx-joypads:joypads)
(gpu (psx-gpu:make-gpu) :type psx-gpu:gpu)
(spu (psx-spu:make-spu) :type psx-spu:spu)
(dma (psx-dma:make-dma) :type psx-dma:dma)
(bios-rom
(make-array #x80000 :element-type '(unsigned-byte 8) :initial-element 0)
:type (simple-array (unsigned-byte 8) (#x80000)))
(ram
(make-array +ram-size-non-mirrored+ :element-type '(unsigned-byte 8) :initial-element 0)
:type (simple-array (unsigned-byte 8) (#.+ram-size-non-mirrored+)))
(data-cache
(make-array +data-cache-size+ :element-type '(unsigned-byte 8) :initial-element 0)
:type (simple-array (unsigned-byte 8) (#.+data-cache-size+))))
(defun load-rom-from-file (filepath)
(with-open-file (stream filepath :element-type '(unsigned-byte 8))
(let ((rom (make-array (file-length stream)
:element-type '(unsigned-byte 8))))
(read-sequence rom stream)
rom)))
(declaim (ftype (function (psx pathname &optional pathname)) console-on))
(defun console-on (psx bios-rom-path &optional iso-path)
(when iso-path
(setf (psx-cdrom:cdrom-image (psx-cdrom psx))
(load-rom-from-file iso-path)))
(setf (psx-bios-rom psx) (load-rom-from-file bios-rom-path))
(map-memory psx)
(psx-cpu:power-on (psx-cpu psx))
(psx-gpu:power-on (psx-gpu psx))
(setf (psx-scheduler:component-sync-callback
(aref (psx-scheduler:scheduler-components (psx-scheduler psx)) 0))
(lambda (epoch) (psx-gpu:sync (psx-gpu psx) epoch)))
(setf (psx-scheduler:component-sync-callback
(aref (psx-scheduler:scheduler-components (psx-scheduler psx)) 1))
(lambda (epoch)
(declare (ignore epoch))
(psx-timers:sync-timers (psx-timers psx))))
(setf (psx-scheduler:component-sync-callback
(aref (psx-scheduler:scheduler-components (psx-scheduler psx)) 2))
(lambda (epoch)
(psx-joypads:sync (psx-joypads psx) epoch)))
(setf (psx-scheduler:component-sync-callback
(aref (psx-scheduler:scheduler-components (psx-scheduler psx)) 3))
(lambda (epoch)
(psx-cdrom:sync (psx-cdrom psx) epoch)))
(setf (psx-timers::timers-system-clock-callback (psx-timers psx))
(lambda () (psx-scheduler:scheduler-master-clock (psx-scheduler psx))))
(setf (psx-cdrom::cdrom-system-clock-callback (psx-cdrom psx))
(lambda () (psx-scheduler:scheduler-master-clock (psx-scheduler psx))))
(psx-timers:init-timers (psx-timers psx))
(values))
(defun make-console (bios-rom-path &key iso-path)
(let ((my-psx (make-psx)))
(console-on my-psx bios-rom-path iso-path)
my-psx))
(defun exe-should-be-loaded (psx exe-path)
(and
(= (psx-cpu::cpu-program-counter (psx-cpu psx)) #x80030000)
exe-path))
(declaim (ftype (function (psx pathname))
load-exe))
(defun load-exe (psx exe-path)
"Loads a psx-exe at the location specified by path."
(let* ((exe (load-rom-from-file exe-path))
(pc (read-word-from-byte-array exe #x10))
(r28 (read-word-from-byte-array exe #x14))
(r29 (read-word-from-byte-array exe #x30))
(r30 (+ r29 (read-word-from-byte-array exe #x34)))
(base-in-ram (read-word-from-byte-array exe #x18))
(exe-size (- (array-dimension exe 0) #x800)))
(setf (aref (psx-cpu::cpu-registers (psx-cpu psx)) 28)
r28)
(setf (aref (psx-cpu::cpu-registers (psx-cpu psx)) 29)
r29)
(setf (aref (psx-cpu::cpu-registers (psx-cpu psx)) 30)
r30)
(setf (psx-cpu::cpu-program-counter (psx-cpu psx))
pc)
(setf (psx-cpu::cpu-next-program-counter (psx-cpu psx))
(+ pc 4))
(loop for i from 0 to (1- exe-size)
do (write-byte* psx (+ i base-in-ram) (aref exe (+ i #x800))))
(values)))
(declaim (ftype (function (pathname &optional pathname)
(unsigned-byte 32))
setup-and-run))
(defun setup-and-run (bios-rom-path &key exe-path iso-path)
(psx-renderer:initialize)
(psx-input:init-pads)
(let ((psx (make-console bios-rom-path :iso-path iso-path)))
(loop for cpu-clocks = (step-cpu (psx-cpu psx))
do (when (exe-should-be-loaded psx exe-path)
(load-exe psx exe-path))
do (psx-scheduler:sync-components (psx-scheduler psx) cpu-clocks)))
0)
|
362bbf0d2346b1001a6f73c0c2af830a4a30fc91ccd3cd36ec0bcdb1c6ebbd33 | programaker-project/Programaker-Core | automate_rest_api_program_assets_by_id.erl | -module(automate_rest_api_program_assets_by_id).
-export([ init/2
, allowed_methods/2
, options/2
, is_authorized/2
, content_types_provided/2
, resource_exists/2
]).
-export([ retrieve_file/2
]).
-include("./records.hrl").
-include("../../automate_storage/src/records.hrl").
-define(UTILS, automate_rest_api_utils).
Seconds in a year
-record(state, { owner_id :: owner_id() | undefined
, program_id :: binary()
, asset_id :: binary()
, asset_info :: #user_asset_entry{} | undefined
}).
-spec init(_,_) -> {'cowboy_rest',_,_}.
init(Req, _Opts) ->
Req1 = automate_rest_api_cors:set_headers(Req),
ProgramId = cowboy_req:binding(program_id, Req1),
AssetId = cowboy_req:binding(asset_id, Req1),
{cowboy_rest, Req1
, #state{ program_id=ProgramId
, asset_id=AssetId
, owner_id=undefined
, asset_info=undefined
}}.
resource_exists(Req, State=#state{program_id=ProgramId, asset_id=AssetId}) ->
{ok, Owner} = automate_storage:get_program_owner(ProgramId),
case automate_storage:get_user_asset_info(Owner, AssetId) of
{error, not_found} ->
{false, Req, State};
{ok, AssetInfo} ->
{true, Req, State#state{owner_id=Owner, asset_info=AssetInfo}}
end.
%% CORS
options(Req, State) ->
{ok, Req, State}.
%% Authentication
-spec allowed_methods(cowboy_req:req(),_) -> {[binary()], cowboy_req:req(),_}.
allowed_methods(Req, State) ->
{[<<"GET">>, <<"OPTIONS">>], Req, State}.
is_authorized(Req, State=#state{owner_id=_OwnerId}) ->
case cowboy_req:method(Req) of
%% Don't do authentication if it's just asking for options
<<"OPTIONS">> ->
{ true, Req, State };
<<"GET">> ->
{ true, Req, State }
end.
%% Image handler
content_types_provided(Req, State) ->
{[{{<<"octet">>, <<"stream">>, []}, retrieve_file}],
Req, State}.
-spec retrieve_file(cowboy_req:req(), #state{}) -> {stop | boolean(),cowboy_req:req(), #state{}}.
retrieve_file(Req, State=#state{ asset_id=AssetId
, owner_id=Owner
, asset_info=#user_asset_entry{mime_type=MimeType}
}) ->
Dir = ?UTILS:get_owner_asset_directory(Owner),
Path = list_to_binary([Dir, "/", AssetId]),
FileSize = filelib:file_size(Path),
ContentType = case MimeType of
{ Type, undefined } ->
Type;
{ Type, SubType } ->
list_to_binary([Type, "/", SubType])
end,
Res = cowboy_req:reply(200, #{ <<"content-type">> => ContentType
, <<"cache-control">> => list_to_binary(io_lib:fwrite("public, max-age=~p, immutable", [?MAX_AGE_IMMUTABLE_SECONDS]))
}, {sendfile, 0, FileSize, Path}, Req),
{stop, Res, State}.
| null | https://raw.githubusercontent.com/programaker-project/Programaker-Core/ef10fc6d2a228b2096b121170c421f5c29f9f270/backend/apps/automate_rest_api/src/automate_rest_api_program_assets_by_id.erl | erlang | CORS
Authentication
Don't do authentication if it's just asking for options
Image handler | -module(automate_rest_api_program_assets_by_id).
-export([ init/2
, allowed_methods/2
, options/2
, is_authorized/2
, content_types_provided/2
, resource_exists/2
]).
-export([ retrieve_file/2
]).
-include("./records.hrl").
-include("../../automate_storage/src/records.hrl").
-define(UTILS, automate_rest_api_utils).
Seconds in a year
-record(state, { owner_id :: owner_id() | undefined
, program_id :: binary()
, asset_id :: binary()
, asset_info :: #user_asset_entry{} | undefined
}).
-spec init(_,_) -> {'cowboy_rest',_,_}.
init(Req, _Opts) ->
Req1 = automate_rest_api_cors:set_headers(Req),
ProgramId = cowboy_req:binding(program_id, Req1),
AssetId = cowboy_req:binding(asset_id, Req1),
{cowboy_rest, Req1
, #state{ program_id=ProgramId
, asset_id=AssetId
, owner_id=undefined
, asset_info=undefined
}}.
resource_exists(Req, State=#state{program_id=ProgramId, asset_id=AssetId}) ->
{ok, Owner} = automate_storage:get_program_owner(ProgramId),
case automate_storage:get_user_asset_info(Owner, AssetId) of
{error, not_found} ->
{false, Req, State};
{ok, AssetInfo} ->
{true, Req, State#state{owner_id=Owner, asset_info=AssetInfo}}
end.
options(Req, State) ->
{ok, Req, State}.
-spec allowed_methods(cowboy_req:req(),_) -> {[binary()], cowboy_req:req(),_}.
allowed_methods(Req, State) ->
{[<<"GET">>, <<"OPTIONS">>], Req, State}.
is_authorized(Req, State=#state{owner_id=_OwnerId}) ->
case cowboy_req:method(Req) of
<<"OPTIONS">> ->
{ true, Req, State };
<<"GET">> ->
{ true, Req, State }
end.
content_types_provided(Req, State) ->
{[{{<<"octet">>, <<"stream">>, []}, retrieve_file}],
Req, State}.
-spec retrieve_file(cowboy_req:req(), #state{}) -> {stop | boolean(),cowboy_req:req(), #state{}}.
retrieve_file(Req, State=#state{ asset_id=AssetId
, owner_id=Owner
, asset_info=#user_asset_entry{mime_type=MimeType}
}) ->
Dir = ?UTILS:get_owner_asset_directory(Owner),
Path = list_to_binary([Dir, "/", AssetId]),
FileSize = filelib:file_size(Path),
ContentType = case MimeType of
{ Type, undefined } ->
Type;
{ Type, SubType } ->
list_to_binary([Type, "/", SubType])
end,
Res = cowboy_req:reply(200, #{ <<"content-type">> => ContentType
, <<"cache-control">> => list_to_binary(io_lib:fwrite("public, max-age=~p, immutable", [?MAX_AGE_IMMUTABLE_SECONDS]))
}, {sendfile, 0, FileSize, Path}, Req),
{stop, Res, State}.
|
f8ec1ce329d4b7e4d4dd63df3ec4fe13cdc45abf64bdade32ff1db29f19a9a0f | reactiveml/rml | depend.ml | (**********************************************************************)
(* *)
(* ReactiveML *)
(* *)
(* *)
(* *)
(* Louis Mandel *)
(* *)
Copyright 2002 , 2007 . All rights reserved .
(* This file is distributed under the terms of the Q Public License *)
version 1.0 .
(* *)
(* ReactiveML has been done in the following labs: *)
- theme SPI , Laboratoire d'Informatique de Paris 6 ( 2002 - 2005 )
- Verimag , CNRS Grenoble ( 2005 - 2006 )
- projet , ( 2006 - 2007 )
(* *)
(**********************************************************************)
(* file: depend.ml *)
(* Warning: *)
(* This file is based on the original version of depend.ml *)
from the Objective Caml 3.10 distribution , INRIA
first modification : 2007 - 02 - 16
modified by :
(***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
open Format
open Location
open Parse_ident
open Parse_ast
module StringSet = Set.Make(struct type t = string let compare = compare end)
(* Collect free module identifiers in the a.s.t. *)
let free_structure_names = ref StringSet.empty
let rec addmodule bv lid =
match lid with
Pdot (s,_) ->
if not (StringSet.mem s bv)
then free_structure_names := StringSet.add s !free_structure_names
| Pident _ -> ()
let add bv id = addmodule bv id.pident_id
let add_opt add_fn bv = function
| None -> ()
| Some x -> add_fn bv x
let rec add_type bv ty =
match ty.pte_desc with
| Ptype_var _ -> ()
| Ptype_arrow (t1, t2) -> add_type bv t1; add_type bv t2
| Ptype_tuple tl -> List.iter (add_type bv) tl
| Ptype_constr (id, tl) -> add bv id; List.iter (add_type bv) tl
| Ptype_process (t, _) -> add_type bv t
let add_type_declaration bv td =
match td with
| Ptype_abstract -> ()
| Ptype_rebind te -> add_type bv te
| Ptype_variant cstrs ->
List.iter (fun (c, args) -> add_opt add_type bv args) cstrs
| Ptype_record lbls ->
List.iter (fun (l, mut, ty) -> add_type bv ty) lbls
let rec add_pattern bv pat =
match pat.ppatt_desc with
Ppatt_any -> ()
| Ppatt_var _ -> ()
| Ppatt_alias(p, _) -> add_pattern bv p
| Ppatt_constant _ -> ()
| Ppatt_tuple pl -> List.iter (add_pattern bv) pl
| Ppatt_construct(c, op) -> add bv c; add_opt add_pattern bv op
| Ppatt_or(p1, p2) -> add_pattern bv p1; add_pattern bv p2
| Ppatt_record pl ->
List.iter (fun (lbl, p) -> add bv lbl; add_pattern bv p) pl
| Ppatt_array pl -> List.iter (add_pattern bv) pl
| Ppatt_constraint(p, ty) -> add_pattern bv p; add_type bv ty
let rec add_expr bv exp =
match exp.pexpr_desc with
Pexpr_ident l -> add bv l
| Pexpr_constant _ -> ()
| Pexpr_let(_, pel, e) -> add_pat_expr_list bv pel; add_expr bv e
| Pexpr_function pel -> add_pat_when_opt_expr_list bv pel
| Pexpr_apply(e, el) ->
add_expr bv e; List.iter (fun e -> add_expr bv e) el
| Pexpr_tuple el -> List.iter (add_expr bv) el
| Pexpr_construct(c, opte) -> add bv c; add_opt add_expr bv opte
| Pexpr_array el -> List.iter (add_expr bv) el
| Pexpr_record lblel ->
List.iter (fun (lbl, e) -> add bv lbl; add_expr bv e) lblel
| Pexpr_record_access(e, fld) -> add_expr bv e; add bv fld
| Pexpr_record_with (e, lblel) ->
add_expr bv e;
List.iter (fun (lbl, e) -> add bv lbl; add_expr bv e) lblel
| Pexpr_record_update(e1, fld, e2) ->
add_expr bv e1; add bv fld; add_expr bv e2
| Pexpr_constraint(e1, ty) ->
add_expr bv e1;
add_type bv ty
| Pexpr_trywith(e, pel) -> add_expr bv e; add_pat_when_opt_expr_list bv pel
| Pexpr_assert (e) -> add_expr bv e
| Pexpr_ifthenelse(e1, e2, opte3) ->
add_expr bv e1; add_expr bv e2; add_opt add_expr bv opte3
| Pexpr_match(e, pel) -> add_expr bv e; add_pat_when_opt_expr_list bv pel
| Pexpr_while(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexpr_for(_, e1, e2, _, e3) ->
add_expr bv e1; add_expr bv e2; add_expr bv e3
| Pexpr_fordopar(_, e1, e2, _, e3) ->
add_expr bv e1; add_expr bv e2; add_expr bv e3
| Pexpr_seq(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexpr_nothing -> ()
| Pexpr_pause -> ()
| Pexpr_halt -> ()
| Pexpr_emit(e1) -> add_expr bv e1
| Pexpr_emit_val(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexpr_loop(e1) -> add_expr bv e1
| Pexpr_par(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexpr_merge(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexpr_signal(ioel, koee, e) ->
List.iter (fun (i, oe) -> add_opt add_type bv oe) ioel;
Rml_misc.opt_iter (fun (_, e1, e2) -> add_expr bv e1; add_expr bv e2) koee;
add_expr bv e
| Pexpr_process(e1) -> add_expr bv e1
| Pexpr_run(e1) -> add_expr bv e1
| Pexpr_until(e1, cfg_when_opt_oe_list) ->
add_expr bv e1;
List.iter
(fun (cfg, when_opt, oe) ->
add_config bv cfg;
Rml_misc.opt_iter (add_expr bv) when_opt;
Rml_misc.opt_iter (fun e -> add_expr bv e) oe)
cfg_when_opt_oe_list
| Pexpr_when(cfg, e1) -> add_config bv cfg; add_expr bv e1
| Pexpr_control(cfg, oe, e1) ->
add_config bv cfg;
Rml_misc.opt_iter (fun e -> add_expr bv e) oe;
add_expr bv e1
| Pexpr_get(e1) -> add_expr bv e1
| Pexpr_present(cfg, e1, e2) ->
add_config bv cfg; add_expr bv e1; add_expr bv e2
| Pexpr_await(_, cfg) -> add_config bv cfg
| Pexpr_await_val(_, _, cfg, when_opt, e1) ->
add_config bv cfg;
add_config bv cfg;
Rml_misc.opt_iter (add_expr bv) when_opt;
add_expr bv e1
| Pexpr_pre(_, e1) -> add_expr bv e1
| Pexpr_last(e1) -> add_expr bv e1
| Pexpr_default(e1) -> add_expr bv e1
and add_config bv conf =
match conf.pconf_desc with
| Pconf_present(e1, op) ->
add_expr bv e1; Rml_misc.opt_iter (fun p -> add_pattern bv p) op
| Pconf_and(e1, e2) -> add_config bv e1; add_config bv e2
| Pconf_or(e1, e2) -> add_config bv e1; add_config bv e2
and add_pat_expr_list bv pel =
List.iter (fun (p, e) -> add_pattern bv p; add_expr bv e) pel
and add_pat_when_opt_expr_list bv pel =
List.iter
(fun (p, when_opt, e) ->
add_pattern bv p;
Rml_misc.opt_iter (add_expr bv) when_opt;
add_expr bv e)
pel
and add_signature bv = function
[] -> ()
| item :: rem -> add_signature (add_sig_item bv item) rem
and add_sig_item bv item =
match item.pintf_desc with
Pintf_val(id, vd) ->
add_type bv vd; bv
| Pintf_type dcls ->
List.iter (fun (_, _, td) -> add_type_declaration bv td) dcls; bv
| Pintf_exn(id, oty) ->
add_opt add_type bv oty; bv
| Pintf_open s ->
if not (StringSet.mem s bv)
then free_structure_names := StringSet.add s !free_structure_names;
bv
and add_structure bv item_list =
List.fold_left add_struct_item bv item_list
and add_struct_item bv item =
match item.pimpl_desc with
Pimpl_expr e ->
add_expr bv e; bv
| Pimpl_let(_, pel) ->
add_pat_expr_list bv pel; bv
| Pimpl_signal(ioel, koee) ->
List.iter (fun (i, oe) -> add_opt add_type bv oe) ioel;
Rml_misc.opt_iter (fun (_,e1, e2) -> add_expr bv e1; add_expr bv e2) koee;
bv
| Pimpl_type dcls ->
List.iter (fun (_, _, td) -> add_type_declaration bv td) dcls; bv
| Pimpl_exn(id, oty) ->
add_opt add_type bv oty; bv
| Pimpl_exn_rebind(id, l) ->
add bv l; bv
| Pimpl_open s ->
if not (StringSet.mem s bv)
then free_structure_names := StringSet.add s !free_structure_names;
bv
| Pimpl_lucky (_, itl1, itl2, _) ->
List.iter (fun (_, t) -> add_type bv t) itl1;
List.iter (fun (_, t) -> add_type bv t) itl2;
bv
and add_use_file bv top_phrs =
ignore (List.fold_left add_struct_item bv top_phrs)
| null | https://raw.githubusercontent.com/reactiveml/rml/d3ac141bd9c6e3333b678716166d988ce04b5c80/tools/rmldep/depend.ml | ocaml | ********************************************************************
ReactiveML
Louis Mandel
This file is distributed under the terms of the Q Public License
ReactiveML has been done in the following labs:
********************************************************************
file: depend.ml
Warning:
This file is based on the original version of depend.ml
*********************************************************************
Objective Caml
*********************************************************************
Collect free module identifiers in the a.s.t. | Copyright 2002 , 2007 . All rights reserved .
version 1.0 .
- theme SPI , Laboratoire d'Informatique de Paris 6 ( 2002 - 2005 )
- Verimag , CNRS Grenoble ( 2005 - 2006 )
- projet , ( 2006 - 2007 )
from the Objective Caml 3.10 distribution , INRIA
first modification : 2007 - 02 - 16
modified by :
, projet Cristal , INRIA Rocquencourt
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
open Format
open Location
open Parse_ident
open Parse_ast
module StringSet = Set.Make(struct type t = string let compare = compare end)
let free_structure_names = ref StringSet.empty
let rec addmodule bv lid =
match lid with
Pdot (s,_) ->
if not (StringSet.mem s bv)
then free_structure_names := StringSet.add s !free_structure_names
| Pident _ -> ()
let add bv id = addmodule bv id.pident_id
let add_opt add_fn bv = function
| None -> ()
| Some x -> add_fn bv x
let rec add_type bv ty =
match ty.pte_desc with
| Ptype_var _ -> ()
| Ptype_arrow (t1, t2) -> add_type bv t1; add_type bv t2
| Ptype_tuple tl -> List.iter (add_type bv) tl
| Ptype_constr (id, tl) -> add bv id; List.iter (add_type bv) tl
| Ptype_process (t, _) -> add_type bv t
let add_type_declaration bv td =
match td with
| Ptype_abstract -> ()
| Ptype_rebind te -> add_type bv te
| Ptype_variant cstrs ->
List.iter (fun (c, args) -> add_opt add_type bv args) cstrs
| Ptype_record lbls ->
List.iter (fun (l, mut, ty) -> add_type bv ty) lbls
let rec add_pattern bv pat =
match pat.ppatt_desc with
Ppatt_any -> ()
| Ppatt_var _ -> ()
| Ppatt_alias(p, _) -> add_pattern bv p
| Ppatt_constant _ -> ()
| Ppatt_tuple pl -> List.iter (add_pattern bv) pl
| Ppatt_construct(c, op) -> add bv c; add_opt add_pattern bv op
| Ppatt_or(p1, p2) -> add_pattern bv p1; add_pattern bv p2
| Ppatt_record pl ->
List.iter (fun (lbl, p) -> add bv lbl; add_pattern bv p) pl
| Ppatt_array pl -> List.iter (add_pattern bv) pl
| Ppatt_constraint(p, ty) -> add_pattern bv p; add_type bv ty
let rec add_expr bv exp =
match exp.pexpr_desc with
Pexpr_ident l -> add bv l
| Pexpr_constant _ -> ()
| Pexpr_let(_, pel, e) -> add_pat_expr_list bv pel; add_expr bv e
| Pexpr_function pel -> add_pat_when_opt_expr_list bv pel
| Pexpr_apply(e, el) ->
add_expr bv e; List.iter (fun e -> add_expr bv e) el
| Pexpr_tuple el -> List.iter (add_expr bv) el
| Pexpr_construct(c, opte) -> add bv c; add_opt add_expr bv opte
| Pexpr_array el -> List.iter (add_expr bv) el
| Pexpr_record lblel ->
List.iter (fun (lbl, e) -> add bv lbl; add_expr bv e) lblel
| Pexpr_record_access(e, fld) -> add_expr bv e; add bv fld
| Pexpr_record_with (e, lblel) ->
add_expr bv e;
List.iter (fun (lbl, e) -> add bv lbl; add_expr bv e) lblel
| Pexpr_record_update(e1, fld, e2) ->
add_expr bv e1; add bv fld; add_expr bv e2
| Pexpr_constraint(e1, ty) ->
add_expr bv e1;
add_type bv ty
| Pexpr_trywith(e, pel) -> add_expr bv e; add_pat_when_opt_expr_list bv pel
| Pexpr_assert (e) -> add_expr bv e
| Pexpr_ifthenelse(e1, e2, opte3) ->
add_expr bv e1; add_expr bv e2; add_opt add_expr bv opte3
| Pexpr_match(e, pel) -> add_expr bv e; add_pat_when_opt_expr_list bv pel
| Pexpr_while(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexpr_for(_, e1, e2, _, e3) ->
add_expr bv e1; add_expr bv e2; add_expr bv e3
| Pexpr_fordopar(_, e1, e2, _, e3) ->
add_expr bv e1; add_expr bv e2; add_expr bv e3
| Pexpr_seq(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexpr_nothing -> ()
| Pexpr_pause -> ()
| Pexpr_halt -> ()
| Pexpr_emit(e1) -> add_expr bv e1
| Pexpr_emit_val(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexpr_loop(e1) -> add_expr bv e1
| Pexpr_par(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexpr_merge(e1, e2) -> add_expr bv e1; add_expr bv e2
| Pexpr_signal(ioel, koee, e) ->
List.iter (fun (i, oe) -> add_opt add_type bv oe) ioel;
Rml_misc.opt_iter (fun (_, e1, e2) -> add_expr bv e1; add_expr bv e2) koee;
add_expr bv e
| Pexpr_process(e1) -> add_expr bv e1
| Pexpr_run(e1) -> add_expr bv e1
| Pexpr_until(e1, cfg_when_opt_oe_list) ->
add_expr bv e1;
List.iter
(fun (cfg, when_opt, oe) ->
add_config bv cfg;
Rml_misc.opt_iter (add_expr bv) when_opt;
Rml_misc.opt_iter (fun e -> add_expr bv e) oe)
cfg_when_opt_oe_list
| Pexpr_when(cfg, e1) -> add_config bv cfg; add_expr bv e1
| Pexpr_control(cfg, oe, e1) ->
add_config bv cfg;
Rml_misc.opt_iter (fun e -> add_expr bv e) oe;
add_expr bv e1
| Pexpr_get(e1) -> add_expr bv e1
| Pexpr_present(cfg, e1, e2) ->
add_config bv cfg; add_expr bv e1; add_expr bv e2
| Pexpr_await(_, cfg) -> add_config bv cfg
| Pexpr_await_val(_, _, cfg, when_opt, e1) ->
add_config bv cfg;
add_config bv cfg;
Rml_misc.opt_iter (add_expr bv) when_opt;
add_expr bv e1
| Pexpr_pre(_, e1) -> add_expr bv e1
| Pexpr_last(e1) -> add_expr bv e1
| Pexpr_default(e1) -> add_expr bv e1
and add_config bv conf =
match conf.pconf_desc with
| Pconf_present(e1, op) ->
add_expr bv e1; Rml_misc.opt_iter (fun p -> add_pattern bv p) op
| Pconf_and(e1, e2) -> add_config bv e1; add_config bv e2
| Pconf_or(e1, e2) -> add_config bv e1; add_config bv e2
and add_pat_expr_list bv pel =
List.iter (fun (p, e) -> add_pattern bv p; add_expr bv e) pel
and add_pat_when_opt_expr_list bv pel =
List.iter
(fun (p, when_opt, e) ->
add_pattern bv p;
Rml_misc.opt_iter (add_expr bv) when_opt;
add_expr bv e)
pel
and add_signature bv = function
[] -> ()
| item :: rem -> add_signature (add_sig_item bv item) rem
and add_sig_item bv item =
match item.pintf_desc with
Pintf_val(id, vd) ->
add_type bv vd; bv
| Pintf_type dcls ->
List.iter (fun (_, _, td) -> add_type_declaration bv td) dcls; bv
| Pintf_exn(id, oty) ->
add_opt add_type bv oty; bv
| Pintf_open s ->
if not (StringSet.mem s bv)
then free_structure_names := StringSet.add s !free_structure_names;
bv
and add_structure bv item_list =
List.fold_left add_struct_item bv item_list
and add_struct_item bv item =
match item.pimpl_desc with
Pimpl_expr e ->
add_expr bv e; bv
| Pimpl_let(_, pel) ->
add_pat_expr_list bv pel; bv
| Pimpl_signal(ioel, koee) ->
List.iter (fun (i, oe) -> add_opt add_type bv oe) ioel;
Rml_misc.opt_iter (fun (_,e1, e2) -> add_expr bv e1; add_expr bv e2) koee;
bv
| Pimpl_type dcls ->
List.iter (fun (_, _, td) -> add_type_declaration bv td) dcls; bv
| Pimpl_exn(id, oty) ->
add_opt add_type bv oty; bv
| Pimpl_exn_rebind(id, l) ->
add bv l; bv
| Pimpl_open s ->
if not (StringSet.mem s bv)
then free_structure_names := StringSet.add s !free_structure_names;
bv
| Pimpl_lucky (_, itl1, itl2, _) ->
List.iter (fun (_, t) -> add_type bv t) itl1;
List.iter (fun (_, t) -> add_type bv t) itl2;
bv
and add_use_file bv top_phrs =
ignore (List.fold_left add_struct_item bv top_phrs)
|
76f6088a81ce4b30871f3256ab4d0299adf943cf2ee0aa93f828c0be60625a91 | input-output-hk/rscoin-haskell | FilePathUtils.hs | module Bench.RSCoin.FilePathUtils
( dbFormatPath
, tempBenchDirectory
, walletPathPrefix
) where
import Data.String (IsString)
import Data.Text (Text, unpack)
import Formatting (int, sformat, stext, (%))
tempBenchDirectory :: FilePath
tempBenchDirectory = ".bench-local"
walletPathPrefix :: IsString s => s
walletPathPrefix = "wallet-db"
dbFormatPath :: Integral i => Text -> i -> FilePath
dbFormatPath dbPath num = unpack $ sformat (stext % int) dbPath num
| null | https://raw.githubusercontent.com/input-output-hk/rscoin-haskell/109d8f6f226e9d0b360fcaac14c5a90da112a810/bench/Bench/RSCoin/FilePathUtils.hs | haskell | module Bench.RSCoin.FilePathUtils
( dbFormatPath
, tempBenchDirectory
, walletPathPrefix
) where
import Data.String (IsString)
import Data.Text (Text, unpack)
import Formatting (int, sformat, stext, (%))
tempBenchDirectory :: FilePath
tempBenchDirectory = ".bench-local"
walletPathPrefix :: IsString s => s
walletPathPrefix = "wallet-db"
dbFormatPath :: Integral i => Text -> i -> FilePath
dbFormatPath dbPath num = unpack $ sformat (stext % int) dbPath num
|
|
ca6af4ad3192e39fc727b56089ebd89a73eb4747256d1dcf3181745d4ab0d77e | haskell-repa/repa | TestPar.hs | # LANGUAGE ScopedTypeVariables , MagicHash , BangPatterns , UnboxedTuples ,
ExistentialQuantification , TypeFamilies #
ExistentialQuantification, TypeFamilies #-}
module Main where
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
import System.IO.Unsafe
import Data.Array.Repa.Flow.Par (Flow)
import qualified Data.Array.Repa.Flow.Par.Segd (Segd)
import qualified Data.Array.Repa.Flow.Par.Segd as Segd
import qualified Data.Array.Repa.Flow.Par as F
import qualified Data.Vector.Unboxed as U
import Prelude as P
import GHC.Exts
-- Framework ------------------------------------------------------------------
main = defaultMainWithArgs tests ["-j", "1"]
tests
= [ testProperty "flow/unflow " prop_flow_unflow
, testProperty "map " prop_map
, testProperty "map/map " prop_map_map
, testProperty "replicate " prop_replicate
, testProperty "enumFromN " prop_enumFromN
, testProperty "replicates " prop_replicates
, testProperty "filter " prop_filter
]
instance (U.Unbox a, Arbitrary a) => Arbitrary (U.Vector a) where
arbitrary
= do elems <- arbitrary
return $ U.fromList elems
Computation / Conversion ---------------------------------------------------
prop_flow_unflow :: U.Vector Int -> Bool
prop_flow_unflow vec
= vec == (F.unflow $ F.flow vec)
prop_replicate :: Positive Int -> Int -> Bool
prop_replicate (Positive len) x
= let !len'@(I# len#) = len `mod` 1000
in U.replicate len' x
== F.unflow (F.replicate len# x)
prop_enumFromN :: Int -> Positive Int -> Bool
prop_enumFromN (I# x) (Positive len)
= let !(I# len') = len `mod` 1000
in U.enumFromN (I# x) (I# len')
== F.unflow (F.enumFromN x len')
prop_map :: U.Vector Int -> Bool
prop_map vec
= U.map (+ 1234) vec
== (F.unflow $ F.map (+ 1234) (F.flow vec))
prop_map_map :: U.Vector Int -> Bool
prop_map_map vec
= (U.map (+ 1234) $ U.map (* 4567) vec)
== (F.unflow $ F.map (+ 1234) $ F.map (* 4567) (F.flow vec))
prop_replicates :: U.Vector Int -> U.Vector Int -> Bool
prop_replicates lens0 vec0
= let maxRepl = 100
(lens, vec) = U.unzip $ U.zip (U.map (abs . (`mod` maxRepl)) lens0) vec0
!(I# total) = U.sum lens
segd = Segd.fromLengths lens
getVal ix = vec0 U.! (I# ix)
in U.toList (F.unflow $ F.replicates segd getVal)
== P.concat (P.zipWith P.replicate (U.toList lens) (U.toList vec))
prop_filter :: U.Vector Int -> Bool
prop_filter vec
= U.filter (\x -> x `mod` 2 == 0) vec
== F.unflow (F.filter (\x -> x `mod` 2 == 0) (F.flow vec))
| null | https://raw.githubusercontent.com/haskell-repa/repa/c867025e99fd008f094a5b18ce4dabd29bed00ba/icebox/abandoned/repa-flow/test/props/TestPar.hs | haskell | Framework ------------------------------------------------------------------
------------------------------------------------- | # LANGUAGE ScopedTypeVariables , MagicHash , BangPatterns , UnboxedTuples ,
ExistentialQuantification , TypeFamilies #
ExistentialQuantification, TypeFamilies #-}
module Main where
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
import System.IO.Unsafe
import Data.Array.Repa.Flow.Par (Flow)
import qualified Data.Array.Repa.Flow.Par.Segd (Segd)
import qualified Data.Array.Repa.Flow.Par.Segd as Segd
import qualified Data.Array.Repa.Flow.Par as F
import qualified Data.Vector.Unboxed as U
import Prelude as P
import GHC.Exts
main = defaultMainWithArgs tests ["-j", "1"]
tests
= [ testProperty "flow/unflow " prop_flow_unflow
, testProperty "map " prop_map
, testProperty "map/map " prop_map_map
, testProperty "replicate " prop_replicate
, testProperty "enumFromN " prop_enumFromN
, testProperty "replicates " prop_replicates
, testProperty "filter " prop_filter
]
instance (U.Unbox a, Arbitrary a) => Arbitrary (U.Vector a) where
arbitrary
= do elems <- arbitrary
return $ U.fromList elems
prop_flow_unflow :: U.Vector Int -> Bool
prop_flow_unflow vec
= vec == (F.unflow $ F.flow vec)
prop_replicate :: Positive Int -> Int -> Bool
prop_replicate (Positive len) x
= let !len'@(I# len#) = len `mod` 1000
in U.replicate len' x
== F.unflow (F.replicate len# x)
prop_enumFromN :: Int -> Positive Int -> Bool
prop_enumFromN (I# x) (Positive len)
= let !(I# len') = len `mod` 1000
in U.enumFromN (I# x) (I# len')
== F.unflow (F.enumFromN x len')
prop_map :: U.Vector Int -> Bool
prop_map vec
= U.map (+ 1234) vec
== (F.unflow $ F.map (+ 1234) (F.flow vec))
prop_map_map :: U.Vector Int -> Bool
prop_map_map vec
= (U.map (+ 1234) $ U.map (* 4567) vec)
== (F.unflow $ F.map (+ 1234) $ F.map (* 4567) (F.flow vec))
prop_replicates :: U.Vector Int -> U.Vector Int -> Bool
prop_replicates lens0 vec0
= let maxRepl = 100
(lens, vec) = U.unzip $ U.zip (U.map (abs . (`mod` maxRepl)) lens0) vec0
!(I# total) = U.sum lens
segd = Segd.fromLengths lens
getVal ix = vec0 U.! (I# ix)
in U.toList (F.unflow $ F.replicates segd getVal)
== P.concat (P.zipWith P.replicate (U.toList lens) (U.toList vec))
prop_filter :: U.Vector Int -> Bool
prop_filter vec
= U.filter (\x -> x `mod` 2 == 0) vec
== F.unflow (F.filter (\x -> x `mod` 2 == 0) (F.flow vec))
|
a1a619c86ab5ee8012fea1815104e473688b9f2c990dce19d1b86c1d13bcb80e | danieljharvey/mimsa | Evaluate.hs | # LANGUAGE DataKinds #
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
module Server.Endpoints.Project.Evaluate
( evaluate,
EvaluateAPI,
)
where
import Control.Monad.Except
import qualified Data.Aeson as JSON
import Data.OpenApi hiding (Server, get)
import Data.Text (Text)
import GHC.Generics
import qualified Language.Mimsa.Actions.Helpers.Parse as Actions
import qualified Language.Mimsa.Actions.Modules.Evaluate as Actions
import Language.Mimsa.Core
import Language.Mimsa.Types.Project
import Language.Mimsa.Types.Store
import Servant
import Server.Handlers
import Server.Helpers.ExpressionData
import Server.MimsaHandler
import Server.Types
-- using -servant/servant/blob/master/doc/cookbook/uverb/UVerb.lhs
type EvaluateAPI = EvaluateModule
evaluate :: MimsaEnvironment -> Server EvaluateAPI
evaluate =
evaluateModuleExpression
-- /project/evaluate-module/
type EvaluateModule =
"evaluate-module"
:> ReqBody '[JSON] EvaluateModuleRequest
:> JsonPost EvaluateModuleResponse
data EvaluateModuleRequest = EvaluateModuleRequest
{ emrCode :: Text,
emrProjectHash :: ProjectHash
}
deriving stock (Eq, Ord, Show, Generic)
deriving anyclass (JSON.FromJSON, ToSchema)
data EvaluateModuleResponse = EvaluateModuleResponse
{ emrResult :: Text,
emrExpressionData :: ExpressionData
}
deriving stock (Eq, Ord, Show, Generic)
deriving anyclass (JSON.ToJSON, ToSchema)
evaluateModuleExpression ::
MimsaEnvironment ->
EvaluateModuleRequest ->
MimsaHandler EvaluateModuleResponse
evaluateModuleExpression mimsaEnv (EvaluateModuleRequest input hash) =
runMimsaHandlerT $ do
let action = do
expr <- Actions.parseExpr input
(mt, exprResult, _newModule) <-
Actions.evaluateModule expr mempty
let se = StoreExpression exprResult mempty mempty mempty mempty
pure $
EvaluateModuleResponse
(prettyPrint exprResult)
(makeMinimalExpressionData se mt input)
response <- lift $ eitherFromActionM mimsaEnv hash action
case response of
Left e -> throwMimsaError e
Right (_, _, a) -> returnMimsa a
| null | https://raw.githubusercontent.com/danieljharvey/mimsa/e6b177dd2c38e8a67d6e27063ca600406b3e6b56/server/server/Server/Endpoints/Project/Evaluate.hs | haskell | # LANGUAGE DeriveAnyClass #
using -servant/servant/blob/master/doc/cookbook/uverb/UVerb.lhs
/project/evaluate-module/ | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingVia #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
module Server.Endpoints.Project.Evaluate
( evaluate,
EvaluateAPI,
)
where
import Control.Monad.Except
import qualified Data.Aeson as JSON
import Data.OpenApi hiding (Server, get)
import Data.Text (Text)
import GHC.Generics
import qualified Language.Mimsa.Actions.Helpers.Parse as Actions
import qualified Language.Mimsa.Actions.Modules.Evaluate as Actions
import Language.Mimsa.Core
import Language.Mimsa.Types.Project
import Language.Mimsa.Types.Store
import Servant
import Server.Handlers
import Server.Helpers.ExpressionData
import Server.MimsaHandler
import Server.Types
type EvaluateAPI = EvaluateModule
evaluate :: MimsaEnvironment -> Server EvaluateAPI
evaluate =
evaluateModuleExpression
type EvaluateModule =
"evaluate-module"
:> ReqBody '[JSON] EvaluateModuleRequest
:> JsonPost EvaluateModuleResponse
data EvaluateModuleRequest = EvaluateModuleRequest
{ emrCode :: Text,
emrProjectHash :: ProjectHash
}
deriving stock (Eq, Ord, Show, Generic)
deriving anyclass (JSON.FromJSON, ToSchema)
data EvaluateModuleResponse = EvaluateModuleResponse
{ emrResult :: Text,
emrExpressionData :: ExpressionData
}
deriving stock (Eq, Ord, Show, Generic)
deriving anyclass (JSON.ToJSON, ToSchema)
evaluateModuleExpression ::
MimsaEnvironment ->
EvaluateModuleRequest ->
MimsaHandler EvaluateModuleResponse
evaluateModuleExpression mimsaEnv (EvaluateModuleRequest input hash) =
runMimsaHandlerT $ do
let action = do
expr <- Actions.parseExpr input
(mt, exprResult, _newModule) <-
Actions.evaluateModule expr mempty
let se = StoreExpression exprResult mempty mempty mempty mempty
pure $
EvaluateModuleResponse
(prettyPrint exprResult)
(makeMinimalExpressionData se mt input)
response <- lift $ eitherFromActionM mimsaEnv hash action
case response of
Left e -> throwMimsaError e
Right (_, _, a) -> returnMimsa a
|
e4379454b05a14c2dfcbea058a7a6cea87857dddb522fb0e9ed5082fbf9bc752 | CloudI/CloudI | auto_export_test2.erl | -*- coding : utf-8 -*-
-*- erlang - indent - level : 2 -*-
%%% -------------------------------------------------------------------
Copyright 2010 - 2019 < > ,
< >
and < >
%%%
This file is part of PropEr .
%%%
%%% PropEr 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.
%%%
%%% PropEr 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 PropEr. If not, see </>.
2010 - 2019 , and
%%% @version {@version}
@author
%%% @doc This module tests whether auto-exporting is disabled when compiling
%%% with PROPER_NO_TRANS enabled.
-module(auto_export_test2).
-compile(nowarn_unused_function).
-define(PROPER_NO_TRANS, true).
-include_lib("proper/include/proper.hrl").
prop_1() ->
?FORALL(_, integer(), true).
| null | https://raw.githubusercontent.com/CloudI/CloudI/3e45031c7ee3e974ead2612ea7dd06c9edf973c9/src/external/proper/test/auto_export_test2.erl | erlang | -------------------------------------------------------------------
PropEr is free software: you can redistribute it and/or modify
(at your option) any later version.
PropEr 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 PropEr. If not, see </>.
@version {@version}
@doc This module tests whether auto-exporting is disabled when compiling
with PROPER_NO_TRANS enabled. | -*- coding : utf-8 -*-
-*- erlang - indent - level : 2 -*-
Copyright 2010 - 2019 < > ,
< >
and < >
This file is part of PropEr .
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
2010 - 2019 , and
@author
-module(auto_export_test2).
-compile(nowarn_unused_function).
-define(PROPER_NO_TRANS, true).
-include_lib("proper/include/proper.hrl").
prop_1() ->
?FORALL(_, integer(), true).
|
dcf49b3ef56e651345844d6c852b3f5aa61572b0a7c3d3548e9759c19ff883f3 | votinginfoproject/data-processor | ballot_selections_postgres_test.clj | (ns vip.data-processor.db.translations.v5-2.ballot-selections-postgres-test
(:require [clojure.test :refer :all]
[vip.data-processor.test-helpers :refer :all]
[vip.data-processor.db.postgres :as postgres]
[vip.data-processor.db.translations.v5-2.ballot-selections :as bs]
[vip.data-processor.errors.process :as process]
[vip.data-processor.pipeline :as pipeline]
[vip.data-processor.validation.csv :as csv]
[vip.data-processor.validation.data-spec :as data-spec]
[vip.data-processor.validation.data-spec.v5-2 :as v5-2]
[clojure.core.async :as a]))
(use-fixtures :once setup-postgres)
(deftest ^:postgres ballot-selection-transforms-test
(testing "ballot_selection.txt is loaded and transformed"
(let [errors-chan (a/chan 100)
ctx {:csv-source-file-paths (csv-inputs ["5-2/ballot_selection.txt"])
:errors-chan errors-chan
:spec-version "5.2"
:spec-family "5.2"
:pipeline [postgres/start-run
(data-spec/add-data-specs v5-2/data-specs)
postgres/prep-v5-2-run
process/process-v5-validations
csv/load-csvs
bs/transformer]}
out-ctx (pipeline/run-pipeline ctx)
errors (all-errors errors-chan)]
(assert-no-problems errors {})
(are-xml-tree-values out-ctx
"bs001" "VipObject.0.BallotSelection.0.id"
"1" "VipObject.0.BallotSelection.0.SequenceOrder.0"
"bs002" "VipObject.0.BallotSelection.1.id"
"2" "VipObject.0.BallotSelection.1.SequenceOrder.0"
"bs003" "VipObject.0.BallotSelection.2.id"
"3" "VipObject.0.BallotSelection.2.SequenceOrder.0"))))
| null | https://raw.githubusercontent.com/votinginfoproject/data-processor/b4baf334b3a6219d12125af8e8c1e3de93ba1dc9/test/vip/data_processor/db/translations/v5_2/ballot_selections_postgres_test.clj | clojure | (ns vip.data-processor.db.translations.v5-2.ballot-selections-postgres-test
(:require [clojure.test :refer :all]
[vip.data-processor.test-helpers :refer :all]
[vip.data-processor.db.postgres :as postgres]
[vip.data-processor.db.translations.v5-2.ballot-selections :as bs]
[vip.data-processor.errors.process :as process]
[vip.data-processor.pipeline :as pipeline]
[vip.data-processor.validation.csv :as csv]
[vip.data-processor.validation.data-spec :as data-spec]
[vip.data-processor.validation.data-spec.v5-2 :as v5-2]
[clojure.core.async :as a]))
(use-fixtures :once setup-postgres)
(deftest ^:postgres ballot-selection-transforms-test
(testing "ballot_selection.txt is loaded and transformed"
(let [errors-chan (a/chan 100)
ctx {:csv-source-file-paths (csv-inputs ["5-2/ballot_selection.txt"])
:errors-chan errors-chan
:spec-version "5.2"
:spec-family "5.2"
:pipeline [postgres/start-run
(data-spec/add-data-specs v5-2/data-specs)
postgres/prep-v5-2-run
process/process-v5-validations
csv/load-csvs
bs/transformer]}
out-ctx (pipeline/run-pipeline ctx)
errors (all-errors errors-chan)]
(assert-no-problems errors {})
(are-xml-tree-values out-ctx
"bs001" "VipObject.0.BallotSelection.0.id"
"1" "VipObject.0.BallotSelection.0.SequenceOrder.0"
"bs002" "VipObject.0.BallotSelection.1.id"
"2" "VipObject.0.BallotSelection.1.SequenceOrder.0"
"bs003" "VipObject.0.BallotSelection.2.id"
"3" "VipObject.0.BallotSelection.2.SequenceOrder.0"))))
|
|
82708bd3654c721d4c08861e03b2a80a6be6cffca20f53755522a3260946ec7a | brendanhay/gogol | Update.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
-- |
Module : . Logging . Projects . Sinks . Update
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
-- Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: destination, and filter.The updated sink might also have a new writer/identity; see the unique/writer_identity field.
--
-- /See:/ </ Cloud Logging API Reference> for @logging.projects.sinks.update@.
module Gogol.Logging.Projects.Sinks.Update
( -- * Resource
LoggingProjectsSinksUpdateResource,
-- ** Constructing a Request
LoggingProjectsSinksUpdate (..),
newLoggingProjectsSinksUpdate,
)
where
import Gogol.Logging.Types
import qualified Gogol.Prelude as Core
| A resource alias for @logging.projects.sinks.update@ method which the
-- 'LoggingProjectsSinksUpdate' request conforms to.
type LoggingProjectsSinksUpdateResource =
"v2"
Core.:> Core.Capture "sinkName" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "uniqueWriterIdentity" Core.Bool
Core.:> Core.QueryParam "updateMask" Core.FieldMask
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.ReqBody '[Core.JSON] LogSink
Core.:> Core.Put '[Core.JSON] LogSink
-- | Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: destination, and filter.The updated sink might also have a new writer/identity; see the unique/writer_identity field.
--
-- /See:/ 'newLoggingProjectsSinksUpdate' smart constructor.
data LoggingProjectsSinksUpdate = LoggingProjectsSinksUpdate
{ -- | V1 error format.
xgafv :: (Core.Maybe Xgafv),
-- | OAuth access token.
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
-- | Multipart request metadata.
payload :: LogSink,
-- | Required. The full resource name of the sink to update, including the parent resource and the sink identifier: \"projects\/[PROJECT/ID]\/sinks\/[SINK/ID]\" \"organizations\/[ORGANIZATION/ID]\/sinks\/[SINK/ID]\" \"billingAccounts\/[BILLING/ACCOUNT/ID]\/sinks\/[SINK/ID]\" \"folders\/[FOLDER/ID]\/sinks\/[SINK_ID]\" For example:\"projects\/my-project\/sinks\/my-sink\"
sinkName :: Core.Text,
| Optional . See sinks.create for a description of this field . When updating a sink , the effect of this field on the value of writer / identity in the updated sink depends on both the old and new values of this field : If the old and new values of this field are both false or both true , then there is no change to the sink\ 's writer / identity . If the old value is false and the new value is true , then writer_identity is changed to a unique service account . It is an error if the old value is true and the new value is set to false or defaulted to false .
uniqueWriterIdentity :: (Core.Maybe Core.Bool),
| Optional . Field mask that specifies the fields in sink that need an update . A sink field will be overwritten if , and only if , it is in the update mask . name and output only fields can not be updated . An empty updateMask is temporarily treated as using the following mask for backwards compatibility purposes : destination , filter , includeChildrenAt some point in the future , behavior will be removed and specifying an empty updateMask will be an error . For a detailed FieldMask definition , see https:\/\/developers.google.com\/protocol - buffers\/docs\/reference\/google.protobuf#google.protobuf . example : updateMask = filter
updateMask :: (Core.Maybe Core.FieldMask),
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
-- | Creates a value of 'LoggingProjectsSinksUpdate' with the minimum fields required to make a request.
newLoggingProjectsSinksUpdate ::
-- | Multipart request metadata. See 'payload'.
LogSink ->
-- | Required. The full resource name of the sink to update, including the parent resource and the sink identifier: \"projects\/[PROJECT/ID]\/sinks\/[SINK/ID]\" \"organizations\/[ORGANIZATION/ID]\/sinks\/[SINK/ID]\" \"billingAccounts\/[BILLING/ACCOUNT/ID]\/sinks\/[SINK/ID]\" \"folders\/[FOLDER/ID]\/sinks\/[SINK_ID]\" For example:\"projects\/my-project\/sinks\/my-sink\" See 'sinkName'.
Core.Text ->
LoggingProjectsSinksUpdate
newLoggingProjectsSinksUpdate payload sinkName =
LoggingProjectsSinksUpdate
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
payload = payload,
sinkName = sinkName,
uniqueWriterIdentity = Core.Nothing,
updateMask = Core.Nothing,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
LoggingProjectsSinksUpdate
where
type Rs LoggingProjectsSinksUpdate = LogSink
type
Scopes LoggingProjectsSinksUpdate =
'[CloudPlatform'FullControl, Logging'Admin]
requestClient LoggingProjectsSinksUpdate {..} =
go
sinkName
xgafv
accessToken
callback
uniqueWriterIdentity
updateMask
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
payload
loggingService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy LoggingProjectsSinksUpdateResource
)
Core.mempty
| null | https://raw.githubusercontent.com/brendanhay/gogol/77394c4e0f5bd729e6fe27119701c45f9d5e1e9a/lib/services/gogol-logging/gen/Gogol/Logging/Projects/Sinks/Update.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: destination, and filter.The updated sink might also have a new writer/identity; see the unique/writer_identity field.
/See:/ </ Cloud Logging API Reference> for @logging.projects.sinks.update@.
* Resource
** Constructing a Request
'LoggingProjectsSinksUpdate' request conforms to.
| Updates a sink. This method replaces the following fields in the existing sink with values from the new sink: destination, and filter.The updated sink might also have a new writer/identity; see the unique/writer_identity field.
/See:/ 'newLoggingProjectsSinksUpdate' smart constructor.
| V1 error format.
| OAuth access token.
| Multipart request metadata.
| Required. The full resource name of the sink to update, including the parent resource and the sink identifier: \"projects\/[PROJECT/ID]\/sinks\/[SINK/ID]\" \"organizations\/[ORGANIZATION/ID]\/sinks\/[SINK/ID]\" \"billingAccounts\/[BILLING/ACCOUNT/ID]\/sinks\/[SINK/ID]\" \"folders\/[FOLDER/ID]\/sinks\/[SINK_ID]\" For example:\"projects\/my-project\/sinks\/my-sink\"
| Upload protocol for media (e.g. \"raw\", \"multipart\").
| Creates a value of 'LoggingProjectsSinksUpdate' with the minimum fields required to make a request.
| Multipart request metadata. See 'payload'.
| Required. The full resource name of the sink to update, including the parent resource and the sink identifier: \"projects\/[PROJECT/ID]\/sinks\/[SINK/ID]\" \"organizations\/[ORGANIZATION/ID]\/sinks\/[SINK/ID]\" \"billingAccounts\/[BILLING/ACCOUNT/ID]\/sinks\/[SINK/ID]\" \"folders\/[FOLDER/ID]\/sinks\/[SINK_ID]\" For example:\"projects\/my-project\/sinks\/my-sink\" See 'sinkName'. | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE PatternSynonyms #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - duplicate - exports #
# OPTIONS_GHC -fno - warn - name - shadowing #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Module : . Logging . Projects . Sinks . Update
Copyright : ( c ) 2015 - 2022
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Gogol.Logging.Projects.Sinks.Update
LoggingProjectsSinksUpdateResource,
LoggingProjectsSinksUpdate (..),
newLoggingProjectsSinksUpdate,
)
where
import Gogol.Logging.Types
import qualified Gogol.Prelude as Core
| A resource alias for @logging.projects.sinks.update@ method which the
type LoggingProjectsSinksUpdateResource =
"v2"
Core.:> Core.Capture "sinkName" Core.Text
Core.:> Core.QueryParam "$.xgafv" Xgafv
Core.:> Core.QueryParam "access_token" Core.Text
Core.:> Core.QueryParam "callback" Core.Text
Core.:> Core.QueryParam "uniqueWriterIdentity" Core.Bool
Core.:> Core.QueryParam "updateMask" Core.FieldMask
Core.:> Core.QueryParam "uploadType" Core.Text
Core.:> Core.QueryParam "upload_protocol" Core.Text
Core.:> Core.QueryParam "alt" Core.AltJSON
Core.:> Core.ReqBody '[Core.JSON] LogSink
Core.:> Core.Put '[Core.JSON] LogSink
data LoggingProjectsSinksUpdate = LoggingProjectsSinksUpdate
xgafv :: (Core.Maybe Xgafv),
accessToken :: (Core.Maybe Core.Text),
| JSONP
callback :: (Core.Maybe Core.Text),
payload :: LogSink,
sinkName :: Core.Text,
| Optional . See sinks.create for a description of this field . When updating a sink , the effect of this field on the value of writer / identity in the updated sink depends on both the old and new values of this field : If the old and new values of this field are both false or both true , then there is no change to the sink\ 's writer / identity . If the old value is false and the new value is true , then writer_identity is changed to a unique service account . It is an error if the old value is true and the new value is set to false or defaulted to false .
uniqueWriterIdentity :: (Core.Maybe Core.Bool),
| Optional . Field mask that specifies the fields in sink that need an update . A sink field will be overwritten if , and only if , it is in the update mask . name and output only fields can not be updated . An empty updateMask is temporarily treated as using the following mask for backwards compatibility purposes : destination , filter , includeChildrenAt some point in the future , behavior will be removed and specifying an empty updateMask will be an error . For a detailed FieldMask definition , see https:\/\/developers.google.com\/protocol - buffers\/docs\/reference\/google.protobuf#google.protobuf . example : updateMask = filter
updateMask :: (Core.Maybe Core.FieldMask),
| Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) .
uploadType :: (Core.Maybe Core.Text),
uploadProtocol :: (Core.Maybe Core.Text)
}
deriving (Core.Eq, Core.Show, Core.Generic)
newLoggingProjectsSinksUpdate ::
LogSink ->
Core.Text ->
LoggingProjectsSinksUpdate
newLoggingProjectsSinksUpdate payload sinkName =
LoggingProjectsSinksUpdate
{ xgafv = Core.Nothing,
accessToken = Core.Nothing,
callback = Core.Nothing,
payload = payload,
sinkName = sinkName,
uniqueWriterIdentity = Core.Nothing,
updateMask = Core.Nothing,
uploadType = Core.Nothing,
uploadProtocol = Core.Nothing
}
instance
Core.GoogleRequest
LoggingProjectsSinksUpdate
where
type Rs LoggingProjectsSinksUpdate = LogSink
type
Scopes LoggingProjectsSinksUpdate =
'[CloudPlatform'FullControl, Logging'Admin]
requestClient LoggingProjectsSinksUpdate {..} =
go
sinkName
xgafv
accessToken
callback
uniqueWriterIdentity
updateMask
uploadType
uploadProtocol
(Core.Just Core.AltJSON)
payload
loggingService
where
go =
Core.buildClient
( Core.Proxy ::
Core.Proxy LoggingProjectsSinksUpdateResource
)
Core.mempty
|
f812f6629d4bf102277532c807b15e49904526ae64b1e67c7d81d44f64de0ed8 | jaspervdj/advent-of-code | 10.hs | {-# LANGUAGE BangPatterns #-}
import qualified AdventOfCode.Grid as G
import qualified AdventOfCode.Parsing as Parsing
import AdventOfCode.V2
import qualified AdventOfCode.V2.Box as Box
import qualified Data.List as L
import qualified Data.Map as M
import qualified System.IO as IO
data Light = Light
{ lPos :: !(V2 Int)
, lVel :: !(V2 Int)
} deriving (Show)
updateLight :: Light -> Light
updateLight l = l {lPos = lPos l .+. lVel l}
parseLights :: IO.Handle -> IO [Light]
parseLights h =
IO.hGetContents h >>= mapM parseLight . lines
where
parseLight line = case Parsing.ints line of
[px, py, vx, vy] -> return $ Light (V2 px py) (V2 vx vy)
_ -> fail $ "Could not parse line: " ++ show line
smallest :: [Light] -> (Int, [Light])
smallest =
\lights -> go 0 (area lights) lights
where
area = Box.area . L.foldl1' (<>) . map (Box.fromV2 . lPos)
go !time area0 lights0 =
let lights1 = map updateLight lights0
area1 = area lights1 in
if area1 > area0 then (time, lights0) else go (time + 1) area1 lights1
main :: IO ()
main = do
lights <- parseLights IO.stdin
let (time, solution) = smallest lights
grid = M.fromList [(lPos l, '#') | l <- solution]
G.printGrid IO.stdout grid
print time
| null | https://raw.githubusercontent.com/jaspervdj/advent-of-code/bdc9628d1495d4e7fdbd9cea2739b929f733e751/2018/10.hs | haskell | # LANGUAGE BangPatterns # |
import qualified AdventOfCode.Grid as G
import qualified AdventOfCode.Parsing as Parsing
import AdventOfCode.V2
import qualified AdventOfCode.V2.Box as Box
import qualified Data.List as L
import qualified Data.Map as M
import qualified System.IO as IO
data Light = Light
{ lPos :: !(V2 Int)
, lVel :: !(V2 Int)
} deriving (Show)
updateLight :: Light -> Light
updateLight l = l {lPos = lPos l .+. lVel l}
parseLights :: IO.Handle -> IO [Light]
parseLights h =
IO.hGetContents h >>= mapM parseLight . lines
where
parseLight line = case Parsing.ints line of
[px, py, vx, vy] -> return $ Light (V2 px py) (V2 vx vy)
_ -> fail $ "Could not parse line: " ++ show line
smallest :: [Light] -> (Int, [Light])
smallest =
\lights -> go 0 (area lights) lights
where
area = Box.area . L.foldl1' (<>) . map (Box.fromV2 . lPos)
go !time area0 lights0 =
let lights1 = map updateLight lights0
area1 = area lights1 in
if area1 > area0 then (time, lights0) else go (time + 1) area1 lights1
main :: IO ()
main = do
lights <- parseLights IO.stdin
let (time, solution) = smallest lights
grid = M.fromList [(lPos l, '#') | l <- solution]
G.printGrid IO.stdout grid
print time
|
b92c0480ff8602d6201e2a13c4790738502784116e30b5892ed3c4322bc34e80 | mage2tv/magento-cache-clean | config.cljs | (ns cache.config
(:require [cache.config.php :as php]
[cache.config.file :as file]))
(defn- use-dump? [magento-basedir]
(file/config-dump-exists? magento-basedir))
(defn- file-or-php [magento-basedir file-fn php-fn]
(let [f (if (use-dump? magento-basedir) file-fn php-fn)]
(partial f magento-basedir)))
(defn- read-config-fn [magento-basedir]
(file-or-php magento-basedir file/read-app-config php/read-app-config))
(defn read-app-config
"Return the app/etc/env.php configuration as keywordized EDN"
[magento-basedir]
(let [read-config (read-config-fn magento-basedir)]
(read-config)))
(defn- list-components-fn [magento-basedir]
(file-or-php magento-basedir file/list-component-dirs php/list-component-dirs))
(defn list-component-dirs
"Return a seq of all module or theme dirs"
[magento-basedir type]
(let [list-component-dirs (list-components-fn magento-basedir)]
(list-component-dirs type)))
(defn watch-for-new-modules! [magento-basedir callback]
(file/watch-for-new-modules! magento-basedir
#(when (use-dump? magento-basedir) (callback)))
(php/watch-for-new-modules! magento-basedir
#(when-not (use-dump? magento-basedir) (callback))))
(defn mtime [magento-basedir]
(let [mtime (file-or-php magento-basedir file/mtime php/mtime)]
(mtime magento-basedir))) | null | https://raw.githubusercontent.com/mage2tv/magento-cache-clean/67d4ce3f06cb42eccceff436580cdfe0ddfc5deb/src/cache/config.cljs | clojure | (ns cache.config
(:require [cache.config.php :as php]
[cache.config.file :as file]))
(defn- use-dump? [magento-basedir]
(file/config-dump-exists? magento-basedir))
(defn- file-or-php [magento-basedir file-fn php-fn]
(let [f (if (use-dump? magento-basedir) file-fn php-fn)]
(partial f magento-basedir)))
(defn- read-config-fn [magento-basedir]
(file-or-php magento-basedir file/read-app-config php/read-app-config))
(defn read-app-config
"Return the app/etc/env.php configuration as keywordized EDN"
[magento-basedir]
(let [read-config (read-config-fn magento-basedir)]
(read-config)))
(defn- list-components-fn [magento-basedir]
(file-or-php magento-basedir file/list-component-dirs php/list-component-dirs))
(defn list-component-dirs
"Return a seq of all module or theme dirs"
[magento-basedir type]
(let [list-component-dirs (list-components-fn magento-basedir)]
(list-component-dirs type)))
(defn watch-for-new-modules! [magento-basedir callback]
(file/watch-for-new-modules! magento-basedir
#(when (use-dump? magento-basedir) (callback)))
(php/watch-for-new-modules! magento-basedir
#(when-not (use-dump? magento-basedir) (callback))))
(defn mtime [magento-basedir]
(let [mtime (file-or-php magento-basedir file/mtime php/mtime)]
(mtime magento-basedir))) |
|
2fd3a426be5a5eefa5d7f09788289eafea8145da0a53b7ac891665f0e3de1066 | c-cube/ocaml-containers | CCCache.ml | (* This file is free software, part of containers. See file "license" for more details. *)
(** {1 Caches} *)
type 'a equal = 'a -> 'a -> bool
type 'a hash = 'a -> int
let default_hash_ = Hashtbl.hash
* { 2 Value interface }
type ('a, 'b) t = {
set: 'a -> 'b -> unit;
get: 'a -> 'b; (* or raise Not_found *)
size: unit -> int;
iter: ('a -> 'b -> unit) -> unit;
clear: unit -> unit;
}
(** Invariants:
- after [cache.set x y], [get cache x] must return [y] or raise [Not_found]
- [cache.set x y] is only called if [get cache x] fails, never if [x] is already bound
- [cache.size()] must be positive and correspond to the number of items in [cache.iter]
- [cache.iter f] calls [f x y] with every [x] such that [cache.get x = y]
- after [cache.clear()], [cache.get x] fails for every [x]
*)
type ('a, 'b) callback = in_cache:bool -> 'a -> 'b -> unit
let clear c = c.clear ()
let add c x y =
try
(* check that x is not bound (see invariants) *)
let _ = c.get x in
false
with Not_found ->
c.set x y;
true
let default_callback_ ~in_cache:_ _ _ = ()
let with_cache ?(cb = default_callback_) c f x =
try
let y = c.get x in
cb ~in_cache:true x y;
y
with Not_found ->
let y = f x in
c.set x y;
cb ~in_cache:false x y;
y
let with_cache_rec ?(cb = default_callback_) c f =
let rec f' x = with_cache ~cb c (f f') x in
f'
let size c = c.size ()
let iter c f = c.iter f
let dummy =
{
set = (fun _ _ -> ());
get = (fun _ -> raise Not_found);
clear = (fun _ -> ());
size = (fun _ -> 0);
iter = (fun _ -> ());
}
module Linear = struct
type ('a, 'b) bucket = Empty | Pair of 'a * 'b
type ('a, 'b) t = {
eq: 'a equal;
arr: ('a, 'b) bucket array;
mutable i: int; (* index for next assertion, cycles through *)
}
let make eq size =
assert (size > 0);
{ arr = Array.make size Empty; eq; i = 0 }
let clear c =
Array.fill c.arr 0 (Array.length c.arr) Empty;
c.i <- 0
(* linear lookup *)
let rec search_ c i x =
if i = Array.length c.arr then raise Not_found;
match c.arr.(i) with
| Pair (x', y) when c.eq x x' -> y
| Pair _ | Empty -> search_ c (i + 1) x
let get c x = search_ c 0 x
let set c x y =
c.arr.(c.i) <- Pair (x, y);
c.i <- (c.i + 1) mod Array.length c.arr
let iter c f =
Array.iter
(function
| Pair (x, y) -> f x y
| Empty -> ())
c.arr
let size c () =
let r = ref 0 in
iter c (fun _ _ -> incr r);
!r
end
let linear ~eq size =
let size = max size 1 in
let arr = Linear.make eq size in
{
get = (fun x -> Linear.get arr x);
set = (fun x y -> Linear.set arr x y);
clear = (fun () -> Linear.clear arr);
size = Linear.size arr;
iter = Linear.iter arr;
}
module Replacing = struct
type ('a, 'b) bucket = Empty | Pair of 'a * 'b
type ('a, 'b) t = {
eq: 'a equal;
hash: 'a hash;
arr: ('a, 'b) bucket array;
mutable c_size: int;
}
let make eq hash size =
assert (size > 0);
{ arr = Array.make size Empty; eq; hash; c_size = 0 }
let clear c =
c.c_size <- 0;
Array.fill c.arr 0 (Array.length c.arr) Empty
let get c x =
let i = c.hash x mod Array.length c.arr in
match c.arr.(i) with
| Pair (x', y) when c.eq x x' -> y
| Pair _ | Empty -> raise Not_found
let is_empty = function
| Empty -> true
| Pair _ -> false
let set c x y =
let i = c.hash x mod Array.length c.arr in
if is_empty c.arr.(i) then c.c_size <- c.c_size + 1;
c.arr.(i) <- Pair (x, y)
let iter c f =
Array.iter
(function
| Empty -> ()
| Pair (x, y) -> f x y)
c.arr
let size c () = c.c_size
end
let replacing ~eq ?(hash = default_hash_) size =
let c = Replacing.make eq hash size in
{
get = (fun x -> Replacing.get c x);
set = (fun x y -> Replacing.set c x y);
clear = (fun () -> Replacing.clear c);
size = Replacing.size c;
iter = Replacing.iter c;
}
module type HASH = sig
type t
val equal : t equal
val hash : t hash
end
module LRU (X : HASH) = struct
type key = X.t
module H = Hashtbl.Make (X)
type 'a t = {
table: 'a node H.t; (* hashtable key -> node *)
mutable first: 'a node option;
size: int; (* max size *)
}
and 'a node = {
mutable key: key;
mutable value: 'a;
mutable next: 'a node;
mutable prev: 'a node;
}
(** Meta data for the value, making a chained list *)
let make size =
assert (size > 0);
{ table = H.create size; size; first = None }
let clear c =
H.clear c.table;
c.first <- None;
()
take first from queue
let take_ c =
match c.first with
| Some n when Stdlib.( == ) n.next n ->
(* last element *)
c.first <- None;
n
| Some n ->
c.first <- Some n.next;
n.prev.next <- n.next;
n.next.prev <- n.prev;
n
| None -> failwith "LRU: empty queue"
(* push at back of queue *)
let push_ c n =
match c.first with
| None ->
n.next <- n;
n.prev <- n;
c.first <- Some n
| Some n1 when Stdlib.( == ) n1 n -> ()
| Some n1 ->
n.prev <- n1.prev;
n.next <- n1;
n1.prev.next <- n;
n1.prev <- n
(* remove from queue *)
let remove_ n =
n.prev.next <- n.next;
n.next.prev <- n.prev
(* Replace least recently used element of [c] by x->y *)
let replace_ c x y =
(* remove old *)
let n = take_ c in
H.remove c.table n.key;
(* add x->y, at the back of the queue *)
n.key <- x;
n.value <- y;
H.add c.table x n;
push_ c n;
()
(* Insert x->y in the cache, increasing its entry count *)
let insert_ c x y =
let rec n = { key = x; value = y; next = n; prev = n } in
H.add c.table x n;
push_ c n;
()
let get c x =
let n = H.find c.table x in
(* put n at the back of the queue *)
remove_ n;
push_ c n;
n.value
let set c x y =
let len = H.length c.table in
assert (len <= c.size);
if len = c.size then
replace_ c x y
else
insert_ c x y
let size c () = H.length c.table
let iter c f = H.iter (fun x node -> f x node.value) c.table
end
let lru (type a) ~eq ?(hash = default_hash_) size =
let module L = LRU (struct
type t = a
let equal = eq
let hash = hash
end) in
let c = L.make size in
{
get = (fun x -> L.get c x);
set = (fun x y -> L.set c x y);
clear = (fun () -> L.clear c);
size = L.size c;
iter = L.iter c;
}
module UNBOUNDED (X : HASH) = struct
module H = Hashtbl.Make (X)
let make size =
assert (size > 0);
H.create size
let clear c = H.clear c
let get c x = H.find c x
let set c x y = H.replace c x y
let size c () = H.length c
let iter c f = H.iter f c
end
let unbounded (type a) ~eq ?(hash = default_hash_) size =
let module C = UNBOUNDED (struct
type t = a
let equal = eq
let hash = hash
end) in
let c = C.make size in
{
get = (fun x -> C.get c x);
set = (fun x y -> C.set c x y);
clear = (fun () -> C.clear c);
iter = C.iter c;
size = C.size c;
}
| null | https://raw.githubusercontent.com/c-cube/ocaml-containers/69f2805f1073c4ebd1063bbd58380d17e62f6324/src/data/CCCache.ml | ocaml | This file is free software, part of containers. See file "license" for more details.
* {1 Caches}
or raise Not_found
* Invariants:
- after [cache.set x y], [get cache x] must return [y] or raise [Not_found]
- [cache.set x y] is only called if [get cache x] fails, never if [x] is already bound
- [cache.size()] must be positive and correspond to the number of items in [cache.iter]
- [cache.iter f] calls [f x y] with every [x] such that [cache.get x = y]
- after [cache.clear()], [cache.get x] fails for every [x]
check that x is not bound (see invariants)
index for next assertion, cycles through
linear lookup
hashtable key -> node
max size
* Meta data for the value, making a chained list
last element
push at back of queue
remove from queue
Replace least recently used element of [c] by x->y
remove old
add x->y, at the back of the queue
Insert x->y in the cache, increasing its entry count
put n at the back of the queue |
type 'a equal = 'a -> 'a -> bool
type 'a hash = 'a -> int
let default_hash_ = Hashtbl.hash
* { 2 Value interface }
type ('a, 'b) t = {
set: 'a -> 'b -> unit;
size: unit -> int;
iter: ('a -> 'b -> unit) -> unit;
clear: unit -> unit;
}
type ('a, 'b) callback = in_cache:bool -> 'a -> 'b -> unit
let clear c = c.clear ()
let add c x y =
try
let _ = c.get x in
false
with Not_found ->
c.set x y;
true
let default_callback_ ~in_cache:_ _ _ = ()
let with_cache ?(cb = default_callback_) c f x =
try
let y = c.get x in
cb ~in_cache:true x y;
y
with Not_found ->
let y = f x in
c.set x y;
cb ~in_cache:false x y;
y
let with_cache_rec ?(cb = default_callback_) c f =
let rec f' x = with_cache ~cb c (f f') x in
f'
let size c = c.size ()
let iter c f = c.iter f
let dummy =
{
set = (fun _ _ -> ());
get = (fun _ -> raise Not_found);
clear = (fun _ -> ());
size = (fun _ -> 0);
iter = (fun _ -> ());
}
module Linear = struct
type ('a, 'b) bucket = Empty | Pair of 'a * 'b
type ('a, 'b) t = {
eq: 'a equal;
arr: ('a, 'b) bucket array;
}
let make eq size =
assert (size > 0);
{ arr = Array.make size Empty; eq; i = 0 }
let clear c =
Array.fill c.arr 0 (Array.length c.arr) Empty;
c.i <- 0
let rec search_ c i x =
if i = Array.length c.arr then raise Not_found;
match c.arr.(i) with
| Pair (x', y) when c.eq x x' -> y
| Pair _ | Empty -> search_ c (i + 1) x
let get c x = search_ c 0 x
let set c x y =
c.arr.(c.i) <- Pair (x, y);
c.i <- (c.i + 1) mod Array.length c.arr
let iter c f =
Array.iter
(function
| Pair (x, y) -> f x y
| Empty -> ())
c.arr
let size c () =
let r = ref 0 in
iter c (fun _ _ -> incr r);
!r
end
let linear ~eq size =
let size = max size 1 in
let arr = Linear.make eq size in
{
get = (fun x -> Linear.get arr x);
set = (fun x y -> Linear.set arr x y);
clear = (fun () -> Linear.clear arr);
size = Linear.size arr;
iter = Linear.iter arr;
}
module Replacing = struct
type ('a, 'b) bucket = Empty | Pair of 'a * 'b
type ('a, 'b) t = {
eq: 'a equal;
hash: 'a hash;
arr: ('a, 'b) bucket array;
mutable c_size: int;
}
let make eq hash size =
assert (size > 0);
{ arr = Array.make size Empty; eq; hash; c_size = 0 }
let clear c =
c.c_size <- 0;
Array.fill c.arr 0 (Array.length c.arr) Empty
let get c x =
let i = c.hash x mod Array.length c.arr in
match c.arr.(i) with
| Pair (x', y) when c.eq x x' -> y
| Pair _ | Empty -> raise Not_found
let is_empty = function
| Empty -> true
| Pair _ -> false
let set c x y =
let i = c.hash x mod Array.length c.arr in
if is_empty c.arr.(i) then c.c_size <- c.c_size + 1;
c.arr.(i) <- Pair (x, y)
let iter c f =
Array.iter
(function
| Empty -> ()
| Pair (x, y) -> f x y)
c.arr
let size c () = c.c_size
end
let replacing ~eq ?(hash = default_hash_) size =
let c = Replacing.make eq hash size in
{
get = (fun x -> Replacing.get c x);
set = (fun x y -> Replacing.set c x y);
clear = (fun () -> Replacing.clear c);
size = Replacing.size c;
iter = Replacing.iter c;
}
module type HASH = sig
type t
val equal : t equal
val hash : t hash
end
module LRU (X : HASH) = struct
type key = X.t
module H = Hashtbl.Make (X)
type 'a t = {
mutable first: 'a node option;
}
and 'a node = {
mutable key: key;
mutable value: 'a;
mutable next: 'a node;
mutable prev: 'a node;
}
let make size =
assert (size > 0);
{ table = H.create size; size; first = None }
let clear c =
H.clear c.table;
c.first <- None;
()
take first from queue
let take_ c =
match c.first with
| Some n when Stdlib.( == ) n.next n ->
c.first <- None;
n
| Some n ->
c.first <- Some n.next;
n.prev.next <- n.next;
n.next.prev <- n.prev;
n
| None -> failwith "LRU: empty queue"
let push_ c n =
match c.first with
| None ->
n.next <- n;
n.prev <- n;
c.first <- Some n
| Some n1 when Stdlib.( == ) n1 n -> ()
| Some n1 ->
n.prev <- n1.prev;
n.next <- n1;
n1.prev.next <- n;
n1.prev <- n
let remove_ n =
n.prev.next <- n.next;
n.next.prev <- n.prev
let replace_ c x y =
let n = take_ c in
H.remove c.table n.key;
n.key <- x;
n.value <- y;
H.add c.table x n;
push_ c n;
()
let insert_ c x y =
let rec n = { key = x; value = y; next = n; prev = n } in
H.add c.table x n;
push_ c n;
()
let get c x =
let n = H.find c.table x in
remove_ n;
push_ c n;
n.value
let set c x y =
let len = H.length c.table in
assert (len <= c.size);
if len = c.size then
replace_ c x y
else
insert_ c x y
let size c () = H.length c.table
let iter c f = H.iter (fun x node -> f x node.value) c.table
end
let lru (type a) ~eq ?(hash = default_hash_) size =
let module L = LRU (struct
type t = a
let equal = eq
let hash = hash
end) in
let c = L.make size in
{
get = (fun x -> L.get c x);
set = (fun x y -> L.set c x y);
clear = (fun () -> L.clear c);
size = L.size c;
iter = L.iter c;
}
module UNBOUNDED (X : HASH) = struct
module H = Hashtbl.Make (X)
let make size =
assert (size > 0);
H.create size
let clear c = H.clear c
let get c x = H.find c x
let set c x y = H.replace c x y
let size c () = H.length c
let iter c f = H.iter f c
end
let unbounded (type a) ~eq ?(hash = default_hash_) size =
let module C = UNBOUNDED (struct
type t = a
let equal = eq
let hash = hash
end) in
let c = C.make size in
{
get = (fun x -> C.get c x);
set = (fun x y -> C.set c x y);
clear = (fun () -> C.clear c);
iter = C.iter c;
size = C.size c;
}
|
2c348a1b4ee6ee5211df932e8cd0eaca78e7e9d02a0084595ba830bac687d9ef | qiao/sicp-solutions | 2.71.scm | { A B C D E } 31
;; / \
;; / \
{ A B C D } 15 { E } 16
;; / \
;; / \
{ A B C } 7 { D } 8
;; / \
;; / \
{ A B } 3 { C } 4
;; / \
{ A } 1 { B } 2
;;
encoding the most frequent symbol requires 1 bit whereas
;; the least frequent symbol requires n - 1 bits
| null | https://raw.githubusercontent.com/qiao/sicp-solutions/a2fe069ba6909710a0867bdb705b2e58b2a281af/chapter2/2.71.scm | scheme | / \
/ \
/ \
/ \
/ \
/ \
/ \
the least frequent symbol requires n - 1 bits | { A B C D E } 31
{ A B C D } 15 { E } 16
{ A B C } 7 { D } 8
{ A B } 3 { C } 4
{ A } 1 { B } 2
encoding the most frequent symbol requires 1 bit whereas
|
cee5211a9cde0762c0463451c6a8eaeec64e881447264227d428f54ee19ea3ce | GlideAngle/flare-timing | MaskReachMain.hs | {-# OPTIONS_GHC -fplugin Data.UnitsOfMeasure.Plugin #-}
import System.Environment (getProgName)
import System.Console.CmdArgs.Implicit (cmdArgs)
import Formatting ((%), fprint)
import Formatting.Clock (timeSpecs)
import System.Clock (getTime, Clock(Monotonic))
import Control.Exception.Safe (catchIO)
import System.Directory (getCurrentDirectory)
import Flight.Route (OptimalRoute(..))
import Flight.Comp
( FindDirFile(..)
, FileType(CompInput)
, CompInputFile(..)
, PilotName(..)
, IxTask(..)
, CompTaskSettings(..)
, Tweak(..)
, findCompInput
, reshape
, pilotNamed
, mkCompTaskSettings
, compFileToTaskFiles
)
import Flight.Track.Stop (effectiveTagging)
import Flight.Cmd.Paths (LenientFile(..), checkPaths)
import Flight.Cmd.Options (ProgramName(..))
import Flight.Cmd.BatchOptions (CmdBatchOptions(..), mkOptions)
import Flight.Lookup.Stop (stopFlying)
import Flight.Lookup.Tag (tagTaskLeading)
import Flight.Scribe
(readCompAndTasks, readRoutes, readCompTagZone, readCompPegFrame, readCompMaskArrival)
import Flight.Lookup.Route (routeLength)
import MaskReachOptions (description)
import Mask (writeMask)
import Flight.Track.Lead (sumAreas)
import "flight-gap-lead" Flight.Score (mk1Coef, mk2Coef, area1toCoef, area2toCoef)
main :: IO ()
main = do
name <- getProgName
options <- cmdArgs $ mkOptions (ProgramName name) description Nothing
let lf = LenientFile {coerceFile = reshape CompInput}
err <- checkPaths lf options
maybe (drive options) putStrLn err
drive :: CmdBatchOptions -> IO ()
drive o@CmdBatchOptions{file} = do
SEE : -duration-in-haskell
start <- getTime Monotonic
cwd <- getCurrentDirectory
files <- findCompInput $ FindDirFile {dir = cwd, file = file}
if null files then putStrLn "Couldn't find any input files."
else mapM_ (go o) files
end <- getTime Monotonic
fprint ("Masking tracks completed in " % timeSpecs % "\n") start end
go :: CmdBatchOptions -> CompInputFile -> IO ()
go CmdBatchOptions{..} compFile = do
filesTaskAndSettings <-
catchIO
(Just <$> do
ts <- compFileToTaskFiles compFile
s <- readCompAndTasks (compFile, ts)
return (ts, s))
(const $ return Nothing)
tagging <-
catchIO
(Just <$> readCompTagZone compFile)
(const $ return Nothing)
stopping <-
catchIO
(Just <$> readCompPegFrame compFile)
(const $ return Nothing)
arriving <-
catchIO
(Just <$> readCompMaskArrival compFile)
(const $ return Nothing)
routes <-
catchIO
(Just <$> readRoutes compFile)
(const $ return Nothing)
let scoredLookup = stopFlying stopping
let lookupTaskLength =
routeLength
taskRoute
taskRouteSpeedSubset
stopRoute
startRoute
routes
case (filesTaskAndSettings, tagging, stopping, arriving, routes) of
(Nothing, _, _, _, _) -> putStrLn "Couldn't read the comp settings."
(_, Nothing, _, _, _) -> putStrLn "Couldn't read the taggings."
(_, _, Nothing, _, _) -> putStrLn "Couldn't read the scored frames."
(_, _, _, Nothing, _) -> putStrLn "Couldn't read the arrivals."
(_, _, _, _, Nothing) -> putStrLn "Couldn't read the routes."
(Just (taskFiles, settings@(cs, _)), Just tg, Just stp, Just as, Just _) -> do
let cts@CompTaskSettings{compTweak} = uncurry mkCompTaskSettings settings
let tagging' = Just $ effectiveTagging tg stp
let lc1 = writeMask as sumAreas (mk1Coef . area1toCoef) area1toCoef
let lc2 = writeMask as sumAreas (mk2Coef . area2toCoef) area2toCoef
(if maybe True leadingAreaDistanceSquared compTweak then lc2 else lc1)
cts
lookupTaskLength
math
scoredLookup
tagging'
(tagTaskLeading tagging')
(IxTask <$> task)
(pilotNamed cs $ PilotName <$> pilot)
(compFile, taskFiles)
| null | https://raw.githubusercontent.com/GlideAngle/flare-timing/34873946be9b93c37048ed118ef5b4649c71d630/lang-haskell/flare-timing/prod-apps/mask-reach/MaskReachMain.hs | haskell | # OPTIONS_GHC -fplugin Data.UnitsOfMeasure.Plugin # |
import System.Environment (getProgName)
import System.Console.CmdArgs.Implicit (cmdArgs)
import Formatting ((%), fprint)
import Formatting.Clock (timeSpecs)
import System.Clock (getTime, Clock(Monotonic))
import Control.Exception.Safe (catchIO)
import System.Directory (getCurrentDirectory)
import Flight.Route (OptimalRoute(..))
import Flight.Comp
( FindDirFile(..)
, FileType(CompInput)
, CompInputFile(..)
, PilotName(..)
, IxTask(..)
, CompTaskSettings(..)
, Tweak(..)
, findCompInput
, reshape
, pilotNamed
, mkCompTaskSettings
, compFileToTaskFiles
)
import Flight.Track.Stop (effectiveTagging)
import Flight.Cmd.Paths (LenientFile(..), checkPaths)
import Flight.Cmd.Options (ProgramName(..))
import Flight.Cmd.BatchOptions (CmdBatchOptions(..), mkOptions)
import Flight.Lookup.Stop (stopFlying)
import Flight.Lookup.Tag (tagTaskLeading)
import Flight.Scribe
(readCompAndTasks, readRoutes, readCompTagZone, readCompPegFrame, readCompMaskArrival)
import Flight.Lookup.Route (routeLength)
import MaskReachOptions (description)
import Mask (writeMask)
import Flight.Track.Lead (sumAreas)
import "flight-gap-lead" Flight.Score (mk1Coef, mk2Coef, area1toCoef, area2toCoef)
main :: IO ()
main = do
name <- getProgName
options <- cmdArgs $ mkOptions (ProgramName name) description Nothing
let lf = LenientFile {coerceFile = reshape CompInput}
err <- checkPaths lf options
maybe (drive options) putStrLn err
drive :: CmdBatchOptions -> IO ()
drive o@CmdBatchOptions{file} = do
SEE : -duration-in-haskell
start <- getTime Monotonic
cwd <- getCurrentDirectory
files <- findCompInput $ FindDirFile {dir = cwd, file = file}
if null files then putStrLn "Couldn't find any input files."
else mapM_ (go o) files
end <- getTime Monotonic
fprint ("Masking tracks completed in " % timeSpecs % "\n") start end
go :: CmdBatchOptions -> CompInputFile -> IO ()
go CmdBatchOptions{..} compFile = do
filesTaskAndSettings <-
catchIO
(Just <$> do
ts <- compFileToTaskFiles compFile
s <- readCompAndTasks (compFile, ts)
return (ts, s))
(const $ return Nothing)
tagging <-
catchIO
(Just <$> readCompTagZone compFile)
(const $ return Nothing)
stopping <-
catchIO
(Just <$> readCompPegFrame compFile)
(const $ return Nothing)
arriving <-
catchIO
(Just <$> readCompMaskArrival compFile)
(const $ return Nothing)
routes <-
catchIO
(Just <$> readRoutes compFile)
(const $ return Nothing)
let scoredLookup = stopFlying stopping
let lookupTaskLength =
routeLength
taskRoute
taskRouteSpeedSubset
stopRoute
startRoute
routes
case (filesTaskAndSettings, tagging, stopping, arriving, routes) of
(Nothing, _, _, _, _) -> putStrLn "Couldn't read the comp settings."
(_, Nothing, _, _, _) -> putStrLn "Couldn't read the taggings."
(_, _, Nothing, _, _) -> putStrLn "Couldn't read the scored frames."
(_, _, _, Nothing, _) -> putStrLn "Couldn't read the arrivals."
(_, _, _, _, Nothing) -> putStrLn "Couldn't read the routes."
(Just (taskFiles, settings@(cs, _)), Just tg, Just stp, Just as, Just _) -> do
let cts@CompTaskSettings{compTweak} = uncurry mkCompTaskSettings settings
let tagging' = Just $ effectiveTagging tg stp
let lc1 = writeMask as sumAreas (mk1Coef . area1toCoef) area1toCoef
let lc2 = writeMask as sumAreas (mk2Coef . area2toCoef) area2toCoef
(if maybe True leadingAreaDistanceSquared compTweak then lc2 else lc1)
cts
lookupTaskLength
math
scoredLookup
tagging'
(tagTaskLeading tagging')
(IxTask <$> task)
(pilotNamed cs $ PilotName <$> pilot)
(compFile, taskFiles)
|
36a5cf181310e0a2e5890cf31be763f92c8bbebee9917b5cf40417995f0c9a64 | tweag/ormolu | preceding-comment-with-haddock-out.hs | {-
Here we go.
-}
| This is the module 's .
module Main (main) where
main = return ()
| null | https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/module-header/preceding-comment-with-haddock-out.hs | haskell |
Here we go.
|
| This is the module 's .
module Main (main) where
main = return ()
|
08cd9f59fa1590db8514298eb722fae7988b148383c86a7c4da28fa1f639d106 | achin/lein-parent | plugin.clj | (ns lein-parent.plugin
(:require [leiningen.parent :as parent]
[leiningen.core.project :as project]))
(def meta-merge #'project/meta-merge)
(defn middleware [project]
(if-let [inherited (parent/inherited-properties project)]
(with-meta (meta-merge project inherited)
(update (meta project) :profiles merge (:profiles inherited)))
project))
| null | https://raw.githubusercontent.com/achin/lein-parent/37630e184a37f9adc2a431f4016624b3e815f848/src/lein_parent/plugin.clj | clojure | (ns lein-parent.plugin
(:require [leiningen.parent :as parent]
[leiningen.core.project :as project]))
(def meta-merge #'project/meta-merge)
(defn middleware [project]
(if-let [inherited (parent/inherited-properties project)]
(with-meta (meta-merge project inherited)
(update (meta project) :profiles merge (:profiles inherited)))
project))
|
|
c5f4bf64ddd68736a09095ad2e57958b2dfd8024e85a4888dd1f7649f84c90c4 | SimulaVR/godot-haskell | Main.hs | import Classgen.Module
import Classgen.Spec
import Control.Lens
import Control.Monad.State
import Data.Maybe (mapMaybe)
import Data.Aeson
import qualified Data.ByteString.Lazy as BL
import qualified Data.HashMap.Strict as HM
import Language.Haskell.Exts
import Language.Haskell.Exts.SimpleComments
import System.Directory
import System.Environment
import System.Exit
import System.FilePath
import Control.Applicative
import qualified Classgen.Docs as D
import qualified Data.HashMap.Strict as H
import qualified Data.Text as T
main :: IO ()
main = do
args <- getArgs
when (length args /= 3) $ do
putStrLn "See the godot-haskell README.md for instructions"
putStrLn "godot-haskell-classgen <api.json> <godot_doc_classes.json> <godot-haskell-root>"
exitFailure
api <- BL.readFile (args !! 0)
let decodeErr x = either error id (eitherDecode x)
let (Just classes) = decodeErr api :: Maybe GodotClasses
doc <- BL.readFile (args !! 1)
let (Just docs) = decodeErr doc :: Maybe D.GodotDocs
let godotHaskellRootDir = args !! 2
let docTable = D.toTable docs
let state = execState (mapM_ (\cls -> addClass cls (H.lookup (cls ^. Classgen.Spec.name) docTable
<|> (T.stripPrefix "Godot_" (cls ^. Classgen.Spec.name)
>>= \r -> H.lookup r docTable)
<|> (T.stripPrefix "Godot" (cls ^. Classgen.Spec.name)
>>= \r -> H.lookup r docTable)
<|> (T.stripPrefix "_" (cls ^. Classgen.Spec.name)
>>= \r -> H.lookup r docTable)
<|> (H.lookup ("_" <> (cls ^. Classgen.Spec.name)) docTable)
) classes) classes)
(ClassgenState mempty mempty mempty)
writeModule godotHaskellRootDir $ godotApiTypes (state ^. tyDecls)
mapM_ (writeModule godotHaskellRootDir) (HM.elems (state ^. modules))
where
godotApiTypes decls = Module Nothing (Just
$ ModuleHead Nothing (ModuleName Nothing "Godot.Api.Types") Nothing
$ Just (classExports decls))
[LanguagePragma Nothing [Ident Nothing "DerivingStrategies"
,Ident Nothing "GeneralizedNewtypeDeriving"
,Ident Nothing "TypeFamilies"
,Ident Nothing "TemplateHaskell"]]
classImports
(decls ++ mapMaybe fromNewtypeDerivingBase decls)
classExports decls = ExportSpecList Nothing $ tcHasBaseClass : mapMaybe fromNewtypeOnly decls
tcHasBaseClass = fmap (\_ -> Nothing) $ EThingWith () (EWildcard () 0) (UnQual () (Ident () "HasBaseClass")) []
fromNewtypeOnly decl = case decl of
DataDecl _ (NewType _) _ (DHead _ (Ident Nothing ntName)) _ _ ->
Just $ EThingWith Nothing (EWildcard Nothing 0) (UnQual Nothing (Ident Nothing ntName)) []
_ ->
Nothing
fromNewtypeDerivingBase decl = case decl of
DataDecl _ (NewType _) _ (DHead _ (Ident Nothing ntName)) _ _ ->
Just $ SpliceDecl Nothing (App Nothing (Var Nothing (UnQual Nothing (Ident Nothing "deriveBase")))
(TypQuote Nothing (UnQual Nothing (Ident Nothing ntName))))
_ ->
Nothing
classImports = map (\n -> ImportDecl Nothing (ModuleName Nothing n) False False False Nothing Nothing Nothing)
[ "Data.Coerce", "Foreign.C", "Godot.Internal.Dispatch", "Godot.Gdnative.Internal"]
writeModule :: FilePath -> Module (Maybe CodeComment) -> IO ()
writeModule godotHaskellRootDir mdl@(Module _ (Just (ModuleHead _ (ModuleName Nothing name) _ _)) _ _ _) = do
let filepath = godotHaskellRootDir </> "src/" ++ map replaceDot name ++ ".hs"
-- let out = prettyPrint mdl
let out = uncurry exactPrint (ppWithComments mdl)
createDirectoryIfMissing True (takeDirectory filepath)
writeFile filepath out
where
replaceDot '.' = '/'
replaceDot c = c
| null | https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/classgen/app-classgen/Main.hs | haskell | let out = prettyPrint mdl | import Classgen.Module
import Classgen.Spec
import Control.Lens
import Control.Monad.State
import Data.Maybe (mapMaybe)
import Data.Aeson
import qualified Data.ByteString.Lazy as BL
import qualified Data.HashMap.Strict as HM
import Language.Haskell.Exts
import Language.Haskell.Exts.SimpleComments
import System.Directory
import System.Environment
import System.Exit
import System.FilePath
import Control.Applicative
import qualified Classgen.Docs as D
import qualified Data.HashMap.Strict as H
import qualified Data.Text as T
main :: IO ()
main = do
args <- getArgs
when (length args /= 3) $ do
putStrLn "See the godot-haskell README.md for instructions"
putStrLn "godot-haskell-classgen <api.json> <godot_doc_classes.json> <godot-haskell-root>"
exitFailure
api <- BL.readFile (args !! 0)
let decodeErr x = either error id (eitherDecode x)
let (Just classes) = decodeErr api :: Maybe GodotClasses
doc <- BL.readFile (args !! 1)
let (Just docs) = decodeErr doc :: Maybe D.GodotDocs
let godotHaskellRootDir = args !! 2
let docTable = D.toTable docs
let state = execState (mapM_ (\cls -> addClass cls (H.lookup (cls ^. Classgen.Spec.name) docTable
<|> (T.stripPrefix "Godot_" (cls ^. Classgen.Spec.name)
>>= \r -> H.lookup r docTable)
<|> (T.stripPrefix "Godot" (cls ^. Classgen.Spec.name)
>>= \r -> H.lookup r docTable)
<|> (T.stripPrefix "_" (cls ^. Classgen.Spec.name)
>>= \r -> H.lookup r docTable)
<|> (H.lookup ("_" <> (cls ^. Classgen.Spec.name)) docTable)
) classes) classes)
(ClassgenState mempty mempty mempty)
writeModule godotHaskellRootDir $ godotApiTypes (state ^. tyDecls)
mapM_ (writeModule godotHaskellRootDir) (HM.elems (state ^. modules))
where
godotApiTypes decls = Module Nothing (Just
$ ModuleHead Nothing (ModuleName Nothing "Godot.Api.Types") Nothing
$ Just (classExports decls))
[LanguagePragma Nothing [Ident Nothing "DerivingStrategies"
,Ident Nothing "GeneralizedNewtypeDeriving"
,Ident Nothing "TypeFamilies"
,Ident Nothing "TemplateHaskell"]]
classImports
(decls ++ mapMaybe fromNewtypeDerivingBase decls)
classExports decls = ExportSpecList Nothing $ tcHasBaseClass : mapMaybe fromNewtypeOnly decls
tcHasBaseClass = fmap (\_ -> Nothing) $ EThingWith () (EWildcard () 0) (UnQual () (Ident () "HasBaseClass")) []
fromNewtypeOnly decl = case decl of
DataDecl _ (NewType _) _ (DHead _ (Ident Nothing ntName)) _ _ ->
Just $ EThingWith Nothing (EWildcard Nothing 0) (UnQual Nothing (Ident Nothing ntName)) []
_ ->
Nothing
fromNewtypeDerivingBase decl = case decl of
DataDecl _ (NewType _) _ (DHead _ (Ident Nothing ntName)) _ _ ->
Just $ SpliceDecl Nothing (App Nothing (Var Nothing (UnQual Nothing (Ident Nothing "deriveBase")))
(TypQuote Nothing (UnQual Nothing (Ident Nothing ntName))))
_ ->
Nothing
classImports = map (\n -> ImportDecl Nothing (ModuleName Nothing n) False False False Nothing Nothing Nothing)
[ "Data.Coerce", "Foreign.C", "Godot.Internal.Dispatch", "Godot.Gdnative.Internal"]
writeModule :: FilePath -> Module (Maybe CodeComment) -> IO ()
writeModule godotHaskellRootDir mdl@(Module _ (Just (ModuleHead _ (ModuleName Nothing name) _ _)) _ _ _) = do
let filepath = godotHaskellRootDir </> "src/" ++ map replaceDot name ++ ".hs"
let out = uncurry exactPrint (ppWithComments mdl)
createDirectoryIfMissing True (takeDirectory filepath)
writeFile filepath out
where
replaceDot '.' = '/'
replaceDot c = c
|
d1e0d40d568995520fb794841bd75bd6f551558ba713307479e262dea256f83a | freckle/hspec-junit-formatter | Env.hs | -- | Load a 'JUnitConfig' using environment variables
module Test.Hspec.JUnit.Config.Env
( envJUnitEnabled
, envJUnitConfig
) where
import Prelude
import Data.Semigroup (Endo(..))
import Data.Text (pack)
import System.Directory (getCurrentDirectory)
import System.Environment (lookupEnv)
import System.FilePath (takeBaseName)
import Test.Hspec.JUnit.Config
-- | Is @JUNIT_ENABLED=1@ set in the environment?
envJUnitEnabled :: IO Bool
envJUnitEnabled = (== Just "1") <$> lookupEnv (envPrefix <> "ENABLED")
-- | Produce a 'JUnitConfig' by reading environment variables
--
-- Variable names align with setter functions from "Test.Hspec.JUnit.Config":
--
-- * @JUNIT_OUTPUT_DIRECTORY@ 'setJUnitConfigOutputDirectory'
-- * @JUNIT_OUTPUT_NAME@ 'setJUnitConfigOutputName
-- * and so on
--
envJUnitConfig :: IO JUnitConfig
envJUnitConfig = do
modify <- appEndo . foldMap Endo <$> sequence
[ lookupEnvOverride "OUTPUT_DIRECTORY" setJUnitConfigOutputDirectory
, lookupEnvOverride "OUTPUT_NAME" setJUnitConfigOutputName
, lookupEnvOverride "OUTPUT_FILE" setJUnitConfigOutputFile
, lookupEnvOverride "SUITE_NAME" $ setJUnitConfigSuiteName . pack
, lookupEnvOverride "SOURCE_PATH_PREFIX" setJUnitConfigSourcePathPrefix
]
modify . defaultJUnitConfig . pack . takeBaseName <$> getCurrentDirectory
lookupEnvOverride
:: String
-> (String -> JUnitConfig -> JUnitConfig)
-> IO (JUnitConfig -> JUnitConfig)
lookupEnvOverride name setter =
maybe id setter <$> lookupEnv (envPrefix <> name)
envPrefix :: String
envPrefix = "JUNIT_"
| null | https://raw.githubusercontent.com/freckle/hspec-junit-formatter/38eb127982f55a8287f95d7e7532b8b7c0938c4d/library/Test/Hspec/JUnit/Config/Env.hs | haskell | | Load a 'JUnitConfig' using environment variables
| Is @JUNIT_ENABLED=1@ set in the environment?
| Produce a 'JUnitConfig' by reading environment variables
Variable names align with setter functions from "Test.Hspec.JUnit.Config":
* @JUNIT_OUTPUT_DIRECTORY@ 'setJUnitConfigOutputDirectory'
* @JUNIT_OUTPUT_NAME@ 'setJUnitConfigOutputName
* and so on
| module Test.Hspec.JUnit.Config.Env
( envJUnitEnabled
, envJUnitConfig
) where
import Prelude
import Data.Semigroup (Endo(..))
import Data.Text (pack)
import System.Directory (getCurrentDirectory)
import System.Environment (lookupEnv)
import System.FilePath (takeBaseName)
import Test.Hspec.JUnit.Config
envJUnitEnabled :: IO Bool
envJUnitEnabled = (== Just "1") <$> lookupEnv (envPrefix <> "ENABLED")
envJUnitConfig :: IO JUnitConfig
envJUnitConfig = do
modify <- appEndo . foldMap Endo <$> sequence
[ lookupEnvOverride "OUTPUT_DIRECTORY" setJUnitConfigOutputDirectory
, lookupEnvOverride "OUTPUT_NAME" setJUnitConfigOutputName
, lookupEnvOverride "OUTPUT_FILE" setJUnitConfigOutputFile
, lookupEnvOverride "SUITE_NAME" $ setJUnitConfigSuiteName . pack
, lookupEnvOverride "SOURCE_PATH_PREFIX" setJUnitConfigSourcePathPrefix
]
modify . defaultJUnitConfig . pack . takeBaseName <$> getCurrentDirectory
lookupEnvOverride
:: String
-> (String -> JUnitConfig -> JUnitConfig)
-> IO (JUnitConfig -> JUnitConfig)
lookupEnvOverride name setter =
maybe id setter <$> lookupEnv (envPrefix <> name)
envPrefix :: String
envPrefix = "JUNIT_"
|
c0baffb0cf19723882f58d7225dbaaa484c07b478ee49d7f2ebc6dfeccd5ea39 | andrewzhurov/brawl-haus | css.cljs | (ns brawl-haus.fit.css)
(def styles
[[:body {:overflow "hidden"}]
[:svg {:cursor "crosshair"
}]
[:.data-reactroot {:overflow "hidden"}]
[:.timeline {:position "absolute"
:top 0 :right 0 :left 0
:height "40px"
:background "rgba(0,0,0,0.3)"
}
[:input {:width "100%"}]
[:.left {:position "absolute" :top "20px" :left "10px"}]
[:.right {:position "absolute" :top "20px" :right "10px"}]]])
| null | https://raw.githubusercontent.com/andrewzhurov/brawl-haus/7f560c3dcee7b242fda545d87c102471fdb21888/src/cljs/brawl_haus/fit/css.cljs | clojure | (ns brawl-haus.fit.css)
(def styles
[[:body {:overflow "hidden"}]
[:svg {:cursor "crosshair"
}]
[:.data-reactroot {:overflow "hidden"}]
[:.timeline {:position "absolute"
:top 0 :right 0 :left 0
:height "40px"
:background "rgba(0,0,0,0.3)"
}
[:input {:width "100%"}]
[:.left {:position "absolute" :top "20px" :left "10px"}]
[:.right {:position "absolute" :top "20px" :right "10px"}]]])
|
|
f772a084794f227bf734ca9540633470d7cc262eb1dfa7b523b70ec98cc1c74b | footprintanalytics/footprint-web | upgrade_field_literals.clj | (ns metabase.query-processor.middleware.upgrade-field-literals
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.walk :as walk]
[medley.core :as m]
[metabase.config :as config]
[metabase.mbql.util :as mbql.u]
[metabase.query-processor.middleware.resolve-fields :as qp.resolve-fields]
[metabase.query-processor.store :as qp.store]
[metabase.util :as u]
[metabase.util.i18n :refer [trs]]))
(defn- has-a-native-source-query-at-some-level? [{:keys [source-query]}]
(or (:native source-query)
(when source-query
(has-a-native-source-query-at-some-level? source-query))))
(defn- warn-once
"Log only one warning per QP run (regardless of message)."
[message]
Make sure QP store is available since we use caching below ( it may not be in some unit tests )
(when (qp.store/initialized?)
by caching the block below , the warning will only get trigger a maximum of one time per query run . We do n't need
to blow up the logs with a million warnings .
(qp.store/cached ::bad-clause-warning
(log/warn (u/colorize :red message)))))
(defn- fix-clause [{:keys [inner-query source-aliases field-name->field]} [_ field-name options :as field-clause]]
attempt to find a corresponding Field ref from the source metadata .
(let [field-ref (:field_ref (get field-name->field field-name))]
(cond
field-ref
(mbql.u/match-one field-ref
If the matching Field ref is an integer ` : field ` clause then replace it with the corrected clause and log
a developer - facing warning . Things will still work and this should be fixed on the FE , but we do n't need to
;; blow up prod logs
[:field (id :guard integer?) new-options]
(u/prog1 [:field id (merge new-options (dissoc options :base-type))]
(when (and (not config/is-prod?)
(not (has-a-native-source-query-at-some-level? inner-query)))
;; don't i18n this because it's developer-facing only.
(warn-once
(str "Warning: query is using a [:field <string> ...] clause to refer to a Field in an MBQL source query."
\newline
"Use [:field <integer> ...] clauses to refer to Fields in MBQL source queries."
\newline
"We will attempt to fix this, but it may lead to incorrect queries."
\newline
"See #19757 for more information."
\newline
(str "Clause: " (pr-str field-clause))
\newline
(str "Corrected to: " (pr-str <>))))))
Otherwise the Field clause in the source query uses a string Field name as well , but that name differs from
;; the one in `source-aliases`. Will this work? Not sure whether or not we need to log something about this.
[:field (field-name :guard string?) new-options]
(u/prog1 [:field field-name (merge new-options (dissoc options :base-type))]
(warn-once
(trs "Warning: clause {0} does not match a column in the source query. Attempting to correct this to {1}"
(pr-str field-clause)
(pr-str <>)))))
If the field name exists in the ACTUAL names returned by the source query then we 're and do n't need to
;; complain about anything.
(contains? source-aliases field-name)
field-clause
;; no matching Field ref means there's no column with this name in the source query. The query may not work, so
;; log a warning about it. This query is probably not going to work so we should let everyone know why.
:else
(do
(warn-once
(trs "Warning: clause {0} refers to a Field that may not be present in the source query. Query may not work as expected. Found: {1}"
(pr-str field-clause) (pr-str (or (not-empty source-aliases)
(set (keys field-name->field))))))
field-clause))))
(defn- upgrade-field-literals-one-level [{:keys [source-metadata], :as inner-query}]
(let [source-aliases (into #{} (keep :source_alias) source-metadata)
field-name->field (merge (m/index-by :name source-metadata)
(m/index-by (comp str/lower-case :name) source-metadata))]
(mbql.u/replace inner-query
;; don't upgrade anything inside `source-query` or `source-metadata`.
(_ :guard (constantly (some (set &parents) [:source-query :source-metadata])))
&match
;; look for `field` clauses that use a string name that doesn't appear in `source-aliases` (the ACTUAL names that
;; are returned by the source query)
[:field (field-name :guard (every-pred string? (complement source-aliases))) options]
(or (fix-clause {:inner-query inner-query, :source-aliases source-aliases, :field-name->field field-name->field}
&match)
&match))))
(defn upgrade-field-literals
"Look for usage of `:field` (name) forms where `field` (ID) would have been the correct thing to use, and fix it, so
the resulting query doesn't end up being broken."
[query]
(-> (walk/postwalk
(fn [form]
;; find maps that have `source-query` and `source-metadata`, but whose source query is an MBQL source query
;; rather than an native one
(if (and (map? form)
(:source-query form)
(seq (:source-metadata form))
;; we probably shouldn't upgrade things at all if we have a source MBQL query whose source is a native
;; query at ANY level, since `[:field <name>]` might mean `source.<name>` or it might mean
;; `some_join.<name>`. But we'll probably break more things than we fix if turn off this middleware in
;; that case. See #19757 for more info
(not (get-in form [:source-query :native])))
(upgrade-field-literals-one-level form)
form))
(qp.resolve-fields/resolve-fields query))
qp.resolve-fields/resolve-fields))
| null | https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/query_processor/middleware/upgrade_field_literals.clj | clojure | blow up prod logs
don't i18n this because it's developer-facing only.
the one in `source-aliases`. Will this work? Not sure whether or not we need to log something about this.
complain about anything.
no matching Field ref means there's no column with this name in the source query. The query may not work, so
log a warning about it. This query is probably not going to work so we should let everyone know why.
don't upgrade anything inside `source-query` or `source-metadata`.
look for `field` clauses that use a string name that doesn't appear in `source-aliases` (the ACTUAL names that
are returned by the source query)
find maps that have `source-query` and `source-metadata`, but whose source query is an MBQL source query
rather than an native one
we probably shouldn't upgrade things at all if we have a source MBQL query whose source is a native
query at ANY level, since `[:field <name>]` might mean `source.<name>` or it might mean
`some_join.<name>`. But we'll probably break more things than we fix if turn off this middleware in
that case. See #19757 for more info | (ns metabase.query-processor.middleware.upgrade-field-literals
(:require [clojure.string :as str]
[clojure.tools.logging :as log]
[clojure.walk :as walk]
[medley.core :as m]
[metabase.config :as config]
[metabase.mbql.util :as mbql.u]
[metabase.query-processor.middleware.resolve-fields :as qp.resolve-fields]
[metabase.query-processor.store :as qp.store]
[metabase.util :as u]
[metabase.util.i18n :refer [trs]]))
(defn- has-a-native-source-query-at-some-level? [{:keys [source-query]}]
(or (:native source-query)
(when source-query
(has-a-native-source-query-at-some-level? source-query))))
(defn- warn-once
"Log only one warning per QP run (regardless of message)."
[message]
Make sure QP store is available since we use caching below ( it may not be in some unit tests )
(when (qp.store/initialized?)
by caching the block below , the warning will only get trigger a maximum of one time per query run . We do n't need
to blow up the logs with a million warnings .
(qp.store/cached ::bad-clause-warning
(log/warn (u/colorize :red message)))))
(defn- fix-clause [{:keys [inner-query source-aliases field-name->field]} [_ field-name options :as field-clause]]
attempt to find a corresponding Field ref from the source metadata .
(let [field-ref (:field_ref (get field-name->field field-name))]
(cond
field-ref
(mbql.u/match-one field-ref
If the matching Field ref is an integer ` : field ` clause then replace it with the corrected clause and log
a developer - facing warning . Things will still work and this should be fixed on the FE , but we do n't need to
[:field (id :guard integer?) new-options]
(u/prog1 [:field id (merge new-options (dissoc options :base-type))]
(when (and (not config/is-prod?)
(not (has-a-native-source-query-at-some-level? inner-query)))
(warn-once
(str "Warning: query is using a [:field <string> ...] clause to refer to a Field in an MBQL source query."
\newline
"Use [:field <integer> ...] clauses to refer to Fields in MBQL source queries."
\newline
"We will attempt to fix this, but it may lead to incorrect queries."
\newline
"See #19757 for more information."
\newline
(str "Clause: " (pr-str field-clause))
\newline
(str "Corrected to: " (pr-str <>))))))
Otherwise the Field clause in the source query uses a string Field name as well , but that name differs from
[:field (field-name :guard string?) new-options]
(u/prog1 [:field field-name (merge new-options (dissoc options :base-type))]
(warn-once
(trs "Warning: clause {0} does not match a column in the source query. Attempting to correct this to {1}"
(pr-str field-clause)
(pr-str <>)))))
If the field name exists in the ACTUAL names returned by the source query then we 're and do n't need to
(contains? source-aliases field-name)
field-clause
:else
(do
(warn-once
(trs "Warning: clause {0} refers to a Field that may not be present in the source query. Query may not work as expected. Found: {1}"
(pr-str field-clause) (pr-str (or (not-empty source-aliases)
(set (keys field-name->field))))))
field-clause))))
(defn- upgrade-field-literals-one-level [{:keys [source-metadata], :as inner-query}]
(let [source-aliases (into #{} (keep :source_alias) source-metadata)
field-name->field (merge (m/index-by :name source-metadata)
(m/index-by (comp str/lower-case :name) source-metadata))]
(mbql.u/replace inner-query
(_ :guard (constantly (some (set &parents) [:source-query :source-metadata])))
&match
[:field (field-name :guard (every-pred string? (complement source-aliases))) options]
(or (fix-clause {:inner-query inner-query, :source-aliases source-aliases, :field-name->field field-name->field}
&match)
&match))))
(defn upgrade-field-literals
"Look for usage of `:field` (name) forms where `field` (ID) would have been the correct thing to use, and fix it, so
the resulting query doesn't end up being broken."
[query]
(-> (walk/postwalk
(fn [form]
(if (and (map? form)
(:source-query form)
(seq (:source-metadata form))
(not (get-in form [:source-query :native])))
(upgrade-field-literals-one-level form)
form))
(qp.resolve-fields/resolve-fields query))
qp.resolve-fields/resolve-fields))
|
2e6c278aa23a6e9162d8849661ed980b8e4cae1e71aab9898b17a48fdde7d5b5 | xapi-project/xenopsd | table.ml |
* 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.
*)
(** Some string handling functions to help drawing text tables. Modified from
Richard's code in the CLI *)
let pad n s before =
if String.length s > n then
if String.length s > 2 then
String.sub s 0 (n - 2) ^ ".."
else
String.sub s 0 n
else
let padding = String.make (n - String.length s) ' ' in
if before then padding ^ s else s ^ padding
let left n s = pad n s false
let right n s = pad n s true
let compute_col_widths rows =
let mkints n =
let rec f x = if x = n then [] else x :: f (x + 1) in
f 0
in
let numcols = List.length (List.hd rows) in
let column x = List.map (fun row -> List.nth row x) rows in
let cols = List.map column (mkints numcols) in
let max n str = max n (String.length str) in
List.map (List.fold_left max 0) cols
let print (rows : string list list) =
match rows with
| [] ->
()
| _ ->
let widths = compute_col_widths rows in
let sll = List.map (List.map2 right widths) rows in
List.iter (fun line -> print_endline (String.concat " | " line)) sll
| null | https://raw.githubusercontent.com/xapi-project/xenopsd/f4da21a4ead7c6a7082af5ec32f778faf368cf1c/list_domains/table.ml | ocaml | * Some string handling functions to help drawing text tables. Modified from
Richard's code in the CLI |
* 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.
*)
let pad n s before =
if String.length s > n then
if String.length s > 2 then
String.sub s 0 (n - 2) ^ ".."
else
String.sub s 0 n
else
let padding = String.make (n - String.length s) ' ' in
if before then padding ^ s else s ^ padding
let left n s = pad n s false
let right n s = pad n s true
let compute_col_widths rows =
let mkints n =
let rec f x = if x = n then [] else x :: f (x + 1) in
f 0
in
let numcols = List.length (List.hd rows) in
let column x = List.map (fun row -> List.nth row x) rows in
let cols = List.map column (mkints numcols) in
let max n str = max n (String.length str) in
List.map (List.fold_left max 0) cols
let print (rows : string list list) =
match rows with
| [] ->
()
| _ ->
let widths = compute_col_widths rows in
let sll = List.map (List.map2 right widths) rows in
List.iter (fun line -> print_endline (String.concat " | " line)) sll
|
29aca9d8107d6e2f8b2a02fd797bde3d7de02863a945b084b3ac935dedfb1ac4 | williamleferrand/aws | sQS_factory.ml | SQS API
(* *)
module Make = functor (HC : Aws_sigs.HTTP_CLIENT) ->
struct
module C = CalendarLib.Calendar
module P = CalendarLib.Printer.CalendarPrinter
module X = My_xml
open Lwt
open Creds
module Util = Aws_util
exception Error of string
let sprint = Printf.sprintf
let print = Printf.printf
(* copy/paste from EC2; barko you want to move to Util? *)
let signed_request
?region
?(http_method=`POST)
?(http_uri="/")
?expires_minutes
creds
params =
let http_host =
match region with
| Some r -> sprint "sqs.%s.amazonaws.com" r
| None -> "sqs.us-east-1.amazonaws.com"
in
let params =
("Version", "2009-02-01" ) ::
("SignatureVersion", "2") ::
("SignatureMethod", "HmacSHA1") ::
("AWSAccessKeyId", creds.aws_access_key_id) ::
params
in
let params =
match expires_minutes with
| Some i -> ("Expires", Util.minutes_from_now i) :: params
| None -> ("Timestamp", Util.now_as_string ()) :: params
in
let signature =
let sorted_params = Util.sort_assoc_list params in
let key_equals_value = Util.encode_key_equals_value sorted_params in
let uri_query_component = String.concat "&" key_equals_value in
let string_to_sign = String.concat "\n" [
Util.string_of_t http_method ;
String.lowercase http_host ;
http_uri ;
uri_query_component
]
in
let hmac_sha1_encoder = Cryptokit.MAC.hmac_sha1 creds.aws_secret_access_key in
let signed_string = Cryptokit.hash_string hmac_sha1_encoder string_to_sign in
Util.base64 signed_string
in
let params = ("Signature", signature) :: params in
(http_host ^ http_uri), params
let error_msg body =
match X.xml_of_string body with
| X.E ("Response",_,(X.E ("Errors",_,[X.E ("Error",_,[
X.E ("Code",_,[X.P code]);
X.E ("Message",_,[X.P message])
])]))::_) ->
`Error message
| _ -> `Error "unknown message"
(* xml handling utilities *)
let queue_url_of_xml = function
| X.E ("QueueUrl",_ , [ X.P url ]) -> url
| _ ->
raise (Error ("QueueUrlResponse"))
let list_queues_response_of_xml = function
| X.E("ListQueuesResponse", _, [
X.E("ListQueuesResult",_,items) ;
_ ;
]) ->
List.map queue_url_of_xml items
| _ ->
raise (Error "ListQueuesRequestsResponse")
let create_queue_response_of_xml = function
| X.E("CreateQueueResponse", _, kids) -> (
match kids with
| [_ ; X.E ("QueueUrl",_, [ X.P url ])] -> (
url
)
| _ -> raise (Error "CreateQueueResponse.queueurl")
)
| _ -> raise (Error "CreateQueueResponse")
type message =
{
message_id : string ;
receipt_handle : string ;
body : string }
let message_of_xml encoded = function
| X.E ("Message",
_,
X.E ("MessageId", _, [ X.P message_id ])
:: X.E ("ReceiptHandle", _, [ X.P receipt_handle ])
:: X.E ("MD5OfBody", _ , _)
:: X.E ("Body", _, [ X.P body ]) :: attributes
) -> { message_id ; receipt_handle ; body = (if encoded then Util.base64_decoder body else body) }
| _ -> raise (Error "ReceiveMessageResult.message")
let receive_message_response_of_xml ~encoded = function
| X.E ("ReceiveMessageResponse",
_,
[
X.E("ReceiveMessageResult",_ , items) ;
_ ;
]) -> List.map (message_of_xml encoded) items
| _ -> raise (Error "ReceiveMessageResponse")
let send_message_response_of_xml = function
| X.E ("SendMessageResponse",
_,
[
X.E("SendMessageResult",_ ,
[
X.E ("MD5OfMessageBody", _, _) ;
X.E ("MessageId", _, [ X.P message_id ])
]) ;
_ ;
]) -> message_id
| _ -> raise (Error "SendMessageResponse")
(* create queue *)
let create_queue ?(default_visibility_timeout=30) creds queue_name =
let url, params = signed_request ~http_uri:("/") creds
[
"Action", "CreateQueue" ;
"QueueName", queue_name ;
"DefaultVisibilityTimeout", string_of_int default_visibility_timeout ;
] in
try_lwt
let ps = Util.encode_post_url params in
print "posting request on %s: %s\n" url ps ;
lwt header, body = HC.post ~body:(`String ps) url in
let xml = X.xml_of_string body in
return (`Ok (create_queue_response_of_xml xml))
with HC.Http_error (code, _, body) -> print "Error %d %s\n" code body ; return (error_msg body)
(* list existing queues *)
let list_queues ?prefix creds =
let url, params = signed_request ~http_uri:("/") creds
(("Action", "ListQueues")
:: (match prefix with
None -> []
| Some prefix -> [ "QueueNamePrefix", prefix ])) in
try_lwt
let ps = Util.encode_post_url params in
lwt header, body = HC.post ~body:(`String ps) url in
let xml = X.xml_of_string body in
return (`Ok (list_queues_response_of_xml xml))
with HC.Http_error (code, _, body) -> print "Error %d %s\n" code body ; return (error_msg body)
(* get messages from a queue *)
let receive_message ?(attribute_name="All") ?(max_number_of_messages=1) ?(visibility_timeout=30) ?(encoded=true) creds queue_url =
let url, params = signed_request creds ~http_uri:queue_url
[
"Action", "ReceiveMessage" ;
"AttributeName", attribute_name ;
"MaxNumberOfMessages", string_of_int max_number_of_messages ;
"VisibilityTimeout", string_of_int visibility_timeout ;
] in
try_lwt
lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in
let xml = X.xml_of_string body in
return (`Ok (receive_message_response_of_xml ~encoded xml))
with HC.Http_error (_, _, body) -> return (error_msg body)
(* delete a message from a queue *)
let delete_message creds queue_url receipt_handle =
let url, params = signed_request creds ~http_uri:queue_url
[
"Action", "DeleteMessage" ;
"ReceiptHandle", receipt_handle
] in
try_lwt
lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in
ignore (header) ;
ignore (body);
return (`Ok ())
with HC.Http_error (_, _, body) -> return (error_msg body)
(* send a message to a queue *)
let send_message creds queue_url ?(encoded=true) body =
let url, params = signed_request creds ~http_uri:queue_url
[
"Action", "SendMessage" ;
"MessageBody", (if encoded then Util.base64 body else body)
] in
try_lwt
lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in
let xml = X.xml_of_string body in
return (`Ok (send_message_response_of_xml xml))
with HC.Http_error (_, _, body) -> return (error_msg body)
end
| null | https://raw.githubusercontent.com/williamleferrand/aws/d591ef0a2b89082caac6ddd6850b2d8b7824e577/src/sQS_factory.ml | ocaml |
copy/paste from EC2; barko you want to move to Util?
xml handling utilities
create queue
list existing queues
get messages from a queue
delete a message from a queue
send a message to a queue | SQS API
module Make = functor (HC : Aws_sigs.HTTP_CLIENT) ->
struct
module C = CalendarLib.Calendar
module P = CalendarLib.Printer.CalendarPrinter
module X = My_xml
open Lwt
open Creds
module Util = Aws_util
exception Error of string
let sprint = Printf.sprintf
let print = Printf.printf
let signed_request
?region
?(http_method=`POST)
?(http_uri="/")
?expires_minutes
creds
params =
let http_host =
match region with
| Some r -> sprint "sqs.%s.amazonaws.com" r
| None -> "sqs.us-east-1.amazonaws.com"
in
let params =
("Version", "2009-02-01" ) ::
("SignatureVersion", "2") ::
("SignatureMethod", "HmacSHA1") ::
("AWSAccessKeyId", creds.aws_access_key_id) ::
params
in
let params =
match expires_minutes with
| Some i -> ("Expires", Util.minutes_from_now i) :: params
| None -> ("Timestamp", Util.now_as_string ()) :: params
in
let signature =
let sorted_params = Util.sort_assoc_list params in
let key_equals_value = Util.encode_key_equals_value sorted_params in
let uri_query_component = String.concat "&" key_equals_value in
let string_to_sign = String.concat "\n" [
Util.string_of_t http_method ;
String.lowercase http_host ;
http_uri ;
uri_query_component
]
in
let hmac_sha1_encoder = Cryptokit.MAC.hmac_sha1 creds.aws_secret_access_key in
let signed_string = Cryptokit.hash_string hmac_sha1_encoder string_to_sign in
Util.base64 signed_string
in
let params = ("Signature", signature) :: params in
(http_host ^ http_uri), params
let error_msg body =
match X.xml_of_string body with
| X.E ("Response",_,(X.E ("Errors",_,[X.E ("Error",_,[
X.E ("Code",_,[X.P code]);
X.E ("Message",_,[X.P message])
])]))::_) ->
`Error message
| _ -> `Error "unknown message"
let queue_url_of_xml = function
| X.E ("QueueUrl",_ , [ X.P url ]) -> url
| _ ->
raise (Error ("QueueUrlResponse"))
let list_queues_response_of_xml = function
| X.E("ListQueuesResponse", _, [
X.E("ListQueuesResult",_,items) ;
_ ;
]) ->
List.map queue_url_of_xml items
| _ ->
raise (Error "ListQueuesRequestsResponse")
let create_queue_response_of_xml = function
| X.E("CreateQueueResponse", _, kids) -> (
match kids with
| [_ ; X.E ("QueueUrl",_, [ X.P url ])] -> (
url
)
| _ -> raise (Error "CreateQueueResponse.queueurl")
)
| _ -> raise (Error "CreateQueueResponse")
type message =
{
message_id : string ;
receipt_handle : string ;
body : string }
let message_of_xml encoded = function
| X.E ("Message",
_,
X.E ("MessageId", _, [ X.P message_id ])
:: X.E ("ReceiptHandle", _, [ X.P receipt_handle ])
:: X.E ("MD5OfBody", _ , _)
:: X.E ("Body", _, [ X.P body ]) :: attributes
) -> { message_id ; receipt_handle ; body = (if encoded then Util.base64_decoder body else body) }
| _ -> raise (Error "ReceiveMessageResult.message")
let receive_message_response_of_xml ~encoded = function
| X.E ("ReceiveMessageResponse",
_,
[
X.E("ReceiveMessageResult",_ , items) ;
_ ;
]) -> List.map (message_of_xml encoded) items
| _ -> raise (Error "ReceiveMessageResponse")
let send_message_response_of_xml = function
| X.E ("SendMessageResponse",
_,
[
X.E("SendMessageResult",_ ,
[
X.E ("MD5OfMessageBody", _, _) ;
X.E ("MessageId", _, [ X.P message_id ])
]) ;
_ ;
]) -> message_id
| _ -> raise (Error "SendMessageResponse")
let create_queue ?(default_visibility_timeout=30) creds queue_name =
let url, params = signed_request ~http_uri:("/") creds
[
"Action", "CreateQueue" ;
"QueueName", queue_name ;
"DefaultVisibilityTimeout", string_of_int default_visibility_timeout ;
] in
try_lwt
let ps = Util.encode_post_url params in
print "posting request on %s: %s\n" url ps ;
lwt header, body = HC.post ~body:(`String ps) url in
let xml = X.xml_of_string body in
return (`Ok (create_queue_response_of_xml xml))
with HC.Http_error (code, _, body) -> print "Error %d %s\n" code body ; return (error_msg body)
let list_queues ?prefix creds =
let url, params = signed_request ~http_uri:("/") creds
(("Action", "ListQueues")
:: (match prefix with
None -> []
| Some prefix -> [ "QueueNamePrefix", prefix ])) in
try_lwt
let ps = Util.encode_post_url params in
lwt header, body = HC.post ~body:(`String ps) url in
let xml = X.xml_of_string body in
return (`Ok (list_queues_response_of_xml xml))
with HC.Http_error (code, _, body) -> print "Error %d %s\n" code body ; return (error_msg body)
let receive_message ?(attribute_name="All") ?(max_number_of_messages=1) ?(visibility_timeout=30) ?(encoded=true) creds queue_url =
let url, params = signed_request creds ~http_uri:queue_url
[
"Action", "ReceiveMessage" ;
"AttributeName", attribute_name ;
"MaxNumberOfMessages", string_of_int max_number_of_messages ;
"VisibilityTimeout", string_of_int visibility_timeout ;
] in
try_lwt
lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in
let xml = X.xml_of_string body in
return (`Ok (receive_message_response_of_xml ~encoded xml))
with HC.Http_error (_, _, body) -> return (error_msg body)
let delete_message creds queue_url receipt_handle =
let url, params = signed_request creds ~http_uri:queue_url
[
"Action", "DeleteMessage" ;
"ReceiptHandle", receipt_handle
] in
try_lwt
lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in
ignore (header) ;
ignore (body);
return (`Ok ())
with HC.Http_error (_, _, body) -> return (error_msg body)
let send_message creds queue_url ?(encoded=true) body =
let url, params = signed_request creds ~http_uri:queue_url
[
"Action", "SendMessage" ;
"MessageBody", (if encoded then Util.base64 body else body)
] in
try_lwt
lwt header, body = HC.post ~body:(`String (Util.encode_post_url params)) url in
let xml = X.xml_of_string body in
return (`Ok (send_message_response_of_xml xml))
with HC.Http_error (_, _, body) -> return (error_msg body)
end
|
2cfbc9fb3d1c72968daac8a5197ebac6405f3d29740ba9afe1d14991563d8731 | ucsd-progsys/nate | btype.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
and , projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : btype.ml , v 1.39.8.1 2007/06/08 08:03:15 garrigue Exp $
(* Basic operations on core types *)
open Types
(**** Type level management ****)
let generic_level = 100000000
(* Used to mark a type during a traversal. *)
let lowest_level = 0
let pivot_level = 2 * lowest_level - 1
(* pivot_level - lowest_level < lowest_level *)
(**** Some type creators ****)
let new_id = ref (-1)
let newty2 level desc =
incr new_id; { desc = desc; level = level; id = !new_id }
let newgenty desc = newty2 generic_level desc
let newgenvar () = newgenty Tvar
let newmarkedvar level =
incr new_id ; { desc = Tvar ; level = pivot_level - level ; i d = ! new_id }
let ( ) =
incr new_id ;
{ desc = Tvar ; level = pivot_level - generic_level ; i d = ! new_id }
let newmarkedvar level =
incr new_id; { desc = Tvar; level = pivot_level - level; id = !new_id }
let newmarkedgenvar () =
incr new_id;
{ desc = Tvar; level = pivot_level - generic_level; id = !new_id }
*)
(**** Representative of a type ****)
let rec field_kind_repr =
function
Fvar {contents = Some kind} -> field_kind_repr kind
| kind -> kind
let rec repr =
function
{desc = Tlink t'} ->
We do no path compression . Path compression does not seem to
improve notably efficiency , and it prevents from changing a
[ ] into another type ( for instance , for undoing a
unification ) .
We do no path compression. Path compression does not seem to
improve notably efficiency, and it prevents from changing a
[Tlink] into another type (for instance, for undoing a
unification).
*)
repr t'
| {desc = Tfield (_, k, _, t')} when field_kind_repr k = Fabsent ->
repr t'
| t -> t
let rec commu_repr = function
Clink r when !r <> Cunknown -> commu_repr !r
| c -> c
let rec row_field_repr_aux tl = function
Reither(_, tl', _, {contents = Some fi}) ->
row_field_repr_aux (tl@tl') fi
| Reither(c, tl', m, r) ->
Reither(c, tl@tl', m, r)
| Rpresent (Some _) when tl <> [] ->
Rpresent (Some (List.hd tl))
| fi -> fi
let row_field_repr fi = row_field_repr_aux [] fi
let rec rev_concat l ll =
match ll with
[] -> l
| l'::ll -> rev_concat (l'@l) ll
let rec row_repr_aux ll row =
match (repr row.row_more).desc with
| Tvariant row' ->
let f = row.row_fields in
row_repr_aux (if f = [] then ll else f::ll) row'
| _ ->
if ll = [] then row else
{row with row_fields = rev_concat row.row_fields ll}
let row_repr row = row_repr_aux [] row
let rec row_field tag row =
let rec find = function
| (tag',f) :: fields ->
if tag = tag' then row_field_repr f else find fields
| [] ->
match repr row.row_more with
| {desc=Tvariant row'} -> row_field tag row'
| _ -> Rabsent
in find row.row_fields
let rec row_more row =
match repr row.row_more with
| {desc=Tvariant row'} -> row_more row'
| ty -> ty
let static_row row =
let row = row_repr row in
row.row_closed &&
List.for_all
(fun (_,f) -> match row_field_repr f with Reither _ -> false | _ -> true)
row.row_fields
let hash_variant s =
let accu = ref 0 in
for i = 0 to String.length s - 1 do
accu := 223 * !accu + Char.code s.[i]
done;
reduce to 31 bits
accu := !accu land (1 lsl 31 - 1);
make it signed for 64 bits architectures
if !accu > 0x3FFFFFFF then !accu - (1 lsl 31) else !accu
let proxy ty =
let ty0 = repr ty in
match ty0.desc with
| Tvariant row when not (static_row row) ->
row_more row
| Tobject (ty, _) ->
let rec proxy_obj ty =
match ty.desc with
Tfield (_, _, _, ty) | Tlink ty -> proxy_obj ty
| Tvar | Tunivar | Tconstr _ -> ty
| Tnil -> ty0
| _ -> assert false
in proxy_obj ty
| _ -> ty0
(**** Utilities for private types ****)
let has_constr_row t =
match (repr t).desc with
Tobject(t,_) ->
let rec check_row t =
match (repr t).desc with
Tfield(_,_,_,t) -> check_row t
| Tconstr _ -> true
| _ -> false
in check_row t
| Tvariant row ->
(match row_more row with {desc=Tconstr _} -> true | _ -> false)
| _ ->
false
let is_row_name s =
let l = String.length s in
if l < 4 then false else String.sub s (l-4) 4 = "#row"
(**********************************)
Utilities for type traversal
(**********************************)
let rec iter_row f row =
List.iter
(fun (_, fi) ->
match row_field_repr fi with
| Rpresent(Some ty) -> f ty
| Reither(_, tl, _, _) -> List.iter f tl
| _ -> ())
row.row_fields;
match (repr row.row_more).desc with
Tvariant row -> iter_row f row
| Tvar | Tunivar | Tsubst _ | Tconstr _ ->
Misc.may (fun (_,l) -> List.iter f l) row.row_name
| _ -> assert false
let iter_type_expr f ty =
match ty.desc with
Tvar -> ()
| Tarrow (_, ty1, ty2, _) -> f ty1; f ty2
| Ttuple l -> List.iter f l
| Tconstr (_, l, _) -> List.iter f l
| Tobject(ty, {contents = Some (_, p)})
-> f ty; List.iter f p
| Tobject (ty, _) -> f ty
| Tvariant row -> iter_row f row; f (row_more row)
| Tfield (_, _, ty1, ty2) -> f ty1; f ty2
| Tnil -> ()
| Tlink ty -> f ty
| Tsubst ty -> f ty
| Tunivar -> ()
| Tpoly (ty, tyl) -> f ty; List.iter f tyl
let rec iter_abbrev f = function
Mnil -> ()
| Mcons(_, ty, ty', rem) -> f ty; f ty'; iter_abbrev f rem
| Mlink rem -> iter_abbrev f !rem
let copy_row f fixed row keep more =
let fields = List.map
(fun (l, fi) -> l,
match row_field_repr fi with
| Rpresent(Some ty) -> Rpresent(Some(f ty))
| Reither(c, tl, m, e) ->
let e = if keep then e else ref None in
let m = if row.row_fixed then fixed else m in
let tl = List.map f tl in
Reither(c, tl, m, e)
| _ -> fi)
row.row_fields in
let name =
match row.row_name with None -> None
| Some (path, tl) -> Some (path, List.map f tl) in
{ row_fields = fields; row_more = more;
row_bound = (); row_fixed = row.row_fixed && fixed;
row_closed = row.row_closed; row_name = name; }
let rec copy_kind = function
Fvar{contents = Some k} -> copy_kind k
| Fvar _ -> Fvar (ref None)
| Fpresent -> Fpresent
| Fabsent -> assert false
let copy_commu c =
if commu_repr c = Cok then Cok else Clink (ref Cunknown)
(* Since univars may be used as row variables, we need to do some
encoding during substitution *)
let rec norm_univar ty =
match ty.desc with
Tunivar | Tsubst _ -> ty
| Tlink ty -> norm_univar ty
| Ttuple (ty :: _) -> norm_univar ty
| _ -> assert false
let rec copy_type_desc f = function
Tvar -> Tvar
| Tarrow (p, ty1, ty2, c)-> Tarrow (p, f ty1, f ty2, copy_commu c)
| Ttuple l -> Ttuple (List.map f l)
| Tconstr (p, l, _) -> Tconstr (p, List.map f l, ref Mnil)
| Tobject(ty, {contents = Some (p, tl)})
-> Tobject (f ty, ref (Some(p, List.map f tl)))
| Tobject (ty, _) -> Tobject (f ty, ref None)
| Tvariant row -> assert false (* too ambiguous *)
| Tfield (p, k, ty1, ty2) -> (* the kind is kept shared *)
Tfield (p, field_kind_repr k, f ty1, f ty2)
| Tnil -> Tnil
| Tlink ty -> copy_type_desc f ty.desc
| Tsubst ty -> assert false
| Tunivar -> Tunivar
| Tpoly (ty, tyl) ->
let tyl = List.map (fun x -> norm_univar (f x)) tyl in
Tpoly (f ty, tyl)
Utilities for copying
let saved_desc = ref []
(* Saved association of generic nodes with their description. *)
let save_desc ty desc =
saved_desc := (ty, desc)::!saved_desc
let saved_kinds = ref [] (* duplicated kind variables *)
let new_kinds = ref [] (* new kind variables *)
let dup_kind r =
(match !r with None -> () | Some _ -> assert false);
if not (List.memq r !new_kinds) then begin
saved_kinds := r :: !saved_kinds;
let r' = ref None in
new_kinds := r' :: !new_kinds;
r := Some (Fvar r')
end
(* Restored type descriptions. *)
let cleanup_types () =
List.iter (fun (ty, desc) -> ty.desc <- desc) !saved_desc;
List.iter (fun r -> r := None) !saved_kinds;
saved_desc := []; saved_kinds := []; new_kinds := []
(* Mark a type. *)
let rec mark_type ty =
let ty = repr ty in
if ty.level >= lowest_level then begin
ty.level <- pivot_level - ty.level;
iter_type_expr mark_type ty
end
let mark_type_node ty =
let ty = repr ty in
if ty.level >= lowest_level then begin
ty.level <- pivot_level - ty.level;
end
let mark_type_params ty =
iter_type_expr mark_type ty
(* Remove marks from a type. *)
let rec unmark_type ty =
let ty = repr ty in
if ty.level < lowest_level then begin
ty.level <- pivot_level - ty.level;
iter_type_expr unmark_type ty
end
let unmark_type_decl decl =
List.iter unmark_type decl.type_params;
begin match decl.type_kind with
Type_abstract -> ()
| Type_variant (cstrs, priv) ->
List.iter (fun (c, tl) -> List.iter unmark_type tl) cstrs
| Type_record(lbls, rep, priv) ->
List.iter (fun (c, mut, t) -> unmark_type t) lbls
end;
begin match decl.type_manifest with
None -> ()
| Some ty -> unmark_type ty
end
let unmark_class_signature sign =
unmark_type sign.cty_self;
Vars.iter (fun l (m, v, t) -> unmark_type t) sign.cty_vars
let rec unmark_class_type =
function
Tcty_constr (p, tyl, cty) ->
List.iter unmark_type tyl; unmark_class_type cty
| Tcty_signature sign ->
unmark_class_signature sign
| Tcty_fun (_, ty, cty) ->
unmark_type ty; unmark_class_type cty
(*******************************************)
(* Memorization of abbreviation expansion *)
(*******************************************)
(* Search whether the expansion has been memorized. *)
let rec find_expans p1 = function
Mnil -> None
| Mcons (p2, ty0, ty, _) when Path.same p1 p2 -> Some ty
| Mcons (_, _, _, rem) -> find_expans p1 rem
| Mlink {contents = rem} -> find_expans p1 rem
debug : check for cycles in abbreviation . only works with -principal
let rec check_expans visited ty =
let ty = repr ty in
assert ( not ( visited ) ) ;
match ty.desc with
Tconstr ( path , args , abbrev ) - >
begin match find_expans path ! abbrev with
Some ty ' - > check_expans ( ty : : visited ) ty '
| None - > ( )
end
| _ - > ( )
let rec check_expans visited ty =
let ty = repr ty in
assert (not (List.memq ty visited));
match ty.desc with
Tconstr (path, args, abbrev) ->
begin match find_expans path !abbrev with
Some ty' -> check_expans (ty :: visited) ty'
| None -> ()
end
| _ -> ()
*)
let memo = ref []
(* Contains the list of saved abbreviation expansions. *)
let cleanup_abbrev () =
(* Remove all memorized abbreviation expansions. *)
List.iter (fun abbr -> abbr := Mnil) !memo;
memo := []
let memorize_abbrev mem path v v' =
(* Memorize the expansion of an abbreviation. *)
mem := Mcons (path, v, v', !mem);
check_expans [ ] v ;
memo := mem :: !memo
let rec forget_abbrev_rec mem path =
match mem with
Mnil ->
assert false
| Mcons (path', _, _, rem) when Path.same path path' ->
rem
| Mcons (path', v, v', rem) ->
Mcons (path', v, v', forget_abbrev_rec rem path)
| Mlink mem' ->
mem' := forget_abbrev_rec !mem' path;
raise Exit
let forget_abbrev mem path =
try mem := forget_abbrev_rec !mem path with Exit -> ()
debug : check for invalid abbreviations
let rec check_abbrev_rec = function
Mnil - > true
| Mcons ( _ , , ty2 , rem ) - >
repr ! = repr ty2
| Mlink mem ' - >
check_abbrev_rec ! '
let ( ) =
List.for_all ( fun mem - > check_abbrev_rec ! ) ! memo
let rec check_abbrev_rec = function
Mnil -> true
| Mcons (_, ty1, ty2, rem) ->
repr ty1 != repr ty2
| Mlink mem' ->
check_abbrev_rec !mem'
let check_memorized_abbrevs () =
List.for_all (fun mem -> check_abbrev_rec !mem) !memo
*)
(**********************************)
Utilities for labels
(**********************************)
let is_optional l =
String.length l > 0 && l.[0] = '?'
let label_name l =
if is_optional l then String.sub l 1 (String.length l - 1)
else l
let rec extract_label_aux hd l = function
[] -> raise Not_found
| (l',t as p) :: ls ->
if label_name l' = l then (l', t, List.rev hd, ls)
else extract_label_aux (p::hd) l ls
let extract_label l ls = extract_label_aux [] l ls
(**********************************)
Utilities for backtracking
(**********************************)
type change =
Ctype of type_expr * type_desc
| Clevel of type_expr * int
| Cname of
(Path.t * type_expr list) option ref * (Path.t * type_expr list) option
| Crow of row_field option ref * row_field option
| Ckind of field_kind option ref * field_kind option
| Ccommu of commutable ref * commutable
| Cuniv of type_expr option ref * type_expr option
let undo_change = function
Ctype (ty, desc) -> ty.desc <- desc
| Clevel (ty, level) -> ty.level <- level
| Cname (r, v) -> r := v
| Crow (r, v) -> r := v
| Ckind (r, v) -> r := v
| Ccommu (r, v) -> r := v
| Cuniv (r, v) -> r := v
type changes =
Change of change * changes ref
| Unchanged
| Invalid
type snapshot = changes ref * int
let trail = Weak.create 1
let last_snapshot = ref 0
let log_change ch =
match Weak.get trail 0 with None -> ()
| Some r ->
let r' = ref Unchanged in
r := Change (ch, r');
Weak.set trail 0 (Some r')
let log_type ty =
if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc))
let link_type ty ty' = log_type ty; ty.desc <- Tlink ty'
; assert ( ( ) )
; check_expans [ ] ty '
let set_level ty level =
if ty.id <= !last_snapshot then log_change (Clevel (ty, ty.level));
ty.level <- level
let set_univar rty ty =
log_change (Cuniv (rty, !rty)); rty := Some ty
let set_name nm v =
log_change (Cname (nm, !nm)); nm := v
let set_row_field e v =
log_change (Crow (e, !e)); e := Some v
let set_kind rk k =
log_change (Ckind (rk, !rk)); rk := Some k
let set_commu rc c =
log_change (Ccommu (rc, !rc)); rc := c
let snapshot () =
let old = !last_snapshot in
last_snapshot := !new_id;
match Weak.get trail 0 with Some r -> (r, old)
| None ->
let r = ref Unchanged in
Weak.set trail 0 (Some r);
(r, old)
let rec rev_log accu = function
Unchanged -> accu
| Invalid -> assert false
| Change (ch, next) ->
let d = !next in
next := Invalid;
rev_log (ch::accu) d
let backtrack (changes, old) =
match !changes with
Unchanged -> last_snapshot := old
| Invalid -> failwith "Btype.backtrack"
| Change _ as change ->
cleanup_abbrev ();
let backlog = rev_log [] change in
List.iter undo_change backlog;
changes := Unchanged;
last_snapshot := old;
Weak.set trail 0 (Some changes)
| null | https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/typing/btype.ml | ocaml | *********************************************************************
Objective Caml
*********************************************************************
Basic operations on core types
*** Type level management ***
Used to mark a type during a traversal.
pivot_level - lowest_level < lowest_level
*** Some type creators ***
*** Representative of a type ***
*** Utilities for private types ***
********************************
********************************
Since univars may be used as row variables, we need to do some
encoding during substitution
too ambiguous
the kind is kept shared
Saved association of generic nodes with their description.
duplicated kind variables
new kind variables
Restored type descriptions.
Mark a type.
Remove marks from a type.
*****************************************
Memorization of abbreviation expansion
*****************************************
Search whether the expansion has been memorized.
Contains the list of saved abbreviation expansions.
Remove all memorized abbreviation expansions.
Memorize the expansion of an abbreviation.
********************************
********************************
********************************
******************************** | and , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : btype.ml , v 1.39.8.1 2007/06/08 08:03:15 garrigue Exp $
open Types
let generic_level = 100000000
let lowest_level = 0
let pivot_level = 2 * lowest_level - 1
let new_id = ref (-1)
let newty2 level desc =
incr new_id; { desc = desc; level = level; id = !new_id }
let newgenty desc = newty2 generic_level desc
let newgenvar () = newgenty Tvar
let newmarkedvar level =
incr new_id ; { desc = Tvar ; level = pivot_level - level ; i d = ! new_id }
let ( ) =
incr new_id ;
{ desc = Tvar ; level = pivot_level - generic_level ; i d = ! new_id }
let newmarkedvar level =
incr new_id; { desc = Tvar; level = pivot_level - level; id = !new_id }
let newmarkedgenvar () =
incr new_id;
{ desc = Tvar; level = pivot_level - generic_level; id = !new_id }
*)
let rec field_kind_repr =
function
Fvar {contents = Some kind} -> field_kind_repr kind
| kind -> kind
let rec repr =
function
{desc = Tlink t'} ->
We do no path compression . Path compression does not seem to
improve notably efficiency , and it prevents from changing a
[ ] into another type ( for instance , for undoing a
unification ) .
We do no path compression. Path compression does not seem to
improve notably efficiency, and it prevents from changing a
[Tlink] into another type (for instance, for undoing a
unification).
*)
repr t'
| {desc = Tfield (_, k, _, t')} when field_kind_repr k = Fabsent ->
repr t'
| t -> t
let rec commu_repr = function
Clink r when !r <> Cunknown -> commu_repr !r
| c -> c
let rec row_field_repr_aux tl = function
Reither(_, tl', _, {contents = Some fi}) ->
row_field_repr_aux (tl@tl') fi
| Reither(c, tl', m, r) ->
Reither(c, tl@tl', m, r)
| Rpresent (Some _) when tl <> [] ->
Rpresent (Some (List.hd tl))
| fi -> fi
let row_field_repr fi = row_field_repr_aux [] fi
let rec rev_concat l ll =
match ll with
[] -> l
| l'::ll -> rev_concat (l'@l) ll
let rec row_repr_aux ll row =
match (repr row.row_more).desc with
| Tvariant row' ->
let f = row.row_fields in
row_repr_aux (if f = [] then ll else f::ll) row'
| _ ->
if ll = [] then row else
{row with row_fields = rev_concat row.row_fields ll}
let row_repr row = row_repr_aux [] row
let rec row_field tag row =
let rec find = function
| (tag',f) :: fields ->
if tag = tag' then row_field_repr f else find fields
| [] ->
match repr row.row_more with
| {desc=Tvariant row'} -> row_field tag row'
| _ -> Rabsent
in find row.row_fields
let rec row_more row =
match repr row.row_more with
| {desc=Tvariant row'} -> row_more row'
| ty -> ty
let static_row row =
let row = row_repr row in
row.row_closed &&
List.for_all
(fun (_,f) -> match row_field_repr f with Reither _ -> false | _ -> true)
row.row_fields
let hash_variant s =
let accu = ref 0 in
for i = 0 to String.length s - 1 do
accu := 223 * !accu + Char.code s.[i]
done;
reduce to 31 bits
accu := !accu land (1 lsl 31 - 1);
make it signed for 64 bits architectures
if !accu > 0x3FFFFFFF then !accu - (1 lsl 31) else !accu
let proxy ty =
let ty0 = repr ty in
match ty0.desc with
| Tvariant row when not (static_row row) ->
row_more row
| Tobject (ty, _) ->
let rec proxy_obj ty =
match ty.desc with
Tfield (_, _, _, ty) | Tlink ty -> proxy_obj ty
| Tvar | Tunivar | Tconstr _ -> ty
| Tnil -> ty0
| _ -> assert false
in proxy_obj ty
| _ -> ty0
let has_constr_row t =
match (repr t).desc with
Tobject(t,_) ->
let rec check_row t =
match (repr t).desc with
Tfield(_,_,_,t) -> check_row t
| Tconstr _ -> true
| _ -> false
in check_row t
| Tvariant row ->
(match row_more row with {desc=Tconstr _} -> true | _ -> false)
| _ ->
false
let is_row_name s =
let l = String.length s in
if l < 4 then false else String.sub s (l-4) 4 = "#row"
Utilities for type traversal
let rec iter_row f row =
List.iter
(fun (_, fi) ->
match row_field_repr fi with
| Rpresent(Some ty) -> f ty
| Reither(_, tl, _, _) -> List.iter f tl
| _ -> ())
row.row_fields;
match (repr row.row_more).desc with
Tvariant row -> iter_row f row
| Tvar | Tunivar | Tsubst _ | Tconstr _ ->
Misc.may (fun (_,l) -> List.iter f l) row.row_name
| _ -> assert false
let iter_type_expr f ty =
match ty.desc with
Tvar -> ()
| Tarrow (_, ty1, ty2, _) -> f ty1; f ty2
| Ttuple l -> List.iter f l
| Tconstr (_, l, _) -> List.iter f l
| Tobject(ty, {contents = Some (_, p)})
-> f ty; List.iter f p
| Tobject (ty, _) -> f ty
| Tvariant row -> iter_row f row; f (row_more row)
| Tfield (_, _, ty1, ty2) -> f ty1; f ty2
| Tnil -> ()
| Tlink ty -> f ty
| Tsubst ty -> f ty
| Tunivar -> ()
| Tpoly (ty, tyl) -> f ty; List.iter f tyl
let rec iter_abbrev f = function
Mnil -> ()
| Mcons(_, ty, ty', rem) -> f ty; f ty'; iter_abbrev f rem
| Mlink rem -> iter_abbrev f !rem
let copy_row f fixed row keep more =
let fields = List.map
(fun (l, fi) -> l,
match row_field_repr fi with
| Rpresent(Some ty) -> Rpresent(Some(f ty))
| Reither(c, tl, m, e) ->
let e = if keep then e else ref None in
let m = if row.row_fixed then fixed else m in
let tl = List.map f tl in
Reither(c, tl, m, e)
| _ -> fi)
row.row_fields in
let name =
match row.row_name with None -> None
| Some (path, tl) -> Some (path, List.map f tl) in
{ row_fields = fields; row_more = more;
row_bound = (); row_fixed = row.row_fixed && fixed;
row_closed = row.row_closed; row_name = name; }
let rec copy_kind = function
Fvar{contents = Some k} -> copy_kind k
| Fvar _ -> Fvar (ref None)
| Fpresent -> Fpresent
| Fabsent -> assert false
let copy_commu c =
if commu_repr c = Cok then Cok else Clink (ref Cunknown)
let rec norm_univar ty =
match ty.desc with
Tunivar | Tsubst _ -> ty
| Tlink ty -> norm_univar ty
| Ttuple (ty :: _) -> norm_univar ty
| _ -> assert false
let rec copy_type_desc f = function
Tvar -> Tvar
| Tarrow (p, ty1, ty2, c)-> Tarrow (p, f ty1, f ty2, copy_commu c)
| Ttuple l -> Ttuple (List.map f l)
| Tconstr (p, l, _) -> Tconstr (p, List.map f l, ref Mnil)
| Tobject(ty, {contents = Some (p, tl)})
-> Tobject (f ty, ref (Some(p, List.map f tl)))
| Tobject (ty, _) -> Tobject (f ty, ref None)
Tfield (p, field_kind_repr k, f ty1, f ty2)
| Tnil -> Tnil
| Tlink ty -> copy_type_desc f ty.desc
| Tsubst ty -> assert false
| Tunivar -> Tunivar
| Tpoly (ty, tyl) ->
let tyl = List.map (fun x -> norm_univar (f x)) tyl in
Tpoly (f ty, tyl)
Utilities for copying
let saved_desc = ref []
let save_desc ty desc =
saved_desc := (ty, desc)::!saved_desc
let dup_kind r =
(match !r with None -> () | Some _ -> assert false);
if not (List.memq r !new_kinds) then begin
saved_kinds := r :: !saved_kinds;
let r' = ref None in
new_kinds := r' :: !new_kinds;
r := Some (Fvar r')
end
let cleanup_types () =
List.iter (fun (ty, desc) -> ty.desc <- desc) !saved_desc;
List.iter (fun r -> r := None) !saved_kinds;
saved_desc := []; saved_kinds := []; new_kinds := []
let rec mark_type ty =
let ty = repr ty in
if ty.level >= lowest_level then begin
ty.level <- pivot_level - ty.level;
iter_type_expr mark_type ty
end
let mark_type_node ty =
let ty = repr ty in
if ty.level >= lowest_level then begin
ty.level <- pivot_level - ty.level;
end
let mark_type_params ty =
iter_type_expr mark_type ty
let rec unmark_type ty =
let ty = repr ty in
if ty.level < lowest_level then begin
ty.level <- pivot_level - ty.level;
iter_type_expr unmark_type ty
end
let unmark_type_decl decl =
List.iter unmark_type decl.type_params;
begin match decl.type_kind with
Type_abstract -> ()
| Type_variant (cstrs, priv) ->
List.iter (fun (c, tl) -> List.iter unmark_type tl) cstrs
| Type_record(lbls, rep, priv) ->
List.iter (fun (c, mut, t) -> unmark_type t) lbls
end;
begin match decl.type_manifest with
None -> ()
| Some ty -> unmark_type ty
end
let unmark_class_signature sign =
unmark_type sign.cty_self;
Vars.iter (fun l (m, v, t) -> unmark_type t) sign.cty_vars
let rec unmark_class_type =
function
Tcty_constr (p, tyl, cty) ->
List.iter unmark_type tyl; unmark_class_type cty
| Tcty_signature sign ->
unmark_class_signature sign
| Tcty_fun (_, ty, cty) ->
unmark_type ty; unmark_class_type cty
let rec find_expans p1 = function
Mnil -> None
| Mcons (p2, ty0, ty, _) when Path.same p1 p2 -> Some ty
| Mcons (_, _, _, rem) -> find_expans p1 rem
| Mlink {contents = rem} -> find_expans p1 rem
debug : check for cycles in abbreviation . only works with -principal
let rec check_expans visited ty =
let ty = repr ty in
assert ( not ( visited ) ) ;
match ty.desc with
Tconstr ( path , args , abbrev ) - >
begin match find_expans path ! abbrev with
Some ty ' - > check_expans ( ty : : visited ) ty '
| None - > ( )
end
| _ - > ( )
let rec check_expans visited ty =
let ty = repr ty in
assert (not (List.memq ty visited));
match ty.desc with
Tconstr (path, args, abbrev) ->
begin match find_expans path !abbrev with
Some ty' -> check_expans (ty :: visited) ty'
| None -> ()
end
| _ -> ()
*)
let memo = ref []
let cleanup_abbrev () =
List.iter (fun abbr -> abbr := Mnil) !memo;
memo := []
let memorize_abbrev mem path v v' =
mem := Mcons (path, v, v', !mem);
check_expans [ ] v ;
memo := mem :: !memo
let rec forget_abbrev_rec mem path =
match mem with
Mnil ->
assert false
| Mcons (path', _, _, rem) when Path.same path path' ->
rem
| Mcons (path', v, v', rem) ->
Mcons (path', v, v', forget_abbrev_rec rem path)
| Mlink mem' ->
mem' := forget_abbrev_rec !mem' path;
raise Exit
let forget_abbrev mem path =
try mem := forget_abbrev_rec !mem path with Exit -> ()
debug : check for invalid abbreviations
let rec check_abbrev_rec = function
Mnil - > true
| Mcons ( _ , , ty2 , rem ) - >
repr ! = repr ty2
| Mlink mem ' - >
check_abbrev_rec ! '
let ( ) =
List.for_all ( fun mem - > check_abbrev_rec ! ) ! memo
let rec check_abbrev_rec = function
Mnil -> true
| Mcons (_, ty1, ty2, rem) ->
repr ty1 != repr ty2
| Mlink mem' ->
check_abbrev_rec !mem'
let check_memorized_abbrevs () =
List.for_all (fun mem -> check_abbrev_rec !mem) !memo
*)
Utilities for labels
let is_optional l =
String.length l > 0 && l.[0] = '?'
let label_name l =
if is_optional l then String.sub l 1 (String.length l - 1)
else l
let rec extract_label_aux hd l = function
[] -> raise Not_found
| (l',t as p) :: ls ->
if label_name l' = l then (l', t, List.rev hd, ls)
else extract_label_aux (p::hd) l ls
let extract_label l ls = extract_label_aux [] l ls
Utilities for backtracking
type change =
Ctype of type_expr * type_desc
| Clevel of type_expr * int
| Cname of
(Path.t * type_expr list) option ref * (Path.t * type_expr list) option
| Crow of row_field option ref * row_field option
| Ckind of field_kind option ref * field_kind option
| Ccommu of commutable ref * commutable
| Cuniv of type_expr option ref * type_expr option
let undo_change = function
Ctype (ty, desc) -> ty.desc <- desc
| Clevel (ty, level) -> ty.level <- level
| Cname (r, v) -> r := v
| Crow (r, v) -> r := v
| Ckind (r, v) -> r := v
| Ccommu (r, v) -> r := v
| Cuniv (r, v) -> r := v
type changes =
Change of change * changes ref
| Unchanged
| Invalid
type snapshot = changes ref * int
let trail = Weak.create 1
let last_snapshot = ref 0
let log_change ch =
match Weak.get trail 0 with None -> ()
| Some r ->
let r' = ref Unchanged in
r := Change (ch, r');
Weak.set trail 0 (Some r')
let log_type ty =
if ty.id <= !last_snapshot then log_change (Ctype (ty, ty.desc))
let link_type ty ty' = log_type ty; ty.desc <- Tlink ty'
; assert ( ( ) )
; check_expans [ ] ty '
let set_level ty level =
if ty.id <= !last_snapshot then log_change (Clevel (ty, ty.level));
ty.level <- level
let set_univar rty ty =
log_change (Cuniv (rty, !rty)); rty := Some ty
let set_name nm v =
log_change (Cname (nm, !nm)); nm := v
let set_row_field e v =
log_change (Crow (e, !e)); e := Some v
let set_kind rk k =
log_change (Ckind (rk, !rk)); rk := Some k
let set_commu rc c =
log_change (Ccommu (rc, !rc)); rc := c
let snapshot () =
let old = !last_snapshot in
last_snapshot := !new_id;
match Weak.get trail 0 with Some r -> (r, old)
| None ->
let r = ref Unchanged in
Weak.set trail 0 (Some r);
(r, old)
let rec rev_log accu = function
Unchanged -> accu
| Invalid -> assert false
| Change (ch, next) ->
let d = !next in
next := Invalid;
rev_log (ch::accu) d
let backtrack (changes, old) =
match !changes with
Unchanged -> last_snapshot := old
| Invalid -> failwith "Btype.backtrack"
| Change _ as change ->
cleanup_abbrev ();
let backlog = rev_log [] change in
List.iter undo_change backlog;
changes := Unchanged;
last_snapshot := old;
Weak.set trail 0 (Some changes)
|
aced04edf2072d615c7d8f6ef0d8f32af030446f784068a3eb364bfc316f08dd | unnohideyuki/bunny | sample283.hs | f [] = False
f (x:[]) = False
f (x:y:[]) = x > y
f (x:xs) = f xs
main = putStrLn $ show $ f "331223"
| null | https://raw.githubusercontent.com/unnohideyuki/bunny/501856ff48f14b252b674585f25a2bf3801cb185/compiler/test/samples/sample283.hs | haskell | f [] = False
f (x:[]) = False
f (x:y:[]) = x > y
f (x:xs) = f xs
main = putStrLn $ show $ f "331223"
|
|
88102fdd29356a4094d3e676815a06c1602571e16de5e98d6e22497816a50b97 | chetmurthy/ensemble | appl_lwe.ml | (**************************************************************)
APPL_LWE.ML : lwe application interface
Author : , 11/97
(**************************************************************)
open Trans
open Util
open View
open Appl_intf
open New
(**************************************************************)
let name = Trace.file "APPL_LWE"
let failwith = Trace.make_failwith name
let log = Trace.log name
(**************************************************************)
let arrayf_combine5 a b c d e =
let len = Arrayf.length a in
let lb = Arrayf.length b in
let lc = Arrayf.length c in
let ld = Arrayf.length d in
let le = Arrayf.length e in
if lb <> len || lc <> len || ld <> len || le <> len then (
eprintf "APPL_LWG:arrayf_combine:a=%d b=%d c=%d d=%d e=%d\n"
len lb lc ld le ;
failwith sanity
) ;
Arrayf.init len (fun i ->
((Arrayf.get a i),
(Arrayf.get b i),
(Arrayf.get c i),
(Arrayf.get d i),
(Arrayf.get e i))
)
let arrayf_split5 abcde =
let a = Arrayf.map (fun (x,_,_,_,_) -> x) abcde in
let b = Arrayf.map (fun (_,x,_,_,_) -> x) abcde in
let c = Arrayf.map (fun (_,_,x,_,_) -> x) abcde in
let d = Arrayf.map (fun (_,_,_,x,_) -> x) abcde in
let e = Arrayf.map (fun (_,_,_,_,x) -> x) abcde in
(a,b,c,d,e)
(**************************************************************)
in
let genf comb split alarm (ls,vs) il =
if il = [] then failwith "no interfaces given" ;
let endpts,intfs = List.split il in
(* The heartbeat rate is the minimum of all rates.
*)
let heartbeat_rate =
List.fold_left (fun hb intf -> min intf.heartbeat_rate hb) ((List.hd intfs).heartbeat_rate) intfs
in
let disable_asyncs =
let async = Alarm.async alarm in
let hwe_async = Async.find async ls.async in
List.map (fun endpt ->
Async.add async (vs.group,endpt) hwe_async
) endpts
in
(* Exit causes all exits to be called and asyncs to
* be disabled.
*)
let exit () =
List.iter (fun i -> i.exit ()) intfs ;
List.iter (fun f -> f ()) disable_asyncs
in
let install (ls,vs) =
let hwg_view = vs.view in
let ranks = Arrayf.init ls.nmembers ident in
let info = arrayf_combine5 vs.lwe vs.address vs.clients vs.out_of_date ranks in
let info =
Arrayf.map (fun (lwe,address,clients,ood,hw_rank) ->
Arrayf.map (fun endpt -> (endpt,address,clients,ood,hw_rank)) lwe
) info
in
let info = Arrayf.map Arrayf.to_list info in
let info = Arrayf.to_list info in
let info = List.flatten info in
let info = Arrayf.of_list info in
let view,address,clients,ood,hw_ranks = arrayf_split5 info in
let translate rank actions =
Array.map (function
| Cast msg ->
let msg,iov = split msg in
(*
eprintf "APPL_LWG:Cast:%s\n" (Endpt.string_of_id rank) ;
*)
Cast(((LCast rank),msg),iov)
| Send(destsa,msg) ->
let dests = Arrayf.of_array destsa in
let msg,iov = split msg in
(* Calculate actual destinations.
*)
eprintf " APPL_LWG : " ( Endpt.string_of_id endpt ) ( string_of_array Endpt.string_of_id dendpts ) ;
eprintf "APPL_LWG:Send:%s->%s\n" (Endpt.string_of_id endpt) (string_of_array Endpt.string_of_id dendpts) ;
*)
And their ranks in the HWG .
*)
let dranks =
Arrayf.map (Arrayf.get hw_ranks) dests
in
(* Remove duplicate ranks (done implicitly in
* Lset.inject).
*)
let dranks = Lset.inject dranks in
let dranks = Lset.project dranks in
let dranks = Arrayf.to_array dranks in
Send(dranks,((LSend(rank,destsa),msg), iov))
| Send1(dest,msg) ->
let msg,iov = split msg in
Calculate rank in the HWG .
*)
let drank = Arrayf.get hw_ranks dest in
Send1(drank,((LSend(rank,[|dest|]),msg), iov))
| Control o ->
begin
match o with
| Migrate _
| Suspect _
| Block _
| Leave
| XferDone ->
failwith (sprintf "does not support %s actions" (string_of_control o))
| _ -> ()
end ;
Control o
) actions
in
let vs = set vs [
Vs_view view ;
Vs_address address ;
Vs_clients clients ;
Vs_out_of_date ood
;
] in
let ah =
List.map (fun (endpt,intf) ->
let ls = View.local name endpt vs in
let actions,handlers = intf.install (ls,vs) in
let actions = translate ls.rank actions in
(actions,(ls.rank,handlers))
) il
in
let actions,handlers = List.split ah in
let actions = Array.concat actions in
let handlers = Array.of_list handlers in
(* Block local members.
*)
let block () =
let actions =
Array.map (fun (rank,handlers) ->
translate rank (handlers.block ())
) handlers
in
array_flatten actions
in
(* Give heartbeat to all local members.
*)
let heartbeat t =
let actions =
Array.map (fun (rank,handlers) ->
translate rank (handlers.heartbeat t)
) handlers
in
array_flatten actions
in
(* This is an array of handlers for local members.
* For doing fast delivery of Sends.
*)
let handlersa =
let a = Array.create (Arrayf.length view) None in
Array.iter (fun (rank,handlers) ->
a.(rank) <- Some handlers
) handlers ;
a
in
(* PERF: The closures should be cached, but that isn't
* so easy to do.
*)
let receive _ bk cs =
let handler = function
| ((LCast origin),msg),iov ->
let msg = comb msg iov in
let actions =
Array.map (fun (rank,handlers) ->
let actions = handlers.receive origin bk cs msg in
translate rank actions
) handlers
in
array_flatten actions
| (LSend(origin,dests),msg),iov ->
let msg = comb msg iov in
let actions =
Array.map (fun rank ->
match handlersa.(rank) with
| None -> [||]
| Some handlers ->
let actions = handlers.receive origin bk cs msg in
translate rank actions
) dests
in
array_flatten actions
in handler
in
let disable () =
Array.iter (fun (_,handlers) -> handlers.disable ()) handlers
in
let handlers = {
flow_block = (fun _ -> ());
heartbeat = heartbeat ;
receive = receive ;
block = block ;
disable = disable
} in
actions,handlers
in
let intf =
{ heartbeat_rate = heartbeat_rate ;
install = install ;
exit = exit }
in
(* Does not affect ls.
*)
let vs =
View.set vs [
Vs_lwe (Arrayf.singleton (Arrayf.of_list endpts))
]
in
((ls,vs),intf)
let pf appl info =
let comb msg iov = (msg,iov) in
let split (msg,iov) = (msg,iov) in
genf comb split appl info
let f appl info =
let comb () iov = iov in
let split iov = ((),iov) in
genf comb split appl info
(**************************************************************)
| null | https://raw.githubusercontent.com/chetmurthy/ensemble/8266a89e68be24a4aaa5d594662e211eeaa6dc89/ensemble/server/appl/appl_lwe.ml | ocaml | ************************************************************
************************************************************
************************************************************
************************************************************
************************************************************
The heartbeat rate is the minimum of all rates.
Exit causes all exits to be called and asyncs to
* be disabled.
eprintf "APPL_LWG:Cast:%s\n" (Endpt.string_of_id rank) ;
Calculate actual destinations.
Remove duplicate ranks (done implicitly in
* Lset.inject).
Block local members.
Give heartbeat to all local members.
This is an array of handlers for local members.
* For doing fast delivery of Sends.
PERF: The closures should be cached, but that isn't
* so easy to do.
Does not affect ls.
************************************************************ | APPL_LWE.ML : lwe application interface
Author : , 11/97
open Trans
open Util
open View
open Appl_intf
open New
let name = Trace.file "APPL_LWE"
let failwith = Trace.make_failwith name
let log = Trace.log name
let arrayf_combine5 a b c d e =
let len = Arrayf.length a in
let lb = Arrayf.length b in
let lc = Arrayf.length c in
let ld = Arrayf.length d in
let le = Arrayf.length e in
if lb <> len || lc <> len || ld <> len || le <> len then (
eprintf "APPL_LWG:arrayf_combine:a=%d b=%d c=%d d=%d e=%d\n"
len lb lc ld le ;
failwith sanity
) ;
Arrayf.init len (fun i ->
((Arrayf.get a i),
(Arrayf.get b i),
(Arrayf.get c i),
(Arrayf.get d i),
(Arrayf.get e i))
)
let arrayf_split5 abcde =
let a = Arrayf.map (fun (x,_,_,_,_) -> x) abcde in
let b = Arrayf.map (fun (_,x,_,_,_) -> x) abcde in
let c = Arrayf.map (fun (_,_,x,_,_) -> x) abcde in
let d = Arrayf.map (fun (_,_,_,x,_) -> x) abcde in
let e = Arrayf.map (fun (_,_,_,_,x) -> x) abcde in
(a,b,c,d,e)
in
let genf comb split alarm (ls,vs) il =
if il = [] then failwith "no interfaces given" ;
let endpts,intfs = List.split il in
let heartbeat_rate =
List.fold_left (fun hb intf -> min intf.heartbeat_rate hb) ((List.hd intfs).heartbeat_rate) intfs
in
let disable_asyncs =
let async = Alarm.async alarm in
let hwe_async = Async.find async ls.async in
List.map (fun endpt ->
Async.add async (vs.group,endpt) hwe_async
) endpts
in
let exit () =
List.iter (fun i -> i.exit ()) intfs ;
List.iter (fun f -> f ()) disable_asyncs
in
let install (ls,vs) =
let hwg_view = vs.view in
let ranks = Arrayf.init ls.nmembers ident in
let info = arrayf_combine5 vs.lwe vs.address vs.clients vs.out_of_date ranks in
let info =
Arrayf.map (fun (lwe,address,clients,ood,hw_rank) ->
Arrayf.map (fun endpt -> (endpt,address,clients,ood,hw_rank)) lwe
) info
in
let info = Arrayf.map Arrayf.to_list info in
let info = Arrayf.to_list info in
let info = List.flatten info in
let info = Arrayf.of_list info in
let view,address,clients,ood,hw_ranks = arrayf_split5 info in
let translate rank actions =
Array.map (function
| Cast msg ->
let msg,iov = split msg in
Cast(((LCast rank),msg),iov)
| Send(destsa,msg) ->
let dests = Arrayf.of_array destsa in
let msg,iov = split msg in
eprintf " APPL_LWG : " ( Endpt.string_of_id endpt ) ( string_of_array Endpt.string_of_id dendpts ) ;
eprintf "APPL_LWG:Send:%s->%s\n" (Endpt.string_of_id endpt) (string_of_array Endpt.string_of_id dendpts) ;
*)
And their ranks in the HWG .
*)
let dranks =
Arrayf.map (Arrayf.get hw_ranks) dests
in
let dranks = Lset.inject dranks in
let dranks = Lset.project dranks in
let dranks = Arrayf.to_array dranks in
Send(dranks,((LSend(rank,destsa),msg), iov))
| Send1(dest,msg) ->
let msg,iov = split msg in
Calculate rank in the HWG .
*)
let drank = Arrayf.get hw_ranks dest in
Send1(drank,((LSend(rank,[|dest|]),msg), iov))
| Control o ->
begin
match o with
| Migrate _
| Suspect _
| Block _
| Leave
| XferDone ->
failwith (sprintf "does not support %s actions" (string_of_control o))
| _ -> ()
end ;
Control o
) actions
in
let vs = set vs [
Vs_view view ;
Vs_address address ;
Vs_clients clients ;
Vs_out_of_date ood
;
] in
let ah =
List.map (fun (endpt,intf) ->
let ls = View.local name endpt vs in
let actions,handlers = intf.install (ls,vs) in
let actions = translate ls.rank actions in
(actions,(ls.rank,handlers))
) il
in
let actions,handlers = List.split ah in
let actions = Array.concat actions in
let handlers = Array.of_list handlers in
let block () =
let actions =
Array.map (fun (rank,handlers) ->
translate rank (handlers.block ())
) handlers
in
array_flatten actions
in
let heartbeat t =
let actions =
Array.map (fun (rank,handlers) ->
translate rank (handlers.heartbeat t)
) handlers
in
array_flatten actions
in
let handlersa =
let a = Array.create (Arrayf.length view) None in
Array.iter (fun (rank,handlers) ->
a.(rank) <- Some handlers
) handlers ;
a
in
let receive _ bk cs =
let handler = function
| ((LCast origin),msg),iov ->
let msg = comb msg iov in
let actions =
Array.map (fun (rank,handlers) ->
let actions = handlers.receive origin bk cs msg in
translate rank actions
) handlers
in
array_flatten actions
| (LSend(origin,dests),msg),iov ->
let msg = comb msg iov in
let actions =
Array.map (fun rank ->
match handlersa.(rank) with
| None -> [||]
| Some handlers ->
let actions = handlers.receive origin bk cs msg in
translate rank actions
) dests
in
array_flatten actions
in handler
in
let disable () =
Array.iter (fun (_,handlers) -> handlers.disable ()) handlers
in
let handlers = {
flow_block = (fun _ -> ());
heartbeat = heartbeat ;
receive = receive ;
block = block ;
disable = disable
} in
actions,handlers
in
let intf =
{ heartbeat_rate = heartbeat_rate ;
install = install ;
exit = exit }
in
let vs =
View.set vs [
Vs_lwe (Arrayf.singleton (Arrayf.of_list endpts))
]
in
((ls,vs),intf)
let pf appl info =
let comb msg iov = (msg,iov) in
let split (msg,iov) = (msg,iov) in
genf comb split appl info
let f appl info =
let comb () iov = iov in
let split iov = ((),iov) in
genf comb split appl info
|
349f163fafdb970a957e40d871d36d6c73250f386ddd6f7dd7fc8f8301fb71e2 | tmattio/device-detector | device_detector.mli | module Referer : sig
type t = {
domain : string;
medium_name : string;
referer_name : string;
parameters : string list;
}
val find_from_domain : string -> t option
val find_from_uri : string -> t option
val favicon_uri : t -> string option
end
| null | https://raw.githubusercontent.com/tmattio/device-detector/7153345a305c441b2393016cd32153c6ab8e7c95/lib/device_detector.mli | ocaml | module Referer : sig
type t = {
domain : string;
medium_name : string;
referer_name : string;
parameters : string list;
}
val find_from_domain : string -> t option
val find_from_uri : string -> t option
val favicon_uri : t -> string option
end
|
|
48a160657594411c451de01372f7b9c5f3e79eb65a8f6dd884b1bf01653c9200 | andreasabel/java-adt | Syntax.hs | # LANGUAGE DeriveFoldable #
|
Example : ( only ground inductive types )
@
data D = C1 { x1 : : D1 , ... , xn : : Dn }
| C2 ...
...
@
is printed as
@
public abstract class D { }
public class C1 extends D {
public D1 x1 ;
...
public Dn xn ;
public C1 ( D1 x1 , ... , Dn xn ) {
this.x1 = x1 ;
...
this xn = xn ;
}
}
@
@
data D = C1 { x1 : : D1 , ... , xn : : Dn }
| C2 ...
...
--visitor E1 V1
--visitor E2 V2
@
is printed as
@
class D {
public E1 accept ( V1 v ) {
return v.visit ( this ) ;
}
public E2 accept ( V2 v ) {
return v.visit ( this ) ;
}
}
class C1 extends D {
public D1 x1 ;
...
public Dn xn ;
public C1 ( D1 x1 , ... , Dn xn ) {
this.x1 = x1 ;
...
this xn = xn ;
}
}
@
the visitor interface is created as follows
@
interface V1 {
public E1 visit ( C1 x ) ;
public E1 visit ( C2 x ) ;
...
}
@
Example :
@
data List a = Nil | Cons { head : : a , tail : : List a }
@
becomes
@
abstract class List < a > { }
class < a > extends List < a > {
Nil ( ) { }
}
class Cons < a > extends List < a > {
public a head ;
public List < a > tail ;
Cons ( a head , List < a > tail ) {
this.head = head ;
this.tail = tail ;
}
}
@
Grammar :
@
datadecl : : ' data ' uppername ' = ' constructors visitors
constructor : : uppername [ fields ]
fields : : ' { ' fieldlist ' } '
fieldlist : : fieldlist ' , ' field
| field
field : : ' : : ' type
type : : type atom
| atom
atom : : name
| ' [ ' type ' ] '
| ' ( ' type ' )
visitor : : ' --visitor ' name name
@
Example: (only ground inductive types)
@
data D = C1 { x1 :: D1, ..., xn ::Dn }
| C2 ...
...
@
is printed as
@
public abstract class D {}
public class C1 extends D {
public D1 x1;
...
public Dn xn;
public C1 (D1 x1, ..., Dn xn) {
this.x1 = x1;
...
this xn = xn;
}
}
@
@
data D = C1 { x1 :: D1, ..., xn ::Dn }
| C2 ...
...
--visitor E1 V1
--visitor E2 V2
@
is printed as
@
class D {
public E1 accept (V1 v) {
return v.visit (this);
}
public E2 accept (V2 v) {
return v.visit (this);
}
}
class C1 extends D {
public D1 x1;
...
public Dn xn;
public C1 (D1 x1, ..., Dn xn) {
this.x1 = x1;
...
this xn = xn;
}
}
@
the visitor interface is created as follows
@
interface V1 {
public E1 visit (C1 x);
public E1 visit (C2 x);
...
}
@
Example:
@
data List a = Nil | Cons { head :: a, tail :: List a }
@
becomes
@
abstract class List<a> {}
class Nil<a> extends List<a> {
Nil () {}
}
class Cons<a> extends List<a> {
public a head;
public List<a> tail;
Cons (a head, List<a> tail) {
this.head = head;
this.tail = tail;
}
}
@
Grammar:
@
datadecl :: 'data' uppername '=' constructors visitors
constructor :: uppername [fields]
fields :: '{' fieldlist '}'
fieldlist :: fieldlist ',' field
| field
field :: lowername '::' type
type :: type atom
| atom
atom :: name
| '[' type ']'
| '(' type ')
visitor :: '--visitor' name name
@
-}
module Syntax where
for ghc 7.6
import Data.Monoid
type FieldId = String
type ConstrId = String
type DataId = String
type Param = String
type ClassId = String
data TypeId
= TypeId String
| Gen String -- ^ Type variable.
deriving (Eq, Show)
data Visitor = Visitor
{ name :: ClassId
, returnType :: TypeId
} deriving Show
data Type
= List Type -- ^ @List<Type>@
| App Type Type -- ^ @Type<Type>@
| Name String -- ^ @Type@
deriving (Eq, Show)
data Field' a = Field
{ fieldId :: FieldId
, fieldType :: a
} deriving (Show, Foldable)
data Constructor' a = Constructor
{ constrId :: ConstrId
, constrFields :: [Field' a]
} deriving (Show, Foldable)
data Data' a = Data
{ dataId :: DataId
, dataParams :: [Param]
, dataConstructors :: [Constructor' a]
, dataVisitors :: [Visitor]
} deriving (Show, Foldable)
type Field = Field' Type
type Constructor = Constructor' Type
type Data = Data' Type
usesList :: Foldable f => f Type -> Bool
usesList = getAny . foldMap (Any . isList)
where
isList :: Type -> Bool
isList (List _) = True
isList _ = False
| null | https://raw.githubusercontent.com/andreasabel/java-adt/db346d3112cc31823bd70957d331b73af806f3eb/src/Syntax.hs | haskell | visitor E1 V1
visitor E2 V2
visitor ' name name
visitor E1 V1
visitor E2 V2
visitor' name name
^ Type variable.
^ @List<Type>@
^ @Type<Type>@
^ @Type@ | # LANGUAGE DeriveFoldable #
|
Example : ( only ground inductive types )
@
data D = C1 { x1 : : D1 , ... , xn : : Dn }
| C2 ...
...
@
is printed as
@
public abstract class D { }
public class C1 extends D {
public D1 x1 ;
...
public Dn xn ;
public C1 ( D1 x1 , ... , Dn xn ) {
this.x1 = x1 ;
...
this xn = xn ;
}
}
@
@
data D = C1 { x1 : : D1 , ... , xn : : Dn }
| C2 ...
...
@
is printed as
@
class D {
public E1 accept ( V1 v ) {
return v.visit ( this ) ;
}
public E2 accept ( V2 v ) {
return v.visit ( this ) ;
}
}
class C1 extends D {
public D1 x1 ;
...
public Dn xn ;
public C1 ( D1 x1 , ... , Dn xn ) {
this.x1 = x1 ;
...
this xn = xn ;
}
}
@
the visitor interface is created as follows
@
interface V1 {
public E1 visit ( C1 x ) ;
public E1 visit ( C2 x ) ;
...
}
@
Example :
@
data List a = Nil | Cons { head : : a , tail : : List a }
@
becomes
@
abstract class List < a > { }
class < a > extends List < a > {
Nil ( ) { }
}
class Cons < a > extends List < a > {
public a head ;
public List < a > tail ;
Cons ( a head , List < a > tail ) {
this.head = head ;
this.tail = tail ;
}
}
@
Grammar :
@
datadecl : : ' data ' uppername ' = ' constructors visitors
constructor : : uppername [ fields ]
fields : : ' { ' fieldlist ' } '
fieldlist : : fieldlist ' , ' field
| field
field : : ' : : ' type
type : : type atom
| atom
atom : : name
| ' [ ' type ' ] '
| ' ( ' type ' )
@
Example: (only ground inductive types)
@
data D = C1 { x1 :: D1, ..., xn ::Dn }
| C2 ...
...
@
is printed as
@
public abstract class D {}
public class C1 extends D {
public D1 x1;
...
public Dn xn;
public C1 (D1 x1, ..., Dn xn) {
this.x1 = x1;
...
this xn = xn;
}
}
@
@
data D = C1 { x1 :: D1, ..., xn ::Dn }
| C2 ...
...
@
is printed as
@
class D {
public E1 accept (V1 v) {
return v.visit (this);
}
public E2 accept (V2 v) {
return v.visit (this);
}
}
class C1 extends D {
public D1 x1;
...
public Dn xn;
public C1 (D1 x1, ..., Dn xn) {
this.x1 = x1;
...
this xn = xn;
}
}
@
the visitor interface is created as follows
@
interface V1 {
public E1 visit (C1 x);
public E1 visit (C2 x);
...
}
@
Example:
@
data List a = Nil | Cons { head :: a, tail :: List a }
@
becomes
@
abstract class List<a> {}
class Nil<a> extends List<a> {
Nil () {}
}
class Cons<a> extends List<a> {
public a head;
public List<a> tail;
Cons (a head, List<a> tail) {
this.head = head;
this.tail = tail;
}
}
@
Grammar:
@
datadecl :: 'data' uppername '=' constructors visitors
constructor :: uppername [fields]
fields :: '{' fieldlist '}'
fieldlist :: fieldlist ',' field
| field
field :: lowername '::' type
type :: type atom
| atom
atom :: name
| '[' type ']'
| '(' type ')
@
-}
module Syntax where
for ghc 7.6
import Data.Monoid
type FieldId = String
type ConstrId = String
type DataId = String
type Param = String
type ClassId = String
data TypeId
= TypeId String
deriving (Eq, Show)
data Visitor = Visitor
{ name :: ClassId
, returnType :: TypeId
} deriving Show
data Type
deriving (Eq, Show)
data Field' a = Field
{ fieldId :: FieldId
, fieldType :: a
} deriving (Show, Foldable)
data Constructor' a = Constructor
{ constrId :: ConstrId
, constrFields :: [Field' a]
} deriving (Show, Foldable)
data Data' a = Data
{ dataId :: DataId
, dataParams :: [Param]
, dataConstructors :: [Constructor' a]
, dataVisitors :: [Visitor]
} deriving (Show, Foldable)
type Field = Field' Type
type Constructor = Constructor' Type
type Data = Data' Type
usesList :: Foldable f => f Type -> Bool
usesList = getAny . foldMap (Any . isList)
where
isList :: Type -> Bool
isList (List _) = True
isList _ = False
|
50f7014ded1bddee07673472784d027a0fd46396d65324adc8036673ca430dc7 | klutometis/clrs | figure-15.3.scm | (require-extension
syntax-case
srfi-11
array-lib
check)
(require '../15.2/section)
(import section-15.2)
(let ((p '(30 35 15 5 10 20 25)))
(let-values (((m s) (matrix-chain-order p)))
(check (array->list m) =>
'((0 15750 7875 9375 11875 15125)
(+inf 0 2625 4375 7125 10500)
(+inf +inf 0 750 2500 5375)
(+inf +inf +inf 0 1000 3500)
(+inf +inf +inf +inf 0 5000)
(+inf +inf +inf +inf +inf 0)))
(check (array->list s) =>
'((#f 0 0 2 2 2)
(#f #f 1 2 2 2)
(#f #f #f 2 2 2)
(#f #f #f #f 3 4)
(#f #f #f #f #f 4)
(#f #f #f #f #f #f)))))
| null | https://raw.githubusercontent.com/klutometis/clrs/f85a8f0036f0946c9e64dde3259a19acc62b74a1/15.2/figure-15.3.scm | scheme | (require-extension
syntax-case
srfi-11
array-lib
check)
(require '../15.2/section)
(import section-15.2)
(let ((p '(30 35 15 5 10 20 25)))
(let-values (((m s) (matrix-chain-order p)))
(check (array->list m) =>
'((0 15750 7875 9375 11875 15125)
(+inf 0 2625 4375 7125 10500)
(+inf +inf 0 750 2500 5375)
(+inf +inf +inf 0 1000 3500)
(+inf +inf +inf +inf 0 5000)
(+inf +inf +inf +inf +inf 0)))
(check (array->list s) =>
'((#f 0 0 2 2 2)
(#f #f 1 2 2 2)
(#f #f #f 2 2 2)
(#f #f #f #f 3 4)
(#f #f #f #f #f 4)
(#f #f #f #f #f #f)))))
|
|
21f8af8bb47a2a4932d9de82fefc51416b5d0a7209440d0311fdb5b3384bfa60 | may-liu/qtalk | mod_irc.erl | %%%----------------------------------------------------------------------
%%% File : mod_irc.erl
Author : < >
%%% Purpose : IRC transport
Created : 15 Feb 2003 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2014 ProcessOne
%%%
%%% 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. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module(mod_irc).
-author('').
-behaviour(gen_server).
-behaviour(gen_mod).
%% API
-export([start_link/2, start/2, stop/1, export/1, import/1,
import/3, closed_connection/3, get_connection_params/3]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2, code_change/3]).
-include("ejabberd.hrl").
-include("logger.hrl").
-include("jlib.hrl").
-include("adhoc.hrl").
-define(DEFAULT_IRC_ENCODING, <<"iso8859-1">>).
-define(DEFAULT_IRC_PORT, 6667).
-define(POSSIBLE_ENCODINGS,
[<<"koi8-r">>, <<"iso8859-1">>, <<"iso8859-2">>,
<<"utf-8">>, <<"utf-8+latin-1">>]).
-type conn_param() :: {binary(), binary(), inet:port_number(), binary()} |
{binary(), binary(), inet:port_number()} |
{binary(), binary()} |
{binary()}.
-record(irc_connection,
{jid_server_host = {#jid{}, <<"">>, <<"">>} :: {jid(), binary(), binary()},
pid = self() :: pid()}).
-record(irc_custom,
{us_host = {{<<"">>, <<"">>}, <<"">>} :: {{binary(), binary()},
binary()},
data = [] :: [{username, binary()} |
{connections_params, [conn_param()]}]}).
-record(state, {host = <<"">> :: binary(),
server_host = <<"">> :: binary(),
access = all :: atom()}).
-define(PROCNAME, ejabberd_mod_irc).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
%% Description: Starts the server
%%--------------------------------------------------------------------
start_link(Host, Opts) ->
Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
gen_server:start_link({local, Proc}, ?MODULE,
[Host, Opts], []).
start(Host, Opts) ->
start_supervisor(Host),
Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
ChildSpec = {Proc, {?MODULE, start_link, [Host, Opts]},
temporary, 1000, worker, [?MODULE]},
supervisor:start_child(ejabberd_sup, ChildSpec).
stop(Host) ->
stop_supervisor(Host),
Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
gen_server:call(Proc, stop),
supervisor:delete_child(ejabberd_sup, Proc).
%%====================================================================
%% gen_server callbacks
%%====================================================================
%%--------------------------------------------------------------------
%% Function: init(Args) -> {ok, State} |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%% Description: Initiates the server
%%--------------------------------------------------------------------
init([Host, Opts]) ->
ejabberd:start_app(p1_iconv),
MyHost = gen_mod:get_opt_host(Host, Opts,
<<"irc.@HOST@">>),
case gen_mod:db_type(Opts) of
mnesia ->
mnesia:create_table(irc_custom,
[{disc_copies, [node()]},
{attributes, record_info(fields, irc_custom)}]),
update_table();
_ -> ok
end,
Access = gen_mod:get_opt(access, Opts,
fun(A) when is_atom(A) -> A end,
all),
catch ets:new(irc_connection,
[named_table, public,
{keypos, #irc_connection.jid_server_host}]),
ejabberd_router:register_route(MyHost),
{ok,
#state{host = MyHost, server_host = Host,
access = Access}}.
%%--------------------------------------------------------------------
Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} |
%% {stop, Reason, State}
%% Description: Handling call messages
%%--------------------------------------------------------------------
handle_call(stop, _From, State) ->
{stop, normal, ok, State}.
%%--------------------------------------------------------------------
Function : handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling cast messages
%%--------------------------------------------------------------------
handle_cast(_Msg, State) -> {noreply, State}.
%%--------------------------------------------------------------------
Function : handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling all non call/cast messages
%%--------------------------------------------------------------------
handle_info({route, From, To, Packet},
#state{host = Host, server_host = ServerHost,
access = Access} =
State) ->
case catch do_route(Host, ServerHost, Access, From, To,
Packet)
of
{'EXIT', Reason} -> ?ERROR_MSG("~p", [Reason]);
_ -> ok
end,
{noreply, State};
handle_info(_Info, State) -> {noreply, State}.
%%--------------------------------------------------------------------
%% Function: terminate(Reason, State) -> void()
%% Description: This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any necessary
%% cleaning up. When it returns, the gen_server terminates with Reason.
%% The return value is ignored.
%%--------------------------------------------------------------------
terminate(_Reason, State) ->
ejabberd_router:unregister_route(State#state.host), ok.
%%--------------------------------------------------------------------
Func : code_change(OldVsn , State , Extra ) - > { ok , NewState }
%% Description: Convert process state when code is changed
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) -> {ok, State}.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
start_supervisor(Host) ->
Proc = gen_mod:get_module_proc(Host,
ejabberd_mod_irc_sup),
ChildSpec = {Proc,
{ejabberd_tmp_sup, start_link,
[Proc, mod_irc_connection]},
permanent, infinity, supervisor, [ejabberd_tmp_sup]},
supervisor:start_child(ejabberd_sup, ChildSpec).
stop_supervisor(Host) ->
Proc = gen_mod:get_module_proc(Host,
ejabberd_mod_irc_sup),
supervisor:terminate_child(ejabberd_sup, Proc),
supervisor:delete_child(ejabberd_sup, Proc).
do_route(Host, ServerHost, Access, From, To, Packet) ->
case acl:match_rule(ServerHost, Access, From) of
allow -> do_route1(Host, ServerHost, From, To, Packet);
_ ->
#xmlel{attrs = Attrs} = Packet,
Lang = xml:get_attr_s(<<"xml:lang">>, Attrs),
ErrText = <<"Access denied by service policy">>,
Err = jlib:make_error_reply(Packet,
?ERRT_FORBIDDEN(Lang, ErrText)),
ejabberd_router:route(To, From, Err)
end.
do_route1(Host, ServerHost, From, To, Packet) ->
#jid{user = ChanServ, resource = Resource} = To,
#xmlel{} = Packet,
case ChanServ of
<<"">> ->
case Resource of
<<"">> ->
case jlib:iq_query_info(Packet) of
#iq{type = get, xmlns = (?NS_DISCO_INFO) = XMLNS,
sub_el = SubEl, lang = Lang} =
IQ ->
Node = xml:get_tag_attr_s(<<"node">>, SubEl),
Info = ejabberd_hooks:run_fold(disco_info, ServerHost,
[],
[ServerHost, ?MODULE,
<<"">>, <<"">>]),
case iq_disco(ServerHost, Node, Lang) of
[] ->
Res = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>, XMLNS}],
children = []}]},
ejabberd_router:route(To, From,
jlib:iq_to_xml(Res));
DiscoInfo ->
Res = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>, XMLNS}],
children =
DiscoInfo ++ Info}]},
ejabberd_router:route(To, From, jlib:iq_to_xml(Res))
end;
#iq{type = get, xmlns = (?NS_DISCO_ITEMS) = XMLNS,
sub_el = SubEl, lang = Lang} =
IQ ->
Node = xml:get_tag_attr_s(<<"node">>, SubEl),
case Node of
<<>> ->
ResIQ = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>,
XMLNS}],
children = []}]},
Res = jlib:iq_to_xml(ResIQ);
<<"join">> ->
ResIQ = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>,
XMLNS}],
children = []}]},
Res = jlib:iq_to_xml(ResIQ);
<<"register">> ->
ResIQ = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>,
XMLNS}],
children = []}]},
Res = jlib:iq_to_xml(ResIQ);
?NS_COMMANDS ->
ResIQ = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>, XMLNS},
{<<"node">>, Node}],
children =
command_items(ServerHost,
Host,
Lang)}]},
Res = jlib:iq_to_xml(ResIQ);
_ ->
Res = jlib:make_error_reply(Packet,
?ERR_ITEM_NOT_FOUND)
end,
ejabberd_router:route(To, From, Res);
#iq{xmlns = ?NS_REGISTER} = IQ ->
process_register(ServerHost, Host, From, To, IQ);
#iq{type = get, xmlns = (?NS_VCARD) = XMLNS,
lang = Lang} =
IQ ->
Res = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"vCard">>,
attrs = [{<<"xmlns">>, XMLNS}],
children = iq_get_vcard(Lang)}]},
ejabberd_router:route(To, From, jlib:iq_to_xml(Res));
#iq{type = set, xmlns = ?NS_COMMANDS, lang = _Lang,
sub_el = SubEl} =
IQ ->
Request = adhoc:parse_request(IQ),
case lists:keysearch(Request#adhoc_request.node, 1,
commands(ServerHost))
of
{value, {_, _, Function}} ->
case catch Function(From, To, Request) of
{'EXIT', Reason} ->
?ERROR_MSG("~p~nfor ad-hoc handler of ~p",
[Reason, {From, To, IQ}]),
Res = IQ#iq{type = error,
sub_el =
[SubEl,
?ERR_INTERNAL_SERVER_ERROR]};
ignore -> Res = ignore;
{error, Error} ->
Res = IQ#iq{type = error,
sub_el = [SubEl, Error]};
Command ->
Res = IQ#iq{type = result, sub_el = [Command]}
end,
if Res /= ignore ->
ejabberd_router:route(To, From,
jlib:iq_to_xml(Res));
true -> ok
end;
_ ->
Err = jlib:make_error_reply(Packet,
?ERR_ITEM_NOT_FOUND),
ejabberd_router:route(To, From, Err)
end;
#iq{} = _IQ ->
Err = jlib:make_error_reply(Packet,
?ERR_FEATURE_NOT_IMPLEMENTED),
ejabberd_router:route(To, From, Err);
_ -> ok
end;
_ ->
Err = jlib:make_error_reply(Packet, ?ERR_BAD_REQUEST),
ejabberd_router:route(To, From, Err)
end;
_ ->
case str:tokens(ChanServ, <<"%">>) of
[<<_, _/binary>> = Channel, <<_, _/binary>> = Server] ->
case ets:lookup(irc_connection, {From, Server, Host}) of
[] ->
?DEBUG("open new connection~n", []),
{Username, Encoding, Port, Password} =
get_connection_params(Host, ServerHost, From, Server),
ConnectionUsername = case Packet of
%% If the user tries to join a
%% chatroom, the packet for sure
%% contains the desired username.
#xmlel{name = <<"presence">>} ->
Resource;
%% Otherwise, there is no firm
%% conclusion from the packet.
%% Better to use the configured
%% username (which defaults to the
username part of the JID ) .
_ -> Username
end,
{ok, Pid} = mod_irc_connection:start(From, Host,
ServerHost, Server,
ConnectionUsername,
Encoding, Port,
Password, ?MODULE),
ets:insert(irc_connection,
#irc_connection{jid_server_host =
{From, Server, Host},
pid = Pid}),
mod_irc_connection:route_chan(Pid, Channel, Resource,
Packet),
ok;
[R] ->
Pid = R#irc_connection.pid,
?DEBUG("send to process ~p~n", [Pid]),
mod_irc_connection:route_chan(Pid, Channel, Resource,
Packet),
ok
end;
_ ->
case str:tokens(ChanServ, <<"!">>) of
[<<_, _/binary>> = Nick, <<_, _/binary>> = Server] ->
case ets:lookup(irc_connection, {From, Server, Host}) of
[] ->
Err = jlib:make_error_reply(Packet,
?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err);
[R] ->
Pid = R#irc_connection.pid,
?DEBUG("send to process ~p~n", [Pid]),
mod_irc_connection:route_nick(Pid, Nick, Packet),
ok
end;
_ ->
Err = jlib:make_error_reply(Packet, ?ERR_BAD_REQUEST),
ejabberd_router:route(To, From, Err)
end
end
end.
closed_connection(Host, From, Server) ->
ets:delete(irc_connection, {From, Server, Host}).
iq_disco(_ServerHost, <<>>, Lang) ->
[#xmlel{name = <<"identity">>,
attrs =
[{<<"category">>, <<"conference">>},
{<<"type">>, <<"irc">>},
{<<"name">>,
translate:translate(Lang, <<"IRC Transport">>)}],
children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_DISCO_INFO}], children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_MUC}], children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_REGISTER}], children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_VCARD}], children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_COMMANDS}], children = []}];
iq_disco(ServerHost, Node, Lang) ->
case lists:keysearch(Node, 1, commands(ServerHost)) of
{value, {_, Name, _}} ->
[#xmlel{name = <<"identity">>,
attrs =
[{<<"category">>, <<"automation">>},
{<<"type">>, <<"command-node">>},
{<<"name">>, translate:translate(Lang, Name)}],
children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_COMMANDS}], children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_XDATA}], children = []}];
_ -> []
end.
iq_get_vcard(Lang) ->
[#xmlel{name = <<"FN">>, attrs = [],
children = [{xmlcdata, <<"ejabberd/mod_irc">>}]},
#xmlel{name = <<"URL">>, attrs = [],
children = [{xmlcdata, ?EJABBERD_URI}]},
#xmlel{name = <<"DESC">>, attrs = [],
children =
[{xmlcdata,
<<(translate:translate(Lang,
<<"ejabberd IRC module">>))/binary,
"\nCopyright (c) 2003-2014 ProcessOne">>}]}].
command_items(ServerHost, Host, Lang) ->
lists:map(fun ({Node, Name, _Function}) ->
#xmlel{name = <<"item">>,
attrs =
[{<<"jid">>, Host}, {<<"node">>, Node},
{<<"name">>,
translate:translate(Lang, Name)}],
children = []}
end,
commands(ServerHost)).
commands(ServerHost) ->
[{<<"join">>, <<"Join channel">>, fun adhoc_join/3},
{<<"register">>,
<<"Configure username, encoding, port and "
"password">>,
fun (From, To, Request) ->
adhoc_register(ServerHost, From, To, Request)
end}].
process_register(ServerHost, Host, From, To,
#iq{} = IQ) ->
case catch process_irc_register(ServerHost, Host, From,
To, IQ)
of
{'EXIT', Reason} -> ?ERROR_MSG("~p", [Reason]);
ResIQ ->
if ResIQ /= ignore ->
ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ));
true -> ok
end
end.
find_xdata_el(#xmlel{children = SubEls}) ->
find_xdata_el1(SubEls).
find_xdata_el1([]) -> false;
find_xdata_el1([#xmlel{name = Name, attrs = Attrs,
children = SubEls}
| Els]) ->
case xml:get_attr_s(<<"xmlns">>, Attrs) of
?NS_XDATA ->
#xmlel{name = Name, attrs = Attrs, children = SubEls};
_ -> find_xdata_el1(Els)
end;
find_xdata_el1([_ | Els]) -> find_xdata_el1(Els).
process_irc_register(ServerHost, Host, From, _To,
#iq{type = Type, xmlns = XMLNS, lang = Lang,
sub_el = SubEl} =
IQ) ->
case Type of
set ->
XDataEl = find_xdata_el(SubEl),
case XDataEl of
false ->
IQ#iq{type = error,
sub_el = [SubEl, ?ERR_NOT_ACCEPTABLE]};
#xmlel{attrs = Attrs} ->
case xml:get_attr_s(<<"type">>, Attrs) of
<<"cancel">> ->
IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>, XMLNS}],
children = []}]};
<<"submit">> ->
XData = jlib:parse_xdata_submit(XDataEl),
case XData of
invalid ->
IQ#iq{type = error,
sub_el = [SubEl, ?ERR_BAD_REQUEST]};
_ ->
Node = str:tokens(xml:get_tag_attr_s(<<"node">>,
SubEl),
<<"/">>),
case set_form(ServerHost, Host, From, Node, Lang,
XData)
of
{result, Res} ->
IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>, XMLNS}],
children = Res}]};
{error, Error} ->
IQ#iq{type = error, sub_el = [SubEl, Error]}
end
end;
_ ->
IQ#iq{type = error, sub_el = [SubEl, ?ERR_BAD_REQUEST]}
end
end;
get ->
Node = str:tokens(xml:get_tag_attr_s(<<"node">>, SubEl),
<<"/">>),
case get_form(ServerHost, Host, From, Node, Lang) of
{result, Res} ->
IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>, XMLNS}],
children = Res}]};
{error, Error} ->
IQ#iq{type = error, sub_el = [SubEl, Error]}
end
end.
get_data(ServerHost, Host, From) ->
LServer = jlib:nameprep(ServerHost),
get_data(LServer, Host, From,
gen_mod:db_type(LServer, ?MODULE)).
get_data(_LServer, Host, From, mnesia) ->
#jid{luser = LUser, lserver = LServer} = From,
US = {LUser, LServer},
case catch mnesia:dirty_read({irc_custom, {US, Host}})
of
{'EXIT', _Reason} -> error;
[] -> empty;
[#irc_custom{data = Data}] -> Data
end;
get_data(LServer, Host, From, riak) ->
#jid{luser = LUser, lserver = LServer} = From,
US = {LUser, LServer},
case ejabberd_riak:get(irc_custom, irc_custom_schema(), {US, Host}) of
{ok, #irc_custom{data = Data}} ->
Data;
{error, notfound} ->
empty;
_Err ->
error
end;
get_data(LServer, Host, From, odbc) ->
SJID =
ejabberd_odbc:escape(jlib:jid_to_string(jlib:jid_tolower(jlib:jid_remove_resource(From)))),
SHost = ejabberd_odbc:escape(Host),
case catch ejabberd_odbc:sql_query(LServer,
[<<"select data from irc_custom where jid='">>,
SJID, <<"' and host='">>, SHost,
<<"';">>])
of
{selected, [<<"data">>], [[SData]]} ->
data_to_binary(From, ejabberd_odbc:decode_term(SData));
{'EXIT', _} -> error;
{selected, _, _} -> empty
end.
get_form(ServerHost, Host, From, [], Lang) ->
#jid{user = User, server = Server} = From,
DefaultEncoding = get_default_encoding(Host),
Customs = case get_data(ServerHost, Host, From) of
error -> {error, ?ERR_INTERNAL_SERVER_ERROR};
empty -> {User, []};
Data -> get_username_and_connection_params(Data)
end,
case Customs of
{error, _Error} -> Customs;
{Username, ConnectionsParams} ->
{result,
[#xmlel{name = <<"instructions">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang,
<<"You need an x:data capable client to "
"configure mod_irc settings">>)}]},
#xmlel{name = <<"x">>,
attrs = [{<<"xmlns">>, ?NS_XDATA}],
children =
[#xmlel{name = <<"title">>, attrs = [],
children =
[{xmlcdata,
<<(translate:translate(Lang,
<<"Registration in mod_irc for ">>))/binary,
User/binary, "@", Server/binary>>}]},
#xmlel{name = <<"instructions">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang,
<<"Enter username, encodings, ports and "
"passwords you wish to use for connecting "
"to IRC servers">>)}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"type">>, <<"text-single">>},
{<<"label">>,
translate:translate(Lang,
<<"IRC Username">>)},
{<<"var">>, <<"username">>}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, Username}]}]},
#xmlel{name = <<"field">>,
attrs = [{<<"type">>, <<"fixed">>}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children =
[{xmlcdata,
iolist_to_binary(
io_lib:format(
translate:translate(
Lang,
<<"If you want to specify"
" different ports, "
"passwords, encodings "
"for IRC servers, "
"fill this list with "
"values in format "
"'{\"irc server\", "
"\"encoding\", port, "
"\"password\"}'. "
"By default this "
"service use \"~s\" "
"encoding, port ~p, "
"empty password.">>),
[DefaultEncoding,
?DEFAULT_IRC_PORT]))}]}]},
#xmlel{name = <<"field">>,
attrs = [{<<"type">>, <<"fixed">>}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang,
<<"Example: [{\"irc.lucky.net\", \"koi8-r\", "
"6667, \"secret\"}, {\"vendetta.fef.net\", "
"\"iso8859-1\", 7000}, {\"irc.sometestserver.n"
"et\", \"utf-8\"}].">>)}]}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"type">>, <<"text-multi">>},
{<<"label">>,
translate:translate(Lang,
<<"Connections parameters">>)},
{<<"var">>, <<"connections_params">>}],
children =
lists:map(fun (S) ->
#xmlel{name = <<"value">>,
attrs = [],
children =
[{xmlcdata, S}]}
end,
str:tokens(list_to_binary(
io_lib:format(
"~p.",
[conn_params_to_list(
ConnectionsParams)])),
<<"\n">>))}]}]}
end;
get_form(_ServerHost, _Host, _, _, _Lang) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
set_data(ServerHost, Host, From, Data) ->
LServer = jlib:nameprep(ServerHost),
set_data(LServer, Host, From, data_to_binary(From, Data),
gen_mod:db_type(LServer, ?MODULE)).
set_data(_LServer, Host, From, Data, mnesia) ->
{LUser, LServer, _} = jlib:jid_tolower(From),
US = {LUser, LServer},
F = fun () ->
mnesia:write(#irc_custom{us_host = {US, Host},
data = Data})
end,
mnesia:transaction(F);
set_data(LServer, Host, From, Data, riak) ->
{LUser, LServer, _} = jlib:jid_tolower(From),
US = {LUser, LServer},
{atomic, ejabberd_riak:put(#irc_custom{us_host = {US, Host},
data = Data},
irc_custom_schema())};
set_data(LServer, Host, From, Data, odbc) ->
SJID =
ejabberd_odbc:escape(jlib:jid_to_string(jlib:jid_tolower(jlib:jid_remove_resource(From)))),
SHost = ejabberd_odbc:escape(Host),
SData = ejabberd_odbc:encode_term(Data),
F = fun () ->
odbc_queries:update_t(<<"irc_custom">>,
[<<"jid">>, <<"host">>, <<"data">>],
[SJID, SHost, SData],
[<<"jid='">>, SJID, <<"' and host='">>,
SHost, <<"'">>]),
ok
end,
ejabberd_odbc:sql_transaction(LServer, F).
set_form(ServerHost, Host, From, [], _Lang, XData) ->
case {lists:keysearch(<<"username">>, 1, XData),
lists:keysearch(<<"connections_params">>, 1, XData)}
of
{{value, {_, [Username]}}, {value, {_, Strings}}} ->
EncString = lists:foldl(fun (S, Res) ->
<<Res/binary, S/binary, "\n">>
end,
<<"">>, Strings),
case erl_scan:string(binary_to_list(EncString)) of
{ok, Tokens, _} ->
case erl_parse:parse_term(Tokens) of
{ok, ConnectionsParams} ->
case set_data(ServerHost, Host, From,
[{username, Username},
{connections_params, ConnectionsParams}])
of
{atomic, _} -> {result, []};
_ -> {error, ?ERR_NOT_ACCEPTABLE}
end;
_ -> {error, ?ERR_NOT_ACCEPTABLE}
end;
_ -> {error, ?ERR_NOT_ACCEPTABLE}
end;
_ -> {error, ?ERR_NOT_ACCEPTABLE}
end;
set_form(_ServerHost, _Host, _, _, _Lang, _XData) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
%% Host = "irc.example.com"
ServerHost = " example.com "
get_connection_params(Host, From, IRCServer) ->
[_ | HostTail] = str:tokens(Host, <<".">>),
ServerHost = str:join(HostTail, <<".">>),
get_connection_params(Host, ServerHost, From,
IRCServer).
get_default_encoding(ServerHost) ->
Result = gen_mod:get_module_opt(ServerHost, ?MODULE, default_encoding,
fun iolist_to_binary/1,
?DEFAULT_IRC_ENCODING),
?INFO_MSG("The default_encoding configured for "
"host ~p is: ~p~n",
[ServerHost, Result]),
Result.
get_connection_params(Host, ServerHost, From,
IRCServer) ->
#jid{user = User, server = _Server} = From,
DefaultEncoding = get_default_encoding(ServerHost),
case get_data(ServerHost, Host, From) of
error ->
{User, DefaultEncoding, ?DEFAULT_IRC_PORT, <<"">>};
empty ->
{User, DefaultEncoding, ?DEFAULT_IRC_PORT, <<"">>};
Data ->
{Username, ConnParams} = get_username_and_connection_params(Data),
{NewUsername, NewEncoding, NewPort, NewPassword} = case
lists:keysearch(IRCServer,
1,
ConnParams)
of
{value,
{_, Encoding,
Port,
Password}} ->
{Username,
Encoding,
Port,
Password};
{value,
{_, Encoding,
Port}} ->
{Username,
Encoding,
Port,
<<"">>};
{value,
{_,
Encoding}} ->
{Username,
Encoding,
?DEFAULT_IRC_PORT,
<<"">>};
_ ->
{Username,
DefaultEncoding,
?DEFAULT_IRC_PORT,
<<"">>}
end,
{iolist_to_binary(NewUsername),
iolist_to_binary(NewEncoding),
if NewPort >= 0 andalso NewPort =< 65535 -> NewPort;
true -> ?DEFAULT_IRC_PORT
end,
iolist_to_binary(NewPassword)}
end.
adhoc_join(_From, _To,
#adhoc_request{action = <<"cancel">>} = Request) ->
adhoc:produce_response(Request,
#adhoc_response{status = canceled});
adhoc_join(From, To,
#adhoc_request{lang = Lang, node = _Node,
action = _Action, xdata = XData} =
Request) ->
if XData == false ->
Form = #xmlel{name = <<"x">>,
attrs =
[{<<"xmlns">>, ?NS_XDATA},
{<<"type">>, <<"form">>}],
children =
[#xmlel{name = <<"title">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang,
<<"Join IRC channel">>)}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"channel">>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
translate:translate(Lang,
<<"IRC channel (don't put the first #)">>)}],
children =
[#xmlel{name = <<"required">>,
attrs = [], children = []}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"server">>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
translate:translate(Lang,
<<"IRC server">>)}],
children =
[#xmlel{name = <<"required">>,
attrs = [], children = []}]}]},
adhoc:produce_response(Request,
#adhoc_response{status = executing,
elements = [Form]});
true ->
case jlib:parse_xdata_submit(XData) of
invalid -> {error, ?ERR_BAD_REQUEST};
Fields ->
Channel = case lists:keysearch(<<"channel">>, 1, Fields)
of
{value, {<<"channel">>, [C]}} -> C;
_ -> false
end,
Server = case lists:keysearch(<<"server">>, 1, Fields)
of
{value, {<<"server">>, [S]}} -> S;
_ -> false
end,
if Channel /= false, Server /= false ->
RoomJID = <<Channel/binary, "%", Server/binary, "@",
(To#jid.server)/binary>>,
Invite = #xmlel{name = <<"message">>, attrs = [],
children =
[#xmlel{name = <<"x">>,
attrs =
[{<<"xmlns">>,
?NS_MUC_USER}],
children =
[#xmlel{name =
<<"invite">>,
attrs =
[{<<"from">>,
jlib:jid_to_string(From)}],
children =
[#xmlel{name
=
<<"reason">>,
attrs
=
[],
children
=
[{xmlcdata,
translate:translate(Lang,
<<"Join the IRC channel here.">>)}]}]}]},
#xmlel{name = <<"x">>,
attrs =
[{<<"xmlns">>,
?NS_XCONFERENCE}],
children =
[{xmlcdata,
translate:translate(Lang,
<<"Join the IRC channel here.">>)}]},
#xmlel{name = <<"body">>,
attrs = [],
children =
[{xmlcdata,
iolist_to_binary(
io_lib:format(
translate:translate(
Lang,
<<"Join the IRC channel in this Jabber ID: ~s">>),
[RoomJID]))}]}]},
ejabberd_router:route(jlib:string_to_jid(RoomJID), From,
Invite),
adhoc:produce_response(Request,
#adhoc_response{status =
completed});
true -> {error, ?ERR_BAD_REQUEST}
end
end
end.
adhoc_register(_ServerHost, _From, _To,
#adhoc_request{action = <<"cancel">>} = Request) ->
adhoc:produce_response(Request,
#adhoc_response{status = canceled});
adhoc_register(ServerHost, From, To,
#adhoc_request{lang = Lang, node = _Node, xdata = XData,
action = Action} =
Request) ->
#jid{user = User} = From,
#jid{lserver = Host} = To,
if XData == false ->
case get_data(ServerHost, Host, From) of
error -> Username = User, ConnectionsParams = [];
empty -> Username = User, ConnectionsParams = [];
Data ->
{Username, ConnectionsParams} =
get_username_and_connection_params(Data)
end,
Error = false;
true ->
case jlib:parse_xdata_submit(XData) of
invalid ->
Error = {error, ?ERR_BAD_REQUEST},
Username = false,
ConnectionsParams = false;
Fields ->
Username = case lists:keysearch(<<"username">>, 1,
Fields)
of
{value, {<<"username">>, U}} -> U;
_ -> User
end,
ConnectionsParams = parse_connections_params(Fields),
Error = false
end
end,
if Error /= false -> Error;
Action == <<"complete">> ->
case set_data(ServerHost, Host, From,
[{username, Username},
{connections_params, ConnectionsParams}])
of
{atomic, _} ->
adhoc:produce_response(Request,
#adhoc_response{status = completed});
_ -> {error, ?ERR_INTERNAL_SERVER_ERROR}
end;
true ->
Form = generate_adhoc_register_form(Lang, Username,
ConnectionsParams),
adhoc:produce_response(Request,
#adhoc_response{status = executing,
elements = [Form],
actions =
[<<"next">>,
<<"complete">>]})
end.
generate_adhoc_register_form(Lang, Username,
ConnectionsParams) ->
#xmlel{name = <<"x">>,
attrs =
[{<<"xmlns">>, ?NS_XDATA}, {<<"type">>, <<"form">>}],
children =
[#xmlel{name = <<"title">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang, <<"IRC settings">>)}]},
#xmlel{name = <<"instructions">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang,
<<"Enter username and encodings you wish "
"to use for connecting to IRC servers. "
" Press 'Next' to get more fields to "
"fill in. Press 'Complete' to save settings.">>)}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"username">>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
translate:translate(Lang, <<"IRC username">>)}],
children =
[#xmlel{name = <<"required">>, attrs = [],
children = []},
#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, Username}]}]}]
++
generate_connection_params_fields(Lang,
ConnectionsParams, 1, [])}.
generate_connection_params_fields(Lang, [], Number,
Acc) ->
Field = generate_connection_params_field(Lang, <<"">>,
<<"">>, -1, <<"">>, Number),
lists:reverse(Field ++ Acc);
generate_connection_params_fields(Lang,
[ConnectionParams | ConnectionsParams],
Number, Acc) ->
case ConnectionParams of
{Server, Encoding, Port, Password} ->
Field = generate_connection_params_field(Lang, Server,
Encoding, Port, Password,
Number),
generate_connection_params_fields(Lang,
ConnectionsParams, Number + 1,
Field ++ Acc);
{Server, Encoding, Port} ->
Field = generate_connection_params_field(Lang, Server,
Encoding, Port, <<"">>, Number),
generate_connection_params_fields(Lang,
ConnectionsParams, Number + 1,
Field ++ Acc);
{Server, Encoding} ->
Field = generate_connection_params_field(Lang, Server,
Encoding, -1, <<"">>, Number),
generate_connection_params_fields(Lang,
ConnectionsParams, Number + 1,
Field ++ Acc);
_ -> []
end.
generate_connection_params_field(Lang, Server, Encoding,
Port, Password, Number) ->
EncodingUsed = case Encoding of
<<>> -> get_default_encoding(Server);
_ -> Encoding
end,
PortUsedInt = if Port >= 0 andalso Port =< 65535 ->
Port;
true -> ?DEFAULT_IRC_PORT
end,
PortUsed =
iolist_to_binary(integer_to_list(PortUsedInt)),
PasswordUsed = case Password of
<<>> -> <<>>;
_ -> Password
end,
NumberString =
iolist_to_binary(integer_to_list(Number)),
[#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"password", NumberString/binary>>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
iolist_to_binary(
io_lib:format(
translate:translate(Lang, <<"Password ~b">>),
[Number]))}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, PasswordUsed}]}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"port", NumberString/binary>>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
iolist_to_binary(
io_lib:format(translate:translate(Lang, <<"Port ~b">>),
[Number]))}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, PortUsed}]}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"encoding", NumberString/binary>>},
{<<"type">>, <<"list-single">>},
{<<"label">>,
list_to_binary(
io_lib:format(translate:translate(
Lang,
<<"Encoding for server ~b">>),
[Number]))}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, EncodingUsed}]}
| lists:map(fun (E) ->
#xmlel{name = <<"option">>,
attrs = [{<<"label">>, E}],
children =
[#xmlel{name = <<"value">>,
attrs = [],
children =
[{xmlcdata, E}]}]}
end,
?POSSIBLE_ENCODINGS)]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"server", NumberString/binary>>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
list_to_binary(
io_lib:format(translate:translate(Lang, <<"Server ~b">>),
[Number]))}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, Server}]}]}].
parse_connections_params(Fields) ->
Servers = lists:flatmap(
fun({<<"server", Var/binary>>, Value}) ->
[{Var, Value}];
(_) ->
[]
end, Fields),
Encodings = lists:flatmap(
fun({<<"encoding", Var/binary>>, Value}) ->
[{Var, Value}];
(_) ->
[]
end, Fields),
Ports = lists:flatmap(
fun({<<"port", Var/binary>>, Value}) ->
[{Var, Value}];
(_) ->
[]
end, Fields),
Passwords = lists:flatmap(
fun({<<"password", Var/binary>>, Value}) ->
[{Var, Value}];
(_) ->
[]
end, Fields),
parse_connections_params(Servers, Encodings, Ports,
Passwords).
retrieve_connections_params(ConnectionParams,
ServerN) ->
case ConnectionParams of
[{ConnectionParamN, ConnectionParam}
| ConnectionParamsTail] ->
if ServerN == ConnectionParamN ->
{ConnectionParam, ConnectionParamsTail};
ServerN < ConnectionParamN ->
{[],
[{ConnectionParamN, ConnectionParam}
| ConnectionParamsTail]};
ServerN > ConnectionParamN -> {[], ConnectionParamsTail}
end;
_ -> {[], []}
end.
parse_connections_params([], _, _, _) -> [];
parse_connections_params(_, [], [], []) -> [];
parse_connections_params([{ServerN, Server} | Servers],
Encodings, Ports, Passwords) ->
{NewEncoding, NewEncodings} =
retrieve_connections_params(Encodings, ServerN),
{NewPort, NewPorts} = retrieve_connections_params(Ports,
ServerN),
{NewPassword, NewPasswords} =
retrieve_connections_params(Passwords, ServerN),
[{Server, NewEncoding, NewPort, NewPassword}
| parse_connections_params(Servers, NewEncodings,
NewPorts, NewPasswords)].
get_username_and_connection_params(Data) ->
Username = case lists:keysearch(username, 1, Data) of
{value, {_, U}} when is_binary(U) ->
U;
_ ->
<<"">>
end,
ConnParams = case lists:keysearch(connections_params, 1, Data) of
{value, {_, L}} when is_list(L) ->
L;
_ ->
[]
end,
{Username, ConnParams}.
data_to_binary(JID, Data) ->
lists:map(
fun({username, U}) ->
{username, iolist_to_binary(U)};
({connections_params, Params}) ->
{connections_params,
lists:flatmap(
fun(Param) ->
try
[conn_param_to_binary(Param)]
catch _:_ ->
if JID /= error ->
?ERROR_MSG("failed to convert "
"parameter ~p for user ~s",
[Param,
jlib:jid_to_string(JID)]);
true ->
?ERROR_MSG("failed to convert "
"parameter ~p",
[Param])
end,
[]
end
end, Params)};
(Opt) ->
Opt
end, Data).
conn_param_to_binary({S}) ->
{iolist_to_binary(S)};
conn_param_to_binary({S, E}) ->
{iolist_to_binary(S), iolist_to_binary(E)};
conn_param_to_binary({S, E, Port}) when is_integer(Port) ->
{iolist_to_binary(S), iolist_to_binary(E), Port};
conn_param_to_binary({S, E, Port, P}) when is_integer(Port) ->
{iolist_to_binary(S), iolist_to_binary(E), Port, iolist_to_binary(P)}.
conn_params_to_list(Params) ->
lists:map(
fun({S}) ->
{binary_to_list(S)};
({S, E}) ->
{binary_to_list(S), binary_to_list(E)};
({S, E, Port}) ->
{binary_to_list(S), binary_to_list(E), Port};
({S, E, Port, P}) ->
{binary_to_list(S), binary_to_list(E),
Port, binary_to_list(P)}
end, Params).
irc_custom_schema() ->
{record_info(fields, irc_custom), #irc_custom{}}.
update_table() ->
Fields = record_info(fields, irc_custom),
case mnesia:table_info(irc_custom, attributes) of
Fields ->
ejabberd_config:convert_table_to_binary(
irc_custom, Fields, set,
fun(#irc_custom{us_host = {_, H}}) -> H end,
fun(#irc_custom{us_host = {{U, S}, H},
data = Data} = R) ->
JID = jlib:make_jid(U, S, <<"">>),
R#irc_custom{us_host = {{iolist_to_binary(U),
iolist_to_binary(S)},
iolist_to_binary(H)},
data = data_to_binary(JID, Data)}
end);
_ ->
?INFO_MSG("Recreating irc_custom table", []),
mnesia:transform_table(irc_custom, ignore, Fields)
end.
export(_Server) ->
[{irc_custom,
fun(Host, #irc_custom{us_host = {{U, S}, IRCHost},
data = Data}) ->
case str:suffix(Host, IRCHost) of
true ->
SJID = ejabberd_odbc:escape(
jlib:jid_to_string(
jlib:make_jid(U, S, <<"">>))),
SIRCHost = ejabberd_odbc:escape(IRCHost),
SData = ejabberd_odbc:encode_term(Data),
[[<<"delete from irc_custom where jid='">>, SJID,
<<"' and host='">>, SIRCHost, <<"';">>],
[<<"insert into irc_custom(jid, host, "
"data) values ('">>,
SJID, <<"', '">>, SIRCHost, <<"', '">>, SData,
<<"');">>]];
false ->
[]
end
end}].
import(_LServer) ->
[{<<"select jid, host, data from irc_custom;">>,
fun([SJID, IRCHost, SData]) ->
#jid{luser = U, lserver = S} = jlib:string_to_jid(SJID),
Data = ejabberd_odbc:decode_term(SData),
#irc_custom{us_host = {{U, S}, IRCHost},
data = Data}
end}].
import(_LServer, mnesia, #irc_custom{} = R) ->
mnesia:dirty_write(R);
import(_LServer, riak, #irc_custom{} = R) ->
ejabberd_riak:put(R, irc_custom_schema());
import(_, _, _) ->
pass.
| null | https://raw.githubusercontent.com/may-liu/qtalk/f5431e5a7123975e9656e7ab239e674ce33713cd/qtalk_opensource/src/mod_irc.erl | erlang | ----------------------------------------------------------------------
File : mod_irc.erl
Purpose : IRC transport
This program is free software; you can redistribute it and/or
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.
----------------------------------------------------------------------
API
gen_server callbacks
====================================================================
API
====================================================================
--------------------------------------------------------------------
Description: Starts the server
--------------------------------------------------------------------
====================================================================
gen_server callbacks
====================================================================
--------------------------------------------------------------------
Function: init(Args) -> {ok, State} |
ignore |
{stop, Reason}
Description: Initiates the server
--------------------------------------------------------------------
--------------------------------------------------------------------
% handle_call(Request , From , State ) - > { reply , Reply , State } |
{stop, Reason, Reply, State} |
{stop, Reason, State}
Description: Handling call messages
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
Description: Handling cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
Description: Handling all non call/cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: terminate(Reason, State) -> void()
Description: This function is called by a gen_server when it is about to
terminate. It should be the opposite of Module:init/1 and do any necessary
cleaning up. When it returns, the gen_server terminates with Reason.
The return value is ignored.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Convert process state when code is changed
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
If the user tries to join a
chatroom, the packet for sure
contains the desired username.
Otherwise, there is no firm
conclusion from the packet.
Better to use the configured
username (which defaults to the
Host = "irc.example.com" | Author : < >
Created : 15 Feb 2003 by < >
ejabberd , Copyright ( C ) 2002 - 2014 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
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. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(mod_irc).
-author('').
-behaviour(gen_server).
-behaviour(gen_mod).
-export([start_link/2, start/2, stop/1, export/1, import/1,
import/3, closed_connection/3, get_connection_params/3]).
-export([init/1, handle_call/3, handle_cast/2,
handle_info/2, terminate/2, code_change/3]).
-include("ejabberd.hrl").
-include("logger.hrl").
-include("jlib.hrl").
-include("adhoc.hrl").
-define(DEFAULT_IRC_ENCODING, <<"iso8859-1">>).
-define(DEFAULT_IRC_PORT, 6667).
-define(POSSIBLE_ENCODINGS,
[<<"koi8-r">>, <<"iso8859-1">>, <<"iso8859-2">>,
<<"utf-8">>, <<"utf-8+latin-1">>]).
-type conn_param() :: {binary(), binary(), inet:port_number(), binary()} |
{binary(), binary(), inet:port_number()} |
{binary(), binary()} |
{binary()}.
-record(irc_connection,
{jid_server_host = {#jid{}, <<"">>, <<"">>} :: {jid(), binary(), binary()},
pid = self() :: pid()}).
-record(irc_custom,
{us_host = {{<<"">>, <<"">>}, <<"">>} :: {{binary(), binary()},
binary()},
data = [] :: [{username, binary()} |
{connections_params, [conn_param()]}]}).
-record(state, {host = <<"">> :: binary(),
server_host = <<"">> :: binary(),
access = all :: atom()}).
-define(PROCNAME, ejabberd_mod_irc).
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
start_link(Host, Opts) ->
Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
gen_server:start_link({local, Proc}, ?MODULE,
[Host, Opts], []).
start(Host, Opts) ->
start_supervisor(Host),
Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
ChildSpec = {Proc, {?MODULE, start_link, [Host, Opts]},
temporary, 1000, worker, [?MODULE]},
supervisor:start_child(ejabberd_sup, ChildSpec).
stop(Host) ->
stop_supervisor(Host),
Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
gen_server:call(Proc, stop),
supervisor:delete_child(ejabberd_sup, Proc).
{ ok , State , Timeout } |
init([Host, Opts]) ->
ejabberd:start_app(p1_iconv),
MyHost = gen_mod:get_opt_host(Host, Opts,
<<"irc.@HOST@">>),
case gen_mod:db_type(Opts) of
mnesia ->
mnesia:create_table(irc_custom,
[{disc_copies, [node()]},
{attributes, record_info(fields, irc_custom)}]),
update_table();
_ -> ok
end,
Access = gen_mod:get_opt(access, Opts,
fun(A) when is_atom(A) -> A end,
all),
catch ets:new(irc_connection,
[named_table, public,
{keypos, #irc_connection.jid_server_host}]),
ejabberd_router:register_route(MyHost),
{ok,
#state{host = MyHost, server_host = Host,
access = Access}}.
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call(stop, _From, State) ->
{stop, normal, ok, State}.
Function : handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_cast(_Msg, State) -> {noreply, State}.
Function : handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_info({route, From, To, Packet},
#state{host = Host, server_host = ServerHost,
access = Access} =
State) ->
case catch do_route(Host, ServerHost, Access, From, To,
Packet)
of
{'EXIT', Reason} -> ?ERROR_MSG("~p", [Reason]);
_ -> ok
end,
{noreply, State};
handle_info(_Info, State) -> {noreply, State}.
terminate(_Reason, State) ->
ejabberd_router:unregister_route(State#state.host), ok.
Func : code_change(OldVsn , State , Extra ) - > { ok , NewState }
code_change(_OldVsn, State, _Extra) -> {ok, State}.
Internal functions
start_supervisor(Host) ->
Proc = gen_mod:get_module_proc(Host,
ejabberd_mod_irc_sup),
ChildSpec = {Proc,
{ejabberd_tmp_sup, start_link,
[Proc, mod_irc_connection]},
permanent, infinity, supervisor, [ejabberd_tmp_sup]},
supervisor:start_child(ejabberd_sup, ChildSpec).
stop_supervisor(Host) ->
Proc = gen_mod:get_module_proc(Host,
ejabberd_mod_irc_sup),
supervisor:terminate_child(ejabberd_sup, Proc),
supervisor:delete_child(ejabberd_sup, Proc).
do_route(Host, ServerHost, Access, From, To, Packet) ->
case acl:match_rule(ServerHost, Access, From) of
allow -> do_route1(Host, ServerHost, From, To, Packet);
_ ->
#xmlel{attrs = Attrs} = Packet,
Lang = xml:get_attr_s(<<"xml:lang">>, Attrs),
ErrText = <<"Access denied by service policy">>,
Err = jlib:make_error_reply(Packet,
?ERRT_FORBIDDEN(Lang, ErrText)),
ejabberd_router:route(To, From, Err)
end.
do_route1(Host, ServerHost, From, To, Packet) ->
#jid{user = ChanServ, resource = Resource} = To,
#xmlel{} = Packet,
case ChanServ of
<<"">> ->
case Resource of
<<"">> ->
case jlib:iq_query_info(Packet) of
#iq{type = get, xmlns = (?NS_DISCO_INFO) = XMLNS,
sub_el = SubEl, lang = Lang} =
IQ ->
Node = xml:get_tag_attr_s(<<"node">>, SubEl),
Info = ejabberd_hooks:run_fold(disco_info, ServerHost,
[],
[ServerHost, ?MODULE,
<<"">>, <<"">>]),
case iq_disco(ServerHost, Node, Lang) of
[] ->
Res = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>, XMLNS}],
children = []}]},
ejabberd_router:route(To, From,
jlib:iq_to_xml(Res));
DiscoInfo ->
Res = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>, XMLNS}],
children =
DiscoInfo ++ Info}]},
ejabberd_router:route(To, From, jlib:iq_to_xml(Res))
end;
#iq{type = get, xmlns = (?NS_DISCO_ITEMS) = XMLNS,
sub_el = SubEl, lang = Lang} =
IQ ->
Node = xml:get_tag_attr_s(<<"node">>, SubEl),
case Node of
<<>> ->
ResIQ = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>,
XMLNS}],
children = []}]},
Res = jlib:iq_to_xml(ResIQ);
<<"join">> ->
ResIQ = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>,
XMLNS}],
children = []}]},
Res = jlib:iq_to_xml(ResIQ);
<<"register">> ->
ResIQ = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>,
XMLNS}],
children = []}]},
Res = jlib:iq_to_xml(ResIQ);
?NS_COMMANDS ->
ResIQ = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>, XMLNS},
{<<"node">>, Node}],
children =
command_items(ServerHost,
Host,
Lang)}]},
Res = jlib:iq_to_xml(ResIQ);
_ ->
Res = jlib:make_error_reply(Packet,
?ERR_ITEM_NOT_FOUND)
end,
ejabberd_router:route(To, From, Res);
#iq{xmlns = ?NS_REGISTER} = IQ ->
process_register(ServerHost, Host, From, To, IQ);
#iq{type = get, xmlns = (?NS_VCARD) = XMLNS,
lang = Lang} =
IQ ->
Res = IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"vCard">>,
attrs = [{<<"xmlns">>, XMLNS}],
children = iq_get_vcard(Lang)}]},
ejabberd_router:route(To, From, jlib:iq_to_xml(Res));
#iq{type = set, xmlns = ?NS_COMMANDS, lang = _Lang,
sub_el = SubEl} =
IQ ->
Request = adhoc:parse_request(IQ),
case lists:keysearch(Request#adhoc_request.node, 1,
commands(ServerHost))
of
{value, {_, _, Function}} ->
case catch Function(From, To, Request) of
{'EXIT', Reason} ->
?ERROR_MSG("~p~nfor ad-hoc handler of ~p",
[Reason, {From, To, IQ}]),
Res = IQ#iq{type = error,
sub_el =
[SubEl,
?ERR_INTERNAL_SERVER_ERROR]};
ignore -> Res = ignore;
{error, Error} ->
Res = IQ#iq{type = error,
sub_el = [SubEl, Error]};
Command ->
Res = IQ#iq{type = result, sub_el = [Command]}
end,
if Res /= ignore ->
ejabberd_router:route(To, From,
jlib:iq_to_xml(Res));
true -> ok
end;
_ ->
Err = jlib:make_error_reply(Packet,
?ERR_ITEM_NOT_FOUND),
ejabberd_router:route(To, From, Err)
end;
#iq{} = _IQ ->
Err = jlib:make_error_reply(Packet,
?ERR_FEATURE_NOT_IMPLEMENTED),
ejabberd_router:route(To, From, Err);
_ -> ok
end;
_ ->
Err = jlib:make_error_reply(Packet, ?ERR_BAD_REQUEST),
ejabberd_router:route(To, From, Err)
end;
_ ->
case str:tokens(ChanServ, <<"%">>) of
[<<_, _/binary>> = Channel, <<_, _/binary>> = Server] ->
case ets:lookup(irc_connection, {From, Server, Host}) of
[] ->
?DEBUG("open new connection~n", []),
{Username, Encoding, Port, Password} =
get_connection_params(Host, ServerHost, From, Server),
ConnectionUsername = case Packet of
#xmlel{name = <<"presence">>} ->
Resource;
username part of the JID ) .
_ -> Username
end,
{ok, Pid} = mod_irc_connection:start(From, Host,
ServerHost, Server,
ConnectionUsername,
Encoding, Port,
Password, ?MODULE),
ets:insert(irc_connection,
#irc_connection{jid_server_host =
{From, Server, Host},
pid = Pid}),
mod_irc_connection:route_chan(Pid, Channel, Resource,
Packet),
ok;
[R] ->
Pid = R#irc_connection.pid,
?DEBUG("send to process ~p~n", [Pid]),
mod_irc_connection:route_chan(Pid, Channel, Resource,
Packet),
ok
end;
_ ->
case str:tokens(ChanServ, <<"!">>) of
[<<_, _/binary>> = Nick, <<_, _/binary>> = Server] ->
case ets:lookup(irc_connection, {From, Server, Host}) of
[] ->
Err = jlib:make_error_reply(Packet,
?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err);
[R] ->
Pid = R#irc_connection.pid,
?DEBUG("send to process ~p~n", [Pid]),
mod_irc_connection:route_nick(Pid, Nick, Packet),
ok
end;
_ ->
Err = jlib:make_error_reply(Packet, ?ERR_BAD_REQUEST),
ejabberd_router:route(To, From, Err)
end
end
end.
closed_connection(Host, From, Server) ->
ets:delete(irc_connection, {From, Server, Host}).
iq_disco(_ServerHost, <<>>, Lang) ->
[#xmlel{name = <<"identity">>,
attrs =
[{<<"category">>, <<"conference">>},
{<<"type">>, <<"irc">>},
{<<"name">>,
translate:translate(Lang, <<"IRC Transport">>)}],
children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_DISCO_INFO}], children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_MUC}], children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_REGISTER}], children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_VCARD}], children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_COMMANDS}], children = []}];
iq_disco(ServerHost, Node, Lang) ->
case lists:keysearch(Node, 1, commands(ServerHost)) of
{value, {_, Name, _}} ->
[#xmlel{name = <<"identity">>,
attrs =
[{<<"category">>, <<"automation">>},
{<<"type">>, <<"command-node">>},
{<<"name">>, translate:translate(Lang, Name)}],
children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_COMMANDS}], children = []},
#xmlel{name = <<"feature">>,
attrs = [{<<"var">>, ?NS_XDATA}], children = []}];
_ -> []
end.
iq_get_vcard(Lang) ->
[#xmlel{name = <<"FN">>, attrs = [],
children = [{xmlcdata, <<"ejabberd/mod_irc">>}]},
#xmlel{name = <<"URL">>, attrs = [],
children = [{xmlcdata, ?EJABBERD_URI}]},
#xmlel{name = <<"DESC">>, attrs = [],
children =
[{xmlcdata,
<<(translate:translate(Lang,
<<"ejabberd IRC module">>))/binary,
"\nCopyright (c) 2003-2014 ProcessOne">>}]}].
command_items(ServerHost, Host, Lang) ->
lists:map(fun ({Node, Name, _Function}) ->
#xmlel{name = <<"item">>,
attrs =
[{<<"jid">>, Host}, {<<"node">>, Node},
{<<"name">>,
translate:translate(Lang, Name)}],
children = []}
end,
commands(ServerHost)).
commands(ServerHost) ->
[{<<"join">>, <<"Join channel">>, fun adhoc_join/3},
{<<"register">>,
<<"Configure username, encoding, port and "
"password">>,
fun (From, To, Request) ->
adhoc_register(ServerHost, From, To, Request)
end}].
process_register(ServerHost, Host, From, To,
#iq{} = IQ) ->
case catch process_irc_register(ServerHost, Host, From,
To, IQ)
of
{'EXIT', Reason} -> ?ERROR_MSG("~p", [Reason]);
ResIQ ->
if ResIQ /= ignore ->
ejabberd_router:route(To, From, jlib:iq_to_xml(ResIQ));
true -> ok
end
end.
find_xdata_el(#xmlel{children = SubEls}) ->
find_xdata_el1(SubEls).
find_xdata_el1([]) -> false;
find_xdata_el1([#xmlel{name = Name, attrs = Attrs,
children = SubEls}
| Els]) ->
case xml:get_attr_s(<<"xmlns">>, Attrs) of
?NS_XDATA ->
#xmlel{name = Name, attrs = Attrs, children = SubEls};
_ -> find_xdata_el1(Els)
end;
find_xdata_el1([_ | Els]) -> find_xdata_el1(Els).
process_irc_register(ServerHost, Host, From, _To,
#iq{type = Type, xmlns = XMLNS, lang = Lang,
sub_el = SubEl} =
IQ) ->
case Type of
set ->
XDataEl = find_xdata_el(SubEl),
case XDataEl of
false ->
IQ#iq{type = error,
sub_el = [SubEl, ?ERR_NOT_ACCEPTABLE]};
#xmlel{attrs = Attrs} ->
case xml:get_attr_s(<<"type">>, Attrs) of
<<"cancel">> ->
IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>, XMLNS}],
children = []}]};
<<"submit">> ->
XData = jlib:parse_xdata_submit(XDataEl),
case XData of
invalid ->
IQ#iq{type = error,
sub_el = [SubEl, ?ERR_BAD_REQUEST]};
_ ->
Node = str:tokens(xml:get_tag_attr_s(<<"node">>,
SubEl),
<<"/">>),
case set_form(ServerHost, Host, From, Node, Lang,
XData)
of
{result, Res} ->
IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs =
[{<<"xmlns">>, XMLNS}],
children = Res}]};
{error, Error} ->
IQ#iq{type = error, sub_el = [SubEl, Error]}
end
end;
_ ->
IQ#iq{type = error, sub_el = [SubEl, ?ERR_BAD_REQUEST]}
end
end;
get ->
Node = str:tokens(xml:get_tag_attr_s(<<"node">>, SubEl),
<<"/">>),
case get_form(ServerHost, Host, From, Node, Lang) of
{result, Res} ->
IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs = [{<<"xmlns">>, XMLNS}],
children = Res}]};
{error, Error} ->
IQ#iq{type = error, sub_el = [SubEl, Error]}
end
end.
get_data(ServerHost, Host, From) ->
LServer = jlib:nameprep(ServerHost),
get_data(LServer, Host, From,
gen_mod:db_type(LServer, ?MODULE)).
get_data(_LServer, Host, From, mnesia) ->
#jid{luser = LUser, lserver = LServer} = From,
US = {LUser, LServer},
case catch mnesia:dirty_read({irc_custom, {US, Host}})
of
{'EXIT', _Reason} -> error;
[] -> empty;
[#irc_custom{data = Data}] -> Data
end;
get_data(LServer, Host, From, riak) ->
#jid{luser = LUser, lserver = LServer} = From,
US = {LUser, LServer},
case ejabberd_riak:get(irc_custom, irc_custom_schema(), {US, Host}) of
{ok, #irc_custom{data = Data}} ->
Data;
{error, notfound} ->
empty;
_Err ->
error
end;
get_data(LServer, Host, From, odbc) ->
SJID =
ejabberd_odbc:escape(jlib:jid_to_string(jlib:jid_tolower(jlib:jid_remove_resource(From)))),
SHost = ejabberd_odbc:escape(Host),
case catch ejabberd_odbc:sql_query(LServer,
[<<"select data from irc_custom where jid='">>,
SJID, <<"' and host='">>, SHost,
<<"';">>])
of
{selected, [<<"data">>], [[SData]]} ->
data_to_binary(From, ejabberd_odbc:decode_term(SData));
{'EXIT', _} -> error;
{selected, _, _} -> empty
end.
get_form(ServerHost, Host, From, [], Lang) ->
#jid{user = User, server = Server} = From,
DefaultEncoding = get_default_encoding(Host),
Customs = case get_data(ServerHost, Host, From) of
error -> {error, ?ERR_INTERNAL_SERVER_ERROR};
empty -> {User, []};
Data -> get_username_and_connection_params(Data)
end,
case Customs of
{error, _Error} -> Customs;
{Username, ConnectionsParams} ->
{result,
[#xmlel{name = <<"instructions">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang,
<<"You need an x:data capable client to "
"configure mod_irc settings">>)}]},
#xmlel{name = <<"x">>,
attrs = [{<<"xmlns">>, ?NS_XDATA}],
children =
[#xmlel{name = <<"title">>, attrs = [],
children =
[{xmlcdata,
<<(translate:translate(Lang,
<<"Registration in mod_irc for ">>))/binary,
User/binary, "@", Server/binary>>}]},
#xmlel{name = <<"instructions">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang,
<<"Enter username, encodings, ports and "
"passwords you wish to use for connecting "
"to IRC servers">>)}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"type">>, <<"text-single">>},
{<<"label">>,
translate:translate(Lang,
<<"IRC Username">>)},
{<<"var">>, <<"username">>}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, Username}]}]},
#xmlel{name = <<"field">>,
attrs = [{<<"type">>, <<"fixed">>}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children =
[{xmlcdata,
iolist_to_binary(
io_lib:format(
translate:translate(
Lang,
<<"If you want to specify"
" different ports, "
"passwords, encodings "
"for IRC servers, "
"fill this list with "
"values in format "
"'{\"irc server\", "
"\"encoding\", port, "
"\"password\"}'. "
"By default this "
"service use \"~s\" "
"encoding, port ~p, "
"empty password.">>),
[DefaultEncoding,
?DEFAULT_IRC_PORT]))}]}]},
#xmlel{name = <<"field">>,
attrs = [{<<"type">>, <<"fixed">>}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang,
<<"Example: [{\"irc.lucky.net\", \"koi8-r\", "
"6667, \"secret\"}, {\"vendetta.fef.net\", "
"\"iso8859-1\", 7000}, {\"irc.sometestserver.n"
"et\", \"utf-8\"}].">>)}]}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"type">>, <<"text-multi">>},
{<<"label">>,
translate:translate(Lang,
<<"Connections parameters">>)},
{<<"var">>, <<"connections_params">>}],
children =
lists:map(fun (S) ->
#xmlel{name = <<"value">>,
attrs = [],
children =
[{xmlcdata, S}]}
end,
str:tokens(list_to_binary(
io_lib:format(
"~p.",
[conn_params_to_list(
ConnectionsParams)])),
<<"\n">>))}]}]}
end;
get_form(_ServerHost, _Host, _, _, _Lang) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
set_data(ServerHost, Host, From, Data) ->
LServer = jlib:nameprep(ServerHost),
set_data(LServer, Host, From, data_to_binary(From, Data),
gen_mod:db_type(LServer, ?MODULE)).
set_data(_LServer, Host, From, Data, mnesia) ->
{LUser, LServer, _} = jlib:jid_tolower(From),
US = {LUser, LServer},
F = fun () ->
mnesia:write(#irc_custom{us_host = {US, Host},
data = Data})
end,
mnesia:transaction(F);
set_data(LServer, Host, From, Data, riak) ->
{LUser, LServer, _} = jlib:jid_tolower(From),
US = {LUser, LServer},
{atomic, ejabberd_riak:put(#irc_custom{us_host = {US, Host},
data = Data},
irc_custom_schema())};
set_data(LServer, Host, From, Data, odbc) ->
SJID =
ejabberd_odbc:escape(jlib:jid_to_string(jlib:jid_tolower(jlib:jid_remove_resource(From)))),
SHost = ejabberd_odbc:escape(Host),
SData = ejabberd_odbc:encode_term(Data),
F = fun () ->
odbc_queries:update_t(<<"irc_custom">>,
[<<"jid">>, <<"host">>, <<"data">>],
[SJID, SHost, SData],
[<<"jid='">>, SJID, <<"' and host='">>,
SHost, <<"'">>]),
ok
end,
ejabberd_odbc:sql_transaction(LServer, F).
set_form(ServerHost, Host, From, [], _Lang, XData) ->
case {lists:keysearch(<<"username">>, 1, XData),
lists:keysearch(<<"connections_params">>, 1, XData)}
of
{{value, {_, [Username]}}, {value, {_, Strings}}} ->
EncString = lists:foldl(fun (S, Res) ->
<<Res/binary, S/binary, "\n">>
end,
<<"">>, Strings),
case erl_scan:string(binary_to_list(EncString)) of
{ok, Tokens, _} ->
case erl_parse:parse_term(Tokens) of
{ok, ConnectionsParams} ->
case set_data(ServerHost, Host, From,
[{username, Username},
{connections_params, ConnectionsParams}])
of
{atomic, _} -> {result, []};
_ -> {error, ?ERR_NOT_ACCEPTABLE}
end;
_ -> {error, ?ERR_NOT_ACCEPTABLE}
end;
_ -> {error, ?ERR_NOT_ACCEPTABLE}
end;
_ -> {error, ?ERR_NOT_ACCEPTABLE}
end;
set_form(_ServerHost, _Host, _, _, _Lang, _XData) ->
{error, ?ERR_SERVICE_UNAVAILABLE}.
ServerHost = " example.com "
get_connection_params(Host, From, IRCServer) ->
[_ | HostTail] = str:tokens(Host, <<".">>),
ServerHost = str:join(HostTail, <<".">>),
get_connection_params(Host, ServerHost, From,
IRCServer).
get_default_encoding(ServerHost) ->
Result = gen_mod:get_module_opt(ServerHost, ?MODULE, default_encoding,
fun iolist_to_binary/1,
?DEFAULT_IRC_ENCODING),
?INFO_MSG("The default_encoding configured for "
"host ~p is: ~p~n",
[ServerHost, Result]),
Result.
get_connection_params(Host, ServerHost, From,
IRCServer) ->
#jid{user = User, server = _Server} = From,
DefaultEncoding = get_default_encoding(ServerHost),
case get_data(ServerHost, Host, From) of
error ->
{User, DefaultEncoding, ?DEFAULT_IRC_PORT, <<"">>};
empty ->
{User, DefaultEncoding, ?DEFAULT_IRC_PORT, <<"">>};
Data ->
{Username, ConnParams} = get_username_and_connection_params(Data),
{NewUsername, NewEncoding, NewPort, NewPassword} = case
lists:keysearch(IRCServer,
1,
ConnParams)
of
{value,
{_, Encoding,
Port,
Password}} ->
{Username,
Encoding,
Port,
Password};
{value,
{_, Encoding,
Port}} ->
{Username,
Encoding,
Port,
<<"">>};
{value,
{_,
Encoding}} ->
{Username,
Encoding,
?DEFAULT_IRC_PORT,
<<"">>};
_ ->
{Username,
DefaultEncoding,
?DEFAULT_IRC_PORT,
<<"">>}
end,
{iolist_to_binary(NewUsername),
iolist_to_binary(NewEncoding),
if NewPort >= 0 andalso NewPort =< 65535 -> NewPort;
true -> ?DEFAULT_IRC_PORT
end,
iolist_to_binary(NewPassword)}
end.
adhoc_join(_From, _To,
#adhoc_request{action = <<"cancel">>} = Request) ->
adhoc:produce_response(Request,
#adhoc_response{status = canceled});
adhoc_join(From, To,
#adhoc_request{lang = Lang, node = _Node,
action = _Action, xdata = XData} =
Request) ->
if XData == false ->
Form = #xmlel{name = <<"x">>,
attrs =
[{<<"xmlns">>, ?NS_XDATA},
{<<"type">>, <<"form">>}],
children =
[#xmlel{name = <<"title">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang,
<<"Join IRC channel">>)}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"channel">>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
translate:translate(Lang,
<<"IRC channel (don't put the first #)">>)}],
children =
[#xmlel{name = <<"required">>,
attrs = [], children = []}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"server">>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
translate:translate(Lang,
<<"IRC server">>)}],
children =
[#xmlel{name = <<"required">>,
attrs = [], children = []}]}]},
adhoc:produce_response(Request,
#adhoc_response{status = executing,
elements = [Form]});
true ->
case jlib:parse_xdata_submit(XData) of
invalid -> {error, ?ERR_BAD_REQUEST};
Fields ->
Channel = case lists:keysearch(<<"channel">>, 1, Fields)
of
{value, {<<"channel">>, [C]}} -> C;
_ -> false
end,
Server = case lists:keysearch(<<"server">>, 1, Fields)
of
{value, {<<"server">>, [S]}} -> S;
_ -> false
end,
if Channel /= false, Server /= false ->
RoomJID = <<Channel/binary, "%", Server/binary, "@",
(To#jid.server)/binary>>,
Invite = #xmlel{name = <<"message">>, attrs = [],
children =
[#xmlel{name = <<"x">>,
attrs =
[{<<"xmlns">>,
?NS_MUC_USER}],
children =
[#xmlel{name =
<<"invite">>,
attrs =
[{<<"from">>,
jlib:jid_to_string(From)}],
children =
[#xmlel{name
=
<<"reason">>,
attrs
=
[],
children
=
[{xmlcdata,
translate:translate(Lang,
<<"Join the IRC channel here.">>)}]}]}]},
#xmlel{name = <<"x">>,
attrs =
[{<<"xmlns">>,
?NS_XCONFERENCE}],
children =
[{xmlcdata,
translate:translate(Lang,
<<"Join the IRC channel here.">>)}]},
#xmlel{name = <<"body">>,
attrs = [],
children =
[{xmlcdata,
iolist_to_binary(
io_lib:format(
translate:translate(
Lang,
<<"Join the IRC channel in this Jabber ID: ~s">>),
[RoomJID]))}]}]},
ejabberd_router:route(jlib:string_to_jid(RoomJID), From,
Invite),
adhoc:produce_response(Request,
#adhoc_response{status =
completed});
true -> {error, ?ERR_BAD_REQUEST}
end
end
end.
adhoc_register(_ServerHost, _From, _To,
#adhoc_request{action = <<"cancel">>} = Request) ->
adhoc:produce_response(Request,
#adhoc_response{status = canceled});
adhoc_register(ServerHost, From, To,
#adhoc_request{lang = Lang, node = _Node, xdata = XData,
action = Action} =
Request) ->
#jid{user = User} = From,
#jid{lserver = Host} = To,
if XData == false ->
case get_data(ServerHost, Host, From) of
error -> Username = User, ConnectionsParams = [];
empty -> Username = User, ConnectionsParams = [];
Data ->
{Username, ConnectionsParams} =
get_username_and_connection_params(Data)
end,
Error = false;
true ->
case jlib:parse_xdata_submit(XData) of
invalid ->
Error = {error, ?ERR_BAD_REQUEST},
Username = false,
ConnectionsParams = false;
Fields ->
Username = case lists:keysearch(<<"username">>, 1,
Fields)
of
{value, {<<"username">>, U}} -> U;
_ -> User
end,
ConnectionsParams = parse_connections_params(Fields),
Error = false
end
end,
if Error /= false -> Error;
Action == <<"complete">> ->
case set_data(ServerHost, Host, From,
[{username, Username},
{connections_params, ConnectionsParams}])
of
{atomic, _} ->
adhoc:produce_response(Request,
#adhoc_response{status = completed});
_ -> {error, ?ERR_INTERNAL_SERVER_ERROR}
end;
true ->
Form = generate_adhoc_register_form(Lang, Username,
ConnectionsParams),
adhoc:produce_response(Request,
#adhoc_response{status = executing,
elements = [Form],
actions =
[<<"next">>,
<<"complete">>]})
end.
generate_adhoc_register_form(Lang, Username,
ConnectionsParams) ->
#xmlel{name = <<"x">>,
attrs =
[{<<"xmlns">>, ?NS_XDATA}, {<<"type">>, <<"form">>}],
children =
[#xmlel{name = <<"title">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang, <<"IRC settings">>)}]},
#xmlel{name = <<"instructions">>, attrs = [],
children =
[{xmlcdata,
translate:translate(Lang,
<<"Enter username and encodings you wish "
"to use for connecting to IRC servers. "
" Press 'Next' to get more fields to "
"fill in. Press 'Complete' to save settings.">>)}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"username">>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
translate:translate(Lang, <<"IRC username">>)}],
children =
[#xmlel{name = <<"required">>, attrs = [],
children = []},
#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, Username}]}]}]
++
generate_connection_params_fields(Lang,
ConnectionsParams, 1, [])}.
generate_connection_params_fields(Lang, [], Number,
Acc) ->
Field = generate_connection_params_field(Lang, <<"">>,
<<"">>, -1, <<"">>, Number),
lists:reverse(Field ++ Acc);
generate_connection_params_fields(Lang,
[ConnectionParams | ConnectionsParams],
Number, Acc) ->
case ConnectionParams of
{Server, Encoding, Port, Password} ->
Field = generate_connection_params_field(Lang, Server,
Encoding, Port, Password,
Number),
generate_connection_params_fields(Lang,
ConnectionsParams, Number + 1,
Field ++ Acc);
{Server, Encoding, Port} ->
Field = generate_connection_params_field(Lang, Server,
Encoding, Port, <<"">>, Number),
generate_connection_params_fields(Lang,
ConnectionsParams, Number + 1,
Field ++ Acc);
{Server, Encoding} ->
Field = generate_connection_params_field(Lang, Server,
Encoding, -1, <<"">>, Number),
generate_connection_params_fields(Lang,
ConnectionsParams, Number + 1,
Field ++ Acc);
_ -> []
end.
generate_connection_params_field(Lang, Server, Encoding,
Port, Password, Number) ->
EncodingUsed = case Encoding of
<<>> -> get_default_encoding(Server);
_ -> Encoding
end,
PortUsedInt = if Port >= 0 andalso Port =< 65535 ->
Port;
true -> ?DEFAULT_IRC_PORT
end,
PortUsed =
iolist_to_binary(integer_to_list(PortUsedInt)),
PasswordUsed = case Password of
<<>> -> <<>>;
_ -> Password
end,
NumberString =
iolist_to_binary(integer_to_list(Number)),
[#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"password", NumberString/binary>>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
iolist_to_binary(
io_lib:format(
translate:translate(Lang, <<"Password ~b">>),
[Number]))}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, PasswordUsed}]}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"port", NumberString/binary>>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
iolist_to_binary(
io_lib:format(translate:translate(Lang, <<"Port ~b">>),
[Number]))}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, PortUsed}]}]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"encoding", NumberString/binary>>},
{<<"type">>, <<"list-single">>},
{<<"label">>,
list_to_binary(
io_lib:format(translate:translate(
Lang,
<<"Encoding for server ~b">>),
[Number]))}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, EncodingUsed}]}
| lists:map(fun (E) ->
#xmlel{name = <<"option">>,
attrs = [{<<"label">>, E}],
children =
[#xmlel{name = <<"value">>,
attrs = [],
children =
[{xmlcdata, E}]}]}
end,
?POSSIBLE_ENCODINGS)]},
#xmlel{name = <<"field">>,
attrs =
[{<<"var">>, <<"server", NumberString/binary>>},
{<<"type">>, <<"text-single">>},
{<<"label">>,
list_to_binary(
io_lib:format(translate:translate(Lang, <<"Server ~b">>),
[Number]))}],
children =
[#xmlel{name = <<"value">>, attrs = [],
children = [{xmlcdata, Server}]}]}].
parse_connections_params(Fields) ->
Servers = lists:flatmap(
fun({<<"server", Var/binary>>, Value}) ->
[{Var, Value}];
(_) ->
[]
end, Fields),
Encodings = lists:flatmap(
fun({<<"encoding", Var/binary>>, Value}) ->
[{Var, Value}];
(_) ->
[]
end, Fields),
Ports = lists:flatmap(
fun({<<"port", Var/binary>>, Value}) ->
[{Var, Value}];
(_) ->
[]
end, Fields),
Passwords = lists:flatmap(
fun({<<"password", Var/binary>>, Value}) ->
[{Var, Value}];
(_) ->
[]
end, Fields),
parse_connections_params(Servers, Encodings, Ports,
Passwords).
retrieve_connections_params(ConnectionParams,
ServerN) ->
case ConnectionParams of
[{ConnectionParamN, ConnectionParam}
| ConnectionParamsTail] ->
if ServerN == ConnectionParamN ->
{ConnectionParam, ConnectionParamsTail};
ServerN < ConnectionParamN ->
{[],
[{ConnectionParamN, ConnectionParam}
| ConnectionParamsTail]};
ServerN > ConnectionParamN -> {[], ConnectionParamsTail}
end;
_ -> {[], []}
end.
parse_connections_params([], _, _, _) -> [];
parse_connections_params(_, [], [], []) -> [];
parse_connections_params([{ServerN, Server} | Servers],
Encodings, Ports, Passwords) ->
{NewEncoding, NewEncodings} =
retrieve_connections_params(Encodings, ServerN),
{NewPort, NewPorts} = retrieve_connections_params(Ports,
ServerN),
{NewPassword, NewPasswords} =
retrieve_connections_params(Passwords, ServerN),
[{Server, NewEncoding, NewPort, NewPassword}
| parse_connections_params(Servers, NewEncodings,
NewPorts, NewPasswords)].
get_username_and_connection_params(Data) ->
Username = case lists:keysearch(username, 1, Data) of
{value, {_, U}} when is_binary(U) ->
U;
_ ->
<<"">>
end,
ConnParams = case lists:keysearch(connections_params, 1, Data) of
{value, {_, L}} when is_list(L) ->
L;
_ ->
[]
end,
{Username, ConnParams}.
data_to_binary(JID, Data) ->
lists:map(
fun({username, U}) ->
{username, iolist_to_binary(U)};
({connections_params, Params}) ->
{connections_params,
lists:flatmap(
fun(Param) ->
try
[conn_param_to_binary(Param)]
catch _:_ ->
if JID /= error ->
?ERROR_MSG("failed to convert "
"parameter ~p for user ~s",
[Param,
jlib:jid_to_string(JID)]);
true ->
?ERROR_MSG("failed to convert "
"parameter ~p",
[Param])
end,
[]
end
end, Params)};
(Opt) ->
Opt
end, Data).
conn_param_to_binary({S}) ->
{iolist_to_binary(S)};
conn_param_to_binary({S, E}) ->
{iolist_to_binary(S), iolist_to_binary(E)};
conn_param_to_binary({S, E, Port}) when is_integer(Port) ->
{iolist_to_binary(S), iolist_to_binary(E), Port};
conn_param_to_binary({S, E, Port, P}) when is_integer(Port) ->
{iolist_to_binary(S), iolist_to_binary(E), Port, iolist_to_binary(P)}.
conn_params_to_list(Params) ->
lists:map(
fun({S}) ->
{binary_to_list(S)};
({S, E}) ->
{binary_to_list(S), binary_to_list(E)};
({S, E, Port}) ->
{binary_to_list(S), binary_to_list(E), Port};
({S, E, Port, P}) ->
{binary_to_list(S), binary_to_list(E),
Port, binary_to_list(P)}
end, Params).
irc_custom_schema() ->
{record_info(fields, irc_custom), #irc_custom{}}.
update_table() ->
Fields = record_info(fields, irc_custom),
case mnesia:table_info(irc_custom, attributes) of
Fields ->
ejabberd_config:convert_table_to_binary(
irc_custom, Fields, set,
fun(#irc_custom{us_host = {_, H}}) -> H end,
fun(#irc_custom{us_host = {{U, S}, H},
data = Data} = R) ->
JID = jlib:make_jid(U, S, <<"">>),
R#irc_custom{us_host = {{iolist_to_binary(U),
iolist_to_binary(S)},
iolist_to_binary(H)},
data = data_to_binary(JID, Data)}
end);
_ ->
?INFO_MSG("Recreating irc_custom table", []),
mnesia:transform_table(irc_custom, ignore, Fields)
end.
export(_Server) ->
[{irc_custom,
fun(Host, #irc_custom{us_host = {{U, S}, IRCHost},
data = Data}) ->
case str:suffix(Host, IRCHost) of
true ->
SJID = ejabberd_odbc:escape(
jlib:jid_to_string(
jlib:make_jid(U, S, <<"">>))),
SIRCHost = ejabberd_odbc:escape(IRCHost),
SData = ejabberd_odbc:encode_term(Data),
[[<<"delete from irc_custom where jid='">>, SJID,
<<"' and host='">>, SIRCHost, <<"';">>],
[<<"insert into irc_custom(jid, host, "
"data) values ('">>,
SJID, <<"', '">>, SIRCHost, <<"', '">>, SData,
<<"');">>]];
false ->
[]
end
end}].
import(_LServer) ->
[{<<"select jid, host, data from irc_custom;">>,
fun([SJID, IRCHost, SData]) ->
#jid{luser = U, lserver = S} = jlib:string_to_jid(SJID),
Data = ejabberd_odbc:decode_term(SData),
#irc_custom{us_host = {{U, S}, IRCHost},
data = Data}
end}].
import(_LServer, mnesia, #irc_custom{} = R) ->
mnesia:dirty_write(R);
import(_LServer, riak, #irc_custom{} = R) ->
ejabberd_riak:put(R, irc_custom_schema());
import(_, _, _) ->
pass.
|
3987c9930575104614cf117048c62ead89d74fef876b1ce2654d4ca88d2e5454 | wangsix/VMO_repeated_themes_discovery | converter.lisp |
;(in-package :common-lisp-user)
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/csv-files.lisp"))
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/humdrum-by-col.lisp"))
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/midi-save.lisp"))
(setq
*path&name*
(concatenate
'string *music-data-root*
"/beethovenOp2No1Mvt3/polyphonic/repeatedPatterns"
"/sectionalRepetitions/E"))
(setq
csv-destination
(concatenate
'string *path&name* "/csv/sonata01-3.csv"))
(setq
MIDI-destination
(concatenate
'string *path&name* "/midi/sonata01-3.mid"))
(setq
dataset-destination
(concatenate
'string *path&name* "/lisp/sonata01-3.txt"))
(progn
(setq *scale* 1000)
(setq *anacrusis* -1)
(setq
dataset
(humdrum-file2dataset-by-col
(concatenate
'string *path&name* "/kern/sonata01-3.krn")))
(saveit
MIDI-destination
(modify-to-check-dataset dataset *scale*))
(write-to-file
(mapcar
#'(lambda (x)
(append
(list (+ (first x) *anacrusis*))
(rest x)))
dataset)
dataset-destination)
(dataset2csv
dataset-destination csv-destination))
| null | https://raw.githubusercontent.com/wangsix/VMO_repeated_themes_discovery/0082b3c55e64ed447c8b68bcb705fd6da8e3541f/JKUPDD-Aug2013/groundTruth/beethovenOp2No1Mvt3/polyphonic/repeatedPatterns/sectionalRepetitions/E/script/converter.lisp | lisp | (in-package :common-lisp-user) |
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/csv-files.lisp"))
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/humdrum-by-col.lisp"))
(load
(concatenate
'string
*lisp-code-root* "/File conversion"
"/midi-save.lisp"))
(setq
*path&name*
(concatenate
'string *music-data-root*
"/beethovenOp2No1Mvt3/polyphonic/repeatedPatterns"
"/sectionalRepetitions/E"))
(setq
csv-destination
(concatenate
'string *path&name* "/csv/sonata01-3.csv"))
(setq
MIDI-destination
(concatenate
'string *path&name* "/midi/sonata01-3.mid"))
(setq
dataset-destination
(concatenate
'string *path&name* "/lisp/sonata01-3.txt"))
(progn
(setq *scale* 1000)
(setq *anacrusis* -1)
(setq
dataset
(humdrum-file2dataset-by-col
(concatenate
'string *path&name* "/kern/sonata01-3.krn")))
(saveit
MIDI-destination
(modify-to-check-dataset dataset *scale*))
(write-to-file
(mapcar
#'(lambda (x)
(append
(list (+ (first x) *anacrusis*))
(rest x)))
dataset)
dataset-destination)
(dataset2csv
dataset-destination csv-destination))
|
89d500abfd2fb52a5b6f2777bb3363f154436243cf8b880211b8a5db3a2743d9 | cyverse-archive/DiscoveryEnvironmentBackend | coercions.clj | (ns metadactyl.util.coercions
(:require [ring.swagger.coerce :as rc]
[ring.swagger.common :refer [value-of]]
[schema.coerce :as sc]
[schema.utils :as su]
[slingshot.slingshot :refer [throw+]])
(:import [java.util UUID]))
(defn- stringify-uuids
[v]
(if (instance? UUID v)
(str v)
v))
(def ^:private custom-coercions {String stringify-uuids})
(defn- custom-coercion-matcher
[schema]
(or (rc/json-schema-coercion-matcher schema)
(custom-coercions schema)))
(defn coerce
[schema value]
((sc/coercer (value-of schema) custom-coercion-matcher) value))
(defn coerce!
[schema value]
(let [result (coerce schema value)]
(if (su/error? result)
(throw+ {:type :ring.swagger.schema/validation
:error (:error result)})
result)))
| null | https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/metadactyl-clj/src/metadactyl/util/coercions.clj | clojure | (ns metadactyl.util.coercions
(:require [ring.swagger.coerce :as rc]
[ring.swagger.common :refer [value-of]]
[schema.coerce :as sc]
[schema.utils :as su]
[slingshot.slingshot :refer [throw+]])
(:import [java.util UUID]))
(defn- stringify-uuids
[v]
(if (instance? UUID v)
(str v)
v))
(def ^:private custom-coercions {String stringify-uuids})
(defn- custom-coercion-matcher
[schema]
(or (rc/json-schema-coercion-matcher schema)
(custom-coercions schema)))
(defn coerce
[schema value]
((sc/coercer (value-of schema) custom-coercion-matcher) value))
(defn coerce!
[schema value]
(let [result (coerce schema value)]
(if (su/error? result)
(throw+ {:type :ring.swagger.schema/validation
:error (:error result)})
result)))
|
|
d7da5d382e3b89df2b8fdefca8a8da5915bad236bddbf1c51ebef64854301301 | yesodweb/wai | FdCache.hs | # LANGUAGE BangPatterns , CPP #
-- | File descriptor cache to avoid locks in kernel.
module Network.Wai.Handler.Warp.FdCache (
withFdCache
, Fd
, Refresh
#ifndef WINDOWS
, openFile
, closeFile
, setFileCloseOnExec
#endif
) where
#ifndef WINDOWS
import UnliftIO.Exception (bracket)
import Control.Reaper
import Data.IORef
import Network.Wai.Handler.Warp.MultiMap as MM
import System.Posix.IO (openFd, OpenFileFlags(..), defaultFileFlags, OpenMode(ReadOnly), closeFd, FdOption(CloseOnExec), setFdOption)
#endif
import System.Posix.Types (Fd)
----------------------------------------------------------------
-- | An action to activate a Fd cache entry.
type Refresh = IO ()
getFdNothing :: FilePath -> IO (Maybe Fd, Refresh)
getFdNothing _ = return (Nothing, return ())
----------------------------------------------------------------
| Creating ' MutableFdCache ' and executing the action in the second
argument . The first argument is a cache duration in second .
withFdCache :: Int -> ((FilePath -> IO (Maybe Fd, Refresh)) -> IO a) -> IO a
#ifdef WINDOWS
withFdCache _ action = action getFdNothing
#else
withFdCache 0 action = action getFdNothing
withFdCache duration action = bracket (initialize duration)
terminate
(action . getFd)
----------------------------------------------------------------
data Status = Active | Inactive
newtype MutableStatus = MutableStatus (IORef Status)
status :: MutableStatus -> IO Status
status (MutableStatus ref) = readIORef ref
newActiveStatus :: IO MutableStatus
newActiveStatus = MutableStatus <$> newIORef Active
refresh :: MutableStatus -> Refresh
refresh (MutableStatus ref) = writeIORef ref Active
inactive :: MutableStatus -> IO ()
inactive (MutableStatus ref) = writeIORef ref Inactive
----------------------------------------------------------------
data FdEntry = FdEntry !Fd !MutableStatus
openFile :: FilePath -> IO Fd
openFile path = do
fd <- openFd path ReadOnly Nothing defaultFileFlags{nonBlock=False}
setFileCloseOnExec fd
return fd
closeFile :: Fd -> IO ()
closeFile = closeFd
newFdEntry :: FilePath -> IO FdEntry
newFdEntry path = FdEntry <$> openFile path <*> newActiveStatus
setFileCloseOnExec :: Fd -> IO ()
setFileCloseOnExec fd = setFdOption fd CloseOnExec True
----------------------------------------------------------------
type FdCache = MultiMap FdEntry
-- | Mutable Fd cacher.
newtype MutableFdCache = MutableFdCache (Reaper FdCache (FilePath,FdEntry))
fdCache :: MutableFdCache -> IO FdCache
fdCache (MutableFdCache reaper) = reaperRead reaper
look :: MutableFdCache -> FilePath -> IO (Maybe FdEntry)
look mfc path = MM.lookup path <$> fdCache mfc
----------------------------------------------------------------
The first argument is a cache duration in second .
initialize :: Int -> IO MutableFdCache
initialize duration = MutableFdCache <$> mkReaper settings
where
settings = defaultReaperSettings {
reaperAction = clean
, reaperDelay = duration
, reaperCons = uncurry insert
, reaperNull = isEmpty
, reaperEmpty = empty
}
clean :: FdCache -> IO (FdCache -> FdCache)
clean old = do
new <- pruneWith old prune
return $ merge new
where
prune (_,FdEntry fd mst) = status mst >>= act
where
act Active = inactive mst >> return True
act Inactive = closeFd fd >> return False
----------------------------------------------------------------
terminate :: MutableFdCache -> IO ()
terminate (MutableFdCache reaper) = do
!t <- reaperStop reaper
mapM_ (closeIt . snd) $ toList t
where
closeIt (FdEntry fd _) = closeFd fd
----------------------------------------------------------------
| Getting ' Fd ' and ' Refresh ' from the mutable Fd cacher .
getFd :: MutableFdCache -> FilePath -> IO (Maybe Fd, Refresh)
getFd mfc@(MutableFdCache reaper) path = look mfc path >>= get
where
get Nothing = do
ent@(FdEntry fd mst) <- newFdEntry path
reaperAdd reaper (path,ent)
return (Just fd, refresh mst)
get (Just (FdEntry fd mst)) = do
refresh mst
return (Just fd, refresh mst)
#endif
| null | https://raw.githubusercontent.com/yesodweb/wai/052b875effb45fbf7fd3bb9123592fc5002c9763/warp/Network/Wai/Handler/Warp/FdCache.hs | haskell | | File descriptor cache to avoid locks in kernel.
--------------------------------------------------------------
| An action to activate a Fd cache entry.
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
--------------------------------------------------------------
| Mutable Fd cacher.
--------------------------------------------------------------
--------------------------------------------------------------
-------------------------------------------------------------- | # LANGUAGE BangPatterns , CPP #
module Network.Wai.Handler.Warp.FdCache (
withFdCache
, Fd
, Refresh
#ifndef WINDOWS
, openFile
, closeFile
, setFileCloseOnExec
#endif
) where
#ifndef WINDOWS
import UnliftIO.Exception (bracket)
import Control.Reaper
import Data.IORef
import Network.Wai.Handler.Warp.MultiMap as MM
import System.Posix.IO (openFd, OpenFileFlags(..), defaultFileFlags, OpenMode(ReadOnly), closeFd, FdOption(CloseOnExec), setFdOption)
#endif
import System.Posix.Types (Fd)
type Refresh = IO ()
getFdNothing :: FilePath -> IO (Maybe Fd, Refresh)
getFdNothing _ = return (Nothing, return ())
| Creating ' MutableFdCache ' and executing the action in the second
argument . The first argument is a cache duration in second .
withFdCache :: Int -> ((FilePath -> IO (Maybe Fd, Refresh)) -> IO a) -> IO a
#ifdef WINDOWS
withFdCache _ action = action getFdNothing
#else
withFdCache 0 action = action getFdNothing
withFdCache duration action = bracket (initialize duration)
terminate
(action . getFd)
data Status = Active | Inactive
newtype MutableStatus = MutableStatus (IORef Status)
status :: MutableStatus -> IO Status
status (MutableStatus ref) = readIORef ref
newActiveStatus :: IO MutableStatus
newActiveStatus = MutableStatus <$> newIORef Active
refresh :: MutableStatus -> Refresh
refresh (MutableStatus ref) = writeIORef ref Active
inactive :: MutableStatus -> IO ()
inactive (MutableStatus ref) = writeIORef ref Inactive
data FdEntry = FdEntry !Fd !MutableStatus
openFile :: FilePath -> IO Fd
openFile path = do
fd <- openFd path ReadOnly Nothing defaultFileFlags{nonBlock=False}
setFileCloseOnExec fd
return fd
closeFile :: Fd -> IO ()
closeFile = closeFd
newFdEntry :: FilePath -> IO FdEntry
newFdEntry path = FdEntry <$> openFile path <*> newActiveStatus
setFileCloseOnExec :: Fd -> IO ()
setFileCloseOnExec fd = setFdOption fd CloseOnExec True
type FdCache = MultiMap FdEntry
newtype MutableFdCache = MutableFdCache (Reaper FdCache (FilePath,FdEntry))
fdCache :: MutableFdCache -> IO FdCache
fdCache (MutableFdCache reaper) = reaperRead reaper
look :: MutableFdCache -> FilePath -> IO (Maybe FdEntry)
look mfc path = MM.lookup path <$> fdCache mfc
The first argument is a cache duration in second .
initialize :: Int -> IO MutableFdCache
initialize duration = MutableFdCache <$> mkReaper settings
where
settings = defaultReaperSettings {
reaperAction = clean
, reaperDelay = duration
, reaperCons = uncurry insert
, reaperNull = isEmpty
, reaperEmpty = empty
}
clean :: FdCache -> IO (FdCache -> FdCache)
clean old = do
new <- pruneWith old prune
return $ merge new
where
prune (_,FdEntry fd mst) = status mst >>= act
where
act Active = inactive mst >> return True
act Inactive = closeFd fd >> return False
terminate :: MutableFdCache -> IO ()
terminate (MutableFdCache reaper) = do
!t <- reaperStop reaper
mapM_ (closeIt . snd) $ toList t
where
closeIt (FdEntry fd _) = closeFd fd
| Getting ' Fd ' and ' Refresh ' from the mutable Fd cacher .
getFd :: MutableFdCache -> FilePath -> IO (Maybe Fd, Refresh)
getFd mfc@(MutableFdCache reaper) path = look mfc path >>= get
where
get Nothing = do
ent@(FdEntry fd mst) <- newFdEntry path
reaperAdd reaper (path,ent)
return (Just fd, refresh mst)
get (Just (FdEntry fd mst)) = do
refresh mst
return (Just fd, refresh mst)
#endif
|
1ccf589d72a8b5bd55550446f534e9210f97046b10ec28e0413d566a068c2837 | bjorng/wings | wpc_jscad.erl | %%
%% wpc_jscad.erl --
%%
%% OpenJSCAD export.
%%
Copyright ( c ) 2019
%%
%% See the file "license.terms" for information on usage and redistribution
%% of this file, and for a DISCLAIMER OF ALL WARRANTIES.
%%
%% $Id$
%%
-module(wpc_jscad).
-export([init/0,menu/2,command/2]).
-include_lib("wings/e3d/e3d.hrl").
-include_lib("wings/intl_tools/wings_intl.hrl").
init() ->
true.
menu({file,export}, Menu) ->
menu_entry(Menu);
menu({file,export_selected}, Menu) ->
menu_entry(Menu);
menu(_, Menu) -> Menu.
command({file,{export,{jscad,Ask}}}, St) ->
Exporter = fun(Ps, Fun) -> wpa:export(Ps, Fun, St) end,
do_export(Ask, export, Exporter, St);
command({file,{export_selected,{jscad,Ask}}}, St) ->
Exporter = fun(Ps, Fun) -> wpa:export_selected(Ps, Fun, St) end,
do_export(Ask, export_selected, Exporter, St);
command(_, _) ->
next.
menu_entry(Menu) ->
Menu ++ [{"OpenJSCAD (.jscad)...",jscad,[option]}].
props() ->
[{ext,".jscad"},{ext_desc,?__(1,"OpenJSCAD File")}].
%%%
%%% Export.
%%%
do_export(Ask, Op, _Exporter, _St) when is_atom(Ask) ->
wpa:dialog(Ask, ?__(1,"OpenJSCAD Export Options"), dialog(export),
fun(Res) ->
{file,{Op,{jscad,Res}}}
end);
do_export(Attr, _Op, Exporter, _St) when is_list(Attr) ->
set_pref(Attr),
FacesGroup = proplists:get_value(faces_group, Attr, false),
CreateRet = proplists:get_value(create_returns, Attr, object),
BuildMain = proplists:get_value(build_main, Attr, true),
SubDivs = proplists:get_value(subdivisions, Attr, 0),
Tesselation = proplists:get_value(tesselation, Attr, none),
Ps = [{tesselation,Tesselation},{faces_group,FacesGroup},{create_returns,CreateRet},
{build_main,BuildMain},{subdivisions,SubDivs}|props()],
Exporter(Ps, export_fun(Attr)).
export_fun(Attr) ->
fun(Filename, Contents) ->
export(Filename, Contents, Attr)
end.
export(Filename, Contents0, Attr) ->
Contents = export_transform(Contents0, Attr),
#e3d_file{objs=Objs,mat=Mat,creator=Creator} = Contents,
{ok,F} = file:open(Filename, [write]),
FName = filename:basename(Filename),
NObjs = length(Objs),
%% Write file head
io:format(F, "// File : ~ts\n",[FName]),
io:format(F, "// Objects : ~lp\n",[NObjs]),
io:format(F, "// Exported from: ~ts\n",[Creator]),
%% Write file body
try
FunNames =
lists:foldl(fun(#e3d_object{name=Name, obj=Obj}, Acc) ->
case proplists:get_bool(group_per_material, Attr) of
true ->
Meshes = e3d_mesh:split_by_material(Obj),
export_object(F, Name, Meshes, Mat, Attr, Acc);
false ->
export_object(F, Name, Obj, Mat, Attr, Acc)
end
end, [], Objs),
case proplists:get_value(build_main, Attr) of
true -> export_main(F, FunNames, Attr);
false -> ignore
end
catch _:Err:Stacktrace ->
io:format(?__(1,"OpenJSCAD Error: ~P in")++" ~p~n", [Err,30,Stacktrace])
end,
ok = file:close(F).
export_main(F, FunNames, Flags) ->
io:put_chars(F, "function main() {\n"),
io:put_chars(F, "\treturn [\n"),
all(fun(FunName) ->
case proplists:get_value(create_returns, Flags) of
object ->
io:format(F, "\t\t~s", [FunName]);
properties ->
io:format(F, "\t\t~s.csg", [FunName])
end
end,F,FunNames),
io:put_chars(F, "\n\t];\n}\n").
export_object(F, Name, Meshes, MatDefs, Flags, Acc0) when is_list(Meshes) ->
lists:foldl(fun(#e3d_mesh{}=Mesh, Acc) ->
export_object(F, Name, Mesh, MatDefs, Flags, Acc)
end, Acc0, Meshes);
export_object(F, Name, #e3d_mesh{vs=Vtab,vc=ColDefs0,fs=Fs}=Mesh, MatDefs, Flags, Acc) ->
GroupPerMat = proplists:get_bool(group_per_material, Flags),
ColDefs = array:from_list(ColDefs0),
ObjName0 =
case GroupPerMat of
true ->
[#e3d_face{mat=[Material|_]}|_] = Fs,
io_lib:format("~ts_~tp()",[Name,Material]);
false ->
io_lib:format("~ts()",[Name])
end,
ObjName = string:replace(ObjName0," ","_"),
%% each mesh will be created by a dedicated function using its name
io:format(F, "function ~s {\n",[ObjName]),
export_obj_vertices(F, Vtab),
case proplists:get_bool(faces_group, Flags) of
true ->
Mats = export_groups_faces(F, Mesh),
export_obj_colors(F, Mats, ColDefs, MatDefs, true),
StrGroup = ",groups:Groups",
io:put_chars(F, "\tCsgPolys = Polygons.map((m,idx) => CSG.Polygon.createFromPoints(m.map(n => Points[n])).setColor(Colors[Groups[idx]])),\n");
false ->
export_obj_faces(F, Fs),
export_obj_colors(F, Fs, ColDefs, MatDefs, false),
StrGroup = "",
io:put_chars(F, "\tCsgPolys = Polygons.map((m,idx) => CSG.Polygon.createFromPoints(m.map(n => Points[n])).setColor(Colors[idx])),\n")
end,
io:put_chars(F, "\tCsg = CSG.fromPolygons(CsgPolys);\n"),
case proplists:get_value(create_returns, Flags) of
object ->
io:put_chars(F, "\treturn Csg;\n");
properties ->
io:put_chars(F, "\treturn {points:Points,polygons:Polygons"++StrGroup++",csgpolys:CsgPolys,csg:Csg};\n")
end,
io:put_chars(F, "}\n\n"),
Acc++[ObjName].
export_obj_vertices(F, Vtab) ->
%% Writes vertex coordinates
io:put_chars(F, "\tlet Points = [\n"),
all(fun({X,Y,Z}) -> io:format(F, "\t\t\t[~.9f,~.9f,~.9f]", [X,Y,Z]) end,F,Vtab),
io:put_chars(F, "\n\t\t];\n").
export_obj_faces(F, Fs) ->
%% Writes vertex index of each face
io:put_chars(F, "\tlet Polygons = [\n"),
all(fun(#e3d_face{vs=Vs}) -> io:format(F, "\t\t\t~w", [Vs]) end,F,Fs),
io:put_chars(F, "\n\t\t];\n").
export_groups_faces(F, #e3d_mesh{fs=Fs0}) ->
{_,MatUsed,MatFaces} =
lists:foldl(fun(#e3d_face{vs=Vs,mat=[Mat|_]}, {Grp0,AccMat0,AccFs}) ->
case gb_trees:lookup(Mat,AccMat0) of
none ->
Grp = Grp0+1,
AccMat = gb_trees:enter(Mat,Grp,AccMat0);
{value,Grp1} ->
Grp = Grp1,
AccMat = AccMat0
end,
{Grp, AccMat, [{Grp,Vs}|AccFs]}
end, {-1,gb_trees:empty(),[]}, Fs0),
{Grs,Fs} = split_group_face(MatFaces),
%% Writes vertex index of each face
io:put_chars(F, "\tlet Polygons = [\n"),
all(fun(Vs) -> io:format(F, "\t\t\t~w", [Vs]) end,F,Fs),
io:put_chars(F, "\n\t\t];\n"),
%% Writes group index of each face
io:put_chars(F, "\tlet Groups = [\n"),
all(fun(G) -> io:format(F, "\t\t\t~w", [G]) end,F,Grs),
io:put_chars(F, "\n\t\t];\n"),
ordsets:from_list([{Grp,Mat} || {Mat,Grp} <- gb_trees:to_list(MatUsed)]).
split_group_face(GrpFaces) ->
split_group_face(GrpFaces, {[],[]}).
split_group_face([], Acc) -> Acc;
split_group_face([{G,F}|GrpFaces], {GAcc,FAcc}) ->
split_group_face(GrpFaces,{[G|GAcc],[F|FAcc]}).
export_obj_colors(F, [#e3d_face{}|_]=Fs, ColDefs, MatDefs, FacesGroup) ->
io:put_chars(F, "\tlet Colors = [\n"),
all(fun(#e3d_face{vc=Cols,mat=[Mat|_]}) ->
[R,G,B,A] = choose_color(Cols, Mat, ColDefs, MatDefs, FacesGroup),
io:format(F, "\t\t\t[~.6f,~.6f,~.6f,~.6f]", [R,G,B,A])
end,F,Fs),
io:put_chars(F, "\n\t\t];\n");
export_obj_colors(F, Mats, ColDefs, MatDefs, FacesGroup) ->
io:put_chars(F, "\tlet Colors = [\n"),
all(fun({_,Mat}) ->
[R,G,B,A] = choose_color([], Mat, ColDefs, MatDefs, FacesGroup),
io:format(F, "\t\t\t[~.6f,~.6f,~.6f,~.6f]", [R,G,B,A])
end,F,Mats),
io:put_chars(F, "\n\t\t];\n").
choose_color(Cols, Mat, ColDefs, MatDefs, FacesGroup) ->
case {Mat,FacesGroup} of
{default,false} ->
%% if set, it uses the face color in case not grouping by material
case Cols of
[] -> material(default, MatDefs);
_ ->
C0 = [array:get(Ic,ColDefs) || Ic <- Cols],
%% jscad doesn't supports vertex color, so we compute the face's average color
{R0,G0,B0} = e3d_vec:average(C0),
[R0,G0,B0,1.0]
end;
_ -> material(Mat, MatDefs)
end.
material(Name, Mat_defs) ->
MatInfo = lookup(Name, Mat_defs),
Mat = lookup(opengl, MatInfo),
{Dr, Dg, Db, Da} = lookup(diffuse, Mat),
[Dr, Dg, Db, Da].
dialog(export) ->
[wpa:dialog_template(?MODULE, tesselation),
{label_column,
[{?__(1,"One group per material"),
{"",get_pref(group_per_material, true),
[{key,group_per_material}]}},
{?__(6,"Swap Y and Z Axes"),
{"",get_pref(swap_y_z, true),
[{key,swap_y_z}]}},
{export_scale_s(),
{text,get_pref(export_scale, 1.0),
[{key,export_scale},{range,{1.0,infinity}}]}},
{?__(7,"Sub-division Steps"),
{text,get_pref(subdivisions, 0),
[{key,subdivisions},{range,{0,4}}]}},
{?__(2,"Export faces group"),
{"",get_pref(faces_group, false),
[{key,faces_group},{info,?__(3,"Exports face's group IDs by material")}]}},
{?__(4,"Build the main() statement"),
{"",get_pref(build_main, true),
[{key,build_main},{info,?__(5,"Add a main() function to build the scene")}]}}
]},
{vframe,[{vradio,[{?__(9,"CSG Object"),object},
{?__(10,"Properties"),properties}],
get_pref(create_returns, object),
[{key,create_returns},
{info,?__(11,"Returns the object or properties: {points:?,polygons:?,groups:?,"++
"cgspolygons:?,csg:?}")}]}],
[{title,?__(8,"Creation function returns")}]}
].
get_pref(Key, Def) ->
wpa:pref_get(?MODULE, Key, Def).
set_pref(KeyVals) ->
wpa:pref_set(?MODULE, KeyVals).
export_transform(Contents, Attr) ->
Mat = wpa:export_matrix(Attr),
e3d_file:transform(Contents, Mat).
export_scale_s() -> ?__( 1, "Export scale").
%%% useful helpers
all(F, IO, [H,H1|T]) ->
F(H),
io:put_chars(IO, ",\n"),
all(F, IO, [H1|T]);
all(F, _, [H]) ->
F(H),
ok.
lookup(K, L) ->
{value, {K, V}} = lists:keysearch(K, 1, L),
V.
| null | https://raw.githubusercontent.com/bjorng/wings/1e2c2d62e93a98c263b167c7a41f8611e0ff08cd/plugins_src/import_export/wpc_jscad.erl | erlang |
wpc_jscad.erl --
OpenJSCAD export.
See the file "license.terms" for information on usage and redistribution
of this file, and for a DISCLAIMER OF ALL WARRANTIES.
$Id$
Export.
Write file head
Write file body
each mesh will be created by a dedicated function using its name
Writes vertex coordinates
Writes vertex index of each face
Writes vertex index of each face
Writes group index of each face
if set, it uses the face color in case not grouping by material
jscad doesn't supports vertex color, so we compute the face's average color
useful helpers | Copyright ( c ) 2019
-module(wpc_jscad).
-export([init/0,menu/2,command/2]).
-include_lib("wings/e3d/e3d.hrl").
-include_lib("wings/intl_tools/wings_intl.hrl").
init() ->
true.
menu({file,export}, Menu) ->
menu_entry(Menu);
menu({file,export_selected}, Menu) ->
menu_entry(Menu);
menu(_, Menu) -> Menu.
command({file,{export,{jscad,Ask}}}, St) ->
Exporter = fun(Ps, Fun) -> wpa:export(Ps, Fun, St) end,
do_export(Ask, export, Exporter, St);
command({file,{export_selected,{jscad,Ask}}}, St) ->
Exporter = fun(Ps, Fun) -> wpa:export_selected(Ps, Fun, St) end,
do_export(Ask, export_selected, Exporter, St);
command(_, _) ->
next.
menu_entry(Menu) ->
Menu ++ [{"OpenJSCAD (.jscad)...",jscad,[option]}].
props() ->
[{ext,".jscad"},{ext_desc,?__(1,"OpenJSCAD File")}].
do_export(Ask, Op, _Exporter, _St) when is_atom(Ask) ->
wpa:dialog(Ask, ?__(1,"OpenJSCAD Export Options"), dialog(export),
fun(Res) ->
{file,{Op,{jscad,Res}}}
end);
do_export(Attr, _Op, Exporter, _St) when is_list(Attr) ->
set_pref(Attr),
FacesGroup = proplists:get_value(faces_group, Attr, false),
CreateRet = proplists:get_value(create_returns, Attr, object),
BuildMain = proplists:get_value(build_main, Attr, true),
SubDivs = proplists:get_value(subdivisions, Attr, 0),
Tesselation = proplists:get_value(tesselation, Attr, none),
Ps = [{tesselation,Tesselation},{faces_group,FacesGroup},{create_returns,CreateRet},
{build_main,BuildMain},{subdivisions,SubDivs}|props()],
Exporter(Ps, export_fun(Attr)).
export_fun(Attr) ->
fun(Filename, Contents) ->
export(Filename, Contents, Attr)
end.
export(Filename, Contents0, Attr) ->
Contents = export_transform(Contents0, Attr),
#e3d_file{objs=Objs,mat=Mat,creator=Creator} = Contents,
{ok,F} = file:open(Filename, [write]),
FName = filename:basename(Filename),
NObjs = length(Objs),
io:format(F, "// File : ~ts\n",[FName]),
io:format(F, "// Objects : ~lp\n",[NObjs]),
io:format(F, "// Exported from: ~ts\n",[Creator]),
try
FunNames =
lists:foldl(fun(#e3d_object{name=Name, obj=Obj}, Acc) ->
case proplists:get_bool(group_per_material, Attr) of
true ->
Meshes = e3d_mesh:split_by_material(Obj),
export_object(F, Name, Meshes, Mat, Attr, Acc);
false ->
export_object(F, Name, Obj, Mat, Attr, Acc)
end
end, [], Objs),
case proplists:get_value(build_main, Attr) of
true -> export_main(F, FunNames, Attr);
false -> ignore
end
catch _:Err:Stacktrace ->
io:format(?__(1,"OpenJSCAD Error: ~P in")++" ~p~n", [Err,30,Stacktrace])
end,
ok = file:close(F).
export_main(F, FunNames, Flags) ->
io:put_chars(F, "function main() {\n"),
io:put_chars(F, "\treturn [\n"),
all(fun(FunName) ->
case proplists:get_value(create_returns, Flags) of
object ->
io:format(F, "\t\t~s", [FunName]);
properties ->
io:format(F, "\t\t~s.csg", [FunName])
end
end,F,FunNames),
io:put_chars(F, "\n\t];\n}\n").
export_object(F, Name, Meshes, MatDefs, Flags, Acc0) when is_list(Meshes) ->
lists:foldl(fun(#e3d_mesh{}=Mesh, Acc) ->
export_object(F, Name, Mesh, MatDefs, Flags, Acc)
end, Acc0, Meshes);
export_object(F, Name, #e3d_mesh{vs=Vtab,vc=ColDefs0,fs=Fs}=Mesh, MatDefs, Flags, Acc) ->
GroupPerMat = proplists:get_bool(group_per_material, Flags),
ColDefs = array:from_list(ColDefs0),
ObjName0 =
case GroupPerMat of
true ->
[#e3d_face{mat=[Material|_]}|_] = Fs,
io_lib:format("~ts_~tp()",[Name,Material]);
false ->
io_lib:format("~ts()",[Name])
end,
ObjName = string:replace(ObjName0," ","_"),
io:format(F, "function ~s {\n",[ObjName]),
export_obj_vertices(F, Vtab),
case proplists:get_bool(faces_group, Flags) of
true ->
Mats = export_groups_faces(F, Mesh),
export_obj_colors(F, Mats, ColDefs, MatDefs, true),
StrGroup = ",groups:Groups",
io:put_chars(F, "\tCsgPolys = Polygons.map((m,idx) => CSG.Polygon.createFromPoints(m.map(n => Points[n])).setColor(Colors[Groups[idx]])),\n");
false ->
export_obj_faces(F, Fs),
export_obj_colors(F, Fs, ColDefs, MatDefs, false),
StrGroup = "",
io:put_chars(F, "\tCsgPolys = Polygons.map((m,idx) => CSG.Polygon.createFromPoints(m.map(n => Points[n])).setColor(Colors[idx])),\n")
end,
io:put_chars(F, "\tCsg = CSG.fromPolygons(CsgPolys);\n"),
case proplists:get_value(create_returns, Flags) of
object ->
io:put_chars(F, "\treturn Csg;\n");
properties ->
io:put_chars(F, "\treturn {points:Points,polygons:Polygons"++StrGroup++",csgpolys:CsgPolys,csg:Csg};\n")
end,
io:put_chars(F, "}\n\n"),
Acc++[ObjName].
export_obj_vertices(F, Vtab) ->
io:put_chars(F, "\tlet Points = [\n"),
all(fun({X,Y,Z}) -> io:format(F, "\t\t\t[~.9f,~.9f,~.9f]", [X,Y,Z]) end,F,Vtab),
io:put_chars(F, "\n\t\t];\n").
export_obj_faces(F, Fs) ->
io:put_chars(F, "\tlet Polygons = [\n"),
all(fun(#e3d_face{vs=Vs}) -> io:format(F, "\t\t\t~w", [Vs]) end,F,Fs),
io:put_chars(F, "\n\t\t];\n").
export_groups_faces(F, #e3d_mesh{fs=Fs0}) ->
{_,MatUsed,MatFaces} =
lists:foldl(fun(#e3d_face{vs=Vs,mat=[Mat|_]}, {Grp0,AccMat0,AccFs}) ->
case gb_trees:lookup(Mat,AccMat0) of
none ->
Grp = Grp0+1,
AccMat = gb_trees:enter(Mat,Grp,AccMat0);
{value,Grp1} ->
Grp = Grp1,
AccMat = AccMat0
end,
{Grp, AccMat, [{Grp,Vs}|AccFs]}
end, {-1,gb_trees:empty(),[]}, Fs0),
{Grs,Fs} = split_group_face(MatFaces),
io:put_chars(F, "\tlet Polygons = [\n"),
all(fun(Vs) -> io:format(F, "\t\t\t~w", [Vs]) end,F,Fs),
io:put_chars(F, "\n\t\t];\n"),
io:put_chars(F, "\tlet Groups = [\n"),
all(fun(G) -> io:format(F, "\t\t\t~w", [G]) end,F,Grs),
io:put_chars(F, "\n\t\t];\n"),
ordsets:from_list([{Grp,Mat} || {Mat,Grp} <- gb_trees:to_list(MatUsed)]).
split_group_face(GrpFaces) ->
split_group_face(GrpFaces, {[],[]}).
split_group_face([], Acc) -> Acc;
split_group_face([{G,F}|GrpFaces], {GAcc,FAcc}) ->
split_group_face(GrpFaces,{[G|GAcc],[F|FAcc]}).
export_obj_colors(F, [#e3d_face{}|_]=Fs, ColDefs, MatDefs, FacesGroup) ->
io:put_chars(F, "\tlet Colors = [\n"),
all(fun(#e3d_face{vc=Cols,mat=[Mat|_]}) ->
[R,G,B,A] = choose_color(Cols, Mat, ColDefs, MatDefs, FacesGroup),
io:format(F, "\t\t\t[~.6f,~.6f,~.6f,~.6f]", [R,G,B,A])
end,F,Fs),
io:put_chars(F, "\n\t\t];\n");
export_obj_colors(F, Mats, ColDefs, MatDefs, FacesGroup) ->
io:put_chars(F, "\tlet Colors = [\n"),
all(fun({_,Mat}) ->
[R,G,B,A] = choose_color([], Mat, ColDefs, MatDefs, FacesGroup),
io:format(F, "\t\t\t[~.6f,~.6f,~.6f,~.6f]", [R,G,B,A])
end,F,Mats),
io:put_chars(F, "\n\t\t];\n").
choose_color(Cols, Mat, ColDefs, MatDefs, FacesGroup) ->
case {Mat,FacesGroup} of
{default,false} ->
case Cols of
[] -> material(default, MatDefs);
_ ->
C0 = [array:get(Ic,ColDefs) || Ic <- Cols],
{R0,G0,B0} = e3d_vec:average(C0),
[R0,G0,B0,1.0]
end;
_ -> material(Mat, MatDefs)
end.
material(Name, Mat_defs) ->
MatInfo = lookup(Name, Mat_defs),
Mat = lookup(opengl, MatInfo),
{Dr, Dg, Db, Da} = lookup(diffuse, Mat),
[Dr, Dg, Db, Da].
dialog(export) ->
[wpa:dialog_template(?MODULE, tesselation),
{label_column,
[{?__(1,"One group per material"),
{"",get_pref(group_per_material, true),
[{key,group_per_material}]}},
{?__(6,"Swap Y and Z Axes"),
{"",get_pref(swap_y_z, true),
[{key,swap_y_z}]}},
{export_scale_s(),
{text,get_pref(export_scale, 1.0),
[{key,export_scale},{range,{1.0,infinity}}]}},
{?__(7,"Sub-division Steps"),
{text,get_pref(subdivisions, 0),
[{key,subdivisions},{range,{0,4}}]}},
{?__(2,"Export faces group"),
{"",get_pref(faces_group, false),
[{key,faces_group},{info,?__(3,"Exports face's group IDs by material")}]}},
{?__(4,"Build the main() statement"),
{"",get_pref(build_main, true),
[{key,build_main},{info,?__(5,"Add a main() function to build the scene")}]}}
]},
{vframe,[{vradio,[{?__(9,"CSG Object"),object},
{?__(10,"Properties"),properties}],
get_pref(create_returns, object),
[{key,create_returns},
{info,?__(11,"Returns the object or properties: {points:?,polygons:?,groups:?,"++
"cgspolygons:?,csg:?}")}]}],
[{title,?__(8,"Creation function returns")}]}
].
get_pref(Key, Def) ->
wpa:pref_get(?MODULE, Key, Def).
set_pref(KeyVals) ->
wpa:pref_set(?MODULE, KeyVals).
export_transform(Contents, Attr) ->
Mat = wpa:export_matrix(Attr),
e3d_file:transform(Contents, Mat).
export_scale_s() -> ?__( 1, "Export scale").
all(F, IO, [H,H1|T]) ->
F(H),
io:put_chars(IO, ",\n"),
all(F, IO, [H1|T]);
all(F, _, [H]) ->
F(H),
ok.
lookup(K, L) ->
{value, {K, V}} = lists:keysearch(K, 1, L),
V.
|
e4d8076c1a5384458f715efb9261eaab09542bc1e9c1f01b88252fde388b02a4 | unclebob/ScriptSchedule | core.clj | (ns ScriptSchedule.test.core
(:use [ScriptSchedule.core])
(:use [midje.sweet])
(:use [clojure.java.io])
(:use [clojure.xml]))
(def expected-header "Set\tCharacter\tDialogs\tScene\tPage\n")
(def simple-script
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>
<FinalDraft DocumentType=\"Script\" Template=\"No\" Version=\"1\">
<Content>
<Paragraph Number=\"3\" Type=\"Scene Heading\">
<SceneProperties Page=\"1\"/>
<Text>INT. FRONT DOOR - DAY</Text>
</Paragraph>
<Paragraph Type=\"Action\">
<Text>Title: This is a title</Text>
</Paragraph>
<gunk/>
<Paragraph Number=\"4\" Type=\"Scene Heading\">
<SceneProperties Page=\"2\"/>
<Text>INT. GS - DAY</Text>
</Paragraph>
<Paragraph Type=\"Action\">
<Text>some action</Text>
</Paragraph>
<Paragraph Type=\"Character\">
<Text>UNCLE BOB</Text>
</Paragraph>
<Paragraph Type=\"Dialogue\">
<Text>some dialog</Text>
</Paragraph>
<Paragraph Type=\"Action\">
<Text>Note: note another action</Text>
</Paragraph>
<Paragraph Type=\"Character\">
<Text>UNCLE BOB (</Text>
<Text AdornmentStyle=\"-1\">CONT�D</Text>
<Text>)</Text>
</Paragraph>
<Paragraph Type=\"Dialogue\">
<Text>more dialog</Text>
</Paragraph>
<Paragraph Number=\"5\" Type=\"Scene Heading\">
<SceneProperties Page=\"3\"/>
<Text>INT. FRONT DOOR - DAY</Text>
</Paragraph>
<Paragraph Type=\"Action\">
<Text>Note:n1</Text>
</Paragraph>
<Paragraph Type=\"Action\">
<Text>Note:P my prop 1</Text>
</Paragraph>\n
<Paragraph Type=\"Action\">
<Text>Note:n2</Text>
</Paragraph>
<Paragraph Type=\"Character\">
<Text>UNCLE BOB</Text>
</Paragraph>
<Paragraph Type=\"Dialogue\">
<Text>some dialog</Text>
</Paragraph>
</Content>
</FinalDraft>
")
(def simple-scene
(new-scene "GS" "UNCLE BOB" 2 4 2))
(fact (to-scene-line simple-scene) => "GS\tUNCLE BOB\t2\t4\t2\t\t")
(defn parsed-finalDraft [content]
{:tag :FinalDraft,
:attrs {:DocumentType "Script",
:Template "No",
:Version "1"},
:content [{:tag :Content,
:attrs nil,
:content content}]})
(defn parsed-scene-raw [set scene page]
{:tag :Paragraph,
:attrs {:Number scene,
:Type "Scene Heading"},
:content [{:tag :SceneProperties,
:attrs {:Page page},
:content nil}
{:tag :Text,
:attrs nil,
:content [set]}]})
(defn parsed-scene [set scene page]
(parsed-scene-raw (str "INT. " set " - DAY") scene page))
(defn parsed-tag [tag]
{:tag tag, :attrs nil, :content nil})
(defn parsed-action [action]
{:tag :Paragraph,
:attrs {:Type "Action"},
:content [{:tag :Text,
:attrs nil,
:content [action]}]})
(defn parsed-double-action [action1 action2]
{:tag :Paragraph,
:attrs {:Type "Action"},
:content [{:tag :Text,
:attrs nil,
:content [action1]}
{:tag :Text,
:attrs nil,
:content [action2]}]})
(defn parsed-actor [character]
{:tag :Paragraph,
:attrs {:Type "Character"},
:content [{:tag :Text,
:attrs nil,
:content [character]}]})
(defn parsed-continued-actor [character]
{:tag :Paragraph,
:attrs {:Type "Character"},
:content [{:tag :Text,
:attrs nil,
:content [(str character " (")]}
{:tag :Text,
:attrs {:AdornmentStyle "-1"},
:content ["CONT�D"]}
{:tag :Text,
:attrs nil,
:content [")"]}]})
(defn parsed-dialog [dialog]
{:tag :Paragraph,
:attrs {:Type "Dialogue"},
:content [{:tag :Text,
:attrs nil,
:content [dialog]}]})
(def parsed-script
(parsed-finalDraft
[(parsed-scene "FRONT DOOR" "3" "1")
(parsed-action "Title: This is a title")
(parsed-tag :gunk)
(parsed-scene "GS", "4" "2")
(parsed-action "some action")
(parsed-actor "UNCLE BOB")
(parsed-dialog "some dialog")
(parsed-action "Note: note another action")
(parsed-continued-actor "UNCLE BOB")
(parsed-dialog "more dialog")
(parsed-scene "FRONT DOOR" "5" "3")
(parsed-action "Note:n1")
(parsed-action "Note:P my prop 1")
(parsed-action "Note:n2")
(parsed-actor "UNCLE BOB")
(parsed-dialog "some dialog")]))
(facts "low level unit tests"
(fact "an empty script has no paragraphs"
(paragraphs-from-script (parsed-finalDraft [])) => [])
(fact "a script with no scene headings, characters, or actions has no paragraphs"
(paragraphs-from-script (parsed-finalDraft [(parsed-tag :gunk)
(parsed-dialog "dialog")])) => [])
(fact "a script with one scene heading gives one scene paragraph"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene "GS" 3 2)])) => [(new-scene-head "GS" 3 2)])
(fact "a scene without a daytime is parsed correctly"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene-raw "INT. GS" 3 2)])) => [(new-scene-head "GS" 3 2)])
(fact "a scene without a int/ext is parsed correctly"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene-raw "GS - DAY" 3 2)])) => [(new-scene-head "GS" 3 2)])
(fact "a scene without a daytime or int/ext is parsed correctly"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene-raw "GS" 3 2)])) => [(new-scene-head "GS" 3 2)])
(fact "a script with two scene headings gives two scene paragraphs"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene "GS" 1 1)
(parsed-scene "FRONT DOOR" 2 1)])) => [(new-scene-head "GS" 1 1) (new-scene-head "FRONT DOOR" 2 1)])
(fact "a script with one character gives a character paragraph"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-actor "UB")])) => [(new-actor "UB")])
(fact "a script with one action gives an action paragraph"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-action "action")])) => [(new-action "action")])
(fact "a script with one action having two text tags gives an action paragraph"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-double-action "action1" "-action2")])) => [(new-action "action1-action2")])
(fact "a script with scene headings and characters creates paragraphs"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene "Office" 1 1)
(parsed-action "some action")
(parsed-actor "Uncle Bob")
(parsed-dialog "dialog")
(parsed-scene "Desk" 2 1)
(parsed-actor "Sherlock")])) => [(new-scene-head "Office" 1 1)
(new-action "some action")
(new-actor "Uncle Bob")
(new-scene-head "Desk" 2 1)
(new-actor "Sherlock")])
(fact "a script with a continued actor reates an actor paragraph"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-continued-actor "Uncle Bob")])) => [(new-actor "Uncle Bob")])
(fact "can detect a scene header"
(scene-header? (parsed-scene "GS" 3 2)) => truthy)
(fact "can extract location from set"
(extract-location "Int. LOCATION - Day") => "LOCATION")
(fact "can extract location from set without time"
(extract-location "Int. LOCATION") => "LOCATION")
)
(facts "high level unit tests"
(fact "an empty script yeilds no scenes"
(build-scenes-from-script-xml (parsed-finalDraft [])) => [])
(fact "a script with just one scene heading yeilds one scene"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)])) => [{:character "", :dialogs 0, :notes "",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with two scene headings yeilds two scenes"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-scene "WSR" 3 2)])) => [{:character "", :dialogs 0, :notes "",
:page 1, :scene 2, :set "WSL", :title ""}
{:character "", :dialogs 0, :notes "",
:page 2, :scene 3, :set "WSR", :title ""}])
(fact "a script with a scene head and an actor yeilds an acted scene"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")])) => [{:character "UB", :dialogs 1, :notes "",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with more than one actor in a scene will count dialogs"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-continued-actor "UB")])) => [{:character "UB", :dialogs 2, :notes "",
:page 1, :scene 2, :set "WSL", :title ""}]))
(facts "action notes"
(fact "a script with a simple action in a scene has no effect"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "some action")])) => [{:character "UB", :dialogs 1, :notes "",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with a simple note action in a scene adds the note"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Note: a")])) => [{:character "UB", :dialogs 1, :notes "a",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with a complex note action in a scene adds the note"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Note: a Some Note")])) => [{:character "UB", :dialogs 1, :notes "a",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with several note actions in a scene adds the notes"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Note: a Some Note")
(parsed-action "note: b some other note")])) => [{:character "UB", :dialogs 1, :notes "a,b",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with a prop note adds the prop"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Note: P Some Prop")])) => [{:character "UB", :dialogs 1, :notes "P",
:page 1, :scene 2, :set "WSL", :title "", :props ["Some Prop"]}])
(fact "a script with two prop notes adds the props"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Note: P Some Prop 1")
(parsed-action "Note: P Some Prop 2")])) => [{:character "UB", :dialogs 1, :notes "P,P",
:page 1, :scene 2, :set "WSL", :title "",
:props ["Some Prop 1", "Some Prop 2"]}])
(fact "a script with a title action in a scene sets the title"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Title: some title")])) => [{:character "UB", :dialogs 1, :notes "",
:page 1, :scene 2, :set "WSL", :title "some title"}]))
(facts "warnings"
(fact "a script with more than one actor but with no action notes will create a warning"
(let [scenes (build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" "2" "1")
(parsed-actor "UB")
(parsed-actor "BU")]))
warnings (make-warnings scenes)]
warnings => [{:warning :multiple-dialogs-without-notes :scene "2" :page "1" :dialogs 2}]))
(fact "a script with more than one actor and with action notes will not create a warning"
(let [scenes (build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" "2" "1")
(parsed-actor "UB")
(parsed-actor "BU")
(parsed-action "Note: a Some Note")]))
warnings (make-warnings scenes)]
warnings => []))
(fact "a scene with no location will create a warning"
(let [scenes (build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "" "2" "1")
(parsed-actor "UB")]))
warnings (make-warnings scenes)]
warnings => [{:warning :empty-scene :scene "2" :page "1"}]))
(fact "a scene with no dialogs will create a warning"
(let [scenes (build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" "2" "1")]))
warnings (make-warnings scenes)]
warnings => [{:warning :no-dialogs :scene "2" :page "1"}]))
(fact "a scene with no scene number will create a warning"
(let [scenes (build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" "" "1")
(parsed-actor "UB")]))
warnings (make-warnings scenes)]
warnings => [{:warning :no-scene-number :page "1"}])))
(defn to-scene-lines [file-name]
(let [scenes (build-scenes-from-file file-name)]
(map to-scene-line scenes)))
(facts "acceptance tests"
(fact (to-scene-lines "script.xml") => ["FRONT DOOR\t\t0\t3\t1\t\tTHIS IS A TITLE"
"GS\tUNCLE BOB\t2\t4\t2\tNOTE\t"
"FRONT DOOR\tUNCLE BOB\t1\t5\t3\tN1,P,N2\t"])
(fact "props are found"
(let [scenes (build-scenes-from-file "script.xml")]
(get-all-props scenes) => ["my prop 1"]))
(fact (parse "script.xml") => parsed-script)
(fact (-main "script.xml") => nil)
(against-background
(before :contents (spit "script.xml" simple-script))
(after :contents (delete-file "script.xml")))) | null | https://raw.githubusercontent.com/unclebob/ScriptSchedule/f9bbe667cb4885bea8aea00e3ac4dabeccd75ee7/test/ScriptSchedule/test/core.clj | clojure | (ns ScriptSchedule.test.core
(:use [ScriptSchedule.core])
(:use [midje.sweet])
(:use [clojure.java.io])
(:use [clojure.xml]))
(def expected-header "Set\tCharacter\tDialogs\tScene\tPage\n")
(def simple-script
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>
<FinalDraft DocumentType=\"Script\" Template=\"No\" Version=\"1\">
<Content>
<Paragraph Number=\"3\" Type=\"Scene Heading\">
<SceneProperties Page=\"1\"/>
<Text>INT. FRONT DOOR - DAY</Text>
</Paragraph>
<Paragraph Type=\"Action\">
<Text>Title: This is a title</Text>
</Paragraph>
<gunk/>
<Paragraph Number=\"4\" Type=\"Scene Heading\">
<SceneProperties Page=\"2\"/>
<Text>INT. GS - DAY</Text>
</Paragraph>
<Paragraph Type=\"Action\">
<Text>some action</Text>
</Paragraph>
<Paragraph Type=\"Character\">
<Text>UNCLE BOB</Text>
</Paragraph>
<Paragraph Type=\"Dialogue\">
<Text>some dialog</Text>
</Paragraph>
<Paragraph Type=\"Action\">
<Text>Note: note another action</Text>
</Paragraph>
<Paragraph Type=\"Character\">
<Text>UNCLE BOB (</Text>
<Text AdornmentStyle=\"-1\">CONT�D</Text>
<Text>)</Text>
</Paragraph>
<Paragraph Type=\"Dialogue\">
<Text>more dialog</Text>
</Paragraph>
<Paragraph Number=\"5\" Type=\"Scene Heading\">
<SceneProperties Page=\"3\"/>
<Text>INT. FRONT DOOR - DAY</Text>
</Paragraph>
<Paragraph Type=\"Action\">
<Text>Note:n1</Text>
</Paragraph>
<Paragraph Type=\"Action\">
<Text>Note:P my prop 1</Text>
</Paragraph>\n
<Paragraph Type=\"Action\">
<Text>Note:n2</Text>
</Paragraph>
<Paragraph Type=\"Character\">
<Text>UNCLE BOB</Text>
</Paragraph>
<Paragraph Type=\"Dialogue\">
<Text>some dialog</Text>
</Paragraph>
</Content>
</FinalDraft>
")
(def simple-scene
(new-scene "GS" "UNCLE BOB" 2 4 2))
(fact (to-scene-line simple-scene) => "GS\tUNCLE BOB\t2\t4\t2\t\t")
(defn parsed-finalDraft [content]
{:tag :FinalDraft,
:attrs {:DocumentType "Script",
:Template "No",
:Version "1"},
:content [{:tag :Content,
:attrs nil,
:content content}]})
(defn parsed-scene-raw [set scene page]
{:tag :Paragraph,
:attrs {:Number scene,
:Type "Scene Heading"},
:content [{:tag :SceneProperties,
:attrs {:Page page},
:content nil}
{:tag :Text,
:attrs nil,
:content [set]}]})
(defn parsed-scene [set scene page]
(parsed-scene-raw (str "INT. " set " - DAY") scene page))
(defn parsed-tag [tag]
{:tag tag, :attrs nil, :content nil})
(defn parsed-action [action]
{:tag :Paragraph,
:attrs {:Type "Action"},
:content [{:tag :Text,
:attrs nil,
:content [action]}]})
(defn parsed-double-action [action1 action2]
{:tag :Paragraph,
:attrs {:Type "Action"},
:content [{:tag :Text,
:attrs nil,
:content [action1]}
{:tag :Text,
:attrs nil,
:content [action2]}]})
(defn parsed-actor [character]
{:tag :Paragraph,
:attrs {:Type "Character"},
:content [{:tag :Text,
:attrs nil,
:content [character]}]})
(defn parsed-continued-actor [character]
{:tag :Paragraph,
:attrs {:Type "Character"},
:content [{:tag :Text,
:attrs nil,
:content [(str character " (")]}
{:tag :Text,
:attrs {:AdornmentStyle "-1"},
:content ["CONT�D"]}
{:tag :Text,
:attrs nil,
:content [")"]}]})
(defn parsed-dialog [dialog]
{:tag :Paragraph,
:attrs {:Type "Dialogue"},
:content [{:tag :Text,
:attrs nil,
:content [dialog]}]})
(def parsed-script
(parsed-finalDraft
[(parsed-scene "FRONT DOOR" "3" "1")
(parsed-action "Title: This is a title")
(parsed-tag :gunk)
(parsed-scene "GS", "4" "2")
(parsed-action "some action")
(parsed-actor "UNCLE BOB")
(parsed-dialog "some dialog")
(parsed-action "Note: note another action")
(parsed-continued-actor "UNCLE BOB")
(parsed-dialog "more dialog")
(parsed-scene "FRONT DOOR" "5" "3")
(parsed-action "Note:n1")
(parsed-action "Note:P my prop 1")
(parsed-action "Note:n2")
(parsed-actor "UNCLE BOB")
(parsed-dialog "some dialog")]))
(facts "low level unit tests"
(fact "an empty script has no paragraphs"
(paragraphs-from-script (parsed-finalDraft [])) => [])
(fact "a script with no scene headings, characters, or actions has no paragraphs"
(paragraphs-from-script (parsed-finalDraft [(parsed-tag :gunk)
(parsed-dialog "dialog")])) => [])
(fact "a script with one scene heading gives one scene paragraph"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene "GS" 3 2)])) => [(new-scene-head "GS" 3 2)])
(fact "a scene without a daytime is parsed correctly"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene-raw "INT. GS" 3 2)])) => [(new-scene-head "GS" 3 2)])
(fact "a scene without a int/ext is parsed correctly"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene-raw "GS - DAY" 3 2)])) => [(new-scene-head "GS" 3 2)])
(fact "a scene without a daytime or int/ext is parsed correctly"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene-raw "GS" 3 2)])) => [(new-scene-head "GS" 3 2)])
(fact "a script with two scene headings gives two scene paragraphs"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene "GS" 1 1)
(parsed-scene "FRONT DOOR" 2 1)])) => [(new-scene-head "GS" 1 1) (new-scene-head "FRONT DOOR" 2 1)])
(fact "a script with one character gives a character paragraph"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-actor "UB")])) => [(new-actor "UB")])
(fact "a script with one action gives an action paragraph"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-action "action")])) => [(new-action "action")])
(fact "a script with one action having two text tags gives an action paragraph"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-double-action "action1" "-action2")])) => [(new-action "action1-action2")])
(fact "a script with scene headings and characters creates paragraphs"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-scene "Office" 1 1)
(parsed-action "some action")
(parsed-actor "Uncle Bob")
(parsed-dialog "dialog")
(parsed-scene "Desk" 2 1)
(parsed-actor "Sherlock")])) => [(new-scene-head "Office" 1 1)
(new-action "some action")
(new-actor "Uncle Bob")
(new-scene-head "Desk" 2 1)
(new-actor "Sherlock")])
(fact "a script with a continued actor reates an actor paragraph"
(paragraphs-from-script
(parsed-finalDraft
[(parsed-continued-actor "Uncle Bob")])) => [(new-actor "Uncle Bob")])
(fact "can detect a scene header"
(scene-header? (parsed-scene "GS" 3 2)) => truthy)
(fact "can extract location from set"
(extract-location "Int. LOCATION - Day") => "LOCATION")
(fact "can extract location from set without time"
(extract-location "Int. LOCATION") => "LOCATION")
)
(facts "high level unit tests"
(fact "an empty script yeilds no scenes"
(build-scenes-from-script-xml (parsed-finalDraft [])) => [])
(fact "a script with just one scene heading yeilds one scene"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)])) => [{:character "", :dialogs 0, :notes "",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with two scene headings yeilds two scenes"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-scene "WSR" 3 2)])) => [{:character "", :dialogs 0, :notes "",
:page 1, :scene 2, :set "WSL", :title ""}
{:character "", :dialogs 0, :notes "",
:page 2, :scene 3, :set "WSR", :title ""}])
(fact "a script with a scene head and an actor yeilds an acted scene"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")])) => [{:character "UB", :dialogs 1, :notes "",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with more than one actor in a scene will count dialogs"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-continued-actor "UB")])) => [{:character "UB", :dialogs 2, :notes "",
:page 1, :scene 2, :set "WSL", :title ""}]))
(facts "action notes"
(fact "a script with a simple action in a scene has no effect"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "some action")])) => [{:character "UB", :dialogs 1, :notes "",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with a simple note action in a scene adds the note"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Note: a")])) => [{:character "UB", :dialogs 1, :notes "a",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with a complex note action in a scene adds the note"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Note: a Some Note")])) => [{:character "UB", :dialogs 1, :notes "a",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with several note actions in a scene adds the notes"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Note: a Some Note")
(parsed-action "note: b some other note")])) => [{:character "UB", :dialogs 1, :notes "a,b",
:page 1, :scene 2, :set "WSL", :title ""}])
(fact "a script with a prop note adds the prop"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Note: P Some Prop")])) => [{:character "UB", :dialogs 1, :notes "P",
:page 1, :scene 2, :set "WSL", :title "", :props ["Some Prop"]}])
(fact "a script with two prop notes adds the props"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Note: P Some Prop 1")
(parsed-action "Note: P Some Prop 2")])) => [{:character "UB", :dialogs 1, :notes "P,P",
:page 1, :scene 2, :set "WSL", :title "",
:props ["Some Prop 1", "Some Prop 2"]}])
(fact "a script with a title action in a scene sets the title"
(build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" 2 1)
(parsed-actor "UB")
(parsed-action "Title: some title")])) => [{:character "UB", :dialogs 1, :notes "",
:page 1, :scene 2, :set "WSL", :title "some title"}]))
(facts "warnings"
(fact "a script with more than one actor but with no action notes will create a warning"
(let [scenes (build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" "2" "1")
(parsed-actor "UB")
(parsed-actor "BU")]))
warnings (make-warnings scenes)]
warnings => [{:warning :multiple-dialogs-without-notes :scene "2" :page "1" :dialogs 2}]))
(fact "a script with more than one actor and with action notes will not create a warning"
(let [scenes (build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" "2" "1")
(parsed-actor "UB")
(parsed-actor "BU")
(parsed-action "Note: a Some Note")]))
warnings (make-warnings scenes)]
warnings => []))
(fact "a scene with no location will create a warning"
(let [scenes (build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "" "2" "1")
(parsed-actor "UB")]))
warnings (make-warnings scenes)]
warnings => [{:warning :empty-scene :scene "2" :page "1"}]))
(fact "a scene with no dialogs will create a warning"
(let [scenes (build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" "2" "1")]))
warnings (make-warnings scenes)]
warnings => [{:warning :no-dialogs :scene "2" :page "1"}]))
(fact "a scene with no scene number will create a warning"
(let [scenes (build-scenes-from-script-xml
(parsed-finalDraft
[(parsed-scene "WSL" "" "1")
(parsed-actor "UB")]))
warnings (make-warnings scenes)]
warnings => [{:warning :no-scene-number :page "1"}])))
(defn to-scene-lines [file-name]
(let [scenes (build-scenes-from-file file-name)]
(map to-scene-line scenes)))
(facts "acceptance tests"
(fact (to-scene-lines "script.xml") => ["FRONT DOOR\t\t0\t3\t1\t\tTHIS IS A TITLE"
"GS\tUNCLE BOB\t2\t4\t2\tNOTE\t"
"FRONT DOOR\tUNCLE BOB\t1\t5\t3\tN1,P,N2\t"])
(fact "props are found"
(let [scenes (build-scenes-from-file "script.xml")]
(get-all-props scenes) => ["my prop 1"]))
(fact (parse "script.xml") => parsed-script)
(fact (-main "script.xml") => nil)
(against-background
(before :contents (spit "script.xml" simple-script))
(after :contents (delete-file "script.xml")))) |
|
9325b2b9c99d5a9bb9ffa20cd77039868cb349efd2fe1587bb60cd468e56b01c | 40ants/ci | lisp-job.lisp | (defpackage #:40ants-ci/jobs/lisp-job
(:use #:cl)
(:import-from #:40ants-ci/jobs/job
#:os
#:lisp
#:quicklisp)
(:import-from #:40ants-ci/steps/action
#:action)
(:import-from #:40ants-ci/utils
#:single
#:dedent
#:current-system-name)
(:import-from #:40ants-ci/steps/sh
#:sh)
(:import-from #:40ants-ci/vars
#:*use-cache*)
(:export
#:lisp-job
#:asdf-system))
(in-package 40ants-ci/jobs/lisp-job)
(defclass lisp-job (40ants-ci/jobs/job:job)
((qlfile :initarg :qlfile
:initform nil
:reader qlfile)
(asdf-system :initarg :asdf-system
:initform nil
:type (or null string)
:reader asdf-system)
(asdf-version :initarg :asdf-version
:initform nil
:type (or null string)
:documentation "ASDF version to use when setting up Lisp environment. If NIL, then the latest will be used."
:reader asdf-version)
(roswell-version :initarg :roswell-version
:initform nil
:type (or null string)
:documentation "Roswell version to use when setting up Lisp environment. If NIL, then will be used version, pinned in SETUP-LISP github action."
:reader roswell-version)
(qlot-version :initarg :qlot-version
:initform nil
:type (or null string)
:documentation "Qlot version to use when setting up Lisp environment. If NIL, then will be used version, pinned in SETUP-LISP github action."
:reader qlot-version))
(:documentation "This job checkouts the sources, installs Roswell and Qlot. Also, it caches results between runs."))
(defmethod asdf-system :around ((job lisp-job))
(or (call-next-method)
(current-system-name)))
(defgeneric make-cache-key (job)
(:method ((job lisp-job))
(with-output-to-string (s)
(write-string "a-${{ steps.current-month.outputs.value }}-${{ env.cache-name }}-" s)
(let ((os (os job)))
(if (single os)
(format s "~A-" (first os))
(write-string "${{ matrix.os }}-" s)))
(let ((quicklisp (quicklisp job)))
(if (single quicklisp)
(format s "~A-" (first quicklisp))
(write-string "${{ matrix.quicklisp }}-" s)))
(let ((lisp (lisp job)))
(if (single lisp)
(format s "~A-" (first lisp))
(write-string "${{ matrix.lisp }}-" s)))
;; Here we need to hash *.asd files to make cache different
;; for each project. Cache content will depend not only
;; on qlfile, but also on ASD systems installed during
;; the build.
(write-string "${{ hashFiles('qlfile.lock', '*.asd') }}" s))))
(defgeneric make-cache-steps (job)
(:method ((job lisp-job))
(when 40ants-ci/vars:*use-cache*
(let ((paths-to-cache
(list "qlfile"
"qlfile.lock"
"~/.cache/common-lisp/"
"~/.roswell"
"/usr/local/etc/roswell"
"/usr/local/bin/ros"
On OSX Roswell is installed
using Homebrew and /usr / local / bin /
;; is a symlink into a Cellar directory:
"/usr/local/Cellar/roswell"
".qlot")))
(list (sh "Grant All Perms to Make Cache Restoring Possible"
"sudo mkdir -p /usr/local/etc/roswell
sudo chown \"${USER}\" /usr/local/etc/roswell
# Here the ros binary will be restored:
sudo chown \"${USER}\" /usr/local/bin")
(sh "Get Current Month"
"echo \"value=$(date -u \"+%Y-%m\")\" >> $GITHUB_OUTPUT"
:id "current-month")
(action "Cache Roswell Setup"
"actions/cache@v3"
:id "cache"
:path (format nil "~{~A~^~%~}" paths-to-cache)
:key (make-cache-key job))
(sh "Restore Path To Cached Files"
"echo $HOME/.roswell/bin >> $GITHUB_PATH
echo .qlot/bin >> $GITHUB_PATH"
:if "steps.cache.outputs.cache-hit == 'true'"))))))
(defmethod 40ants-ci/jobs/job:steps ((job lisp-job))
(append (list
(action "Checkout Code"
"actions/checkout@v3"))
(make-cache-steps job)
(list
(action "Setup Common Lisp Environment"
"40ants/setup-lisp@v2"
:asdf-system (asdf-system job)
:asdf-version (asdf-version job)
:roswell-version (roswell-version job)
:qlot-version (qlot-version job)
:qlfile-template (when (qlfile job)
(dedent (qlfile job)))
:if (when *use-cache*
"steps.cache.outputs.cache-hit != 'true'")))
(call-next-method)))
| null | https://raw.githubusercontent.com/40ants/ci/2e9bc031247c394012677f1629e2a278aadb0c81/src/jobs/lisp-job.lisp | lisp | Here we need to hash *.asd files to make cache different
for each project. Cache content will depend not only
on qlfile, but also on ASD systems installed during
the build.
is a symlink into a Cellar directory: | (defpackage #:40ants-ci/jobs/lisp-job
(:use #:cl)
(:import-from #:40ants-ci/jobs/job
#:os
#:lisp
#:quicklisp)
(:import-from #:40ants-ci/steps/action
#:action)
(:import-from #:40ants-ci/utils
#:single
#:dedent
#:current-system-name)
(:import-from #:40ants-ci/steps/sh
#:sh)
(:import-from #:40ants-ci/vars
#:*use-cache*)
(:export
#:lisp-job
#:asdf-system))
(in-package 40ants-ci/jobs/lisp-job)
(defclass lisp-job (40ants-ci/jobs/job:job)
((qlfile :initarg :qlfile
:initform nil
:reader qlfile)
(asdf-system :initarg :asdf-system
:initform nil
:type (or null string)
:reader asdf-system)
(asdf-version :initarg :asdf-version
:initform nil
:type (or null string)
:documentation "ASDF version to use when setting up Lisp environment. If NIL, then the latest will be used."
:reader asdf-version)
(roswell-version :initarg :roswell-version
:initform nil
:type (or null string)
:documentation "Roswell version to use when setting up Lisp environment. If NIL, then will be used version, pinned in SETUP-LISP github action."
:reader roswell-version)
(qlot-version :initarg :qlot-version
:initform nil
:type (or null string)
:documentation "Qlot version to use when setting up Lisp environment. If NIL, then will be used version, pinned in SETUP-LISP github action."
:reader qlot-version))
(:documentation "This job checkouts the sources, installs Roswell and Qlot. Also, it caches results between runs."))
(defmethod asdf-system :around ((job lisp-job))
(or (call-next-method)
(current-system-name)))
(defgeneric make-cache-key (job)
(:method ((job lisp-job))
(with-output-to-string (s)
(write-string "a-${{ steps.current-month.outputs.value }}-${{ env.cache-name }}-" s)
(let ((os (os job)))
(if (single os)
(format s "~A-" (first os))
(write-string "${{ matrix.os }}-" s)))
(let ((quicklisp (quicklisp job)))
(if (single quicklisp)
(format s "~A-" (first quicklisp))
(write-string "${{ matrix.quicklisp }}-" s)))
(let ((lisp (lisp job)))
(if (single lisp)
(format s "~A-" (first lisp))
(write-string "${{ matrix.lisp }}-" s)))
(write-string "${{ hashFiles('qlfile.lock', '*.asd') }}" s))))
(defgeneric make-cache-steps (job)
(:method ((job lisp-job))
(when 40ants-ci/vars:*use-cache*
(let ((paths-to-cache
(list "qlfile"
"qlfile.lock"
"~/.cache/common-lisp/"
"~/.roswell"
"/usr/local/etc/roswell"
"/usr/local/bin/ros"
On OSX Roswell is installed
using Homebrew and /usr / local / bin /
"/usr/local/Cellar/roswell"
".qlot")))
(list (sh "Grant All Perms to Make Cache Restoring Possible"
"sudo mkdir -p /usr/local/etc/roswell
sudo chown \"${USER}\" /usr/local/etc/roswell
# Here the ros binary will be restored:
sudo chown \"${USER}\" /usr/local/bin")
(sh "Get Current Month"
"echo \"value=$(date -u \"+%Y-%m\")\" >> $GITHUB_OUTPUT"
:id "current-month")
(action "Cache Roswell Setup"
"actions/cache@v3"
:id "cache"
:path (format nil "~{~A~^~%~}" paths-to-cache)
:key (make-cache-key job))
(sh "Restore Path To Cached Files"
"echo $HOME/.roswell/bin >> $GITHUB_PATH
echo .qlot/bin >> $GITHUB_PATH"
:if "steps.cache.outputs.cache-hit == 'true'"))))))
(defmethod 40ants-ci/jobs/job:steps ((job lisp-job))
(append (list
(action "Checkout Code"
"actions/checkout@v3"))
(make-cache-steps job)
(list
(action "Setup Common Lisp Environment"
"40ants/setup-lisp@v2"
:asdf-system (asdf-system job)
:asdf-version (asdf-version job)
:roswell-version (roswell-version job)
:qlot-version (qlot-version job)
:qlfile-template (when (qlfile job)
(dedent (qlfile job)))
:if (when *use-cache*
"steps.cache.outputs.cache-hit != 'true'")))
(call-next-method)))
|
c76ec31afe2c6c26fb84f93918d9fb745c03bce7020f5c77dc465dfabb3acc50 | janegca/htdp2e | Exercise-182-CompleteInDictionary.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname Exercise-182-CompleteInDictionary) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")))))
Exercise 182 .
;
Complete the design of the in - dictionary function specified in figure 50 .
Hint Figure 49 shows how to turn the 2htdp / batch - io library to read the
; dictionary on your computer into a list of strings.
;
(define DICTIONARY-LOCATION "words.txt")
(define DICTIONARY-AS-LIST (read-lines DICTIONARY-LOCATION))
; List-of-strings -> List-of-strings
; pick out all those Strings that occur in the dictionary
(check-expect (in-dictionary '()) '())
(check-expect (in-dictionary (list "act" "tca" "cat"))
(list "act" "cat"))
(define (in-dictionary los)
(cond [(empty? los) '()]
[(member? (first los) DICTIONARY-AS-LIST)
(cons (first los) (in-dictionary (rest los)))]
[else (in-dictionary (rest los))]))
| null | https://raw.githubusercontent.com/janegca/htdp2e/2d50378135edc2b8b1816204021f8763f8b2707b/02-ArbitrarilyLargeData/Exercise-182-CompleteInDictionary.rkt | racket | about the language level of this file in a form that our tools can easily process.
dictionary on your computer into a list of strings.
List-of-strings -> List-of-strings
pick out all those Strings that occur in the dictionary | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname Exercise-182-CompleteInDictionary) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")))))
Exercise 182 .
Complete the design of the in - dictionary function specified in figure 50 .
Hint Figure 49 shows how to turn the 2htdp / batch - io library to read the
(define DICTIONARY-LOCATION "words.txt")
(define DICTIONARY-AS-LIST (read-lines DICTIONARY-LOCATION))
(check-expect (in-dictionary '()) '())
(check-expect (in-dictionary (list "act" "tca" "cat"))
(list "act" "cat"))
(define (in-dictionary los)
(cond [(empty? los) '()]
[(member? (first los) DICTIONARY-AS-LIST)
(cons (first los) (in-dictionary (rest los)))]
[else (in-dictionary (rest los))]))
|
b518eaad422c148e4dc3a040e4ba3d0e017a1fc9060696c312c9b715c37bbea9 | futurice/haskell-mega-repo | Machine.hs | {-# LANGUAGE GADTs #-}
-- | Implementation of the machine API.
module Futurice.App.FUM.Machine (machineServer) where
import Control.Concurrent.STM (readTVarIO)
import Control.Monad.Reader (Reader, asks, runReader)
import Data.Set.Lens (setOf)
import Futurice.Prelude
import Futurice.Signed (SecretKey, Signed, signed, sign)
import Prelude ()
import Servant
import Futurice.App.FUM.API
import Futurice.App.FUM.Config
import Futurice.App.FUM.Ctx
import Futurice.App.FUM.Types
import Futurice.FUM.MachineAPI
machineServer :: Ctx -> Server FumCarbonMachineApi
machineServer ctx = machineServer' ctx
machineServer' :: Ctx -> Server FUMMachineAPI
machineServer' ctx = hoistServer fumMachineApi nt $ traverse haxl
:<|> eg
where
nt :: Reader World a -> Handler a
nt m = liftIO $ do
w <- readTVarIO (ctxWorld ctx)
return (runReader m w)
haxl :: SomeFUM6 -> Reader World SomeFUM6Response
haxl (SomeFUM6 req) = SomeFUM6Response req <$> haxl' req
haxl' :: FUM6 a -> Reader World a
haxl' (FUMGroupEmployees n) = signed <$> eg n
secretKey :: SecretKey
secretKey = cfgSecretKey (ctxConfig ctx)
eg :: GroupName -> Reader World (Signed (Set Login))
eg name = asks
$ sign [ secretKey ]
. setOf (worldGroups . ix name . groupEmployees . folded)
| null | https://raw.githubusercontent.com/futurice/haskell-mega-repo/2647723f12f5435e2edc373f6738386a9668f603/fum-carbon-app/src/Futurice/App/FUM/Machine.hs | haskell | # LANGUAGE GADTs #
| Implementation of the machine API. | module Futurice.App.FUM.Machine (machineServer) where
import Control.Concurrent.STM (readTVarIO)
import Control.Monad.Reader (Reader, asks, runReader)
import Data.Set.Lens (setOf)
import Futurice.Prelude
import Futurice.Signed (SecretKey, Signed, signed, sign)
import Prelude ()
import Servant
import Futurice.App.FUM.API
import Futurice.App.FUM.Config
import Futurice.App.FUM.Ctx
import Futurice.App.FUM.Types
import Futurice.FUM.MachineAPI
machineServer :: Ctx -> Server FumCarbonMachineApi
machineServer ctx = machineServer' ctx
machineServer' :: Ctx -> Server FUMMachineAPI
machineServer' ctx = hoistServer fumMachineApi nt $ traverse haxl
:<|> eg
where
nt :: Reader World a -> Handler a
nt m = liftIO $ do
w <- readTVarIO (ctxWorld ctx)
return (runReader m w)
haxl :: SomeFUM6 -> Reader World SomeFUM6Response
haxl (SomeFUM6 req) = SomeFUM6Response req <$> haxl' req
haxl' :: FUM6 a -> Reader World a
haxl' (FUMGroupEmployees n) = signed <$> eg n
secretKey :: SecretKey
secretKey = cfgSecretKey (ctxConfig ctx)
eg :: GroupName -> Reader World (Signed (Set Login))
eg name = asks
$ sign [ secretKey ]
. setOf (worldGroups . ix name . groupEmployees . folded)
|
5112fe9487f2bfb6b5e9dbd5659bbd6f2b5f05e10f049c31a264f57b43d229ae | freckle/stackctl | CLI.hs | module Stackctl.CLI
( App
, optionsL
, AppT
, runAppT
) where
import Stackctl.Prelude
import qualified Blammo.Logging.LogSettings.Env as LoggingEnv
import Control.Monad.Catch (MonadCatch)
import Control.Monad.Trans.Resource (ResourceT, runResourceT)
import Stackctl.AWS
import Stackctl.AWS.Scope
import Stackctl.ColorOption
import Stackctl.Config
import Stackctl.DirectoryOption
import Stackctl.FilterOption
import Stackctl.VerboseOption
data App options = App
{ appLogger :: Logger
, appConfig :: Config
, appOptions :: options
, appAwsScope :: AwsScope
, appAwsEnv :: AwsEnv
}
optionsL :: Lens' (App options) options
optionsL = lens appOptions $ \x y -> x { appOptions = y }
instance HasLogger (App options) where
loggerL = lens appLogger $ \x y -> x { appLogger = y }
instance HasConfig (App options) where
configL = lens appConfig $ \x y -> x { appConfig = y }
instance HasAwsScope (App options) where
awsScopeL = lens appAwsScope $ \x y -> x { appAwsScope = y }
instance HasAwsEnv (App options) where
awsEnvL = lens appAwsEnv $ \x y -> x { appAwsEnv = y }
instance HasDirectoryOption options => HasDirectoryOption (App options) where
directoryOptionL = optionsL . directoryOptionL
instance HasFilterOption options => HasFilterOption (App options) where
filterOptionL = optionsL . filterOptionL
instance HasColorOption options => HasColorOption (App options) where
colorOptionL = optionsL . colorOptionL
instance HasVerboseOption options => HasVerboseOption (App options) where
verboseOptionL = optionsL . verboseOptionL
newtype AppT app m a = AppT
{ unAppT :: ReaderT app (LoggingT (ResourceT m)) a
}
deriving newtype
( Functor
, Applicative
, Monad
, MonadIO
, MonadUnliftIO
, MonadResource
, MonadReader app
, MonadLogger
, MonadThrow
, MonadCatch
, MonadMask
)
runAppT
:: ( MonadMask m
, MonadUnliftIO m
, HasColorOption options
, HasVerboseOption options
)
=> options
-> AppT (App options) m a
-> m a
runAppT options f = do
envLogSettings <-
liftIO
. LoggingEnv.parseWith
. setLogSettingsConcurrency (Just 1)
$ defaultLogSettings
logger <- newLogger $ adjustLogSettings
(options ^. colorOptionL)
(options ^. verboseOptionL)
envLogSettings
app <- runResourceT $ runLoggerLoggingT logger $ do
aws <- awsEnvDiscover
App logger
<$> loadConfigOrExit
<*> pure options
<*> runReaderT fetchAwsScope aws
<*> pure aws
let
AwsScope {..} = appAwsScope app
context =
[ "region" .= awsRegion
, "accountId" .= awsAccountId
, "accountName" .= awsAccountName
]
runResourceT
$ runLoggerLoggingT app
$ flip runReaderT app
$ withThreadContext context
$ unAppT f
adjustLogSettings
:: Maybe ColorOption -> Verbosity -> LogSettings -> LogSettings
adjustLogSettings mco v =
maybe id (setLogSettingsColor . unColorOption) mco . verbositySetLogLevels v
| null | https://raw.githubusercontent.com/freckle/stackctl/b04e1790dc523cea39e07c868b4fa328f4e453cb/src/Stackctl/CLI.hs | haskell | module Stackctl.CLI
( App
, optionsL
, AppT
, runAppT
) where
import Stackctl.Prelude
import qualified Blammo.Logging.LogSettings.Env as LoggingEnv
import Control.Monad.Catch (MonadCatch)
import Control.Monad.Trans.Resource (ResourceT, runResourceT)
import Stackctl.AWS
import Stackctl.AWS.Scope
import Stackctl.ColorOption
import Stackctl.Config
import Stackctl.DirectoryOption
import Stackctl.FilterOption
import Stackctl.VerboseOption
data App options = App
{ appLogger :: Logger
, appConfig :: Config
, appOptions :: options
, appAwsScope :: AwsScope
, appAwsEnv :: AwsEnv
}
optionsL :: Lens' (App options) options
optionsL = lens appOptions $ \x y -> x { appOptions = y }
instance HasLogger (App options) where
loggerL = lens appLogger $ \x y -> x { appLogger = y }
instance HasConfig (App options) where
configL = lens appConfig $ \x y -> x { appConfig = y }
instance HasAwsScope (App options) where
awsScopeL = lens appAwsScope $ \x y -> x { appAwsScope = y }
instance HasAwsEnv (App options) where
awsEnvL = lens appAwsEnv $ \x y -> x { appAwsEnv = y }
instance HasDirectoryOption options => HasDirectoryOption (App options) where
directoryOptionL = optionsL . directoryOptionL
instance HasFilterOption options => HasFilterOption (App options) where
filterOptionL = optionsL . filterOptionL
instance HasColorOption options => HasColorOption (App options) where
colorOptionL = optionsL . colorOptionL
instance HasVerboseOption options => HasVerboseOption (App options) where
verboseOptionL = optionsL . verboseOptionL
newtype AppT app m a = AppT
{ unAppT :: ReaderT app (LoggingT (ResourceT m)) a
}
deriving newtype
( Functor
, Applicative
, Monad
, MonadIO
, MonadUnliftIO
, MonadResource
, MonadReader app
, MonadLogger
, MonadThrow
, MonadCatch
, MonadMask
)
runAppT
:: ( MonadMask m
, MonadUnliftIO m
, HasColorOption options
, HasVerboseOption options
)
=> options
-> AppT (App options) m a
-> m a
runAppT options f = do
envLogSettings <-
liftIO
. LoggingEnv.parseWith
. setLogSettingsConcurrency (Just 1)
$ defaultLogSettings
logger <- newLogger $ adjustLogSettings
(options ^. colorOptionL)
(options ^. verboseOptionL)
envLogSettings
app <- runResourceT $ runLoggerLoggingT logger $ do
aws <- awsEnvDiscover
App logger
<$> loadConfigOrExit
<*> pure options
<*> runReaderT fetchAwsScope aws
<*> pure aws
let
AwsScope {..} = appAwsScope app
context =
[ "region" .= awsRegion
, "accountId" .= awsAccountId
, "accountName" .= awsAccountName
]
runResourceT
$ runLoggerLoggingT app
$ flip runReaderT app
$ withThreadContext context
$ unAppT f
adjustLogSettings
:: Maybe ColorOption -> Verbosity -> LogSettings -> LogSettings
adjustLogSettings mco v =
maybe id (setLogSettingsColor . unColorOption) mco . verbositySetLogLevels v
|
|
2481e0240351420e89b30907f26962baf2f1ad4c158c8fea3a2320d362f100a5 | racket/typed-racket | tc-subst.rkt | #lang racket/base
;; Functions in this file implement the substitution function in
figure 8 , pg 8 of " Logical Types for Untyped Languages "
(require "../utils/utils.rkt"
"../utils/tc-utils.rkt"
racket/match
(contract-req)
"../env/lexical-env.rkt"
"../types/utils.rkt"
"../types/prop-ops.rkt"
"../types/subtype.rkt"
"../types/path-type.rkt"
"../types/subtract.rkt"
"../types/overlap.rkt"
(except-in "../types/abbrev.rkt" -> ->* one-of/c)
(only-in "../infer/infer.rkt" intersect restrict)
"../rep/core-rep.rkt"
"../rep/type-rep.rkt"
"../rep/object-rep.rkt"
"../rep/prop-rep.rkt"
"../rep/rep-utils.rkt"
"../rep/values-rep.rkt")
(provide instantiate-obj+simplify)
(provide/cond-contract
[values->tc-results (->* (SomeValues? (listof OptObject?))
((listof Type?))
full-tc-results/c)]
[values->tc-results/explicit-subst
(-> SomeValues?
(listof (cons/c exact-nonnegative-integer?
(cons/c OptObject?
Type?)))
full-tc-results/c)]
[erase-identifiers (-> tc-results/c
(listof identifier?)
tc-results/c)])
;; Substitutes the given objects into the values and turns it into a
;; tc-result. This matches up to the substitutions in the T-App rule
;; from the ICFP paper.
;; NOTE! 'os' should contain no unbound relative addresses (i.e. "free"
indices ) as those indices will NOT be updated if they
;; are substituted under binders.
(define (values->tc-results v objs [types '()])
(values->tc-results/explicit-subst
v
(for/list ([o (in-list objs)]
[t (in-list/rest types Univ)]
[idx (in-naturals)])
(list* idx o t))))
(define (values->tc-results/explicit-subst v subst)
(define res->tc-res
(match-lambda
[(Result: t ps o n-exi) (-tc-result t ps o (not (zero? n-exi)))]))
(match (instantiate-obj+simplify v subst)
[(AnyValues: p)
(-tc-any-results p)]
[(Values: rs)
(-tc-results (map res->tc-res rs) #f)]
[(ValuesDots: rs dty dbound)
(-tc-results (map res->tc-res rs) (make-RestDots dty dbound))]))
(define (erase-identifiers res names)
(substitute-names res names (for/list ([_ (in-list names)])
-empty-obj)))
(define (instantiate-obj+simplify rep mapping)
lookup : if idx has a mapping ,
;; then returns (cons/c OptObject? Type?),
;; else returns #f
(define (lookup idx) (match (assv idx mapping)
[(cons _ entry) entry]
[_ #f]))
(let subst/lvl ([rep rep] [lvl 0])
(define (subst rep) (subst/lvl rep lvl))
(match rep
;; Functions
;; increment the level of the substituted object
[(Arrow: dom rst kws rng rng-T+)
(make-Arrow (map subst dom)
(and rst (subst rst))
(map subst kws)
(subst/lvl rng (add1 lvl))
rng-T+)]
[(DepFun: dom pre rng)
(make-DepFun (for/list ([d (in-list dom)])
(subst/lvl d (add1 lvl)))
(subst/lvl pre (add1 lvl))
(subst/lvl rng (add1 lvl)))]
[(Intersection: ts raw-prop)
(-refine (make-Intersection (map subst ts))
(subst/lvl raw-prop (add1 lvl)))]
[(Path: flds (cons (== lvl) (app lookup (cons o _))))
(make-Path (map subst flds) o)]
;; restrict with the type for results and props
[(TypeProp: (Path: flds (cons (== lvl) (app lookup (? pair? entry))))
prop-ty)
(define o (make-Path (map subst flds) (car entry)))
(define o-ty (or (path-type flds (cdr entry)) Univ))
(define new-prop-ty (intersect prop-ty o-ty o))
(cond
[(Bottom? new-prop-ty) -ff]
[(and (not (F? prop-ty)) (subtype o-ty prop-ty)) -tt]
[(Empty? o) -tt]
[else (-is-type o new-prop-ty)])]
[(NotTypeProp: (Path: flds (cons (== lvl) (app lookup (? pair? entry))))
prop-ty)
(define o (make-Path (map subst flds) (car entry)))
(define o-ty (or (path-type flds (cdr entry)) Univ))
(define new-o-ty (subtract o-ty prop-ty o))
(define new-prop-ty (restrict prop-ty o-ty o))
(cond
[(or (Bottom? new-o-ty)
(Univ? new-prop-ty))
-ff]
[(Empty? o) -tt]
[else (-not-type o new-prop-ty)])]
[(tc-result: orig-t
orig-ps
(Path: flds (cons (== lvl) (app lookup (? pair? entry)))))
(define o (make-Path (map subst flds) (car entry)))
(define t (intersect orig-t (or (path-type flds (cdr entry)) Univ)))
(define ps (subst orig-ps))
(-tc-result t ps o)]
[(Result: orig-t
orig-ps
(Path: flds (cons (== lvl) (app lookup (? pair? entry)))))
(define o (make-Path (map subst flds) (car entry)))
(define t (intersect orig-t (or (path-type flds (cdr entry)) Univ)))
(define ps (subst orig-ps))
(make-Result t ps o)]
;; else default fold over subfields
[_ (Rep-fmap rep subst)])))
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-lib/typed-racket/typecheck/tc-subst.rkt | racket | Functions in this file implement the substitution function in
Substitutes the given objects into the values and turns it into a
tc-result. This matches up to the substitutions in the T-App rule
from the ICFP paper.
NOTE! 'os' should contain no unbound relative addresses (i.e. "free"
are substituted under binders.
then returns (cons/c OptObject? Type?),
else returns #f
Functions
increment the level of the substituted object
restrict with the type for results and props
else default fold over subfields | #lang racket/base
figure 8 , pg 8 of " Logical Types for Untyped Languages "
(require "../utils/utils.rkt"
"../utils/tc-utils.rkt"
racket/match
(contract-req)
"../env/lexical-env.rkt"
"../types/utils.rkt"
"../types/prop-ops.rkt"
"../types/subtype.rkt"
"../types/path-type.rkt"
"../types/subtract.rkt"
"../types/overlap.rkt"
(except-in "../types/abbrev.rkt" -> ->* one-of/c)
(only-in "../infer/infer.rkt" intersect restrict)
"../rep/core-rep.rkt"
"../rep/type-rep.rkt"
"../rep/object-rep.rkt"
"../rep/prop-rep.rkt"
"../rep/rep-utils.rkt"
"../rep/values-rep.rkt")
(provide instantiate-obj+simplify)
(provide/cond-contract
[values->tc-results (->* (SomeValues? (listof OptObject?))
((listof Type?))
full-tc-results/c)]
[values->tc-results/explicit-subst
(-> SomeValues?
(listof (cons/c exact-nonnegative-integer?
(cons/c OptObject?
Type?)))
full-tc-results/c)]
[erase-identifiers (-> tc-results/c
(listof identifier?)
tc-results/c)])
indices ) as those indices will NOT be updated if they
(define (values->tc-results v objs [types '()])
(values->tc-results/explicit-subst
v
(for/list ([o (in-list objs)]
[t (in-list/rest types Univ)]
[idx (in-naturals)])
(list* idx o t))))
(define (values->tc-results/explicit-subst v subst)
(define res->tc-res
(match-lambda
[(Result: t ps o n-exi) (-tc-result t ps o (not (zero? n-exi)))]))
(match (instantiate-obj+simplify v subst)
[(AnyValues: p)
(-tc-any-results p)]
[(Values: rs)
(-tc-results (map res->tc-res rs) #f)]
[(ValuesDots: rs dty dbound)
(-tc-results (map res->tc-res rs) (make-RestDots dty dbound))]))
(define (erase-identifiers res names)
(substitute-names res names (for/list ([_ (in-list names)])
-empty-obj)))
(define (instantiate-obj+simplify rep mapping)
lookup : if idx has a mapping ,
(define (lookup idx) (match (assv idx mapping)
[(cons _ entry) entry]
[_ #f]))
(let subst/lvl ([rep rep] [lvl 0])
(define (subst rep) (subst/lvl rep lvl))
(match rep
[(Arrow: dom rst kws rng rng-T+)
(make-Arrow (map subst dom)
(and rst (subst rst))
(map subst kws)
(subst/lvl rng (add1 lvl))
rng-T+)]
[(DepFun: dom pre rng)
(make-DepFun (for/list ([d (in-list dom)])
(subst/lvl d (add1 lvl)))
(subst/lvl pre (add1 lvl))
(subst/lvl rng (add1 lvl)))]
[(Intersection: ts raw-prop)
(-refine (make-Intersection (map subst ts))
(subst/lvl raw-prop (add1 lvl)))]
[(Path: flds (cons (== lvl) (app lookup (cons o _))))
(make-Path (map subst flds) o)]
[(TypeProp: (Path: flds (cons (== lvl) (app lookup (? pair? entry))))
prop-ty)
(define o (make-Path (map subst flds) (car entry)))
(define o-ty (or (path-type flds (cdr entry)) Univ))
(define new-prop-ty (intersect prop-ty o-ty o))
(cond
[(Bottom? new-prop-ty) -ff]
[(and (not (F? prop-ty)) (subtype o-ty prop-ty)) -tt]
[(Empty? o) -tt]
[else (-is-type o new-prop-ty)])]
[(NotTypeProp: (Path: flds (cons (== lvl) (app lookup (? pair? entry))))
prop-ty)
(define o (make-Path (map subst flds) (car entry)))
(define o-ty (or (path-type flds (cdr entry)) Univ))
(define new-o-ty (subtract o-ty prop-ty o))
(define new-prop-ty (restrict prop-ty o-ty o))
(cond
[(or (Bottom? new-o-ty)
(Univ? new-prop-ty))
-ff]
[(Empty? o) -tt]
[else (-not-type o new-prop-ty)])]
[(tc-result: orig-t
orig-ps
(Path: flds (cons (== lvl) (app lookup (? pair? entry)))))
(define o (make-Path (map subst flds) (car entry)))
(define t (intersect orig-t (or (path-type flds (cdr entry)) Univ)))
(define ps (subst orig-ps))
(-tc-result t ps o)]
[(Result: orig-t
orig-ps
(Path: flds (cons (== lvl) (app lookup (? pair? entry)))))
(define o (make-Path (map subst flds) (car entry)))
(define t (intersect orig-t (or (path-type flds (cdr entry)) Univ)))
(define ps (subst orig-ps))
(make-Result t ps o)]
[_ (Rep-fmap rep subst)])))
|
18f54db1a703bf287384e7b16fdbc2836d225abdd2f1add5fe7f6884ea847bcf | chrisa/acts_as_encrypted | skel_app.erl | @author author < >
YYYY author .
%% @doc Callbacks for the skel application.
-module(skel_app).
-author('author <>').
-behaviour(application).
-export([start/2,stop/1]).
, _ ) - > ServerRet
%% @doc application start callback for skel.
start(_Type, _StartArgs) ->
skel_deps:ensure(),
skel_sup:start_link().
@spec stop(_State ) - > ServerRet
%% @doc application stop callback for skel.
stop(_State) ->
ok.
| null | https://raw.githubusercontent.com/chrisa/acts_as_encrypted/587558a31876dfbbc47d7ab2070782fd3d9395d7/server/deps/mochiweb-src/priv/skel/src/skel_app.erl | erlang | @doc Callbacks for the skel application.
@doc application start callback for skel.
@doc application stop callback for skel. | @author author < >
YYYY author .
-module(skel_app).
-author('author <>').
-behaviour(application).
-export([start/2,stop/1]).
, _ ) - > ServerRet
start(_Type, _StartArgs) ->
skel_deps:ensure(),
skel_sup:start_link().
@spec stop(_State ) - > ServerRet
stop(_State) ->
ok.
|
047fe2e48bedc34d0a6cea1ccc993502c8a45ba452e00647f3cdf821f9cc191e | clojure/java.jdbc | spec.clj | Copyright ( c ) 2016 - 2019 . All rights reserved .
;; The use and distribution terms for this software are covered by
the Eclipse Public License 1.0
;; (-1.0.php) which can be
;; found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be
;; bound by the terms of this license. You must not remove this
;; notice, or any other, from this software.
;;
jdbc / spec.clj
;;
;; Optional specifications for clojure.java.jdbc
(ns ^{:author "Sean Corfield"
:doc "Optional specifications for use with Clojure 1.9 or later."}
clojure.java.jdbc.spec
(:require [clojure.spec.alpha :as s]
[clojure.java.jdbc :as sql]))
(set! *warn-on-reflection* true)
;; basic java.sql types -- cannot be generated!
(s/def ::connection #(instance? java.sql.Connection %))
(s/def ::datasource #(instance? javax.sql.DataSource %))
(s/def ::prepared-statement #(instance? java.sql.PreparedStatement %))
(s/def ::result-set #(instance? java.sql.ResultSet %))
(s/def ::result-set-metadata #(instance? java.sql.ResultSetMetaData %))
(s/def ::uri #(instance? java.net.URI %))
;; database specification (connection description)
(s/def ::subprotocol-base #{"derby" "h2" "h2:mem" "hsqldb" "jtds:sqlserver" "mysql"
"oracle:oci" "oracle:thin" "pgsql" "postgresql"
"redshift" "sqlite" "sqlserver"})
(s/def ::subprotocol-alias #{"hsql" "jtds" "mssql" "oracle" "postgres"})
;; technically :subprotocol can be any string...
(s/def ::subprotocol string?)
... but : dbtype must be a recognizable database type
(s/def ::dbtype (s/or :alias ::subprotocol-alias
:name ::subprotocol-base))
(s/def ::dbname string?)
;; usually IP address or domain name but could be more general string
;; (e.g., it could be username:)
(s/def ::host string?)
;; usually a numeric port number, but could be an arbitrary string if
;; the specified database accepts URIs constructed that way
(s/def ::port (s/or :port pos-int?
:s string?))
(s/def ::subname string?)
will be a valid Java classname ( including package )
(s/def ::classname string?)
(s/def ::factory (s/fspec :args (s/cat :db-spec ::db-spec)
:ret ::connection))
(s/def ::user string?)
(s/def ::username ::user) ; an alias
(s/def ::password string?)
(s/def ::name string?)
(s/def ::environment (s/nilable map?))
;; raw connection-uri
(s/def ::connection-uri string?)
(s/def ::db-spec-connection (s/keys :req-un [::connection]))
(s/def ::db-spec-friendly (s/keys :req-un [::dbtype ::dbname]
:opt-un [::host ::port ::user ::password
::classname]))
(s/def ::db-spec-raw (s/keys :req-un [::connection-uri]
:opt-un [::user ::password]))
(s/def ::db-spec-driver-manager (s/keys :req-un [::subprotocol ::subname]
:opt-un [::classname ::user ::password]))
(s/def ::db-spec-factory (s/keys :req-un [::factory]))
(s/def ::db-spec-data-source (s/keys :req-un [::datasource]
:opt-un [::username ::user ::password]))
(s/def ::db-spec-jndi (s/keys :req-un [::name]
:opt-un [::environment]))
(s/def ::db-spec-string string?)
(s/def ::db-spec-uri ::uri)
(s/def ::db-spec (s/or :connection ::db-spec-connection
:friendly ::db-spec-friendly
:raw ::db-spec-raw
:driver-mgr ::db-spec-driver-manager
:factory ::db-spec-factory
:datasource ::db-spec-data-source
:jndi ::db-spec-jndi
:uri-str ::db-spec-string
:uri-obj ::db-spec-uri))
;; naming
(s/def ::entity string?)
(s/def ::identifier (s/or :kw keyword? :s string?))
;; SQL and parameters
(s/def ::sql-stmt (s/or :sql string? :stmt ::prepared-statement))
(s/def ::sql-value any?) ;; for now
(s/def ::sql-params (s/or :sql ::sql-stmt
:sql-params (s/cat :sql ::sql-stmt :params (s/* ::sql-value))))
(s/def ::where-clause (s/cat :where string? :params (s/* ::sql-value)))
;; results
(s/def ::execute-result (s/* integer?))
;; specific options that can be passed
;; a few of them are nilable, where the functions either pass a possibly nil
;; version of the option to a called function, but most are not nilable because
;; the corresponding options must either be omitted or given valid values
(s/def ::as-arrays? (s/or :as-is #{:cols-as-is} :truthy (s/nilable boolean?)))
(s/def ::auto-commit? boolean?)
(s/def ::concurrency (set (keys @#'sql/result-set-concurrency)))
(s/def ::cursors (set (keys @#'sql/result-set-holdability)))
(s/def ::fetch-size nat-int?)
;; note the asymmetry here: the identifiers function converts a SQL entity to
;; an identifier (a symbol or a string), whereas the entities function converts
;; a string (not an identifier) to a SQL entity; SQL entities are always strings
;; but whilst java.jdbc lets you produce a keyword from identifiers, it does not
;; assume that entities can accept keywords!
(s/def ::identifiers (s/fspec :args (s/cat :s ::entity)
:ret ::identifier))
(s/def ::isolation (set (keys @#'sql/isolation-levels)))
(s/def ::entities (s/fspec :args (s/cat :s string?)
:ret ::entity))
(s/def ::keywordize? boolean?)
(s/def ::max-size nat-int?)
(s/def ::multi? boolean?)
;; strictly speaking we accept any keyword or string whose upper case name
is either ASC or DESC so this spec is overly restrictive ; the : id - dir
;; can actually be an empty map although that is not very useful
(s/def ::direction #{:asc :desc "asc" "desc" "ASC" "DESC"})
(s/def ::column-direction (s/or :id ::identifier
:id-dir (s/map-of ::identifier ::direction)))
(s/def ::order-by (s/coll-of ::column-direction))
(s/def ::qualifier (s/nilable string?))
;; cannot generate a result set so we can't specify this yet
#_(s/def ::read-columns (s/fspec :args (s/cat :rs ::result-set
:rsmeta ::result-set-metadata
:idxs (s/coll-of pos-int?))
:ret (s/coll-of any?)))
(s/def ::read-columns fn?)
(s/def ::read-only? boolean?)
;; there's not much we can say about result-set-fn -- it accepts a collection of
;; transformed rows (from row-fn), and it produces whatever it wants
(s/def ::result-set-fn (s/fspec :args (s/cat :rs (s/coll-of any?))
:ret any?))
(s/def ::result-type (set (keys @#'sql/result-set-type)))
there 's not much we can say about row - fn -- it accepts a row from a ResultSet
;; which is a map of keywords to SQL values, and it produces whatever it wants
(s/def ::row-fn (s/fspec :args (s/cat :row (s/map-of keyword? ::sql-value))
:ret any?))
(s/def ::return-keys (s/or :columns (s/coll-of ::entity :kind vector?)
:boolean boolean?))
(s/def ::table-spec string?)
(s/def ::timeout nat-int?)
(s/def ::transaction? boolean?)
(s/def ::explain? (s/or :b boolean? :s string?))
(s/def ::explain-fn fn?)
(s/def ::conditional? (s/or :b boolean? :s string? :f fn?))
;; various types of options
(s/def ::exec-sql-options (s/keys :req-un [] :opt-un [::entities ::transaction?]))
(s/def ::execute-options (s/keys :req-un [] :opt-un [::transaction? ::multi?
::return-keys]))
(s/def ::find-by-keys-options (s/keys :req-un []
:opt-un [::entities ::order-by
::result-set-fn ::row-fn
::identifiers ::qualifier
::keywordize?
::as-arrays? ::read-columns]))
(s/def ::connection-options (s/keys :req-un []
:opt-un [::auto-commit? ::read-only?]))
(s/def ::prepare-options (s/merge (s/keys :req-un []
:opt-un [::return-keys ::result-type
::concurrency ::cursors ::fetch-size
::max-rows ::timeout])
::connection-options))
(s/def ::transaction-options (s/keys :req-un []
:opt-un [::isolation ::read-only?]))
(s/def ::query-options (s/merge (s/keys :req-un []
:opt-un [::result-set-fn ::row-fn
::identifiers ::qualifier
::keywordize?
::as-arrays? ::read-columns])
::prepare-options))
(s/def ::reducible-query-options (s/merge (s/keys :req-un []
:opt-un [::identifiers
::keywordize?
::qualifier
::read-columns])
::prepare-options))
;; the function API
(s/def ::naming-strategy (s/fspec :args (s/cat :x ::identifier)
:ret ::identifier))
(s/fdef sql/as-sql-name
:args (s/cat :f ::naming-strategy :x ::identifier)
:ret ::identifier)
(s/def ::delimiter (s/or :s string? :c char?))
(s/fdef sql/quoted
:args (s/cat :q (s/or :pair (s/coll-of ::delimiter
:kind vector? :count 2)
:delimiter ::delimiter
:dialect #{:ansi :mysql :sqlserver :oracle}))
:ret ::naming-strategy)
(s/fdef sql/get-connection
:args (s/cat :db-spec ::db-spec
:opts (s/? ::connection-options))
:ret ::connection)
(s/fdef sql/result-set-seq
:args (s/cat :rs ::result-set
:opts (s/? ::query-options))
:ret any?)
(s/fdef sql/prepare-statement
:args (s/cat :con ::connection
:sql string?
:opts (s/? ::prepare-options))
:ret ::prepared-statement)
;; print-sql-exception, print-sql-exception-chain, print-update-counts
(s/fdef sql/db-find-connection
:args (s/cat :db-spec ::db-spec)
:ret (s/nilable ::connection))
(s/fdef sql/db-connection
:args (s/cat :db-spec ::db-spec)
:ret ::connection)
;; transaction functions
(s/fdef sql/db-set-rollback-only!
:args (s/cat :db ::db-spec))
(s/fdef sql/db-unset-rollback-only!
:args (s/cat :db ::db-spec))
(s/fdef sql/db-is-rollback-only
:args (s/cat :db ::db-spec)
:ret boolean?)
(s/fdef sql/get-isolation-level
:args (s/cat :db ::db-spec)
:ret (s/nilable (s/or :isolation ::isolation
:unknown #{:unknown})))
(s/fdef sql/db-transaction*
:args (s/cat :db ::db-spec
:func ifn?
:opts (s/? ::transaction-options))
:ret any?)
(s/def ::transaction-binding (s/spec (s/cat :t-con simple-symbol?
:db-spec any?
:opts (s/? any?))))
(s/fdef sql/with-db-transaction
:args (s/cat :binding ::transaction-binding
:body (s/* any?)))
(s/def ::connection-binding (s/spec (s/cat :con-db simple-symbol?
:db-spec any?
:opts (s/? any?))))
(s/fdef sql/with-db-connection
:args (s/cat :binding ::connection-binding
:body (s/* any?)))
(s/fdef sql/with-db-metadata
:args (s/cat :binding ::connection-binding
:body (s/* any?)))
(s/fdef sql/metadata-result
:args (s/cat :rs-or-value any?
:opts (s/? ::query-options))
:ret any?)
(s/fdef sql/metadata-query
:args (s/cat :meta-query any?
:opt-args (s/? any?)))
(s/fdef sql/db-do-commands
:args (s/cat :db ::db-spec
:transaction? (s/? boolean?)
:sql-commands (s/or :command string?
:commands (s/coll-of string?)))
:ret any?)
(s/fdef sql/db-do-prepared-return-keys
:args (s/cat :db ::db-spec
:transaction? (s/? boolean?)
:sql-params ::sql-params
:opts (s/? (s/merge ::execute-options ::query-options)))
:ret any?)
(s/fdef sql/db-do-prepared
:args (s/cat :db ::db-spec
:transaction? (s/? boolean?)
:sql-params ::sql-params
;; TODO: this set of options needs reviewing:
:opts (s/? (s/merge ::execute-options ::query-options)))
:ret any?)
(s/fdef sql/db-query-with-resultset
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:func ifn?
:opts (s/? ::query-options))
:ret any?)
(s/fdef sql/query
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:opts (s/? (s/merge ::query-options
(s/keys :req-un []
:opt-un [::explain?
::explain-fn]))))
:ret any?)
(s/fdef sql/reducible-result-set
:args (s/cat :rs ::result-set
:opts (s/? ::reducible-query-options))
:ret any?)
(s/fdef sql/reducible-query
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:opts (s/? ::reducible-query-options))
:ret any?)
(s/fdef sql/find-by-keys
:args (s/cat :db ::db-spec
:table ::identifier
:columns (s/map-of ::identifier ::sql-value)
:opts (s/? ::find-by-keys-options))
:ret any?)
(s/fdef sql/get-by-id
:args (s/cat :db ::db-spec
:table ::identifier
:pk-value ::sql-value
:opt-args (s/cat :pk-name (s/? ::identifier)
:opts (s/? ::find-by-keys-options)))
:ret any?)
(s/fdef sql/execute!
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:opts (s/? ::execute-options))
:ret (s/or :rows ::execute-result
:keys (s/coll-of map?)))
(s/fdef sql/delete!
:args (s/cat :db ::db-spec
:table ::identifier
:where-clause (s/spec ::where-clause)
:opts (s/? ::exec-sql-options))
:ret ::execute-result)
(s/fdef sql/insert!
:args (s/or :row (s/cat :db ::db-spec
:table ::identifier
:row (s/map-of ::identifier any?)
:opts (s/? (s/merge ::execute-options ::query-options)))
:cvs (s/cat :db ::db-spec
:table ::identifier
:cols (s/nilable (s/coll-of ::identifier))
:vals (s/coll-of any?)
:opts (s/? (s/merge ::execute-options ::query-options))))
:ret any?)
(s/fdef sql/insert-multi!
:args (s/or :rows (s/cat :db ::db-spec
:table ::identifier
:rows (s/coll-of (s/map-of ::identifier any?))
:opts (s/? (s/merge ::execute-options ::query-options)))
:cvs (s/cat :db ::db-spec
:table ::identifier
:cols (s/nilable (s/coll-of ::identifier))
:vals (s/coll-of (s/coll-of any?))
:opts (s/? (s/merge ::execute-options ::query-options))))
:ret any?)
(s/fdef sql/update!
:args (s/cat :db ::db-spec
:table ::identifier
:set-map (s/map-of ::identifier ::sql-value)
:where-clause (s/spec ::where-clause)
:opts (s/? ::exec-sql-options))
:ret ::execute-result)
(s/def ::column-spec (s/cat :col ::identifier :spec (s/* (s/or :kw keyword?
:str string?
:num number?))))
(s/fdef sql/create-table-ddl
:args (s/cat :table ::identifier
:specs (s/coll-of ::column-spec)
:opts (s/? (s/keys :req-un []
:opt-un [::entities
::conditional?
::table-spec])))
:ret string?)
(s/fdef sql/drop-table-ddl
:args (s/cat :table ::identifier
:opts (s/? (s/keys :req-un []
:opt-un [::entities
::conditional?])))
:ret string?)
| null | https://raw.githubusercontent.com/clojure/java.jdbc/acffd9f5f216f8b8c1fc960c1d47b0b5feb56730/src/main/clojure/clojure/java/jdbc/spec.clj | clojure | The use and distribution terms for this software are covered by
(-1.0.php) which can be
found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be
bound by the terms of this license. You must not remove this
notice, or any other, from this software.
Optional specifications for clojure.java.jdbc
basic java.sql types -- cannot be generated!
database specification (connection description)
technically :subprotocol can be any string...
usually IP address or domain name but could be more general string
(e.g., it could be username:)
usually a numeric port number, but could be an arbitrary string if
the specified database accepts URIs constructed that way
an alias
raw connection-uri
naming
SQL and parameters
for now
results
specific options that can be passed
a few of them are nilable, where the functions either pass a possibly nil
version of the option to a called function, but most are not nilable because
the corresponding options must either be omitted or given valid values
note the asymmetry here: the identifiers function converts a SQL entity to
an identifier (a symbol or a string), whereas the entities function converts
a string (not an identifier) to a SQL entity; SQL entities are always strings
but whilst java.jdbc lets you produce a keyword from identifiers, it does not
assume that entities can accept keywords!
strictly speaking we accept any keyword or string whose upper case name
the : id - dir
can actually be an empty map although that is not very useful
cannot generate a result set so we can't specify this yet
there's not much we can say about result-set-fn -- it accepts a collection of
transformed rows (from row-fn), and it produces whatever it wants
which is a map of keywords to SQL values, and it produces whatever it wants
various types of options
the function API
print-sql-exception, print-sql-exception-chain, print-update-counts
transaction functions
TODO: this set of options needs reviewing: | Copyright ( c ) 2016 - 2019 . All rights reserved .
the Eclipse Public License 1.0
jdbc / spec.clj
(ns ^{:author "Sean Corfield"
:doc "Optional specifications for use with Clojure 1.9 or later."}
clojure.java.jdbc.spec
(:require [clojure.spec.alpha :as s]
[clojure.java.jdbc :as sql]))
(set! *warn-on-reflection* true)
(s/def ::connection #(instance? java.sql.Connection %))
(s/def ::datasource #(instance? javax.sql.DataSource %))
(s/def ::prepared-statement #(instance? java.sql.PreparedStatement %))
(s/def ::result-set #(instance? java.sql.ResultSet %))
(s/def ::result-set-metadata #(instance? java.sql.ResultSetMetaData %))
(s/def ::uri #(instance? java.net.URI %))
(s/def ::subprotocol-base #{"derby" "h2" "h2:mem" "hsqldb" "jtds:sqlserver" "mysql"
"oracle:oci" "oracle:thin" "pgsql" "postgresql"
"redshift" "sqlite" "sqlserver"})
(s/def ::subprotocol-alias #{"hsql" "jtds" "mssql" "oracle" "postgres"})
(s/def ::subprotocol string?)
... but : dbtype must be a recognizable database type
(s/def ::dbtype (s/or :alias ::subprotocol-alias
:name ::subprotocol-base))
(s/def ::dbname string?)
(s/def ::host string?)
(s/def ::port (s/or :port pos-int?
:s string?))
(s/def ::subname string?)
will be a valid Java classname ( including package )
(s/def ::classname string?)
(s/def ::factory (s/fspec :args (s/cat :db-spec ::db-spec)
:ret ::connection))
(s/def ::user string?)
(s/def ::password string?)
(s/def ::name string?)
(s/def ::environment (s/nilable map?))
(s/def ::connection-uri string?)
(s/def ::db-spec-connection (s/keys :req-un [::connection]))
(s/def ::db-spec-friendly (s/keys :req-un [::dbtype ::dbname]
:opt-un [::host ::port ::user ::password
::classname]))
(s/def ::db-spec-raw (s/keys :req-un [::connection-uri]
:opt-un [::user ::password]))
(s/def ::db-spec-driver-manager (s/keys :req-un [::subprotocol ::subname]
:opt-un [::classname ::user ::password]))
(s/def ::db-spec-factory (s/keys :req-un [::factory]))
(s/def ::db-spec-data-source (s/keys :req-un [::datasource]
:opt-un [::username ::user ::password]))
(s/def ::db-spec-jndi (s/keys :req-un [::name]
:opt-un [::environment]))
(s/def ::db-spec-string string?)
(s/def ::db-spec-uri ::uri)
(s/def ::db-spec (s/or :connection ::db-spec-connection
:friendly ::db-spec-friendly
:raw ::db-spec-raw
:driver-mgr ::db-spec-driver-manager
:factory ::db-spec-factory
:datasource ::db-spec-data-source
:jndi ::db-spec-jndi
:uri-str ::db-spec-string
:uri-obj ::db-spec-uri))
(s/def ::entity string?)
(s/def ::identifier (s/or :kw keyword? :s string?))
(s/def ::sql-stmt (s/or :sql string? :stmt ::prepared-statement))
(s/def ::sql-params (s/or :sql ::sql-stmt
:sql-params (s/cat :sql ::sql-stmt :params (s/* ::sql-value))))
(s/def ::where-clause (s/cat :where string? :params (s/* ::sql-value)))
(s/def ::execute-result (s/* integer?))
(s/def ::as-arrays? (s/or :as-is #{:cols-as-is} :truthy (s/nilable boolean?)))
(s/def ::auto-commit? boolean?)
(s/def ::concurrency (set (keys @#'sql/result-set-concurrency)))
(s/def ::cursors (set (keys @#'sql/result-set-holdability)))
(s/def ::fetch-size nat-int?)
(s/def ::identifiers (s/fspec :args (s/cat :s ::entity)
:ret ::identifier))
(s/def ::isolation (set (keys @#'sql/isolation-levels)))
(s/def ::entities (s/fspec :args (s/cat :s string?)
:ret ::entity))
(s/def ::keywordize? boolean?)
(s/def ::max-size nat-int?)
(s/def ::multi? boolean?)
(s/def ::direction #{:asc :desc "asc" "desc" "ASC" "DESC"})
(s/def ::column-direction (s/or :id ::identifier
:id-dir (s/map-of ::identifier ::direction)))
(s/def ::order-by (s/coll-of ::column-direction))
(s/def ::qualifier (s/nilable string?))
#_(s/def ::read-columns (s/fspec :args (s/cat :rs ::result-set
:rsmeta ::result-set-metadata
:idxs (s/coll-of pos-int?))
:ret (s/coll-of any?)))
(s/def ::read-columns fn?)
(s/def ::read-only? boolean?)
(s/def ::result-set-fn (s/fspec :args (s/cat :rs (s/coll-of any?))
:ret any?))
(s/def ::result-type (set (keys @#'sql/result-set-type)))
there 's not much we can say about row - fn -- it accepts a row from a ResultSet
(s/def ::row-fn (s/fspec :args (s/cat :row (s/map-of keyword? ::sql-value))
:ret any?))
(s/def ::return-keys (s/or :columns (s/coll-of ::entity :kind vector?)
:boolean boolean?))
(s/def ::table-spec string?)
(s/def ::timeout nat-int?)
(s/def ::transaction? boolean?)
(s/def ::explain? (s/or :b boolean? :s string?))
(s/def ::explain-fn fn?)
(s/def ::conditional? (s/or :b boolean? :s string? :f fn?))
(s/def ::exec-sql-options (s/keys :req-un [] :opt-un [::entities ::transaction?]))
(s/def ::execute-options (s/keys :req-un [] :opt-un [::transaction? ::multi?
::return-keys]))
(s/def ::find-by-keys-options (s/keys :req-un []
:opt-un [::entities ::order-by
::result-set-fn ::row-fn
::identifiers ::qualifier
::keywordize?
::as-arrays? ::read-columns]))
(s/def ::connection-options (s/keys :req-un []
:opt-un [::auto-commit? ::read-only?]))
(s/def ::prepare-options (s/merge (s/keys :req-un []
:opt-un [::return-keys ::result-type
::concurrency ::cursors ::fetch-size
::max-rows ::timeout])
::connection-options))
(s/def ::transaction-options (s/keys :req-un []
:opt-un [::isolation ::read-only?]))
(s/def ::query-options (s/merge (s/keys :req-un []
:opt-un [::result-set-fn ::row-fn
::identifiers ::qualifier
::keywordize?
::as-arrays? ::read-columns])
::prepare-options))
(s/def ::reducible-query-options (s/merge (s/keys :req-un []
:opt-un [::identifiers
::keywordize?
::qualifier
::read-columns])
::prepare-options))
(s/def ::naming-strategy (s/fspec :args (s/cat :x ::identifier)
:ret ::identifier))
(s/fdef sql/as-sql-name
:args (s/cat :f ::naming-strategy :x ::identifier)
:ret ::identifier)
(s/def ::delimiter (s/or :s string? :c char?))
(s/fdef sql/quoted
:args (s/cat :q (s/or :pair (s/coll-of ::delimiter
:kind vector? :count 2)
:delimiter ::delimiter
:dialect #{:ansi :mysql :sqlserver :oracle}))
:ret ::naming-strategy)
(s/fdef sql/get-connection
:args (s/cat :db-spec ::db-spec
:opts (s/? ::connection-options))
:ret ::connection)
(s/fdef sql/result-set-seq
:args (s/cat :rs ::result-set
:opts (s/? ::query-options))
:ret any?)
(s/fdef sql/prepare-statement
:args (s/cat :con ::connection
:sql string?
:opts (s/? ::prepare-options))
:ret ::prepared-statement)
(s/fdef sql/db-find-connection
:args (s/cat :db-spec ::db-spec)
:ret (s/nilable ::connection))
(s/fdef sql/db-connection
:args (s/cat :db-spec ::db-spec)
:ret ::connection)
(s/fdef sql/db-set-rollback-only!
:args (s/cat :db ::db-spec))
(s/fdef sql/db-unset-rollback-only!
:args (s/cat :db ::db-spec))
(s/fdef sql/db-is-rollback-only
:args (s/cat :db ::db-spec)
:ret boolean?)
(s/fdef sql/get-isolation-level
:args (s/cat :db ::db-spec)
:ret (s/nilable (s/or :isolation ::isolation
:unknown #{:unknown})))
(s/fdef sql/db-transaction*
:args (s/cat :db ::db-spec
:func ifn?
:opts (s/? ::transaction-options))
:ret any?)
(s/def ::transaction-binding (s/spec (s/cat :t-con simple-symbol?
:db-spec any?
:opts (s/? any?))))
(s/fdef sql/with-db-transaction
:args (s/cat :binding ::transaction-binding
:body (s/* any?)))
(s/def ::connection-binding (s/spec (s/cat :con-db simple-symbol?
:db-spec any?
:opts (s/? any?))))
(s/fdef sql/with-db-connection
:args (s/cat :binding ::connection-binding
:body (s/* any?)))
(s/fdef sql/with-db-metadata
:args (s/cat :binding ::connection-binding
:body (s/* any?)))
(s/fdef sql/metadata-result
:args (s/cat :rs-or-value any?
:opts (s/? ::query-options))
:ret any?)
(s/fdef sql/metadata-query
:args (s/cat :meta-query any?
:opt-args (s/? any?)))
(s/fdef sql/db-do-commands
:args (s/cat :db ::db-spec
:transaction? (s/? boolean?)
:sql-commands (s/or :command string?
:commands (s/coll-of string?)))
:ret any?)
(s/fdef sql/db-do-prepared-return-keys
:args (s/cat :db ::db-spec
:transaction? (s/? boolean?)
:sql-params ::sql-params
:opts (s/? (s/merge ::execute-options ::query-options)))
:ret any?)
(s/fdef sql/db-do-prepared
:args (s/cat :db ::db-spec
:transaction? (s/? boolean?)
:sql-params ::sql-params
:opts (s/? (s/merge ::execute-options ::query-options)))
:ret any?)
(s/fdef sql/db-query-with-resultset
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:func ifn?
:opts (s/? ::query-options))
:ret any?)
(s/fdef sql/query
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:opts (s/? (s/merge ::query-options
(s/keys :req-un []
:opt-un [::explain?
::explain-fn]))))
:ret any?)
(s/fdef sql/reducible-result-set
:args (s/cat :rs ::result-set
:opts (s/? ::reducible-query-options))
:ret any?)
(s/fdef sql/reducible-query
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:opts (s/? ::reducible-query-options))
:ret any?)
(s/fdef sql/find-by-keys
:args (s/cat :db ::db-spec
:table ::identifier
:columns (s/map-of ::identifier ::sql-value)
:opts (s/? ::find-by-keys-options))
:ret any?)
(s/fdef sql/get-by-id
:args (s/cat :db ::db-spec
:table ::identifier
:pk-value ::sql-value
:opt-args (s/cat :pk-name (s/? ::identifier)
:opts (s/? ::find-by-keys-options)))
:ret any?)
(s/fdef sql/execute!
:args (s/cat :db ::db-spec
:sql-params ::sql-params
:opts (s/? ::execute-options))
:ret (s/or :rows ::execute-result
:keys (s/coll-of map?)))
(s/fdef sql/delete!
:args (s/cat :db ::db-spec
:table ::identifier
:where-clause (s/spec ::where-clause)
:opts (s/? ::exec-sql-options))
:ret ::execute-result)
(s/fdef sql/insert!
:args (s/or :row (s/cat :db ::db-spec
:table ::identifier
:row (s/map-of ::identifier any?)
:opts (s/? (s/merge ::execute-options ::query-options)))
:cvs (s/cat :db ::db-spec
:table ::identifier
:cols (s/nilable (s/coll-of ::identifier))
:vals (s/coll-of any?)
:opts (s/? (s/merge ::execute-options ::query-options))))
:ret any?)
(s/fdef sql/insert-multi!
:args (s/or :rows (s/cat :db ::db-spec
:table ::identifier
:rows (s/coll-of (s/map-of ::identifier any?))
:opts (s/? (s/merge ::execute-options ::query-options)))
:cvs (s/cat :db ::db-spec
:table ::identifier
:cols (s/nilable (s/coll-of ::identifier))
:vals (s/coll-of (s/coll-of any?))
:opts (s/? (s/merge ::execute-options ::query-options))))
:ret any?)
(s/fdef sql/update!
:args (s/cat :db ::db-spec
:table ::identifier
:set-map (s/map-of ::identifier ::sql-value)
:where-clause (s/spec ::where-clause)
:opts (s/? ::exec-sql-options))
:ret ::execute-result)
(s/def ::column-spec (s/cat :col ::identifier :spec (s/* (s/or :kw keyword?
:str string?
:num number?))))
(s/fdef sql/create-table-ddl
:args (s/cat :table ::identifier
:specs (s/coll-of ::column-spec)
:opts (s/? (s/keys :req-un []
:opt-un [::entities
::conditional?
::table-spec])))
:ret string?)
(s/fdef sql/drop-table-ddl
:args (s/cat :table ::identifier
:opts (s/? (s/keys :req-un []
:opt-un [::entities
::conditional?])))
:ret string?)
|
158a42311e7d87f337a985eb7a1e5da1a99dcc7108d523f03f12e45ffdc17b78 | c-cube/jsonrpc2 | jsonrpc2.ml |
* { 1 Simple JSON - RPC2 implementation }
See { { : } the spec }
See {{: } the spec} *)
module type IO = Jsonrpc2_intf.IO
module type S = Jsonrpc2_intf.S
module Make = Jsonrpc2_core.Make
| null | https://raw.githubusercontent.com/c-cube/jsonrpc2/c230d056c8084435b0d681f1be5cc15a0fba834b/src/jsonrpc2.ml | ocaml |
* { 1 Simple JSON - RPC2 implementation }
See { { : } the spec }
See {{: } the spec} *)
module type IO = Jsonrpc2_intf.IO
module type S = Jsonrpc2_intf.S
module Make = Jsonrpc2_core.Make
|
|
5e9d4d98021eb372c3897775990ea666a7f7f4772d75d7e0ec82fa23b386abe5 | mwand/eopl3 | interp.scm | (module interp (lib "eopl.ss" "eopl")
(require "drscheme-init.scm")
(require "lang.scm")
(require "data-structures.scm")
(require "environments.scm")
(provide value-of-program value-of)
;;;;;;;;;;;;;;;; the interpreter ;;;;;;;;;;;;;;;;
;; value-of-program : Program -> Expval
Page : 284
(define value-of-program
(lambda (pgm)
(cases program pgm
(a-program (module-defs body)
(let ((env
(add-module-defns-to-env module-defs (empty-env))))
;; (eopl:pretty-print env)
(value-of body env))))))
;; add-module-defns-to-env : Listof(Defn) * Env -> Env
Page : 284
(define add-module-defns-to-env
(lambda (defs env)
(if (null? defs)
env
(cases module-definition (car defs)
(a-module-definition (m-name iface m-body)
(add-module-defns-to-env
(cdr defs)
(extend-env-with-module
m-name
(value-of-module-body m-body env)
env)))))))
;; We will have let* scoping inside a module body.
;; We put all the values in the environment, not just the ones
;; that are in the interface. But the typechecker will prevent
;; anybody from using the extras.
;; value-of-module-body : ModuleBody * Env -> TypedModule
Page : 285 , 320
(define value-of-module-body
(lambda (m-body env)
(cases module-body m-body
(defns-module-body (defns)
(simple-module
(defns-to-env defns env))) )))
(define raise-cant-apply-non-proc-module!
(lambda (rator-val)
(eopl:error 'value-of-module-body
"can't apply non-proc-module-value ~s" rator-val)))
;; defns-to-env : Listof(Defn) * Env -> Env
Page : 285 , 303
(define defns-to-env
(lambda (defns env)
(if (null? defns)
(empty-env) ; we're making a little environment
(cases definition (car defns)
(val-defn (var exp)
(let ((val (value-of exp env)))
;; new environment for subsequent definitions
(let ((new-env (extend-env var val env)))
(extend-env var val
(defns-to-env
(cdr defns) new-env)))))
;; type definitions are ignored at run time
(else
(defns-to-env (cdr defns) env))
))))
value - of : Exp * Env - > ExpVal
(define value-of
(lambda (exp env)
(cases expression exp
(const-exp (num) (num-val num))
(var-exp (var) (apply-env env var))
(qualified-var-exp (m-name var-name)
(lookup-qualified-var-in-env m-name var-name env))
(diff-exp (exp1 exp2)
(let ((val1
(expval->num
(value-of exp1 env)))
(val2
(expval->num
(value-of exp2 env))))
(num-val
(- val1 val2))))
(zero?-exp (exp1)
(let ((val1 (expval->num (value-of exp1 env))))
(if (zero? val1)
(bool-val #t)
(bool-val #f))))
(if-exp (exp0 exp1 exp2)
(if (expval->bool (value-of exp0 env))
(value-of exp1 env)
(value-of exp2 env)))
(let-exp (var exp1 body)
(let ((val (value-of exp1 env)))
(let ((new-env (extend-env var val env)))
;; (eopl:pretty-print new-env)
(value-of body new-env))))
(proc-exp (bvar ty body)
(proc-val
(procedure bvar body env)))
(call-exp (rator rand)
(let ((proc (expval->proc (value-of rator env)))
(arg (value-of rand env)))
(apply-procedure proc arg)))
(letrec-exp (ty1 proc-name bvar ty2 proc-body letrec-body)
(value-of letrec-body
(extend-env-recursively proc-name bvar proc-body env)))
)))
apply - procedure : Proc * ExpVal - > ExpVal
(define apply-procedure
(lambda (proc1 arg)
(cases proc proc1
(procedure (var body saved-env)
(value-of body (extend-env var arg saved-env))))))
)
| null | https://raw.githubusercontent.com/mwand/eopl3/b50e015be7f021d94c1af5f0e3a05d40dd2b0cbf/chapter8/abstract-types-lang/interp.scm | scheme | the interpreter ;;;;;;;;;;;;;;;;
value-of-program : Program -> Expval
(eopl:pretty-print env)
add-module-defns-to-env : Listof(Defn) * Env -> Env
We will have let* scoping inside a module body.
We put all the values in the environment, not just the ones
that are in the interface. But the typechecker will prevent
anybody from using the extras.
value-of-module-body : ModuleBody * Env -> TypedModule
defns-to-env : Listof(Defn) * Env -> Env
we're making a little environment
new environment for subsequent definitions
type definitions are ignored at run time
(eopl:pretty-print new-env) | (module interp (lib "eopl.ss" "eopl")
(require "drscheme-init.scm")
(require "lang.scm")
(require "data-structures.scm")
(require "environments.scm")
(provide value-of-program value-of)
Page : 284
(define value-of-program
(lambda (pgm)
(cases program pgm
(a-program (module-defs body)
(let ((env
(add-module-defns-to-env module-defs (empty-env))))
(value-of body env))))))
Page : 284
(define add-module-defns-to-env
(lambda (defs env)
(if (null? defs)
env
(cases module-definition (car defs)
(a-module-definition (m-name iface m-body)
(add-module-defns-to-env
(cdr defs)
(extend-env-with-module
m-name
(value-of-module-body m-body env)
env)))))))
Page : 285 , 320
(define value-of-module-body
(lambda (m-body env)
(cases module-body m-body
(defns-module-body (defns)
(simple-module
(defns-to-env defns env))) )))
(define raise-cant-apply-non-proc-module!
(lambda (rator-val)
(eopl:error 'value-of-module-body
"can't apply non-proc-module-value ~s" rator-val)))
Page : 285 , 303
(define defns-to-env
(lambda (defns env)
(if (null? defns)
(cases definition (car defns)
(val-defn (var exp)
(let ((val (value-of exp env)))
(let ((new-env (extend-env var val env)))
(extend-env var val
(defns-to-env
(cdr defns) new-env)))))
(else
(defns-to-env (cdr defns) env))
))))
value - of : Exp * Env - > ExpVal
(define value-of
(lambda (exp env)
(cases expression exp
(const-exp (num) (num-val num))
(var-exp (var) (apply-env env var))
(qualified-var-exp (m-name var-name)
(lookup-qualified-var-in-env m-name var-name env))
(diff-exp (exp1 exp2)
(let ((val1
(expval->num
(value-of exp1 env)))
(val2
(expval->num
(value-of exp2 env))))
(num-val
(- val1 val2))))
(zero?-exp (exp1)
(let ((val1 (expval->num (value-of exp1 env))))
(if (zero? val1)
(bool-val #t)
(bool-val #f))))
(if-exp (exp0 exp1 exp2)
(if (expval->bool (value-of exp0 env))
(value-of exp1 env)
(value-of exp2 env)))
(let-exp (var exp1 body)
(let ((val (value-of exp1 env)))
(let ((new-env (extend-env var val env)))
(value-of body new-env))))
(proc-exp (bvar ty body)
(proc-val
(procedure bvar body env)))
(call-exp (rator rand)
(let ((proc (expval->proc (value-of rator env)))
(arg (value-of rand env)))
(apply-procedure proc arg)))
(letrec-exp (ty1 proc-name bvar ty2 proc-body letrec-body)
(value-of letrec-body
(extend-env-recursively proc-name bvar proc-body env)))
)))
apply - procedure : Proc * ExpVal - > ExpVal
(define apply-procedure
(lambda (proc1 arg)
(cases proc proc1
(procedure (var body saved-env)
(value-of body (extend-env var arg saved-env))))))
)
|
996694a0038faff9670b46b791903289523cb34a6b4acb5cc23fbcb14da9a563 | ixy-languages/ixy.hs | Memory.hs | # LANGUAGE TemplateHaskell #
-- |
-- Module : Lib.Memory
Copyright : 2018
-- License : BSD3
--
-- Maintainer :
-- Stability : experimental
-- Portability : unknown
--
--
--
module Lib.Memory
( allocateMem
, mkMemPool
, allocateBuf
, idToPtr
, freeBuf
, translate
, peekId
, peekAddr
, peekSize
, pokeSize
, MemPool(..)
, PacketBuf(..)
, PhysAddr(..)
, VirtAddr(..)
)
where
import Lib.Prelude
import Control.Monad.Logger ( MonadLogger
, logDebug
)
import Control.Monad.Catch hiding ( bracket )
import qualified Data.Array.IO as Array
import Data.Binary.Get
import qualified Data.ByteString as B
import Data.ByteString.Unsafe
import Data.IORef
import Foreign.Marshal.Utils ( copyBytes )
import Foreign.Ptr ( WordPtr(..)
, castPtr
, plusPtr
, ptrToWordPtr
)
import Foreign.Storable ( sizeOf
, alignment
, peek
, peekByteOff
, poke
, pokeByteOff
)
import System.IO.Error ( userError )
import qualified System.Path as Path
import qualified System.Path.IO as PathIO
import System.Posix.IO ( closeFd
, handleToFd
)
import System.Posix.Memory ( MemoryMapFlag(MemoryMapShared)
, MemoryProtection
( MemoryProtectionRead
, MemoryProtectionWrite
)
, memoryLock
, memoryMap
, sysconfPageSize
)
newtype PhysAddr = PhysAddr Word64
newtype VirtAddr a = VirtAddr (Ptr a)
-- $ Huge Pages
hugepageBits :: Int
hugepageBits = 21
hugepageSize :: Int
hugepageSize = shift 1 hugepageBits
-- $ Allocations
allocateMem
:: (MonadThrow m, MonadIO m, MonadLogger m) => Int -> Bool -> m (Ptr a)
allocateMem size contiguous = do
$(logDebug)
$ "Allocating a memory chunk with size "
<> show size
<> "B (contiguous="
<> show contiguous
<> ")."
let s = if size `mod` hugepageSize /= 0
then shift (shiftR size hugepageBits + 1) hugepageBits
else size
liftIO $ do
(_, h) <- PathIO.openBinaryTempFile (Path.absDir "/mnt/huge")
(Path.relFile "ixy.huge")
PathIO.hSetFileSize h $ fromIntegral s
let f = memoryMap Nothing
(fromIntegral s)
[MemoryProtectionRead, MemoryProtectionWrite]
MemoryMapShared
ptr <- bracket (handleToFd h) closeFd (\fd -> Just fd `f` 0)
memoryLock ptr $ fromIntegral s
-- TODO: We should remove this, but not here.
-- Dir.removeFile fname
return ptr
-- $ Memory Pools
data PacketBuf = PacketBuf { pbId :: Int
, pbAddr :: PhysAddr
, pbSize :: Int
, pbData :: ByteString }
instance Storable PacketBuf where
sizeOf _ = 2048
alignment = sizeOf
peek ptr = do
id <- peek (castPtr ptr)
addr <- peekByteOff ptr addrOffset
size <- peekByteOff ptr sizeOffset
bufData <- unsafePackCStringLen (castPtr (ptr `plusPtr` dataOffset), size)
return PacketBuf {pbId = id, pbAddr = PhysAddr addr, pbSize = size, pbData = bufData}
poke ptr buf = do
poke (castPtr ptr) $ pbId buf
pokeByteOff ptr addrOffset bufAddr
pokeByteOff ptr sizeOffset $ pbSize buf
unsafeUseAsCStringLen (pbData buf) $ uncurry (copyBytes (ptr `plusPtr` dataOffset))
where PhysAddr bufAddr = pbAddr buf
addrOffset :: Int
addrOffset = sizeOf (0 :: Int)
sizeOffset :: Int
sizeOffset = addrOffset + sizeOf (0 :: Word64)
dataOffset :: Int
dataOffset = sizeOffset + sizeOf (0 :: Int)
data MemPool = MemPool { mpBaseAddr :: Ptr Word8
, mpNumEntries :: Int
, mpFreeBufs :: Array.IOUArray Int Int
, mpTop :: IORef Int
}
mkMemPool :: (MonadThrow m, MonadIO m, MonadLogger m) => Int -> m MemPool
mkMemPool numEntries = do
ptr <- allocateMem (numEntries * bufSize) False
mapM_ initBuf
[ (ptr `plusPtr` (i * bufSize), i) | i <- [0 .. numEntries - 1] ]
freeBufs <- liftIO
$ Array.newListArray (0, numEntries - 1) [0 .. numEntries - 1]
topRef <- liftIO $ newIORef (numEntries :: Int)
return MemPool
{ mpBaseAddr = ptr
, mpNumEntries = numEntries
, mpFreeBufs = freeBufs
, mpTop = topRef
}
where
initBuf (bufPtr, i) = do
bufPhysAddr <- liftIO $ translate $ VirtAddr (bufPtr `plusPtr` dataOffset)
liftIO $ poke
bufPtr
PacketBuf {pbId = i, pbAddr = bufPhysAddr, pbSize = 0, pbData = B.empty}
bufSize = sizeOf (undefined :: PacketBuf)
allocateBuf :: MemPool -> IO (Ptr PacketBuf)
allocateBuf memPool = do
let topRef = mpTop memPool
modifyIORef' topRef (\i -> i - 1)
top <- readIORef topRef
id <- Array.readArray (mpFreeBufs memPool) top
return $ idToPtr memPool id
idToPtr :: MemPool -> Int -> Ptr PacketBuf
idToPtr memPool id =
(mpBaseAddr memPool) `plusPtr` (id * sizeOf (undefined :: PacketBuf))
peekId :: Ptr PacketBuf -> IO Int
peekId ptr = peek (castPtr ptr)
peekAddr :: Ptr PacketBuf -> IO PhysAddr
peekAddr ptr = PhysAddr <$> peekByteOff ptr addrOffset
peekSize :: Ptr PacketBuf -> IO Int
peekSize ptr = peekByteOff ptr sizeOffset
pokeSize :: Ptr PacketBuf -> Int -> IO ()
pokeSize ptr = pokeByteOff ptr sizeOffset
freeBuf :: MemPool -> Int -> IO ()
freeBuf memPool id = do
let topRef = mpTop memPool
top <- readIORef topRef
Array.writeArray (mpFreeBufs memPool) top id
modifyIORef' topRef (+ 1)
-- $ Utility
translate :: VirtAddr a -> IO PhysAddr
translate (VirtAddr virt) = PathIO.withBinaryFile path PathIO.ReadMode inner
where
inner h = do
PathIO.hSeek h PathIO.AbsoluteSeek $ fromIntegral offset
buf <- B.hGet h 8
case runGetIncremental getWord64le `pushChunk` buf of
Done _ _ b -> return $ PhysAddr $ getAddr $ fromIntegral b
Partial _ ->
throwM $ userError "Partial input when parsing physical address."
Fail{} -> throwM $ userError "Physical address was malformed."
path = Path.absFile "/proc/self/pagemap"
WordPtr addr = ptrToWordPtr virt
offset = (addr `quot` pageSize) * 8 -- This is not arch-specific, hence the magic number.
getAddr x =
fromIntegral $ (x .&. 0x7fffffffffffff) * pageSize + addr `mod` pageSize
pageSize = fromIntegral sysconfPageSize
| null | https://raw.githubusercontent.com/ixy-languages/ixy.hs/4a24031adf9ba0737cebe1bb4f86bdf11fbf61c3/src/Lib/Memory.hs | haskell | |
Module : Lib.Memory
License : BSD3
Maintainer :
Stability : experimental
Portability : unknown
$ Huge Pages
$ Allocations
TODO: We should remove this, but not here.
Dir.removeFile fname
$ Memory Pools
$ Utility
This is not arch-specific, hence the magic number. | # LANGUAGE TemplateHaskell #
Copyright : 2018
module Lib.Memory
( allocateMem
, mkMemPool
, allocateBuf
, idToPtr
, freeBuf
, translate
, peekId
, peekAddr
, peekSize
, pokeSize
, MemPool(..)
, PacketBuf(..)
, PhysAddr(..)
, VirtAddr(..)
)
where
import Lib.Prelude
import Control.Monad.Logger ( MonadLogger
, logDebug
)
import Control.Monad.Catch hiding ( bracket )
import qualified Data.Array.IO as Array
import Data.Binary.Get
import qualified Data.ByteString as B
import Data.ByteString.Unsafe
import Data.IORef
import Foreign.Marshal.Utils ( copyBytes )
import Foreign.Ptr ( WordPtr(..)
, castPtr
, plusPtr
, ptrToWordPtr
)
import Foreign.Storable ( sizeOf
, alignment
, peek
, peekByteOff
, poke
, pokeByteOff
)
import System.IO.Error ( userError )
import qualified System.Path as Path
import qualified System.Path.IO as PathIO
import System.Posix.IO ( closeFd
, handleToFd
)
import System.Posix.Memory ( MemoryMapFlag(MemoryMapShared)
, MemoryProtection
( MemoryProtectionRead
, MemoryProtectionWrite
)
, memoryLock
, memoryMap
, sysconfPageSize
)
newtype PhysAddr = PhysAddr Word64
newtype VirtAddr a = VirtAddr (Ptr a)
hugepageBits :: Int
hugepageBits = 21
hugepageSize :: Int
hugepageSize = shift 1 hugepageBits
allocateMem
:: (MonadThrow m, MonadIO m, MonadLogger m) => Int -> Bool -> m (Ptr a)
allocateMem size contiguous = do
$(logDebug)
$ "Allocating a memory chunk with size "
<> show size
<> "B (contiguous="
<> show contiguous
<> ")."
let s = if size `mod` hugepageSize /= 0
then shift (shiftR size hugepageBits + 1) hugepageBits
else size
liftIO $ do
(_, h) <- PathIO.openBinaryTempFile (Path.absDir "/mnt/huge")
(Path.relFile "ixy.huge")
PathIO.hSetFileSize h $ fromIntegral s
let f = memoryMap Nothing
(fromIntegral s)
[MemoryProtectionRead, MemoryProtectionWrite]
MemoryMapShared
ptr <- bracket (handleToFd h) closeFd (\fd -> Just fd `f` 0)
memoryLock ptr $ fromIntegral s
return ptr
data PacketBuf = PacketBuf { pbId :: Int
, pbAddr :: PhysAddr
, pbSize :: Int
, pbData :: ByteString }
instance Storable PacketBuf where
sizeOf _ = 2048
alignment = sizeOf
peek ptr = do
id <- peek (castPtr ptr)
addr <- peekByteOff ptr addrOffset
size <- peekByteOff ptr sizeOffset
bufData <- unsafePackCStringLen (castPtr (ptr `plusPtr` dataOffset), size)
return PacketBuf {pbId = id, pbAddr = PhysAddr addr, pbSize = size, pbData = bufData}
poke ptr buf = do
poke (castPtr ptr) $ pbId buf
pokeByteOff ptr addrOffset bufAddr
pokeByteOff ptr sizeOffset $ pbSize buf
unsafeUseAsCStringLen (pbData buf) $ uncurry (copyBytes (ptr `plusPtr` dataOffset))
where PhysAddr bufAddr = pbAddr buf
addrOffset :: Int
addrOffset = sizeOf (0 :: Int)
sizeOffset :: Int
sizeOffset = addrOffset + sizeOf (0 :: Word64)
dataOffset :: Int
dataOffset = sizeOffset + sizeOf (0 :: Int)
data MemPool = MemPool { mpBaseAddr :: Ptr Word8
, mpNumEntries :: Int
, mpFreeBufs :: Array.IOUArray Int Int
, mpTop :: IORef Int
}
mkMemPool :: (MonadThrow m, MonadIO m, MonadLogger m) => Int -> m MemPool
mkMemPool numEntries = do
ptr <- allocateMem (numEntries * bufSize) False
mapM_ initBuf
[ (ptr `plusPtr` (i * bufSize), i) | i <- [0 .. numEntries - 1] ]
freeBufs <- liftIO
$ Array.newListArray (0, numEntries - 1) [0 .. numEntries - 1]
topRef <- liftIO $ newIORef (numEntries :: Int)
return MemPool
{ mpBaseAddr = ptr
, mpNumEntries = numEntries
, mpFreeBufs = freeBufs
, mpTop = topRef
}
where
initBuf (bufPtr, i) = do
bufPhysAddr <- liftIO $ translate $ VirtAddr (bufPtr `plusPtr` dataOffset)
liftIO $ poke
bufPtr
PacketBuf {pbId = i, pbAddr = bufPhysAddr, pbSize = 0, pbData = B.empty}
bufSize = sizeOf (undefined :: PacketBuf)
allocateBuf :: MemPool -> IO (Ptr PacketBuf)
allocateBuf memPool = do
let topRef = mpTop memPool
modifyIORef' topRef (\i -> i - 1)
top <- readIORef topRef
id <- Array.readArray (mpFreeBufs memPool) top
return $ idToPtr memPool id
idToPtr :: MemPool -> Int -> Ptr PacketBuf
idToPtr memPool id =
(mpBaseAddr memPool) `plusPtr` (id * sizeOf (undefined :: PacketBuf))
peekId :: Ptr PacketBuf -> IO Int
peekId ptr = peek (castPtr ptr)
peekAddr :: Ptr PacketBuf -> IO PhysAddr
peekAddr ptr = PhysAddr <$> peekByteOff ptr addrOffset
peekSize :: Ptr PacketBuf -> IO Int
peekSize ptr = peekByteOff ptr sizeOffset
pokeSize :: Ptr PacketBuf -> Int -> IO ()
pokeSize ptr = pokeByteOff ptr sizeOffset
freeBuf :: MemPool -> Int -> IO ()
freeBuf memPool id = do
let topRef = mpTop memPool
top <- readIORef topRef
Array.writeArray (mpFreeBufs memPool) top id
modifyIORef' topRef (+ 1)
translate :: VirtAddr a -> IO PhysAddr
translate (VirtAddr virt) = PathIO.withBinaryFile path PathIO.ReadMode inner
where
inner h = do
PathIO.hSeek h PathIO.AbsoluteSeek $ fromIntegral offset
buf <- B.hGet h 8
case runGetIncremental getWord64le `pushChunk` buf of
Done _ _ b -> return $ PhysAddr $ getAddr $ fromIntegral b
Partial _ ->
throwM $ userError "Partial input when parsing physical address."
Fail{} -> throwM $ userError "Physical address was malformed."
path = Path.absFile "/proc/self/pagemap"
WordPtr addr = ptrToWordPtr virt
getAddr x =
fromIntegral $ (x .&. 0x7fffffffffffff) * pageSize + addr `mod` pageSize
pageSize = fromIntegral sysconfPageSize
|
354221af60908e043e6842945434fd59cb718ffe952af7faca7f96e014230ce5 | onyx-platform/onyx | transform.clj | (ns ^:no-doc onyx.peer.transform
(:require [onyx.types :refer [->Result]]
[taoensso.timbre :refer [tracef trace]]
[onyx.protocol.task-state :refer :all]
[clj-tuple :as t]))
(defn collect-next-segments [f input throw-fn]
(let [segments (try (f input)
(catch Throwable e
(throw-fn (ex-info "Segment threw exception"
{:exception e :segment input}))))]
(if (sequential? segments) segments (t/vector segments))))
(defn apply-fn-single [f {:keys [onyx.core/batch onyx.core/task-map] :as event} throw-fn]
(assoc event
:onyx.core/transformed
(doall (map (fn [leaf] (collect-next-segments f leaf throw-fn)) batch))))
(defn collect-next-segments-batch [f input throw-fn]
(try (f input)
(catch Throwable e
(mapv (fn [segment]
(throw-fn
(ex-info "Batch threw exception"
{:exception e
:segment segment})))
input))))
(defn apply-fn-batch [f {:keys [onyx.core/batch] :as event} throw-fn]
(let [batch-results (collect-next-segments-batch f batch throw-fn)]
(when-not (= (count batch-results) (count batch))
(throw (ex-info ":onyx/batch-fn? functions must return the same number of elements as its input argment."
{:input-elements batch
:output-elements batch-results
:task (:onyx/name (:onyx.core/task-map event))})))
(assoc event
:onyx.core/transformed
(doall
(map
(fn [leaf output]
(if (sequential? output) output (t/vector output)))
batch
batch-results)))))
(defn curry-params [f params]
(reduce partial f params))
(defn apply-fn [a-fn f throw-fn state]
(-> state
(set-event! (let [event (get-event state)
;; dynamic param currying is pretty slow
;; maybe we can make a separate task-map option to turn this on
g (curry-params f (:onyx.core/params event))]
(a-fn g event throw-fn)))
(advance)))
| null | https://raw.githubusercontent.com/onyx-platform/onyx/74f9ae58cdbcfcb1163464595f1e6ae6444c9782/src/onyx/peer/transform.clj | clojure | dynamic param currying is pretty slow
maybe we can make a separate task-map option to turn this on | (ns ^:no-doc onyx.peer.transform
(:require [onyx.types :refer [->Result]]
[taoensso.timbre :refer [tracef trace]]
[onyx.protocol.task-state :refer :all]
[clj-tuple :as t]))
(defn collect-next-segments [f input throw-fn]
(let [segments (try (f input)
(catch Throwable e
(throw-fn (ex-info "Segment threw exception"
{:exception e :segment input}))))]
(if (sequential? segments) segments (t/vector segments))))
(defn apply-fn-single [f {:keys [onyx.core/batch onyx.core/task-map] :as event} throw-fn]
(assoc event
:onyx.core/transformed
(doall (map (fn [leaf] (collect-next-segments f leaf throw-fn)) batch))))
(defn collect-next-segments-batch [f input throw-fn]
(try (f input)
(catch Throwable e
(mapv (fn [segment]
(throw-fn
(ex-info "Batch threw exception"
{:exception e
:segment segment})))
input))))
(defn apply-fn-batch [f {:keys [onyx.core/batch] :as event} throw-fn]
(let [batch-results (collect-next-segments-batch f batch throw-fn)]
(when-not (= (count batch-results) (count batch))
(throw (ex-info ":onyx/batch-fn? functions must return the same number of elements as its input argment."
{:input-elements batch
:output-elements batch-results
:task (:onyx/name (:onyx.core/task-map event))})))
(assoc event
:onyx.core/transformed
(doall
(map
(fn [leaf output]
(if (sequential? output) output (t/vector output)))
batch
batch-results)))))
(defn curry-params [f params]
(reduce partial f params))
(defn apply-fn [a-fn f throw-fn state]
(-> state
(set-event! (let [event (get-event state)
g (curry-params f (:onyx.core/params event))]
(a-fn g event throw-fn)))
(advance)))
|
9b0b5cf5c2df6f9e88fe77ff6e95de9c580a81058deb038517623fe0351b8951 | caisah/sicp-exercises-and-examples | streams-of-pairs.scm | (define (interleave s1 s2)
(if (stream-null? s1)
s2
(cons-stream (stream-car s1)
(interleave s2 (stream-cdr s1)))))
(define (pairs s t)
(cons-stream
(list (stream-car s) (stream-car t))
(interleave
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(pairs (stream-cdr s) (stream-cdr t)))))
| null | https://raw.githubusercontent.com/caisah/sicp-exercises-and-examples/605c698d7495aa3474c2b6edcd1312cb16c5b5cb/3.5.3-exploiting_the_stream_paradigm/streams-of-pairs.scm | scheme | (define (interleave s1 s2)
(if (stream-null? s1)
s2
(cons-stream (stream-car s1)
(interleave s2 (stream-cdr s1)))))
(define (pairs s t)
(cons-stream
(list (stream-car s) (stream-car t))
(interleave
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(pairs (stream-cdr s) (stream-cdr t)))))
|
|
0b91c5a02bcf7d37f8e8c2b5a776090fdb75de890afb675e2fd875493dc93ae4 | esl/MongooseIM | shared_roster_SUITE.erl | %%==============================================================================
Copyright 2012 Erlang Solutions Ltd.
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%==============================================================================
-module(shared_roster_SUITE).
-compile([export_all, nowarn_export_all]).
-define(USERS, [alice, bob]).
-import(distributed_helper, [mim/0,
require_rpc_nodes/1,
rpc/4]).
-import(domain_helper, [host_type/0]).
%%--------------------------------------------------------------------
%% Suite configuration
%%--------------------------------------------------------------------
all() ->
[{group, shared_roster}].
groups() ->
G = [{shared_roster, [sequence], [receive_presences,
get_contacts,
delete_user,
add_user]}],
ct_helper:repeat_all_until_all_ok(G).
suite() ->
require_rpc_nodes([mim]) ++ escalus:suite().
%%--------------------------------------------------------------------
Init & teardown
%%--------------------------------------------------------------------
init_per_suite(Config0) ->
Config = dynamic_modules:save_modules(host_type(), Config0),
case get_auth_method() of
ldap ->
start_roster_module(ldap),
escalus:init_per_suite([{escalus_user_db, {module, ldap_helper}},
{ldap_auth, true} | Config]);
_ ->
escalus:init_per_suite([{ldap_auth, false} | Config])
end.
end_per_suite(Config) ->
dynamic_modules:restore_modules(Config),
escalus:end_per_suite(Config).
init_per_group(_, Config) ->
escalus:create_users(Config, escalus:get_users(?USERS)).
end_per_group(_, Config) ->
escalus:delete_users(Config, escalus:get_users(?USERS)).
init_per_testcase(CaseName,Config) ->
case proplists:get_value(ldap_auth, Config) of
false ->
{skip, no_shared_roster_available};
_ ->
escalus:init_per_testcase(CaseName,Config)
end.
end_per_testcase(CaseName,Config) ->
escalus:end_per_testcase(CaseName,Config).
%%--------------------------------------------------------------------
%% Tests
%%--------------------------------------------------------------------
%% Receive presences from roster people
receive_presences(Config) ->
escalus:story(Config,[{alice, 1}],fun(Alice) ->
becomes available
{ok, Bob} = escalus_client:start_for(Config, bob, <<"res1">>),
escalus:send(Bob, escalus_stanza:presence(<<"available">>)),
receives presence from
ReceivedA = escalus:wait_for_stanza(Alice),
escalus:assert(is_presence,ReceivedA),
escalus_assert:is_stanza_from(Bob,ReceivedA),
no_stanzas([Alice]),
escalus_client:stop(Config, Bob)
end).
get_contacts(Config) ->
escalus:story(Config,[{alice, 1}],fun(Alice) ->
sends
escalus_client:send(Alice, escalus_stanza:roster_get()),
Roster=escalus_client:wait_for_stanza(Alice),
Roster contains all created users excluding
escalus:assert(is_roster_result,Roster),
NumOfOtherUsers = length(escalus_users:get_users(?USERS))-1,
escalus:assert(count_roster_items,[NumOfOtherUsers],Roster)
end).
delete_user(Config) ->
NumOfOtherUsers = length(escalus_users:get_users(?USERS)) - 2,
%% wait to invalidate the roster group cache
timer:sleep(1200),
escalus:delete_users(Config, escalus:get_users([bob])),
escalus:story(Config, [{alice, 1}], fun(Alice) ->
escalus_client:send(Alice, escalus_stanza:roster_get()),
Roster=escalus_client:wait_for_stanza(Alice),
escalus:assert(is_roster_result, Roster),
escalus:assert(count_roster_items, [NumOfOtherUsers], Roster)
end).
add_user(Config) ->
escalus:create_users(Config, escalus:get_users([bob])),
timer:sleep(1200),
escalus:story(Config, [{alice, 1}], fun(Alice) ->
NumOfOtherUsers = length(escalus_users:get_users(?USERS)) - 1,
escalus_client:send(Alice, escalus_stanza:roster_get()),
Roster=escalus_client:wait_for_stanza(Alice),
escalus:assert(is_roster_result, Roster),
escalus:assert(count_roster_items, [NumOfOtherUsers], Roster)
end).
%%--------------------------------------------------------------------
%% Helpers
%%--------------------------------------------------------------------
start_roster_module(ldap) ->
dynamic_modules:ensure_modules(host_type(), [{mod_shared_roster_ldap, get_ldap_opts()}]);
start_roster_module(_) ->
ok.
get_auth_method() ->
HT = host_type(),
case rpc(mim(), mongoose_config, get_opt, [[{auth, HT}, methods], []]) of
[Method|_] ->
Method;
_ ->
none
end.
get_ldap_opts() ->
Opts = #{base => <<"ou=Users,dc=esl,dc=com">>,
groupattr => <<"ou">>,
memberattr => <<"cn">>,
userdesc => <<"cn">>,
filter => <<"(objectClass=inetOrgPerson)">>,
rfilter => <<"(objectClass=inetOrgPerson)">>,
group_cache_validity => 1,
user_cache_validity => 1},
maps:merge(config_parser_helper:default_mod_config(mod_shared_roster_ldap), Opts).
no_stanzas(Users) ->
lists:foreach(fun escalus_assert:has_no_stanzas/1, Users).
| null | https://raw.githubusercontent.com/esl/MongooseIM/2de7beed551c40223e3a7721e26d4eb76934d7b8/big_tests/tests/shared_roster_SUITE.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.
==============================================================================
--------------------------------------------------------------------
Suite configuration
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Tests
--------------------------------------------------------------------
Receive presences from roster people
wait to invalidate the roster group cache
--------------------------------------------------------------------
Helpers
-------------------------------------------------------------------- | Copyright 2012 Erlang Solutions Ltd.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(shared_roster_SUITE).
-compile([export_all, nowarn_export_all]).
-define(USERS, [alice, bob]).
-import(distributed_helper, [mim/0,
require_rpc_nodes/1,
rpc/4]).
-import(domain_helper, [host_type/0]).
all() ->
[{group, shared_roster}].
groups() ->
G = [{shared_roster, [sequence], [receive_presences,
get_contacts,
delete_user,
add_user]}],
ct_helper:repeat_all_until_all_ok(G).
suite() ->
require_rpc_nodes([mim]) ++ escalus:suite().
Init & teardown
init_per_suite(Config0) ->
Config = dynamic_modules:save_modules(host_type(), Config0),
case get_auth_method() of
ldap ->
start_roster_module(ldap),
escalus:init_per_suite([{escalus_user_db, {module, ldap_helper}},
{ldap_auth, true} | Config]);
_ ->
escalus:init_per_suite([{ldap_auth, false} | Config])
end.
end_per_suite(Config) ->
dynamic_modules:restore_modules(Config),
escalus:end_per_suite(Config).
init_per_group(_, Config) ->
escalus:create_users(Config, escalus:get_users(?USERS)).
end_per_group(_, Config) ->
escalus:delete_users(Config, escalus:get_users(?USERS)).
init_per_testcase(CaseName,Config) ->
case proplists:get_value(ldap_auth, Config) of
false ->
{skip, no_shared_roster_available};
_ ->
escalus:init_per_testcase(CaseName,Config)
end.
end_per_testcase(CaseName,Config) ->
escalus:end_per_testcase(CaseName,Config).
receive_presences(Config) ->
escalus:story(Config,[{alice, 1}],fun(Alice) ->
becomes available
{ok, Bob} = escalus_client:start_for(Config, bob, <<"res1">>),
escalus:send(Bob, escalus_stanza:presence(<<"available">>)),
receives presence from
ReceivedA = escalus:wait_for_stanza(Alice),
escalus:assert(is_presence,ReceivedA),
escalus_assert:is_stanza_from(Bob,ReceivedA),
no_stanzas([Alice]),
escalus_client:stop(Config, Bob)
end).
get_contacts(Config) ->
escalus:story(Config,[{alice, 1}],fun(Alice) ->
sends
escalus_client:send(Alice, escalus_stanza:roster_get()),
Roster=escalus_client:wait_for_stanza(Alice),
Roster contains all created users excluding
escalus:assert(is_roster_result,Roster),
NumOfOtherUsers = length(escalus_users:get_users(?USERS))-1,
escalus:assert(count_roster_items,[NumOfOtherUsers],Roster)
end).
delete_user(Config) ->
NumOfOtherUsers = length(escalus_users:get_users(?USERS)) - 2,
timer:sleep(1200),
escalus:delete_users(Config, escalus:get_users([bob])),
escalus:story(Config, [{alice, 1}], fun(Alice) ->
escalus_client:send(Alice, escalus_stanza:roster_get()),
Roster=escalus_client:wait_for_stanza(Alice),
escalus:assert(is_roster_result, Roster),
escalus:assert(count_roster_items, [NumOfOtherUsers], Roster)
end).
add_user(Config) ->
escalus:create_users(Config, escalus:get_users([bob])),
timer:sleep(1200),
escalus:story(Config, [{alice, 1}], fun(Alice) ->
NumOfOtherUsers = length(escalus_users:get_users(?USERS)) - 1,
escalus_client:send(Alice, escalus_stanza:roster_get()),
Roster=escalus_client:wait_for_stanza(Alice),
escalus:assert(is_roster_result, Roster),
escalus:assert(count_roster_items, [NumOfOtherUsers], Roster)
end).
start_roster_module(ldap) ->
dynamic_modules:ensure_modules(host_type(), [{mod_shared_roster_ldap, get_ldap_opts()}]);
start_roster_module(_) ->
ok.
get_auth_method() ->
HT = host_type(),
case rpc(mim(), mongoose_config, get_opt, [[{auth, HT}, methods], []]) of
[Method|_] ->
Method;
_ ->
none
end.
get_ldap_opts() ->
Opts = #{base => <<"ou=Users,dc=esl,dc=com">>,
groupattr => <<"ou">>,
memberattr => <<"cn">>,
userdesc => <<"cn">>,
filter => <<"(objectClass=inetOrgPerson)">>,
rfilter => <<"(objectClass=inetOrgPerson)">>,
group_cache_validity => 1,
user_cache_validity => 1},
maps:merge(config_parser_helper:default_mod_config(mod_shared_roster_ldap), Opts).
no_stanzas(Users) ->
lists:foreach(fun escalus_assert:has_no_stanzas/1, Users).
|
b5ce331441b2055e4e99f899eec28504be05bf2691d1ce0d27baad58183c96d7 | uw-unsat/leanette-popl22-artifact | imdb250_2.rkt | #lang rosette
(require (only-in racket/runtime-path define-runtime-path))
(require "../dom.rkt")
(require "../websynth.rkt")
(require "../websynthlib.rkt")
(define-runtime-path html (build-path ".." "html/imdb250.html"))
(define dom (read-DOMNode html))
(define-tags (tags dom))
(define max_zpath_depth (depth dom))
; Record 0 fields
(define-symbolic r0f0zpath tag? [max_zpath_depth])
(define-symbolic r0fieldmask boolean? [max_zpath_depth])
; Record 1 fields
(define-symbolic r1f0zpath tag? [max_zpath_depth])
(define-symbolic r1fieldmask boolean? [max_zpath_depth])
; Cross-record Mask
(define-symbolic recordmask boolean? [max_zpath_depth])
(current-bitwidth #f)
(define (demonstration)
; Record 0 zpath asserts
(assert (path? r0f0zpath dom "The Shawshank Redemption"))
; Record 1 zpath asserts
(assert (path? r1f0zpath dom "Fight Club"))
; Record Mask
(generate-mask r0f0zpath r1f0zpath recordmask max_zpath_depth))
; Solve
(define (scrape)
(define sol (solve (demonstration)))
; Record 0 zpaths
; Record 1 zpaths
Construct final zpaths
(define r0f0zpath_list (map label (evaluate r0f0zpath sol)))
(define generalized_r0f0zpath_list
(apply-mask r0f0zpath_list (evaluate recordmask sol)))
(define field0_zpath (synthsis_solution->zpath generalized_r0f0zpath_list))
(zip
(DOM-Flatten (DOM-XPath dom field0_zpath))
))
(scrape)
| null | https://raw.githubusercontent.com/uw-unsat/leanette-popl22-artifact/80fea2519e61b45a283fbf7903acdf6d5528dbe7/rosette-benchmarks-3/websynth/benchmarks/imdb250_2.rkt | racket | Record 0 fields
Record 1 fields
Cross-record Mask
Record 0 zpath asserts
Record 1 zpath asserts
Record Mask
Solve
Record 0 zpaths
Record 1 zpaths | #lang rosette
(require (only-in racket/runtime-path define-runtime-path))
(require "../dom.rkt")
(require "../websynth.rkt")
(require "../websynthlib.rkt")
(define-runtime-path html (build-path ".." "html/imdb250.html"))
(define dom (read-DOMNode html))
(define-tags (tags dom))
(define max_zpath_depth (depth dom))
(define-symbolic r0f0zpath tag? [max_zpath_depth])
(define-symbolic r0fieldmask boolean? [max_zpath_depth])
(define-symbolic r1f0zpath tag? [max_zpath_depth])
(define-symbolic r1fieldmask boolean? [max_zpath_depth])
(define-symbolic recordmask boolean? [max_zpath_depth])
(current-bitwidth #f)
(define (demonstration)
(assert (path? r0f0zpath dom "The Shawshank Redemption"))
(assert (path? r1f0zpath dom "Fight Club"))
(generate-mask r0f0zpath r1f0zpath recordmask max_zpath_depth))
(define (scrape)
(define sol (solve (demonstration)))
Construct final zpaths
(define r0f0zpath_list (map label (evaluate r0f0zpath sol)))
(define generalized_r0f0zpath_list
(apply-mask r0f0zpath_list (evaluate recordmask sol)))
(define field0_zpath (synthsis_solution->zpath generalized_r0f0zpath_list))
(zip
(DOM-Flatten (DOM-XPath dom field0_zpath))
))
(scrape)
|
ff8bdcf959cee9f53fd132d06439b7763a3aadd871d85be070c5d4988f3e3d14 | chrovis/cljam | writer_test.clj | (ns cljam.io.bcf.writer-test
(:require [clojure.test :refer [deftest is are]]
[clojure.java.io :as cio]
[clojure.string :as cstr]
[cljam.io.bcf.writer :as bcf-writer]
[cljam.io.util.bgzf :as bgzf]
[cljam.test-common :refer
[with-before-after
prepare-cache!
clean-cache!
temp-dir]])
(:import [java.nio ByteBuffer ByteOrder]
[java.io ByteArrayOutputStream File]))
(deftest about-encode-typed-value
(let [ba (#'bcf-writer/encode-typed-value :int (vec (repeat 14 1)))]
(is
(= (seq ba)
[(unchecked-byte 0xE1) 1 1 1 1 1 1 1 1 1 1 1 1 1 1])))
(let [ba (#'bcf-writer/encode-typed-value :int (vec (repeat 15 1)))]
(is
(= (seq ba)
[(unchecked-byte 0xF1) 0x11 0x0F 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1])))
(let [ba (#'bcf-writer/encode-typed-value :int (vec (repeat 127 1)))]
(is
(= (seq ba)
(concat (map unchecked-byte [0xF1 0x11 0x7F]) (repeat 127 1)))))
(let [ba (#'bcf-writer/encode-typed-value :int (vec (repeat 255 1)))]
(is
(= (seq ba)
(concat (map unchecked-byte [0xF1 0x12 0xFF 0x00]) (repeat 255 1)))))
(let [ba (#'bcf-writer/encode-typed-value :int (vec (repeat 32768 1)))]
(is
(= (seq ba)
(concat (map unchecked-byte [0xF1 0x13 0x00 0x80 0x00 0x00])
(repeat 32768 1))))))
(defn- bb->seq [^ByteBuffer bb]
(seq (.array bb)))
(defn- bytes->str [xs]
(cstr/join \space (map #(format "0x%02x" %) xs)))
(deftest about-encode-variant-shared
(are [?var ?bytes]
(= (map unchecked-byte ?bytes)
(bb->seq (@#'bcf-writer/encode-variant-shared ?var)))
{:chr 0, :pos 1, :ref "N", :ref-length 1, :qual nil,
:alt nil, :info [], :format nil, :id nil, :filter nil,
:genotype nil, :n-sample 0}
[0x00 0x00 0x00 0x00 ;; int32 chrom
0x00 0x00 0x00 0x00 ;; int32 pos-1
uint32 ref - length
float32 qual = nil
uint32 n - allele < < 16 | n - info
uint32 n - fmt < < 24 | n - sample
0x07 ;; 0 x 7(char) id = nil
1 x 7(char ) N ref
0x00] ;; 0 filter
{:chr 0, :pos 1, :ref "A", :ref-length 1, :qual 1.0, :alt ["C"],
:info [[0 :int 1] [10 :int 300]], :format [0 1], :id "TEST", :filter [0],
:genotype [[0 :int [0 1]] [1 :int [16 32]]], :n-sample 2}
[0x00 0x00 0x00 0x00 ;; int32 chrom
0x00 0x00 0x00 0x00 ;; int32 pos-1
uint32 ref - length
float32 qual
uint32 n - allele < < 16 | n - info
uint32 n - fmt < < 24 | n - sample
4 x 7(char ) , T , E , S , T
1 x 7(char ) , A ref
1 x 7(char ) , C alt
1 x 1(uint8 ) , 0 filter PASS
1 x 1(uint8 ) , 0 info - key1
1 x 1(uint8 ) , 1 info - value1
1 x 1(uint8 ) , 10 info - key2
1 x 2(uint16 ) , 300 info - value2
{:chr 2, :pos 35, :ref "AC", :ref-length 2, :qual nil,
:alt ["ACCC" "ACCCC"],
:info [[1 :str "VariantCallFormatSampleText"]
[2 :str ["FOO" "BAR"]]
[4 :int [256]]],
:format [], :id nil, :filter [0], :genotype {}, :n-sample 0}
[0x02 0x00 0x00 0x00 ;; int32 chrom
0x22 0x00 0x00 0x00 ;; int32 pos-1
uint32 ref - length
float32 qual = nil
uint32 n - allele < < 16 | n - info
uint32 n - fmt < < 24 | n - sample
0x07 ;; 0 x 7(char) id = nil
2 x 7(char ) , AC ref
4 x 7(char ) ACCC alt
5 x 7(char ) ACCCC alt
1 x 1(uint8 ) , 0 filter PASS
1 x 1(uint8 ) , 1 info - key
0xF0 ( size follows ) | 7(char ) , 1 x 1(uint8 ) , 27 ( length )
0x56 0x61 0x72 0x69 0x61 0x6e 0x74 ;; Variant
0x43 0x61 0x6c 0x6c ;; Call
0x46 0x6f 0x72 0x6d 0x61 0x74 ;; Format
0x53 0x61 0x6d 0x70 0x6c 0x65 ;; Sample
0x54 0x65 0x78 0x74 ;; Text
1 x 1(uint8 ) , 2 info - key
0x77 0x46 0x4f 0x4f 0x2c 0x42 0x41 0x52
1 x 1(uint8 ) , 4 info - key
1 x 2(uint16 ) 0x100
{:chr 2, :pos 321682, :id "bnd_V", :ref "T", :alt ["]13:123456]T"],
:ref-length 1, :qual 6.0, :filter [0],
:info [[1 :char [\a \b \c]]],
:format [], :genotype {}, :n-sample 0}
[0x02 0x00 0x00 0x00 ;; int32 chrom
0x91 0xe8 0x04 0x00 ;; int32 pos-1
uint32 ref - length
float32 qual
uint32 n - allele < < 16 | n - info
uint32 n - fmt < < 24 | n - sample
5 x 7(char ) , i d = bnd_V
1 x 7(char ) , ref = T
12 x 7(char ) ] 13:123456]T
0xc7 0x5d 0x31 0x33 0x3a 0x31 0x32 0x33 0x34 0x35 0x36 0x5d 0x54
1 x 1(uint8 ) , 0 filter PASS
1 x 1(uint8 ) , 1 info - key
5 x 7(char ) , a , b , c
))
(deftest about-encode-variant-indv
(are [?var ?bytes]
(= (bytes->str (map unchecked-byte ?bytes))
(bytes->str (bb->seq (#'bcf-writer/encode-variant-indv ?var))))
{:genotype [[0 :int [[0] [1]]]
[1 :int [[16] [32]]]],
:n-sample 2}
1 x 1(uint8 ) , 0 genotype key
1 x 1(uint8 ) , [ 0 1 ]
1 x 1(uint8 ) , 1 genotype key
1 x 1(uint8 ) , [ 16 32 ]
{:genotype [[0 :int [[2 3] [4 3] [4 4]]]
[1 :int [[48] [48] [43]]]
[2 :int [[1] [8] [5]]]
[3 :int [[51 51] [51 51] [nil nil]]]],
:n-sample 3}
[0x11 0x00
0x21 0x02 0x03 0x04 0x03 0x04 0x04
0x11 0x01
0x11 0x30 0x30 0x2b
0x11 0x02
0x11 0x01 0x08 0x05
0x11 0x03
0x21 0x33 0x33 0x33 0x33 0x80 0x80]
{:genotype [[1 :str [["AA" "BB" "CC"] ["D" "E" "F"]]]
[2 :char [[\a \b \c] [\d]]]],
:n-sample 2}
1 x 1(uint8 ) , 1 genotype key
8 x 7(char )
AA , BB , CC
0x44 0x2c 0x45 0x2c 0x46 0x00 0x00 0x00 ;; D,E,F\0\0\0
1 x 1(uint8 ) , 2 genotype key
6 x 7(char )
0x61 0x2c 0x62 0x2c 0x63 ;; a,b,c
0x64 0x00 0x00 0x00 0x00] ;; d\0\0\0\0
{:genotype [[1 :str [nil ["ALT1" "ALT2"] nil]]],
:n-sample 3}
[0x11 0x01
0x97
0x2e 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x41 0x4c 0x54 0x31 0x2c 0x41 0x4c 0x54 0x32
0x2e 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00]
{:genotype [[2 :int [[1] [2 3] nil]]],
:n-sample 3}
[0x11 0x02
0x21
0x01 0x81
0x02 0x03
0x80 0x81]
{:genotype [[3 :int [[1] [2 3 4] nil]]],
:n-sample 3}
[0x11 0x03
0x31
0x01 0x81 0x81
0x02 0x03 0x04
0x80 0x81 0x81]
{:genotype [[4 :int [[1 nil nil] [2 3 4] nil]]],
:n-sample 3}
[0x11 0x04
0x31
0x01 0x80 0x80
0x02 0x03 0x04
0x80 0x81 0x81]
{:genotype [[5 :int [1 2 nil]]],
:n-sample 3}
[0x11 0x05
0x11
0x01
0x02
0x80]
{:genotype [[6 :float [[1.0] [2.0 3.0] nil]]],
:n-sample 3}
[0x11 0x06
0x25
0x00 0x00 0x80 0x3f 0x02 0x00 0x80 0x7f
0x00 0x00 0x00 0x40 0x00 0x00 0x40 0x40
0x01 0x00 0x80 0x7f 0x02 0x00 0x80 0x7f]
{:genotype [[7 :int [nil [2 2] [2 4]]]],
:n-sample 3}
[0x11 0x07
0x21
0x80 0x81
0x02 0x02
0x02 0x04]))
(defn- bgzf->bb ^ByteBuffer [f]
(with-open [is (bgzf/bgzf-input-stream f)
baos (ByteArrayOutputStream.)]
(while (pos? (.available is))
(.write baos (.read is)))
(.flush baos)
(doto (ByteBuffer/wrap (.toByteArray baos))
(.order ByteOrder/LITTLE_ENDIAN))))
(defn- read-variant-blocks! [f]
(let [bb (bgzf->bb f)]
(doseq [b (map byte [\B \C \F 2 2])]
(assert (= b (.get bb))))
(.position bb (+ (.getInt bb) (.position bb)))
(->> (repeatedly
#(when (.hasRemaining bb)
(let [shared (byte-array (.getInt bb))
indiv (byte-array (.getInt bb))]
(.get bb shared)
(.get bb indiv)
[(vec shared) (vec indiv)])))
(take-while some?)
vec)))
(defn- write-variants&read-blocks [meta-info header variants]
(with-before-after {:before (prepare-cache!)
:after (clean-cache!)}
(let [tmp (cio/file temp-dir "write-variants.bcf")]
(with-open [w (bcf-writer/writer tmp meta-info header)]
(bcf-writer/write-variants w variants))
(read-variant-blocks! tmp))))
(deftest write-variants
(let [meta-info {:fileformat "VCFv4.3"
:contig [{:id "1", :length 100}]}
header ["CHROM" "POS" "ID" "REF" "ALT" "QUAL" "FILTER" "INFO"
"FORMAT" "SAMPLE"]]
(are [?variants ?blocks]
(= (map #(map (partial map unchecked-byte) %) ?blocks)
(write-variants&read-blocks meta-info header ?variants))
[{:chr "1", :pos 10, :ref "A", :alt ["C"],
:info {:UNDECLARED-INFO #{"???"}},
:FORMAT [:UNDECLARED-FORMAT]}]
[[[0x00 0x00 0x00 0x00
0x09 0x00 0x00 0x00
0x01 0x00 0x00 0x00
0x01 0x00 0x80 0x7f
0x00 0x00 0x02 0x00
0x01 0x00 0x00 0x00
0x07
0x17 0x41
0x17 0x43
0x00]
[]]])))
(deftest default-meta-info
(let [tmp (File/createTempFile "default-meta-info" ".bcf")
header ["CHROM" "POS" "ID" "REF" "ALT" "QUAL" "FILTER" "INFO"]
s (->> ["##fileformat=VCFv4.3"
"##FILTER=<ID=PASS,Description=\"All filters passed\",IDX=0>"
(str "#" (cstr/join \tab header) \newline (char 0))]
(cstr/join \newline))
_ (with-open [_ (bcf-writer/writer tmp {} header)])
bytes (bb->seq (bgzf->bb tmp))]
(is (= (concat (.getBytes "BCF\2\2") [(.length s) 0 0 0] (.getBytes s))
bytes))
(.delete tmp)))
| null | https://raw.githubusercontent.com/chrovis/cljam/2b8e7386765be8efdbbbb4f18dbc52447f4a08af/test/cljam/io/bcf/writer_test.clj | clojure | int32 chrom
int32 pos-1
0 x 7(char) id = nil
0 filter
int32 chrom
int32 pos-1
int32 chrom
int32 pos-1
0 x 7(char) id = nil
Variant
Call
Format
Sample
Text
int32 chrom
int32 pos-1
D,E,F\0\0\0
a,b,c
d\0\0\0\0 | (ns cljam.io.bcf.writer-test
(:require [clojure.test :refer [deftest is are]]
[clojure.java.io :as cio]
[clojure.string :as cstr]
[cljam.io.bcf.writer :as bcf-writer]
[cljam.io.util.bgzf :as bgzf]
[cljam.test-common :refer
[with-before-after
prepare-cache!
clean-cache!
temp-dir]])
(:import [java.nio ByteBuffer ByteOrder]
[java.io ByteArrayOutputStream File]))
(deftest about-encode-typed-value
(let [ba (#'bcf-writer/encode-typed-value :int (vec (repeat 14 1)))]
(is
(= (seq ba)
[(unchecked-byte 0xE1) 1 1 1 1 1 1 1 1 1 1 1 1 1 1])))
(let [ba (#'bcf-writer/encode-typed-value :int (vec (repeat 15 1)))]
(is
(= (seq ba)
[(unchecked-byte 0xF1) 0x11 0x0F 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1])))
(let [ba (#'bcf-writer/encode-typed-value :int (vec (repeat 127 1)))]
(is
(= (seq ba)
(concat (map unchecked-byte [0xF1 0x11 0x7F]) (repeat 127 1)))))
(let [ba (#'bcf-writer/encode-typed-value :int (vec (repeat 255 1)))]
(is
(= (seq ba)
(concat (map unchecked-byte [0xF1 0x12 0xFF 0x00]) (repeat 255 1)))))
(let [ba (#'bcf-writer/encode-typed-value :int (vec (repeat 32768 1)))]
(is
(= (seq ba)
(concat (map unchecked-byte [0xF1 0x13 0x00 0x80 0x00 0x00])
(repeat 32768 1))))))
(defn- bb->seq [^ByteBuffer bb]
(seq (.array bb)))
(defn- bytes->str [xs]
(cstr/join \space (map #(format "0x%02x" %) xs)))
(deftest about-encode-variant-shared
(are [?var ?bytes]
(= (map unchecked-byte ?bytes)
(bb->seq (@#'bcf-writer/encode-variant-shared ?var)))
{:chr 0, :pos 1, :ref "N", :ref-length 1, :qual nil,
:alt nil, :info [], :format nil, :id nil, :filter nil,
:genotype nil, :n-sample 0}
uint32 ref - length
float32 qual = nil
uint32 n - allele < < 16 | n - info
uint32 n - fmt < < 24 | n - sample
1 x 7(char ) N ref
{:chr 0, :pos 1, :ref "A", :ref-length 1, :qual 1.0, :alt ["C"],
:info [[0 :int 1] [10 :int 300]], :format [0 1], :id "TEST", :filter [0],
:genotype [[0 :int [0 1]] [1 :int [16 32]]], :n-sample 2}
uint32 ref - length
float32 qual
uint32 n - allele < < 16 | n - info
uint32 n - fmt < < 24 | n - sample
4 x 7(char ) , T , E , S , T
1 x 7(char ) , A ref
1 x 7(char ) , C alt
1 x 1(uint8 ) , 0 filter PASS
1 x 1(uint8 ) , 0 info - key1
1 x 1(uint8 ) , 1 info - value1
1 x 1(uint8 ) , 10 info - key2
1 x 2(uint16 ) , 300 info - value2
{:chr 2, :pos 35, :ref "AC", :ref-length 2, :qual nil,
:alt ["ACCC" "ACCCC"],
:info [[1 :str "VariantCallFormatSampleText"]
[2 :str ["FOO" "BAR"]]
[4 :int [256]]],
:format [], :id nil, :filter [0], :genotype {}, :n-sample 0}
uint32 ref - length
float32 qual = nil
uint32 n - allele < < 16 | n - info
uint32 n - fmt < < 24 | n - sample
2 x 7(char ) , AC ref
4 x 7(char ) ACCC alt
5 x 7(char ) ACCCC alt
1 x 1(uint8 ) , 0 filter PASS
1 x 1(uint8 ) , 1 info - key
0xF0 ( size follows ) | 7(char ) , 1 x 1(uint8 ) , 27 ( length )
1 x 1(uint8 ) , 2 info - key
0x77 0x46 0x4f 0x4f 0x2c 0x42 0x41 0x52
1 x 1(uint8 ) , 4 info - key
1 x 2(uint16 ) 0x100
{:chr 2, :pos 321682, :id "bnd_V", :ref "T", :alt ["]13:123456]T"],
:ref-length 1, :qual 6.0, :filter [0],
:info [[1 :char [\a \b \c]]],
:format [], :genotype {}, :n-sample 0}
uint32 ref - length
float32 qual
uint32 n - allele < < 16 | n - info
uint32 n - fmt < < 24 | n - sample
5 x 7(char ) , i d = bnd_V
1 x 7(char ) , ref = T
12 x 7(char ) ] 13:123456]T
0xc7 0x5d 0x31 0x33 0x3a 0x31 0x32 0x33 0x34 0x35 0x36 0x5d 0x54
1 x 1(uint8 ) , 0 filter PASS
1 x 1(uint8 ) , 1 info - key
5 x 7(char ) , a , b , c
))
(deftest about-encode-variant-indv
(are [?var ?bytes]
(= (bytes->str (map unchecked-byte ?bytes))
(bytes->str (bb->seq (#'bcf-writer/encode-variant-indv ?var))))
{:genotype [[0 :int [[0] [1]]]
[1 :int [[16] [32]]]],
:n-sample 2}
1 x 1(uint8 ) , 0 genotype key
1 x 1(uint8 ) , [ 0 1 ]
1 x 1(uint8 ) , 1 genotype key
1 x 1(uint8 ) , [ 16 32 ]
{:genotype [[0 :int [[2 3] [4 3] [4 4]]]
[1 :int [[48] [48] [43]]]
[2 :int [[1] [8] [5]]]
[3 :int [[51 51] [51 51] [nil nil]]]],
:n-sample 3}
[0x11 0x00
0x21 0x02 0x03 0x04 0x03 0x04 0x04
0x11 0x01
0x11 0x30 0x30 0x2b
0x11 0x02
0x11 0x01 0x08 0x05
0x11 0x03
0x21 0x33 0x33 0x33 0x33 0x80 0x80]
{:genotype [[1 :str [["AA" "BB" "CC"] ["D" "E" "F"]]]
[2 :char [[\a \b \c] [\d]]]],
:n-sample 2}
1 x 1(uint8 ) , 1 genotype key
8 x 7(char )
AA , BB , CC
1 x 1(uint8 ) , 2 genotype key
6 x 7(char )
{:genotype [[1 :str [nil ["ALT1" "ALT2"] nil]]],
:n-sample 3}
[0x11 0x01
0x97
0x2e 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00
0x41 0x4c 0x54 0x31 0x2c 0x41 0x4c 0x54 0x32
0x2e 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00]
{:genotype [[2 :int [[1] [2 3] nil]]],
:n-sample 3}
[0x11 0x02
0x21
0x01 0x81
0x02 0x03
0x80 0x81]
{:genotype [[3 :int [[1] [2 3 4] nil]]],
:n-sample 3}
[0x11 0x03
0x31
0x01 0x81 0x81
0x02 0x03 0x04
0x80 0x81 0x81]
{:genotype [[4 :int [[1 nil nil] [2 3 4] nil]]],
:n-sample 3}
[0x11 0x04
0x31
0x01 0x80 0x80
0x02 0x03 0x04
0x80 0x81 0x81]
{:genotype [[5 :int [1 2 nil]]],
:n-sample 3}
[0x11 0x05
0x11
0x01
0x02
0x80]
{:genotype [[6 :float [[1.0] [2.0 3.0] nil]]],
:n-sample 3}
[0x11 0x06
0x25
0x00 0x00 0x80 0x3f 0x02 0x00 0x80 0x7f
0x00 0x00 0x00 0x40 0x00 0x00 0x40 0x40
0x01 0x00 0x80 0x7f 0x02 0x00 0x80 0x7f]
{:genotype [[7 :int [nil [2 2] [2 4]]]],
:n-sample 3}
[0x11 0x07
0x21
0x80 0x81
0x02 0x02
0x02 0x04]))
(defn- bgzf->bb ^ByteBuffer [f]
(with-open [is (bgzf/bgzf-input-stream f)
baos (ByteArrayOutputStream.)]
(while (pos? (.available is))
(.write baos (.read is)))
(.flush baos)
(doto (ByteBuffer/wrap (.toByteArray baos))
(.order ByteOrder/LITTLE_ENDIAN))))
(defn- read-variant-blocks! [f]
(let [bb (bgzf->bb f)]
(doseq [b (map byte [\B \C \F 2 2])]
(assert (= b (.get bb))))
(.position bb (+ (.getInt bb) (.position bb)))
(->> (repeatedly
#(when (.hasRemaining bb)
(let [shared (byte-array (.getInt bb))
indiv (byte-array (.getInt bb))]
(.get bb shared)
(.get bb indiv)
[(vec shared) (vec indiv)])))
(take-while some?)
vec)))
(defn- write-variants&read-blocks [meta-info header variants]
(with-before-after {:before (prepare-cache!)
:after (clean-cache!)}
(let [tmp (cio/file temp-dir "write-variants.bcf")]
(with-open [w (bcf-writer/writer tmp meta-info header)]
(bcf-writer/write-variants w variants))
(read-variant-blocks! tmp))))
(deftest write-variants
(let [meta-info {:fileformat "VCFv4.3"
:contig [{:id "1", :length 100}]}
header ["CHROM" "POS" "ID" "REF" "ALT" "QUAL" "FILTER" "INFO"
"FORMAT" "SAMPLE"]]
(are [?variants ?blocks]
(= (map #(map (partial map unchecked-byte) %) ?blocks)
(write-variants&read-blocks meta-info header ?variants))
[{:chr "1", :pos 10, :ref "A", :alt ["C"],
:info {:UNDECLARED-INFO #{"???"}},
:FORMAT [:UNDECLARED-FORMAT]}]
[[[0x00 0x00 0x00 0x00
0x09 0x00 0x00 0x00
0x01 0x00 0x00 0x00
0x01 0x00 0x80 0x7f
0x00 0x00 0x02 0x00
0x01 0x00 0x00 0x00
0x07
0x17 0x41
0x17 0x43
0x00]
[]]])))
(deftest default-meta-info
(let [tmp (File/createTempFile "default-meta-info" ".bcf")
header ["CHROM" "POS" "ID" "REF" "ALT" "QUAL" "FILTER" "INFO"]
s (->> ["##fileformat=VCFv4.3"
"##FILTER=<ID=PASS,Description=\"All filters passed\",IDX=0>"
(str "#" (cstr/join \tab header) \newline (char 0))]
(cstr/join \newline))
_ (with-open [_ (bcf-writer/writer tmp {} header)])
bytes (bb->seq (bgzf->bb tmp))]
(is (= (concat (.getBytes "BCF\2\2") [(.length s) 0 0 0] (.getBytes s))
bytes))
(.delete tmp)))
|
3b2d396079b537d20a9b23b1931fa63c1196a431a22f5f406739c6da76e5780d | diku-dk/futhark | SegOp.hs | # LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
-- | Segmented operations. These correspond to perfect @map@ nests on
top of /something/ , except that the @map@s are conceptually only
over @iota@s ( so there will be explicit indexing inside them ) .
module Futhark.IR.SegOp
( SegOp (..),
segLevel,
segBody,
segSpace,
typeCheckSegOp,
SegSpace (..),
scopeOfSegSpace,
segSpaceDims,
-- * Details
HistOp (..),
histType,
splitHistResults,
SegBinOp (..),
segBinOpResults,
segBinOpChunks,
KernelBody (..),
aliasAnalyseKernelBody,
consumedInKernelBody,
ResultManifest (..),
KernelResult (..),
kernelResultCerts,
kernelResultSubExp,
-- ** Generic traversal
SegOpMapper (..),
identitySegOpMapper,
mapSegOpM,
traverseSegOpStms,
-- * Simplification
simplifySegOp,
HasSegOp (..),
segOpRules,
-- * Memory
segOpReturns,
)
where
import Control.Category
import Control.Monad.Identity hiding (mapM_)
import Control.Monad.Reader hiding (mapM_)
import Control.Monad.State.Strict
import Control.Monad.Writer hiding (mapM_)
import Data.Bifunctor (first)
import Data.Bitraversable
import Data.Foldable (traverse_)
import Data.List
( elemIndex,
foldl',
groupBy,
intersperse,
isPrefixOf,
partition,
)
import Data.Map.Strict qualified as M
import Data.Maybe
import Futhark.Analysis.Alias qualified as Alias
import Futhark.Analysis.Metrics
import Futhark.Analysis.PrimExp.Convert
import Futhark.Analysis.SymbolTable qualified as ST
import Futhark.Analysis.UsageTable qualified as UT
import Futhark.IR
import Futhark.IR.Aliases
( Aliases,
CanBeAliased (..),
)
import Futhark.IR.Mem
import Futhark.IR.Prop.Aliases
import Futhark.IR.TypeCheck qualified as TC
import Futhark.Optimise.Simplify.Engine qualified as Engine
import Futhark.Optimise.Simplify.Rep
import Futhark.Optimise.Simplify.Rule
import Futhark.Tools
import Futhark.Transform.Rename
import Futhark.Transform.Substitute
import Futhark.Util (chunks, maybeNth)
import Futhark.Util.Pretty
( Doc,
apply,
hsep,
parens,
ppTuple',
pretty,
(<+>),
(</>),
)
import Futhark.Util.Pretty qualified as PP
import Prelude hiding (id, (.))
-- | An operator for 'SegHist'.
data HistOp rep = HistOp
{ histShape :: Shape,
histRaceFactor :: SubExp,
histDest :: [VName],
histNeutral :: [SubExp],
-- | In case this operator is semantically a vectorised
-- operator (corresponding to a perfect map nest in the
SOACS representation ) , these are the logical
-- "dimensions". This is used to generate more efficient
-- code.
histOpShape :: Shape,
histOp :: Lambda rep
}
deriving (Eq, Ord, Show)
-- | The type of a histogram produced by a 'HistOp'. This can be
-- different from the type of the 'histDest's in case we are
-- dealing with a segmented histogram.
histType :: HistOp rep -> [Type]
histType op =
map (`arrayOfShape` (histShape op <> histOpShape op)) $
lambdaReturnType $
histOp op
-- | Split reduction results returned by a 'KernelBody' into those
-- that correspond to indexes for the 'HistOp's, and those that
-- correspond to value.
splitHistResults :: [HistOp rep] -> [SubExp] -> [([SubExp], [SubExp])]
splitHistResults ops res =
let ranks = map (shapeRank . histShape) ops
(idxs, vals) = splitAt (sum ranks) res
in zip
(chunks ranks idxs)
(chunks (map (length . histDest) ops) vals)
| An operator for ' SegScan ' and ' SegRed ' .
data SegBinOp rep = SegBinOp
{ segBinOpComm :: Commutativity,
segBinOpLambda :: Lambda rep,
segBinOpNeutral :: [SubExp],
-- | In case this operator is semantically a vectorised
-- operator (corresponding to a perfect map nest in the
SOACS representation ) , these are the logical
-- "dimensions". This is used to generate more efficient
-- code.
segBinOpShape :: Shape
}
deriving (Eq, Ord, Show)
-- | How many reduction results are produced by these 'SegBinOp's?
segBinOpResults :: [SegBinOp rep] -> Int
segBinOpResults = sum . map (length . segBinOpNeutral)
-- | Split some list into chunks equal to the number of values
-- returned by each 'SegBinOp'
segBinOpChunks :: [SegBinOp rep] -> [a] -> [[a]]
segBinOpChunks = chunks . map (length . segBinOpNeutral)
-- | The body of a 'SegOp'.
data KernelBody rep = KernelBody
{ kernelBodyDec :: BodyDec rep,
kernelBodyStms :: Stms rep,
kernelBodyResult :: [KernelResult]
}
deriving instance RepTypes rep => Ord (KernelBody rep)
deriving instance RepTypes rep => Show (KernelBody rep)
deriving instance RepTypes rep => Eq (KernelBody rep)
-- | Metadata about whether there is a subtle point to this
' KernelResult ' . This is used to protect things like tiling , which
-- might otherwise be removed by the simplifier because they're
-- semantically redundant. This has no semantic effect and can be
-- ignored at code generation.
data ResultManifest
= -- | Don't simplify this one!
ResultNoSimplify
| -- | Go nuts.
ResultMaySimplify
| -- | The results produced are only used within the
-- same physical thread later on, and can thus be
-- kept in registers.
ResultPrivate
deriving (Eq, Show, Ord)
-- | A 'KernelBody' does not return an ordinary 'Result'. Instead, it
-- returns a list of these.
data KernelResult
= -- | Each "worker" in the kernel returns this.
-- Whether this is a result-per-thread or a
-- result-per-group depends on where the 'SegOp' occurs.
Returns ResultManifest Certs SubExp
| WriteReturns
Certs
Shape -- Size of array. Must match number of dims.
VName -- Which array
[(Slice SubExp, SubExp)]
| TileReturns
Certs
[(SubExp, SubExp)] -- Total/tile for each dimension
VName -- Tile written by this worker.
The TileReturns must not expect more than one
-- result to be written per physical thread.
| RegTileReturns
Certs
-- For each dim of result:
[ ( SubExp, -- size of this dim.
SubExp, -- block tile size for this dim.
SubExp -- reg tile size for this dim.
)
]
VName -- Tile returned by this worker/group.
deriving (Eq, Show, Ord)
| Get the certs for this ' KernelResult ' .
kernelResultCerts :: KernelResult -> Certs
kernelResultCerts (Returns _ cs _) = cs
kernelResultCerts (WriteReturns cs _ _ _) = cs
kernelResultCerts (TileReturns cs _ _) = cs
kernelResultCerts (RegTileReturns cs _ _) = cs
| Get the root t'SubExp ' corresponding values for a ' KernelResult ' .
kernelResultSubExp :: KernelResult -> SubExp
kernelResultSubExp (Returns _ _ se) = se
kernelResultSubExp (WriteReturns _ _ arr _) = Var arr
kernelResultSubExp (TileReturns _ _ v) = Var v
kernelResultSubExp (RegTileReturns _ _ v) = Var v
instance FreeIn KernelResult where
freeIn' (Returns _ cs what) = freeIn' cs <> freeIn' what
freeIn' (WriteReturns cs rws arr res) = freeIn' cs <> freeIn' rws <> freeIn' arr <> freeIn' res
freeIn' (TileReturns cs dims v) =
freeIn' cs <> freeIn' dims <> freeIn' v
freeIn' (RegTileReturns cs dims_n_tiles v) =
freeIn' cs <> freeIn' dims_n_tiles <> freeIn' v
instance ASTRep rep => FreeIn (KernelBody rep) where
freeIn' (KernelBody dec stms res) =
fvBind bound_in_stms $ freeIn' dec <> freeIn' stms <> freeIn' res
where
bound_in_stms = foldMap boundByStm stms
instance ASTRep rep => Substitute (KernelBody rep) where
substituteNames subst (KernelBody dec stms res) =
KernelBody
(substituteNames subst dec)
(substituteNames subst stms)
(substituteNames subst res)
instance Substitute KernelResult where
substituteNames subst (Returns manifest cs se) =
Returns manifest (substituteNames subst cs) (substituteNames subst se)
substituteNames subst (WriteReturns cs rws arr res) =
WriteReturns
(substituteNames subst cs)
(substituteNames subst rws)
(substituteNames subst arr)
(substituteNames subst res)
substituteNames subst (TileReturns cs dims v) =
TileReturns
(substituteNames subst cs)
(substituteNames subst dims)
(substituteNames subst v)
substituteNames subst (RegTileReturns cs dims_n_tiles v) =
RegTileReturns
(substituteNames subst cs)
(substituteNames subst dims_n_tiles)
(substituteNames subst v)
instance ASTRep rep => Rename (KernelBody rep) where
rename (KernelBody dec stms res) = do
dec' <- rename dec
renamingStms stms $ \stms' ->
KernelBody dec' stms' <$> rename res
instance Rename KernelResult where
rename = substituteRename
-- | Perform alias analysis on a 'KernelBody'.
aliasAnalyseKernelBody ::
Alias.AliasableRep rep =>
AliasTable ->
KernelBody rep ->
KernelBody (Aliases rep)
aliasAnalyseKernelBody aliases (KernelBody dec stms res) =
let Body dec' stms' _ = Alias.analyseBody aliases $ Body dec stms []
in KernelBody dec' stms' res
-- | The variables consumed in the kernel body.
consumedInKernelBody ::
Aliased rep =>
KernelBody rep ->
Names
consumedInKernelBody (KernelBody dec stms res) =
consumedInBody (Body dec stms []) <> mconcat (map consumedByReturn res)
where
consumedByReturn (WriteReturns _ _ a _) = oneName a
consumedByReturn _ = mempty
checkKernelBody ::
TC.Checkable rep =>
[Type] ->
KernelBody (Aliases rep) ->
TC.TypeM rep ()
checkKernelBody ts (KernelBody (_, dec) stms kres) = do
TC.checkBodyDec dec
-- We consume the kernel results (when applicable) before
-- type-checking the stms, so we will get an error if a statement
-- uses an array that is written to in a result.
mapM_ consumeKernelResult kres
TC.checkStms stms $ do
unless (length ts == length kres) $
TC.bad . TC.TypeError $
"Kernel return type is "
<> prettyTuple ts
<> ", but body returns "
<> prettyText (length kres)
<> " values."
zipWithM_ checkKernelResult kres ts
where
consumeKernelResult (WriteReturns _ _ arr _) =
TC.consume =<< TC.lookupAliases arr
consumeKernelResult _ =
pure ()
checkKernelResult (Returns _ cs what) t = do
TC.checkCerts cs
TC.require [t] what
checkKernelResult (WriteReturns cs shape arr res) t = do
TC.checkCerts cs
mapM_ (TC.require [Prim int64]) $ shapeDims shape
arr_t <- lookupType arr
forM_ res $ \(slice, e) -> do
traverse_ (TC.require [Prim int64]) slice
TC.require [t] e
unless (arr_t == t `arrayOfShape` shape) $
TC.bad $
TC.TypeError $
"WriteReturns returning "
<> prettyText e
<> " of type "
<> prettyText t
<> ", shape="
<> prettyText shape
<> ", but destination array has type "
<> prettyText arr_t
checkKernelResult (TileReturns cs dims v) t = do
TC.checkCerts cs
forM_ dims $ \(dim, tile) -> do
TC.require [Prim int64] dim
TC.require [Prim int64] tile
vt <- lookupType v
unless (vt == t `arrayOfShape` Shape (map snd dims)) $
TC.bad $
TC.TypeError $
"Invalid type for TileReturns " <> prettyText v
checkKernelResult (RegTileReturns cs dims_n_tiles arr) t = do
TC.checkCerts cs
mapM_ (TC.require [Prim int64]) dims
mapM_ (TC.require [Prim int64]) blk_tiles
mapM_ (TC.require [Prim int64]) reg_tiles
assert that is of element type t and shape ( rev outer_tiles + + reg_tiles )
arr_t <- lookupType arr
unless (arr_t == expected) $
TC.bad . TC.TypeError $
"Invalid type for TileReturns. Expected:\n "
<> prettyText expected
<> ",\ngot:\n "
<> prettyText arr_t
where
(dims, blk_tiles, reg_tiles) = unzip3 dims_n_tiles
expected = t `arrayOfShape` Shape (blk_tiles <> reg_tiles)
kernelBodyMetrics :: OpMetrics (Op rep) => KernelBody rep -> MetricsM ()
kernelBodyMetrics = mapM_ stmMetrics . kernelBodyStms
instance PrettyRep rep => Pretty (KernelBody rep) where
pretty (KernelBody _ stms res) =
PP.stack (map pretty (stmsToList stms))
</> "return"
<+> PP.braces (PP.commasep $ map pretty res)
certAnnots :: Certs -> [Doc ann]
certAnnots cs
| cs == mempty = []
| otherwise = [pretty cs]
instance Pretty KernelResult where
pretty (Returns ResultNoSimplify cs what) =
hsep $ certAnnots cs <> ["returns (manifest)" <+> pretty what]
pretty (Returns ResultPrivate cs what) =
hsep $ certAnnots cs <> ["returns (private)" <+> pretty what]
pretty (Returns ResultMaySimplify cs what) =
hsep $ certAnnots cs <> ["returns" <+> pretty what]
pretty (WriteReturns cs shape arr res) =
hsep $
certAnnots cs
<> [ pretty arr
<+> PP.colon
<+> pretty shape
</> "with"
<+> PP.apply (map ppRes res)
]
where
ppRes (slice, e) = pretty slice <+> "=" <+> pretty e
pretty (TileReturns cs dims v) =
hsep $ certAnnots cs <> ["tile" <> apply (map onDim dims) <+> pretty v]
where
onDim (dim, tile) = pretty dim <+> "/" <+> pretty tile
pretty (RegTileReturns cs dims_n_tiles v) =
hsep $ certAnnots cs <> ["blkreg_tile" <> apply (map onDim dims_n_tiles) <+> pretty v]
where
onDim (dim, blk_tile, reg_tile) =
pretty dim <+> "/" <+> parens (pretty blk_tile <+> "*" <+> pretty reg_tile)
-- | Index space of a 'SegOp'.
data SegSpace = SegSpace
{ -- | Flat physical index corresponding to the
-- dimensions (at code generation used for a
-- thread ID or similar).
segFlat :: VName,
unSegSpace :: [(VName, SubExp)]
}
deriving (Eq, Ord, Show)
| The sizes spanned by the indexes of the ' SegSpace ' .
segSpaceDims :: SegSpace -> [SubExp]
segSpaceDims (SegSpace _ space) = map snd space
-- | A 'Scope' containing all the identifiers brought into scope by
this ' SegSpace ' .
scopeOfSegSpace :: SegSpace -> Scope rep
scopeOfSegSpace (SegSpace phys space) =
M.fromList $ zip (phys : map fst space) $ repeat $ IndexName Int64
checkSegSpace :: TC.Checkable rep => SegSpace -> TC.TypeM rep ()
checkSegSpace (SegSpace _ dims) =
mapM_ (TC.require [Prim int64] . snd) dims
-- | A 'SegOp' is semantically a perfectly nested stack of maps, on
-- top of some bottommost computation (scalar computation, reduction,
scan , or histogram ) . The ' SegSpace ' encodes the original map
-- structure.
--
-- All 'SegOp's are parameterised by the representation of their body,
-- as well as a *level*. The *level* is a representation-specific bit
of information . For example , in GPU backends , it is used to
-- indicate whether the 'SegOp' is expected to run at the thread-level
-- or the group-level.
data SegOp lvl rep
= SegMap lvl SegSpace [Type] (KernelBody rep)
| The KernelSpace must always have at least two dimensions ,
-- implying that the result of a SegRed is always an array.
SegRed lvl SegSpace [SegBinOp rep] [Type] (KernelBody rep)
| SegScan lvl SegSpace [SegBinOp rep] [Type] (KernelBody rep)
| SegHist lvl SegSpace [HistOp rep] [Type] (KernelBody rep)
deriving (Eq, Ord, Show)
-- | The level of a 'SegOp'.
segLevel :: SegOp lvl rep -> lvl
segLevel (SegMap lvl _ _ _) = lvl
segLevel (SegRed lvl _ _ _ _) = lvl
segLevel (SegScan lvl _ _ _ _) = lvl
segLevel (SegHist lvl _ _ _ _) = lvl
-- | The space of a 'SegOp'.
segSpace :: SegOp lvl rep -> SegSpace
segSpace (SegMap _ lvl _ _) = lvl
segSpace (SegRed _ lvl _ _ _) = lvl
segSpace (SegScan _ lvl _ _ _) = lvl
segSpace (SegHist _ lvl _ _ _) = lvl
-- | The body of a 'SegOp'.
segBody :: SegOp lvl rep -> KernelBody rep
segBody segop =
case segop of
SegMap _ _ _ body -> body
SegRed _ _ _ _ body -> body
SegScan _ _ _ _ body -> body
SegHist _ _ _ _ body -> body
segResultShape :: SegSpace -> Type -> KernelResult -> Type
segResultShape _ t (WriteReturns _ shape _ _) =
t `arrayOfShape` shape
segResultShape space t Returns {} =
foldr (flip arrayOfRow) t $ segSpaceDims space
segResultShape _ t (TileReturns _ dims _) =
t `arrayOfShape` Shape (map fst dims)
segResultShape _ t (RegTileReturns _ dims_n_tiles _) =
t `arrayOfShape` Shape (map (\(dim, _, _) -> dim) dims_n_tiles)
-- | The return type of a 'SegOp'.
segOpType :: SegOp lvl rep -> [Type]
segOpType (SegMap _ space ts kbody) =
zipWith (segResultShape space) ts $ kernelBodyResult kbody
segOpType (SegRed _ space reds ts kbody) =
red_ts
++ zipWith
(segResultShape space)
map_ts
(drop (length red_ts) $ kernelBodyResult kbody)
where
map_ts = drop (length red_ts) ts
segment_dims = init $ segSpaceDims space
red_ts = do
op <- reds
let shape = Shape segment_dims <> segBinOpShape op
map (`arrayOfShape` shape) (lambdaReturnType $ segBinOpLambda op)
segOpType (SegScan _ space scans ts kbody) =
scan_ts
++ zipWith
(segResultShape space)
map_ts
(drop (length scan_ts) $ kernelBodyResult kbody)
where
map_ts = drop (length scan_ts) ts
scan_ts = do
op <- scans
let shape = Shape (segSpaceDims space) <> segBinOpShape op
map (`arrayOfShape` shape) (lambdaReturnType $ segBinOpLambda op)
segOpType (SegHist _ space ops _ _) = do
op <- ops
let shape = Shape segment_dims <> histShape op <> histOpShape op
map (`arrayOfShape` shape) (lambdaReturnType $ histOp op)
where
dims = segSpaceDims space
segment_dims = init dims
instance TypedOp (SegOp lvl rep) where
opType = pure . staticShapes . segOpType
instance (ASTConstraints lvl, Aliased rep) => AliasedOp (SegOp lvl rep) where
opAliases = map (const mempty) . segOpType
consumedInOp (SegMap _ _ _ kbody) =
consumedInKernelBody kbody
consumedInOp (SegRed _ _ _ _ kbody) =
consumedInKernelBody kbody
consumedInOp (SegScan _ _ _ _ kbody) =
consumedInKernelBody kbody
consumedInOp (SegHist _ _ ops _ kbody) =
namesFromList (concatMap histDest ops) <> consumedInKernelBody kbody
-- | Type check a 'SegOp', given a checker for its level.
typeCheckSegOp ::
TC.Checkable rep =>
(lvl -> TC.TypeM rep ()) ->
SegOp lvl (Aliases rep) ->
TC.TypeM rep ()
typeCheckSegOp checkLvl (SegMap lvl space ts kbody) = do
checkLvl lvl
checkScanRed space [] ts kbody
typeCheckSegOp checkLvl (SegRed lvl space reds ts body) = do
checkLvl lvl
checkScanRed space reds' ts body
where
reds' =
zip3
(map segBinOpLambda reds)
(map segBinOpNeutral reds)
(map segBinOpShape reds)
typeCheckSegOp checkLvl (SegScan lvl space scans ts body) = do
checkLvl lvl
checkScanRed space scans' ts body
where
scans' =
zip3
(map segBinOpLambda scans)
(map segBinOpNeutral scans)
(map segBinOpShape scans)
typeCheckSegOp checkLvl (SegHist lvl space ops ts kbody) = do
checkLvl lvl
checkSegSpace space
mapM_ TC.checkType ts
TC.binding (scopeOfSegSpace space) $ do
nes_ts <- forM ops $ \(HistOp dest_shape rf dests nes shape op) -> do
mapM_ (TC.require [Prim int64]) dest_shape
TC.require [Prim int64] rf
nes' <- mapM TC.checkArg nes
mapM_ (TC.require [Prim int64]) $ shapeDims shape
-- Operator type must match the type of neutral elements.
let stripVecDims = stripArray $ shapeRank shape
TC.checkLambda op $ map (TC.noArgAliases . first stripVecDims) $ nes' ++ nes'
let nes_t = map TC.argType nes'
unless (nes_t == lambdaReturnType op) $
TC.bad $
TC.TypeError $
"SegHist operator has return type "
<> prettyTuple (lambdaReturnType op)
<> " but neutral element has type "
<> prettyTuple nes_t
-- Arrays must have proper type.
let dest_shape' = Shape segment_dims <> dest_shape <> shape
forM_ (zip nes_t dests) $ \(t, dest) -> do
TC.requireI [t `arrayOfShape` dest_shape'] dest
TC.consume =<< TC.lookupAliases dest
pure $ map (`arrayOfShape` shape) nes_t
checkKernelBody ts kbody
-- Return type of bucket function must be an index for each
-- operation followed by the values to write.
let bucket_ret_t =
concatMap ((`replicate` Prim int64) . shapeRank . histShape) ops
++ concat nes_ts
unless (bucket_ret_t == ts) $
TC.bad $
TC.TypeError $
"SegHist body has return type "
<> prettyTuple ts
<> " but should have type "
<> prettyTuple bucket_ret_t
where
segment_dims = init $ segSpaceDims space
checkScanRed ::
TC.Checkable rep =>
SegSpace ->
[(Lambda (Aliases rep), [SubExp], Shape)] ->
[Type] ->
KernelBody (Aliases rep) ->
TC.TypeM rep ()
checkScanRed space ops ts kbody = do
checkSegSpace space
mapM_ TC.checkType ts
TC.binding (scopeOfSegSpace space) $ do
ne_ts <- forM ops $ \(lam, nes, shape) -> do
mapM_ (TC.require [Prim int64]) $ shapeDims shape
nes' <- mapM TC.checkArg nes
-- Operator type must match the type of neutral elements.
TC.checkLambda lam $ map TC.noArgAliases $ nes' ++ nes'
let nes_t = map TC.argType nes'
unless (lambdaReturnType lam == nes_t) $
TC.bad $
TC.TypeError "wrong type for operator or neutral elements."
pure $ map (`arrayOfShape` shape) nes_t
let expecting = concat ne_ts
got = take (length expecting) ts
unless (expecting == got) $
TC.bad $
TC.TypeError $
"Wrong return for body (does not match neutral elements; expected "
<> prettyText expecting
<> "; found "
<> prettyText got
<> ")"
checkKernelBody ts kbody
| Like ' Mapper ' , but just for ' SegOp 's .
data SegOpMapper lvl frep trep m = SegOpMapper
{ mapOnSegOpSubExp :: SubExp -> m SubExp,
mapOnSegOpLambda :: Lambda frep -> m (Lambda trep),
mapOnSegOpBody :: KernelBody frep -> m (KernelBody trep),
mapOnSegOpVName :: VName -> m VName,
mapOnSegOpLevel :: lvl -> m lvl
}
-- | A mapper that simply returns the 'SegOp' verbatim.
identitySegOpMapper :: Monad m => SegOpMapper lvl rep rep m
identitySegOpMapper =
SegOpMapper
{ mapOnSegOpSubExp = pure,
mapOnSegOpLambda = pure,
mapOnSegOpBody = pure,
mapOnSegOpVName = pure,
mapOnSegOpLevel = pure
}
mapOnSegSpace ::
Monad f => SegOpMapper lvl frep trep f -> SegSpace -> f SegSpace
mapOnSegSpace tv (SegSpace phys dims) =
SegSpace
<$> mapOnSegOpVName tv phys
<*> traverse (bitraverse (mapOnSegOpVName tv) (mapOnSegOpSubExp tv)) dims
mapSegBinOp ::
Monad m =>
SegOpMapper lvl frep trep m ->
SegBinOp frep ->
m (SegBinOp trep)
mapSegBinOp tv (SegBinOp comm red_op nes shape) =
SegBinOp comm
<$> mapOnSegOpLambda tv red_op
<*> mapM (mapOnSegOpSubExp tv) nes
<*> (Shape <$> mapM (mapOnSegOpSubExp tv) (shapeDims shape))
-- | Apply a 'SegOpMapper' to the given 'SegOp'.
mapSegOpM ::
Monad m =>
SegOpMapper lvl frep trep m ->
SegOp lvl frep ->
m (SegOp lvl trep)
mapSegOpM tv (SegMap lvl space ts body) =
SegMap
<$> mapOnSegOpLevel tv lvl
<*> mapOnSegSpace tv space
<*> mapM (mapOnSegOpType tv) ts
<*> mapOnSegOpBody tv body
mapSegOpM tv (SegRed lvl space reds ts lam) =
SegRed
<$> mapOnSegOpLevel tv lvl
<*> mapOnSegSpace tv space
<*> mapM (mapSegBinOp tv) reds
<*> mapM (mapOnType $ mapOnSegOpSubExp tv) ts
<*> mapOnSegOpBody tv lam
mapSegOpM tv (SegScan lvl space scans ts body) =
SegScan
<$> mapOnSegOpLevel tv lvl
<*> mapOnSegSpace tv space
<*> mapM (mapSegBinOp tv) scans
<*> mapM (mapOnType $ mapOnSegOpSubExp tv) ts
<*> mapOnSegOpBody tv body
mapSegOpM tv (SegHist lvl space ops ts body) =
SegHist
<$> mapOnSegOpLevel tv lvl
<*> mapOnSegSpace tv space
<*> mapM onHistOp ops
<*> mapM (mapOnType $ mapOnSegOpSubExp tv) ts
<*> mapOnSegOpBody tv body
where
onHistOp (HistOp w rf arrs nes shape op) =
HistOp
<$> mapM (mapOnSegOpSubExp tv) w
<*> mapOnSegOpSubExp tv rf
<*> mapM (mapOnSegOpVName tv) arrs
<*> mapM (mapOnSegOpSubExp tv) nes
<*> (Shape <$> mapM (mapOnSegOpSubExp tv) (shapeDims shape))
<*> mapOnSegOpLambda tv op
mapOnSegOpType ::
Monad m =>
SegOpMapper lvl frep trep m ->
Type ->
m Type
mapOnSegOpType _tv t@Prim {} = pure t
mapOnSegOpType tv (Acc acc ispace ts u) =
Acc
<$> mapOnSegOpVName tv acc
<*> traverse (mapOnSegOpSubExp tv) ispace
<*> traverse (bitraverse (traverse (mapOnSegOpSubExp tv)) pure) ts
<*> pure u
mapOnSegOpType tv (Array et shape u) =
Array et <$> traverse (mapOnSegOpSubExp tv) shape <*> pure u
mapOnSegOpType _tv (Mem s) = pure $ Mem s
rephraseBinOp ::
Monad f =>
Rephraser f from rep ->
SegBinOp from ->
f (SegBinOp rep)
rephraseBinOp r (SegBinOp comm lam nes shape) =
SegBinOp comm <$> rephraseLambda r lam <*> pure nes <*> pure shape
rephraseKernelBody ::
Monad f =>
Rephraser f from rep ->
KernelBody from ->
f (KernelBody rep)
rephraseKernelBody r (KernelBody dec stms res) =
KernelBody <$> rephraseBodyDec r dec <*> traverse (rephraseStm r) stms <*> pure res
instance RephraseOp (SegOp lvl) where
rephraseInOp r (SegMap lvl space ts body) =
SegMap lvl space ts <$> rephraseKernelBody r body
rephraseInOp r (SegRed lvl space reds ts body) =
SegRed lvl space
<$> mapM (rephraseBinOp r) reds
<*> pure ts
<*> rephraseKernelBody r body
rephraseInOp r (SegScan lvl space scans ts body) =
SegScan lvl space
<$> mapM (rephraseBinOp r) scans
<*> pure ts
<*> rephraseKernelBody r body
rephraseInOp r (SegHist lvl space hists ts body) =
SegHist lvl space
<$> mapM onOp hists
<*> pure ts
<*> rephraseKernelBody r body
where
onOp (HistOp w rf arrs nes shape op) =
HistOp w rf arrs nes shape <$> rephraseLambda r op
-- | A helper for defining 'TraverseOpStms'.
traverseSegOpStms :: Monad m => OpStmsTraverser m (SegOp lvl rep) rep
traverseSegOpStms f segop = mapSegOpM mapper segop
where
seg_scope = scopeOfSegSpace (segSpace segop)
f' scope = f (seg_scope <> scope)
mapper =
identitySegOpMapper
{ mapOnSegOpLambda = traverseLambdaStms f',
mapOnSegOpBody = onBody
}
onBody (KernelBody dec stms res) =
KernelBody dec <$> f seg_scope stms <*> pure res
instance
(ASTRep rep, Substitute lvl) =>
Substitute (SegOp lvl rep)
where
substituteNames subst = runIdentity . mapSegOpM substitute
where
substitute =
SegOpMapper
{ mapOnSegOpSubExp = pure . substituteNames subst,
mapOnSegOpLambda = pure . substituteNames subst,
mapOnSegOpBody = pure . substituteNames subst,
mapOnSegOpVName = pure . substituteNames subst,
mapOnSegOpLevel = pure . substituteNames subst
}
instance (ASTRep rep, ASTConstraints lvl) => Rename (SegOp lvl rep) where
rename op =
renameBound (M.keys (scopeOfSegSpace (segSpace op))) $ mapSegOpM renamer op
where
renamer = SegOpMapper rename rename rename rename rename
instance (ASTRep rep, FreeIn lvl) => FreeIn (SegOp lvl rep) where
freeIn' e =
fvBind (namesFromList $ M.keys $ scopeOfSegSpace (segSpace e)) $
flip execState mempty $
mapSegOpM free e
where
walk f x = modify (<> f x) >> pure x
free =
SegOpMapper
{ mapOnSegOpSubExp = walk freeIn',
mapOnSegOpLambda = walk freeIn',
mapOnSegOpBody = walk freeIn',
mapOnSegOpVName = walk freeIn',
mapOnSegOpLevel = walk freeIn'
}
instance OpMetrics (Op rep) => OpMetrics (SegOp lvl rep) where
opMetrics (SegMap _ _ _ body) =
inside "SegMap" $ kernelBodyMetrics body
opMetrics (SegRed _ _ reds _ body) =
inside "SegRed" $ do
mapM_ (lambdaMetrics . segBinOpLambda) reds
kernelBodyMetrics body
opMetrics (SegScan _ _ scans _ body) =
inside "SegScan" $ do
mapM_ (lambdaMetrics . segBinOpLambda) scans
kernelBodyMetrics body
opMetrics (SegHist _ _ ops _ body) =
inside "SegHist" $ do
mapM_ (lambdaMetrics . histOp) ops
kernelBodyMetrics body
instance Pretty SegSpace where
pretty (SegSpace phys dims) =
apply
( do
(i, d) <- dims
pure $ pretty i <+> "<" <+> pretty d
)
<+> parens ("~" <> pretty phys)
instance PrettyRep rep => Pretty (SegBinOp rep) where
pretty (SegBinOp comm lam nes shape) =
PP.braces (PP.commasep $ map pretty nes) <> PP.comma
</> pretty shape <> PP.comma
</> comm' <> pretty lam
where
comm' = case comm of
Commutative -> "commutative "
Noncommutative -> mempty
instance (PrettyRep rep, PP.Pretty lvl) => PP.Pretty (SegOp lvl rep) where
pretty (SegMap lvl space ts body) =
"segmap" <> pretty lvl
</> PP.align (pretty space)
<+> PP.colon
<+> ppTuple' (map pretty ts)
<+> PP.nestedBlock "{" "}" (pretty body)
pretty (SegRed lvl space reds ts body) =
"segred" <> pretty lvl
</> PP.align (pretty space)
</> PP.parens (mconcat $ intersperse (PP.comma <> PP.line) $ map pretty reds)
</> PP.colon
<+> ppTuple' (map pretty ts)
<+> PP.nestedBlock "{" "}" (pretty body)
pretty (SegScan lvl space scans ts body) =
"segscan" <> pretty lvl
</> PP.align (pretty space)
</> PP.parens (mconcat $ intersperse (PP.comma <> PP.line) $ map pretty scans)
</> PP.colon
<+> ppTuple' (map pretty ts)
<+> PP.nestedBlock "{" "}" (pretty body)
pretty (SegHist lvl space ops ts body) =
"seghist" <> pretty lvl
</> PP.align (pretty space)
</> PP.parens (mconcat $ intersperse (PP.comma <> PP.line) $ map ppOp ops)
</> PP.colon
<+> ppTuple' (map pretty ts)
<+> PP.nestedBlock "{" "}" (pretty body)
where
ppOp (HistOp w rf dests nes shape op) =
pretty w <> PP.comma
<+> pretty rf <> PP.comma
</> PP.braces (PP.commasep $ map pretty dests) <> PP.comma
</> PP.braces (PP.commasep $ map pretty nes) <> PP.comma
</> pretty shape <> PP.comma
</> pretty op
instance CanBeAliased (SegOp lvl) where
addOpAliases aliases = runIdentity . mapSegOpM alias
where
alias =
SegOpMapper
pure
(pure . Alias.analyseLambda aliases)
(pure . aliasAnalyseKernelBody aliases)
pure
pure
informKernelBody :: Informing rep => KernelBody rep -> KernelBody (Wise rep)
informKernelBody (KernelBody dec stms res) =
mkWiseKernelBody dec (informStms stms) res
instance CanBeWise (SegOp lvl) where
addOpWisdom = runIdentity . mapSegOpM add
where
add =
SegOpMapper
pure
(pure . informLambda)
(pure . informKernelBody)
pure
pure
instance ASTRep rep => ST.IndexOp (SegOp lvl rep) where
indexOp vtable k (SegMap _ space _ kbody) is = do
Returns ResultMaySimplify _ se <- maybeNth k $ kernelBodyResult kbody
guard $ length gtids <= length is
let idx_table = M.fromList $ zip gtids $ map (ST.Indexed mempty . untyped) is
idx_table' = foldl' expandIndexedTable idx_table $ kernelBodyStms kbody
case se of
Var v -> M.lookup v idx_table'
_ -> Nothing
where
(gtids, _) = unzip $ unSegSpace space
-- Indexes in excess of what is used to index through the
-- segment dimensions.
excess_is = drop (length gtids) is
expandIndexedTable table stm
| [v] <- patNames $ stmPat stm,
Just (pe, cs) <-
runWriterT $ primExpFromExp (asPrimExp table) $ stmExp stm =
M.insert v (ST.Indexed (stmCerts stm <> cs) pe) table
| [v] <- patNames $ stmPat stm,
BasicOp (Index arr slice) <- stmExp stm,
length (sliceDims slice) == length excess_is,
arr `ST.available` vtable,
Just (slice', cs) <- asPrimExpSlice table slice =
let idx =
ST.IndexedArray
(stmCerts stm <> cs)
arr
(fixSlice (fmap isInt64 slice') excess_is)
in M.insert v idx table
| otherwise =
table
asPrimExpSlice table =
runWriterT . traverse (primExpFromSubExpM (asPrimExp table))
asPrimExp table v
| Just (ST.Indexed cs e) <- M.lookup v table = tell cs >> pure e
| Just (Prim pt) <- ST.lookupType v vtable =
pure $ LeafExp v pt
| otherwise = lift Nothing
indexOp _ _ _ _ = Nothing
instance
(ASTRep rep, ASTConstraints lvl) =>
IsOp (SegOp lvl rep)
where
cheapOp _ = False
safeOp _ = True
--- Simplification
instance Engine.Simplifiable SegSpace where
simplify (SegSpace phys dims) =
SegSpace phys <$> mapM (traverse Engine.simplify) dims
instance Engine.Simplifiable KernelResult where
simplify (Returns manifest cs what) =
Returns manifest <$> Engine.simplify cs <*> Engine.simplify what
simplify (WriteReturns cs ws a res) =
WriteReturns
<$> Engine.simplify cs
<*> Engine.simplify ws
<*> Engine.simplify a
<*> Engine.simplify res
simplify (TileReturns cs dims what) =
TileReturns <$> Engine.simplify cs <*> Engine.simplify dims <*> Engine.simplify what
simplify (RegTileReturns cs dims_n_tiles what) =
RegTileReturns
<$> Engine.simplify cs
<*> Engine.simplify dims_n_tiles
<*> Engine.simplify what
mkWiseKernelBody ::
Informing rep =>
BodyDec rep ->
Stms (Wise rep) ->
[KernelResult] ->
KernelBody (Wise rep)
mkWiseKernelBody dec stms res =
let Body dec' _ _ = mkWiseBody dec stms $ subExpsRes res_vs
in KernelBody dec' stms res
where
res_vs = map kernelResultSubExp res
mkKernelBodyM ::
MonadBuilder m =>
Stms (Rep m) ->
[KernelResult] ->
m (KernelBody (Rep m))
mkKernelBodyM stms kres = do
Body dec' _ _ <- mkBodyM stms $ subExpsRes res_ses
pure $ KernelBody dec' stms kres
where
res_ses = map kernelResultSubExp kres
simplifyKernelBody ::
(Engine.SimplifiableRep rep, BodyDec rep ~ ()) =>
SegSpace ->
KernelBody (Wise rep) ->
Engine.SimpleM rep (KernelBody (Wise rep), Stms (Wise rep))
simplifyKernelBody space (KernelBody _ stms res) = do
par_blocker <- Engine.asksEngineEnv $ Engine.blockHoistPar . Engine.envHoistBlockers
let blocker =
Engine.hasFree bound_here
`Engine.orIf` Engine.isOp
`Engine.orIf` par_blocker
`Engine.orIf` Engine.isConsumed
`Engine.orIf` Engine.isConsuming
`Engine.orIf` Engine.isDeviceMigrated
-- Ensure we do not try to use anything that is consumed in the result.
(body_res, body_stms, hoisted) <-
Engine.localVtable (flip (foldl' (flip ST.consume)) (foldMap consumedInResult res))
. Engine.localVtable (<> scope_vtable)
. Engine.localVtable (\vtable -> vtable {ST.simplifyMemory = True})
. Engine.enterLoop
$ Engine.blockIf blocker stms
$ do
res' <-
Engine.localVtable (ST.hideCertified $ namesFromList $ M.keys $ scopeOf stms) $
mapM Engine.simplify res
pure (res', UT.usages $ freeIn res')
pure (mkWiseKernelBody () body_stms body_res, hoisted)
where
scope_vtable = segSpaceSymbolTable space
bound_here = namesFromList $ M.keys $ scopeOfSegSpace space
consumedInResult (WriteReturns _ _ arr _) =
[arr]
consumedInResult _ =
[]
simplifyLambda ::
Engine.SimplifiableRep rep =>
Names ->
Lambda (Wise rep) ->
Engine.SimpleM rep (Lambda (Wise rep), Stms (Wise rep))
simplifyLambda bound = Engine.blockMigrated . Engine.simplifyLambda bound
segSpaceSymbolTable :: ASTRep rep => SegSpace -> ST.SymbolTable rep
segSpaceSymbolTable (SegSpace flat gtids_and_dims) =
foldl' f (ST.fromScope $ M.singleton flat $ IndexName Int64) gtids_and_dims
where
f vtable (gtid, dim) = ST.insertLoopVar gtid Int64 dim vtable
simplifySegBinOp ::
Engine.SimplifiableRep rep =>
VName ->
SegBinOp (Wise rep) ->
Engine.SimpleM rep (SegBinOp (Wise rep), Stms (Wise rep))
simplifySegBinOp phys_id (SegBinOp comm lam nes shape) = do
(lam', hoisted) <-
Engine.localVtable (\vtable -> vtable {ST.simplifyMemory = True}) $
simplifyLambda (oneName phys_id) lam
shape' <- Engine.simplify shape
nes' <- mapM Engine.simplify nes
pure (SegBinOp comm lam' nes' shape', hoisted)
-- | Simplify the given 'SegOp'.
simplifySegOp ::
( Engine.SimplifiableRep rep,
BodyDec rep ~ (),
Engine.Simplifiable lvl
) =>
SegOp lvl (Wise rep) ->
Engine.SimpleM rep (SegOp lvl (Wise rep), Stms (Wise rep))
simplifySegOp (SegMap lvl space ts kbody) = do
(lvl', space', ts') <- Engine.simplify (lvl, space, ts)
(kbody', body_hoisted) <- simplifyKernelBody space kbody
pure
( SegMap lvl' space' ts' kbody',
body_hoisted
)
simplifySegOp (SegRed lvl space reds ts kbody) = do
(lvl', space', ts') <- Engine.simplify (lvl, space, ts)
(reds', reds_hoisted) <-
Engine.localVtable (<> scope_vtable) $
mapAndUnzipM (simplifySegBinOp (segFlat space)) reds
(kbody', body_hoisted) <- simplifyKernelBody space kbody
pure
( SegRed lvl' space' reds' ts' kbody',
mconcat reds_hoisted <> body_hoisted
)
where
scope = scopeOfSegSpace space
scope_vtable = ST.fromScope scope
simplifySegOp (SegScan lvl space scans ts kbody) = do
(lvl', space', ts') <- Engine.simplify (lvl, space, ts)
(scans', scans_hoisted) <-
Engine.localVtable (<> scope_vtable) $
mapAndUnzipM (simplifySegBinOp (segFlat space)) scans
(kbody', body_hoisted) <- simplifyKernelBody space kbody
pure
( SegScan lvl' space' scans' ts' kbody',
mconcat scans_hoisted <> body_hoisted
)
where
scope = scopeOfSegSpace space
scope_vtable = ST.fromScope scope
simplifySegOp (SegHist lvl space ops ts kbody) = do
(lvl', space', ts') <- Engine.simplify (lvl, space, ts)
(ops', ops_hoisted) <- fmap unzip $
forM ops $
\(HistOp w rf arrs nes dims lam) -> do
w' <- Engine.simplify w
rf' <- Engine.simplify rf
arrs' <- Engine.simplify arrs
nes' <- Engine.simplify nes
dims' <- Engine.simplify dims
(lam', op_hoisted) <-
Engine.localVtable (<> scope_vtable) $
Engine.localVtable (\vtable -> vtable {ST.simplifyMemory = True}) $
simplifyLambda (oneName (segFlat space)) lam
pure
( HistOp w' rf' arrs' nes' dims' lam',
op_hoisted
)
(kbody', body_hoisted) <- simplifyKernelBody space kbody
pure
( SegHist lvl' space' ops' ts' kbody',
mconcat ops_hoisted <> body_hoisted
)
where
scope = scopeOfSegSpace space
scope_vtable = ST.fromScope scope
-- | Does this rep contain 'SegOp's in its t'Op's? A rep must be an
-- instance of this class for the simplification rules to work.
class HasSegOp rep where
type SegOpLevel rep
asSegOp :: Op rep -> Maybe (SegOp (SegOpLevel rep) rep)
segOp :: SegOp (SegOpLevel rep) rep -> Op rep
-- | Simplification rules for simplifying 'SegOp's.
segOpRules ::
(HasSegOp rep, BuilderOps rep, Buildable rep, Aliased rep) =>
RuleBook rep
segOpRules =
ruleBook [RuleOp segOpRuleTopDown] [RuleOp segOpRuleBottomUp]
segOpRuleTopDown ::
(HasSegOp rep, BuilderOps rep, Buildable rep) =>
TopDownRuleOp rep
segOpRuleTopDown vtable pat dec op
| Just op' <- asSegOp op =
topDownSegOp vtable pat dec op'
| otherwise =
Skip
segOpRuleBottomUp ::
(HasSegOp rep, BuilderOps rep, Aliased rep) =>
BottomUpRuleOp rep
segOpRuleBottomUp vtable pat dec op
| Just op' <- asSegOp op =
bottomUpSegOp vtable pat dec op'
| otherwise =
Skip
topDownSegOp ::
(HasSegOp rep, BuilderOps rep, Buildable rep) =>
ST.SymbolTable rep ->
Pat (LetDec rep) ->
StmAux (ExpDec rep) ->
SegOp (SegOpLevel rep) rep ->
Rule rep
-- If a SegOp produces something invariant to the SegOp, turn it
-- into a replicate.
topDownSegOp vtable (Pat kpes) dec (SegMap lvl space ts (KernelBody _ kstms kres)) = Simplify $ do
(ts', kpes', kres') <-
unzip3 <$> filterM checkForInvarianceResult (zip3 ts kpes kres)
-- Check if we did anything at all.
when (kres == kres') cannotSimplify
kbody <- mkKernelBodyM kstms kres'
addStm $
Let (Pat kpes') dec $
Op $
segOp $
SegMap lvl space ts' kbody
where
isInvariant Constant {} = True
isInvariant (Var v) = isJust $ ST.lookup v vtable
checkForInvarianceResult (_, pe, Returns rm cs se)
| cs == mempty,
rm == ResultMaySimplify,
isInvariant se = do
letBindNames [patElemName pe] $
BasicOp $
Replicate (Shape $ segSpaceDims space) se
pure False
checkForInvarianceResult _ =
pure True
If a SegRed contains two reduction operations that have the same
-- vector shape, merge them together. This saves on communication
-- overhead, but can in principle lead to more local memory usage.
topDownSegOp _ (Pat pes) _ (SegRed lvl space ops ts kbody)
| length ops > 1,
op_groupings <-
groupBy sameShape $
zip ops $
chunks (map (length . segBinOpNeutral) ops) $
zip3 red_pes red_ts red_res,
any ((> 1) . length) op_groupings = Simplify $ do
let (ops', aux) = unzip $ mapMaybe combineOps op_groupings
(red_pes', red_ts', red_res') = unzip3 $ concat aux
pes' = red_pes' ++ map_pes
ts' = red_ts' ++ map_ts
kbody' = kbody {kernelBodyResult = red_res' ++ map_res}
letBind (Pat pes') $ Op $ segOp $ SegRed lvl space ops' ts' kbody'
where
(red_pes, map_pes) = splitAt (segBinOpResults ops) pes
(red_ts, map_ts) = splitAt (segBinOpResults ops) ts
(red_res, map_res) = splitAt (segBinOpResults ops) $ kernelBodyResult kbody
sameShape (op1, _) (op2, _) = segBinOpShape op1 == segBinOpShape op2
combineOps [] = Nothing
combineOps (x : xs) = Just $ foldl' combine x xs
combine (op1, op1_aux) (op2, op2_aux) =
let lam1 = segBinOpLambda op1
lam2 = segBinOpLambda op2
(op1_xparams, op1_yparams) =
splitAt (length (segBinOpNeutral op1)) $ lambdaParams lam1
(op2_xparams, op2_yparams) =
splitAt (length (segBinOpNeutral op2)) $ lambdaParams lam2
lam =
Lambda
{ lambdaParams =
op1_xparams
++ op2_xparams
++ op1_yparams
++ op2_yparams,
lambdaReturnType = lambdaReturnType lam1 ++ lambdaReturnType lam2,
lambdaBody =
mkBody (bodyStms (lambdaBody lam1) <> bodyStms (lambdaBody lam2)) $
bodyResult (lambdaBody lam1) <> bodyResult (lambdaBody lam2)
}
in ( SegBinOp
{ segBinOpComm = segBinOpComm op1 <> segBinOpComm op2,
segBinOpLambda = lam,
segBinOpNeutral = segBinOpNeutral op1 ++ segBinOpNeutral op2,
Same as shape of op2 due to the grouping .
},
op1_aux ++ op2_aux
)
topDownSegOp _ _ _ _ = Skip
-- A convenient way of operating on the type and body of a SegOp,
-- without worrying about exactly what kind it is.
segOpGuts ::
SegOp (SegOpLevel rep) rep ->
( [Type],
KernelBody rep,
Int,
[Type] -> KernelBody rep -> SegOp (SegOpLevel rep) rep
)
segOpGuts (SegMap lvl space kts body) =
(kts, body, 0, SegMap lvl space)
segOpGuts (SegScan lvl space ops kts body) =
(kts, body, segBinOpResults ops, SegScan lvl space ops)
segOpGuts (SegRed lvl space ops kts body) =
(kts, body, segBinOpResults ops, SegRed lvl space ops)
segOpGuts (SegHist lvl space ops kts body) =
(kts, body, sum $ map (length . histDest) ops, SegHist lvl space ops)
bottomUpSegOp ::
(Aliased rep, HasSegOp rep, BuilderOps rep) =>
(ST.SymbolTable rep, UT.UsageTable) ->
Pat (LetDec rep) ->
StmAux (ExpDec rep) ->
SegOp (SegOpLevel rep) rep ->
Rule rep
-- Some SegOp results can be moved outside the SegOp, which can
-- simplify further analysis.
bottomUpSegOp (vtable, used) (Pat kpes) dec segop = Simplify $ do
-- Iterate through the bindings. For each, we check whether it is
-- in kres and can be moved outside. If so, we remove it from kres
-- and kpes and make it a binding outside. We have to be careful
-- not to remove anything that is passed on to a scan/map/histogram
operation . Fortunately , these are always first in the result
-- list.
(kpes', kts', kres', kstms') <-
localScope (scopeOfSegSpace space) $
foldM distribute (kpes, kts, kres, mempty) kstms
when
(kpes' == kpes)
cannotSimplify
kbody' <-
localScope (scopeOfSegSpace space) $
mkKernelBodyM kstms' kres'
addStm $ Let (Pat kpes') dec $ Op $ segOp $ mk_segop kts' kbody'
where
(kts, kbody@(KernelBody _ kstms kres), num_nonmap_results, mk_segop) =
segOpGuts segop
free_in_kstms = foldMap freeIn kstms
consumed_in_segop = consumedInKernelBody kbody
space = segSpace segop
sliceWithGtidsFixed stm
| Let _ _ (BasicOp (Index arr slice)) <- stm,
space_slice <- map (DimFix . Var . fst) $ unSegSpace space,
space_slice `isPrefixOf` unSlice slice,
remaining_slice <- Slice $ drop (length space_slice) (unSlice slice),
all (isJust . flip ST.lookup vtable) $
namesToList $
freeIn arr <> freeIn remaining_slice =
Just (remaining_slice, arr)
| otherwise =
Nothing
distribute (kpes', kts', kres', kstms') stm
| Let (Pat [pe]) _ _ <- stm,
Just (Slice remaining_slice, arr) <- sliceWithGtidsFixed stm,
Just (kpe, kpes'', kts'', kres'') <- isResult kpes' kts' kres' pe = do
let outer_slice =
map
( \d ->
DimSlice
(constant (0 :: Int64))
d
(constant (1 :: Int64))
)
$ segSpaceDims space
index kpe' =
letBindNames [patElemName kpe'] . BasicOp . Index arr $
Slice $
outer_slice <> remaining_slice
if patElemName kpe
`UT.isConsumed` used
|| arr
`nameIn` consumed_in_segop
then do
precopy <- newVName $ baseString (patElemName kpe) <> "_precopy"
index kpe {patElemName = precopy}
letBindNames [patElemName kpe] $ BasicOp $ Copy precopy
else index kpe
pure
( kpes'',
kts'',
kres'',
if patElemName pe `nameIn` free_in_kstms
then kstms' <> oneStm stm
else kstms'
)
distribute (kpes', kts', kres', kstms') stm =
pure (kpes', kts', kres', kstms' <> oneStm stm)
isResult kpes' kts' kres' pe =
case partition matches $ zip3 kpes' kts' kres' of
([(kpe, _, _)], kpes_and_kres)
| Just i <- elemIndex kpe kpes,
i >= num_nonmap_results,
(kpes'', kts'', kres'') <- unzip3 kpes_and_kres ->
Just (kpe, kpes'', kts'', kres'')
_ -> Nothing
where
matches (_, _, Returns _ _ (Var v)) = v == patElemName pe
matches _ = False
--- Memory
kernelBodyReturns ::
(Mem rep inner, HasScope rep m, Monad m) =>
KernelBody somerep ->
[ExpReturns] ->
m [ExpReturns]
kernelBodyReturns = zipWithM correct . kernelBodyResult
where
correct (WriteReturns _ _ arr _) _ = varReturns arr
correct _ ret = pure ret
-- | Like 'segOpType', but for memory representations.
segOpReturns ::
(Mem rep inner, Monad m, HasScope rep m) =>
SegOp lvl somerep ->
m [ExpReturns]
segOpReturns k@(SegMap _ _ _ kbody) =
kernelBodyReturns kbody . extReturns =<< opType k
segOpReturns k@(SegRed _ _ _ _ kbody) =
kernelBodyReturns kbody . extReturns =<< opType k
segOpReturns k@(SegScan _ _ _ _ kbody) =
kernelBodyReturns kbody . extReturns =<< opType k
segOpReturns (SegHist _ _ ops _ _) =
concat <$> mapM (mapM varReturns . histDest) ops
| null | https://raw.githubusercontent.com/diku-dk/futhark/1fe93634d63df6005116f55f18e8a35b1a11987a/src/Futhark/IR/SegOp.hs | haskell | | Segmented operations. These correspond to perfect @map@ nests on
* Details
** Generic traversal
* Simplification
* Memory
| An operator for 'SegHist'.
| In case this operator is semantically a vectorised
operator (corresponding to a perfect map nest in the
"dimensions". This is used to generate more efficient
code.
| The type of a histogram produced by a 'HistOp'. This can be
different from the type of the 'histDest's in case we are
dealing with a segmented histogram.
| Split reduction results returned by a 'KernelBody' into those
that correspond to indexes for the 'HistOp's, and those that
correspond to value.
| In case this operator is semantically a vectorised
operator (corresponding to a perfect map nest in the
"dimensions". This is used to generate more efficient
code.
| How many reduction results are produced by these 'SegBinOp's?
| Split some list into chunks equal to the number of values
returned by each 'SegBinOp'
| The body of a 'SegOp'.
| Metadata about whether there is a subtle point to this
might otherwise be removed by the simplifier because they're
semantically redundant. This has no semantic effect and can be
ignored at code generation.
| Don't simplify this one!
| Go nuts.
| The results produced are only used within the
same physical thread later on, and can thus be
kept in registers.
| A 'KernelBody' does not return an ordinary 'Result'. Instead, it
returns a list of these.
| Each "worker" in the kernel returns this.
Whether this is a result-per-thread or a
result-per-group depends on where the 'SegOp' occurs.
Size of array. Must match number of dims.
Which array
Total/tile for each dimension
Tile written by this worker.
result to be written per physical thread.
For each dim of result:
size of this dim.
block tile size for this dim.
reg tile size for this dim.
Tile returned by this worker/group.
| Perform alias analysis on a 'KernelBody'.
| The variables consumed in the kernel body.
We consume the kernel results (when applicable) before
type-checking the stms, so we will get an error if a statement
uses an array that is written to in a result.
| Index space of a 'SegOp'.
| Flat physical index corresponding to the
dimensions (at code generation used for a
thread ID or similar).
| A 'Scope' containing all the identifiers brought into scope by
| A 'SegOp' is semantically a perfectly nested stack of maps, on
top of some bottommost computation (scalar computation, reduction,
structure.
All 'SegOp's are parameterised by the representation of their body,
as well as a *level*. The *level* is a representation-specific bit
indicate whether the 'SegOp' is expected to run at the thread-level
or the group-level.
implying that the result of a SegRed is always an array.
| The level of a 'SegOp'.
| The space of a 'SegOp'.
| The body of a 'SegOp'.
| The return type of a 'SegOp'.
| Type check a 'SegOp', given a checker for its level.
Operator type must match the type of neutral elements.
Arrays must have proper type.
Return type of bucket function must be an index for each
operation followed by the values to write.
Operator type must match the type of neutral elements.
| A mapper that simply returns the 'SegOp' verbatim.
| Apply a 'SegOpMapper' to the given 'SegOp'.
| A helper for defining 'TraverseOpStms'.
Indexes in excess of what is used to index through the
segment dimensions.
- Simplification
Ensure we do not try to use anything that is consumed in the result.
| Simplify the given 'SegOp'.
| Does this rep contain 'SegOp's in its t'Op's? A rep must be an
instance of this class for the simplification rules to work.
| Simplification rules for simplifying 'SegOp's.
If a SegOp produces something invariant to the SegOp, turn it
into a replicate.
Check if we did anything at all.
vector shape, merge them together. This saves on communication
overhead, but can in principle lead to more local memory usage.
A convenient way of operating on the type and body of a SegOp,
without worrying about exactly what kind it is.
Some SegOp results can be moved outside the SegOp, which can
simplify further analysis.
Iterate through the bindings. For each, we check whether it is
in kres and can be moved outside. If so, we remove it from kres
and kpes and make it a binding outside. We have to be careful
not to remove anything that is passed on to a scan/map/histogram
list.
- Memory
| Like 'segOpType', but for memory representations. | # LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
top of /something/ , except that the @map@s are conceptually only
over @iota@s ( so there will be explicit indexing inside them ) .
module Futhark.IR.SegOp
( SegOp (..),
segLevel,
segBody,
segSpace,
typeCheckSegOp,
SegSpace (..),
scopeOfSegSpace,
segSpaceDims,
HistOp (..),
histType,
splitHistResults,
SegBinOp (..),
segBinOpResults,
segBinOpChunks,
KernelBody (..),
aliasAnalyseKernelBody,
consumedInKernelBody,
ResultManifest (..),
KernelResult (..),
kernelResultCerts,
kernelResultSubExp,
SegOpMapper (..),
identitySegOpMapper,
mapSegOpM,
traverseSegOpStms,
simplifySegOp,
HasSegOp (..),
segOpRules,
segOpReturns,
)
where
import Control.Category
import Control.Monad.Identity hiding (mapM_)
import Control.Monad.Reader hiding (mapM_)
import Control.Monad.State.Strict
import Control.Monad.Writer hiding (mapM_)
import Data.Bifunctor (first)
import Data.Bitraversable
import Data.Foldable (traverse_)
import Data.List
( elemIndex,
foldl',
groupBy,
intersperse,
isPrefixOf,
partition,
)
import Data.Map.Strict qualified as M
import Data.Maybe
import Futhark.Analysis.Alias qualified as Alias
import Futhark.Analysis.Metrics
import Futhark.Analysis.PrimExp.Convert
import Futhark.Analysis.SymbolTable qualified as ST
import Futhark.Analysis.UsageTable qualified as UT
import Futhark.IR
import Futhark.IR.Aliases
( Aliases,
CanBeAliased (..),
)
import Futhark.IR.Mem
import Futhark.IR.Prop.Aliases
import Futhark.IR.TypeCheck qualified as TC
import Futhark.Optimise.Simplify.Engine qualified as Engine
import Futhark.Optimise.Simplify.Rep
import Futhark.Optimise.Simplify.Rule
import Futhark.Tools
import Futhark.Transform.Rename
import Futhark.Transform.Substitute
import Futhark.Util (chunks, maybeNth)
import Futhark.Util.Pretty
( Doc,
apply,
hsep,
parens,
ppTuple',
pretty,
(<+>),
(</>),
)
import Futhark.Util.Pretty qualified as PP
import Prelude hiding (id, (.))
data HistOp rep = HistOp
{ histShape :: Shape,
histRaceFactor :: SubExp,
histDest :: [VName],
histNeutral :: [SubExp],
SOACS representation ) , these are the logical
histOpShape :: Shape,
histOp :: Lambda rep
}
deriving (Eq, Ord, Show)
histType :: HistOp rep -> [Type]
histType op =
map (`arrayOfShape` (histShape op <> histOpShape op)) $
lambdaReturnType $
histOp op
splitHistResults :: [HistOp rep] -> [SubExp] -> [([SubExp], [SubExp])]
splitHistResults ops res =
let ranks = map (shapeRank . histShape) ops
(idxs, vals) = splitAt (sum ranks) res
in zip
(chunks ranks idxs)
(chunks (map (length . histDest) ops) vals)
| An operator for ' SegScan ' and ' SegRed ' .
data SegBinOp rep = SegBinOp
{ segBinOpComm :: Commutativity,
segBinOpLambda :: Lambda rep,
segBinOpNeutral :: [SubExp],
SOACS representation ) , these are the logical
segBinOpShape :: Shape
}
deriving (Eq, Ord, Show)
segBinOpResults :: [SegBinOp rep] -> Int
segBinOpResults = sum . map (length . segBinOpNeutral)
segBinOpChunks :: [SegBinOp rep] -> [a] -> [[a]]
segBinOpChunks = chunks . map (length . segBinOpNeutral)
data KernelBody rep = KernelBody
{ kernelBodyDec :: BodyDec rep,
kernelBodyStms :: Stms rep,
kernelBodyResult :: [KernelResult]
}
deriving instance RepTypes rep => Ord (KernelBody rep)
deriving instance RepTypes rep => Show (KernelBody rep)
deriving instance RepTypes rep => Eq (KernelBody rep)
' KernelResult ' . This is used to protect things like tiling , which
data ResultManifest
ResultNoSimplify
ResultMaySimplify
ResultPrivate
deriving (Eq, Show, Ord)
data KernelResult
Returns ResultManifest Certs SubExp
| WriteReturns
Certs
[(Slice SubExp, SubExp)]
| TileReturns
Certs
The TileReturns must not expect more than one
| RegTileReturns
Certs
)
]
deriving (Eq, Show, Ord)
| Get the certs for this ' KernelResult ' .
kernelResultCerts :: KernelResult -> Certs
kernelResultCerts (Returns _ cs _) = cs
kernelResultCerts (WriteReturns cs _ _ _) = cs
kernelResultCerts (TileReturns cs _ _) = cs
kernelResultCerts (RegTileReturns cs _ _) = cs
| Get the root t'SubExp ' corresponding values for a ' KernelResult ' .
kernelResultSubExp :: KernelResult -> SubExp
kernelResultSubExp (Returns _ _ se) = se
kernelResultSubExp (WriteReturns _ _ arr _) = Var arr
kernelResultSubExp (TileReturns _ _ v) = Var v
kernelResultSubExp (RegTileReturns _ _ v) = Var v
instance FreeIn KernelResult where
freeIn' (Returns _ cs what) = freeIn' cs <> freeIn' what
freeIn' (WriteReturns cs rws arr res) = freeIn' cs <> freeIn' rws <> freeIn' arr <> freeIn' res
freeIn' (TileReturns cs dims v) =
freeIn' cs <> freeIn' dims <> freeIn' v
freeIn' (RegTileReturns cs dims_n_tiles v) =
freeIn' cs <> freeIn' dims_n_tiles <> freeIn' v
instance ASTRep rep => FreeIn (KernelBody rep) where
freeIn' (KernelBody dec stms res) =
fvBind bound_in_stms $ freeIn' dec <> freeIn' stms <> freeIn' res
where
bound_in_stms = foldMap boundByStm stms
instance ASTRep rep => Substitute (KernelBody rep) where
substituteNames subst (KernelBody dec stms res) =
KernelBody
(substituteNames subst dec)
(substituteNames subst stms)
(substituteNames subst res)
instance Substitute KernelResult where
substituteNames subst (Returns manifest cs se) =
Returns manifest (substituteNames subst cs) (substituteNames subst se)
substituteNames subst (WriteReturns cs rws arr res) =
WriteReturns
(substituteNames subst cs)
(substituteNames subst rws)
(substituteNames subst arr)
(substituteNames subst res)
substituteNames subst (TileReturns cs dims v) =
TileReturns
(substituteNames subst cs)
(substituteNames subst dims)
(substituteNames subst v)
substituteNames subst (RegTileReturns cs dims_n_tiles v) =
RegTileReturns
(substituteNames subst cs)
(substituteNames subst dims_n_tiles)
(substituteNames subst v)
instance ASTRep rep => Rename (KernelBody rep) where
rename (KernelBody dec stms res) = do
dec' <- rename dec
renamingStms stms $ \stms' ->
KernelBody dec' stms' <$> rename res
instance Rename KernelResult where
rename = substituteRename
aliasAnalyseKernelBody ::
Alias.AliasableRep rep =>
AliasTable ->
KernelBody rep ->
KernelBody (Aliases rep)
aliasAnalyseKernelBody aliases (KernelBody dec stms res) =
let Body dec' stms' _ = Alias.analyseBody aliases $ Body dec stms []
in KernelBody dec' stms' res
consumedInKernelBody ::
Aliased rep =>
KernelBody rep ->
Names
consumedInKernelBody (KernelBody dec stms res) =
consumedInBody (Body dec stms []) <> mconcat (map consumedByReturn res)
where
consumedByReturn (WriteReturns _ _ a _) = oneName a
consumedByReturn _ = mempty
checkKernelBody ::
TC.Checkable rep =>
[Type] ->
KernelBody (Aliases rep) ->
TC.TypeM rep ()
checkKernelBody ts (KernelBody (_, dec) stms kres) = do
TC.checkBodyDec dec
mapM_ consumeKernelResult kres
TC.checkStms stms $ do
unless (length ts == length kres) $
TC.bad . TC.TypeError $
"Kernel return type is "
<> prettyTuple ts
<> ", but body returns "
<> prettyText (length kres)
<> " values."
zipWithM_ checkKernelResult kres ts
where
consumeKernelResult (WriteReturns _ _ arr _) =
TC.consume =<< TC.lookupAliases arr
consumeKernelResult _ =
pure ()
checkKernelResult (Returns _ cs what) t = do
TC.checkCerts cs
TC.require [t] what
checkKernelResult (WriteReturns cs shape arr res) t = do
TC.checkCerts cs
mapM_ (TC.require [Prim int64]) $ shapeDims shape
arr_t <- lookupType arr
forM_ res $ \(slice, e) -> do
traverse_ (TC.require [Prim int64]) slice
TC.require [t] e
unless (arr_t == t `arrayOfShape` shape) $
TC.bad $
TC.TypeError $
"WriteReturns returning "
<> prettyText e
<> " of type "
<> prettyText t
<> ", shape="
<> prettyText shape
<> ", but destination array has type "
<> prettyText arr_t
checkKernelResult (TileReturns cs dims v) t = do
TC.checkCerts cs
forM_ dims $ \(dim, tile) -> do
TC.require [Prim int64] dim
TC.require [Prim int64] tile
vt <- lookupType v
unless (vt == t `arrayOfShape` Shape (map snd dims)) $
TC.bad $
TC.TypeError $
"Invalid type for TileReturns " <> prettyText v
checkKernelResult (RegTileReturns cs dims_n_tiles arr) t = do
TC.checkCerts cs
mapM_ (TC.require [Prim int64]) dims
mapM_ (TC.require [Prim int64]) blk_tiles
mapM_ (TC.require [Prim int64]) reg_tiles
assert that is of element type t and shape ( rev outer_tiles + + reg_tiles )
arr_t <- lookupType arr
unless (arr_t == expected) $
TC.bad . TC.TypeError $
"Invalid type for TileReturns. Expected:\n "
<> prettyText expected
<> ",\ngot:\n "
<> prettyText arr_t
where
(dims, blk_tiles, reg_tiles) = unzip3 dims_n_tiles
expected = t `arrayOfShape` Shape (blk_tiles <> reg_tiles)
kernelBodyMetrics :: OpMetrics (Op rep) => KernelBody rep -> MetricsM ()
kernelBodyMetrics = mapM_ stmMetrics . kernelBodyStms
instance PrettyRep rep => Pretty (KernelBody rep) where
pretty (KernelBody _ stms res) =
PP.stack (map pretty (stmsToList stms))
</> "return"
<+> PP.braces (PP.commasep $ map pretty res)
certAnnots :: Certs -> [Doc ann]
certAnnots cs
| cs == mempty = []
| otherwise = [pretty cs]
instance Pretty KernelResult where
pretty (Returns ResultNoSimplify cs what) =
hsep $ certAnnots cs <> ["returns (manifest)" <+> pretty what]
pretty (Returns ResultPrivate cs what) =
hsep $ certAnnots cs <> ["returns (private)" <+> pretty what]
pretty (Returns ResultMaySimplify cs what) =
hsep $ certAnnots cs <> ["returns" <+> pretty what]
pretty (WriteReturns cs shape arr res) =
hsep $
certAnnots cs
<> [ pretty arr
<+> PP.colon
<+> pretty shape
</> "with"
<+> PP.apply (map ppRes res)
]
where
ppRes (slice, e) = pretty slice <+> "=" <+> pretty e
pretty (TileReturns cs dims v) =
hsep $ certAnnots cs <> ["tile" <> apply (map onDim dims) <+> pretty v]
where
onDim (dim, tile) = pretty dim <+> "/" <+> pretty tile
pretty (RegTileReturns cs dims_n_tiles v) =
hsep $ certAnnots cs <> ["blkreg_tile" <> apply (map onDim dims_n_tiles) <+> pretty v]
where
onDim (dim, blk_tile, reg_tile) =
pretty dim <+> "/" <+> parens (pretty blk_tile <+> "*" <+> pretty reg_tile)
data SegSpace = SegSpace
segFlat :: VName,
unSegSpace :: [(VName, SubExp)]
}
deriving (Eq, Ord, Show)
| The sizes spanned by the indexes of the ' SegSpace ' .
segSpaceDims :: SegSpace -> [SubExp]
segSpaceDims (SegSpace _ space) = map snd space
this ' SegSpace ' .
scopeOfSegSpace :: SegSpace -> Scope rep
scopeOfSegSpace (SegSpace phys space) =
M.fromList $ zip (phys : map fst space) $ repeat $ IndexName Int64
checkSegSpace :: TC.Checkable rep => SegSpace -> TC.TypeM rep ()
checkSegSpace (SegSpace _ dims) =
mapM_ (TC.require [Prim int64] . snd) dims
scan , or histogram ) . The ' SegSpace ' encodes the original map
of information . For example , in GPU backends , it is used to
data SegOp lvl rep
= SegMap lvl SegSpace [Type] (KernelBody rep)
| The KernelSpace must always have at least two dimensions ,
SegRed lvl SegSpace [SegBinOp rep] [Type] (KernelBody rep)
| SegScan lvl SegSpace [SegBinOp rep] [Type] (KernelBody rep)
| SegHist lvl SegSpace [HistOp rep] [Type] (KernelBody rep)
deriving (Eq, Ord, Show)
segLevel :: SegOp lvl rep -> lvl
segLevel (SegMap lvl _ _ _) = lvl
segLevel (SegRed lvl _ _ _ _) = lvl
segLevel (SegScan lvl _ _ _ _) = lvl
segLevel (SegHist lvl _ _ _ _) = lvl
segSpace :: SegOp lvl rep -> SegSpace
segSpace (SegMap _ lvl _ _) = lvl
segSpace (SegRed _ lvl _ _ _) = lvl
segSpace (SegScan _ lvl _ _ _) = lvl
segSpace (SegHist _ lvl _ _ _) = lvl
segBody :: SegOp lvl rep -> KernelBody rep
segBody segop =
case segop of
SegMap _ _ _ body -> body
SegRed _ _ _ _ body -> body
SegScan _ _ _ _ body -> body
SegHist _ _ _ _ body -> body
segResultShape :: SegSpace -> Type -> KernelResult -> Type
segResultShape _ t (WriteReturns _ shape _ _) =
t `arrayOfShape` shape
segResultShape space t Returns {} =
foldr (flip arrayOfRow) t $ segSpaceDims space
segResultShape _ t (TileReturns _ dims _) =
t `arrayOfShape` Shape (map fst dims)
segResultShape _ t (RegTileReturns _ dims_n_tiles _) =
t `arrayOfShape` Shape (map (\(dim, _, _) -> dim) dims_n_tiles)
segOpType :: SegOp lvl rep -> [Type]
segOpType (SegMap _ space ts kbody) =
zipWith (segResultShape space) ts $ kernelBodyResult kbody
segOpType (SegRed _ space reds ts kbody) =
red_ts
++ zipWith
(segResultShape space)
map_ts
(drop (length red_ts) $ kernelBodyResult kbody)
where
map_ts = drop (length red_ts) ts
segment_dims = init $ segSpaceDims space
red_ts = do
op <- reds
let shape = Shape segment_dims <> segBinOpShape op
map (`arrayOfShape` shape) (lambdaReturnType $ segBinOpLambda op)
segOpType (SegScan _ space scans ts kbody) =
scan_ts
++ zipWith
(segResultShape space)
map_ts
(drop (length scan_ts) $ kernelBodyResult kbody)
where
map_ts = drop (length scan_ts) ts
scan_ts = do
op <- scans
let shape = Shape (segSpaceDims space) <> segBinOpShape op
map (`arrayOfShape` shape) (lambdaReturnType $ segBinOpLambda op)
segOpType (SegHist _ space ops _ _) = do
op <- ops
let shape = Shape segment_dims <> histShape op <> histOpShape op
map (`arrayOfShape` shape) (lambdaReturnType $ histOp op)
where
dims = segSpaceDims space
segment_dims = init dims
instance TypedOp (SegOp lvl rep) where
opType = pure . staticShapes . segOpType
instance (ASTConstraints lvl, Aliased rep) => AliasedOp (SegOp lvl rep) where
opAliases = map (const mempty) . segOpType
consumedInOp (SegMap _ _ _ kbody) =
consumedInKernelBody kbody
consumedInOp (SegRed _ _ _ _ kbody) =
consumedInKernelBody kbody
consumedInOp (SegScan _ _ _ _ kbody) =
consumedInKernelBody kbody
consumedInOp (SegHist _ _ ops _ kbody) =
namesFromList (concatMap histDest ops) <> consumedInKernelBody kbody
typeCheckSegOp ::
TC.Checkable rep =>
(lvl -> TC.TypeM rep ()) ->
SegOp lvl (Aliases rep) ->
TC.TypeM rep ()
typeCheckSegOp checkLvl (SegMap lvl space ts kbody) = do
checkLvl lvl
checkScanRed space [] ts kbody
typeCheckSegOp checkLvl (SegRed lvl space reds ts body) = do
checkLvl lvl
checkScanRed space reds' ts body
where
reds' =
zip3
(map segBinOpLambda reds)
(map segBinOpNeutral reds)
(map segBinOpShape reds)
typeCheckSegOp checkLvl (SegScan lvl space scans ts body) = do
checkLvl lvl
checkScanRed space scans' ts body
where
scans' =
zip3
(map segBinOpLambda scans)
(map segBinOpNeutral scans)
(map segBinOpShape scans)
typeCheckSegOp checkLvl (SegHist lvl space ops ts kbody) = do
checkLvl lvl
checkSegSpace space
mapM_ TC.checkType ts
TC.binding (scopeOfSegSpace space) $ do
nes_ts <- forM ops $ \(HistOp dest_shape rf dests nes shape op) -> do
mapM_ (TC.require [Prim int64]) dest_shape
TC.require [Prim int64] rf
nes' <- mapM TC.checkArg nes
mapM_ (TC.require [Prim int64]) $ shapeDims shape
let stripVecDims = stripArray $ shapeRank shape
TC.checkLambda op $ map (TC.noArgAliases . first stripVecDims) $ nes' ++ nes'
let nes_t = map TC.argType nes'
unless (nes_t == lambdaReturnType op) $
TC.bad $
TC.TypeError $
"SegHist operator has return type "
<> prettyTuple (lambdaReturnType op)
<> " but neutral element has type "
<> prettyTuple nes_t
let dest_shape' = Shape segment_dims <> dest_shape <> shape
forM_ (zip nes_t dests) $ \(t, dest) -> do
TC.requireI [t `arrayOfShape` dest_shape'] dest
TC.consume =<< TC.lookupAliases dest
pure $ map (`arrayOfShape` shape) nes_t
checkKernelBody ts kbody
let bucket_ret_t =
concatMap ((`replicate` Prim int64) . shapeRank . histShape) ops
++ concat nes_ts
unless (bucket_ret_t == ts) $
TC.bad $
TC.TypeError $
"SegHist body has return type "
<> prettyTuple ts
<> " but should have type "
<> prettyTuple bucket_ret_t
where
segment_dims = init $ segSpaceDims space
checkScanRed ::
TC.Checkable rep =>
SegSpace ->
[(Lambda (Aliases rep), [SubExp], Shape)] ->
[Type] ->
KernelBody (Aliases rep) ->
TC.TypeM rep ()
checkScanRed space ops ts kbody = do
checkSegSpace space
mapM_ TC.checkType ts
TC.binding (scopeOfSegSpace space) $ do
ne_ts <- forM ops $ \(lam, nes, shape) -> do
mapM_ (TC.require [Prim int64]) $ shapeDims shape
nes' <- mapM TC.checkArg nes
TC.checkLambda lam $ map TC.noArgAliases $ nes' ++ nes'
let nes_t = map TC.argType nes'
unless (lambdaReturnType lam == nes_t) $
TC.bad $
TC.TypeError "wrong type for operator or neutral elements."
pure $ map (`arrayOfShape` shape) nes_t
let expecting = concat ne_ts
got = take (length expecting) ts
unless (expecting == got) $
TC.bad $
TC.TypeError $
"Wrong return for body (does not match neutral elements; expected "
<> prettyText expecting
<> "; found "
<> prettyText got
<> ")"
checkKernelBody ts kbody
| Like ' Mapper ' , but just for ' SegOp 's .
data SegOpMapper lvl frep trep m = SegOpMapper
{ mapOnSegOpSubExp :: SubExp -> m SubExp,
mapOnSegOpLambda :: Lambda frep -> m (Lambda trep),
mapOnSegOpBody :: KernelBody frep -> m (KernelBody trep),
mapOnSegOpVName :: VName -> m VName,
mapOnSegOpLevel :: lvl -> m lvl
}
identitySegOpMapper :: Monad m => SegOpMapper lvl rep rep m
identitySegOpMapper =
SegOpMapper
{ mapOnSegOpSubExp = pure,
mapOnSegOpLambda = pure,
mapOnSegOpBody = pure,
mapOnSegOpVName = pure,
mapOnSegOpLevel = pure
}
mapOnSegSpace ::
Monad f => SegOpMapper lvl frep trep f -> SegSpace -> f SegSpace
mapOnSegSpace tv (SegSpace phys dims) =
SegSpace
<$> mapOnSegOpVName tv phys
<*> traverse (bitraverse (mapOnSegOpVName tv) (mapOnSegOpSubExp tv)) dims
mapSegBinOp ::
Monad m =>
SegOpMapper lvl frep trep m ->
SegBinOp frep ->
m (SegBinOp trep)
mapSegBinOp tv (SegBinOp comm red_op nes shape) =
SegBinOp comm
<$> mapOnSegOpLambda tv red_op
<*> mapM (mapOnSegOpSubExp tv) nes
<*> (Shape <$> mapM (mapOnSegOpSubExp tv) (shapeDims shape))
mapSegOpM ::
Monad m =>
SegOpMapper lvl frep trep m ->
SegOp lvl frep ->
m (SegOp lvl trep)
mapSegOpM tv (SegMap lvl space ts body) =
SegMap
<$> mapOnSegOpLevel tv lvl
<*> mapOnSegSpace tv space
<*> mapM (mapOnSegOpType tv) ts
<*> mapOnSegOpBody tv body
mapSegOpM tv (SegRed lvl space reds ts lam) =
SegRed
<$> mapOnSegOpLevel tv lvl
<*> mapOnSegSpace tv space
<*> mapM (mapSegBinOp tv) reds
<*> mapM (mapOnType $ mapOnSegOpSubExp tv) ts
<*> mapOnSegOpBody tv lam
mapSegOpM tv (SegScan lvl space scans ts body) =
SegScan
<$> mapOnSegOpLevel tv lvl
<*> mapOnSegSpace tv space
<*> mapM (mapSegBinOp tv) scans
<*> mapM (mapOnType $ mapOnSegOpSubExp tv) ts
<*> mapOnSegOpBody tv body
mapSegOpM tv (SegHist lvl space ops ts body) =
SegHist
<$> mapOnSegOpLevel tv lvl
<*> mapOnSegSpace tv space
<*> mapM onHistOp ops
<*> mapM (mapOnType $ mapOnSegOpSubExp tv) ts
<*> mapOnSegOpBody tv body
where
onHistOp (HistOp w rf arrs nes shape op) =
HistOp
<$> mapM (mapOnSegOpSubExp tv) w
<*> mapOnSegOpSubExp tv rf
<*> mapM (mapOnSegOpVName tv) arrs
<*> mapM (mapOnSegOpSubExp tv) nes
<*> (Shape <$> mapM (mapOnSegOpSubExp tv) (shapeDims shape))
<*> mapOnSegOpLambda tv op
mapOnSegOpType ::
Monad m =>
SegOpMapper lvl frep trep m ->
Type ->
m Type
mapOnSegOpType _tv t@Prim {} = pure t
mapOnSegOpType tv (Acc acc ispace ts u) =
Acc
<$> mapOnSegOpVName tv acc
<*> traverse (mapOnSegOpSubExp tv) ispace
<*> traverse (bitraverse (traverse (mapOnSegOpSubExp tv)) pure) ts
<*> pure u
mapOnSegOpType tv (Array et shape u) =
Array et <$> traverse (mapOnSegOpSubExp tv) shape <*> pure u
mapOnSegOpType _tv (Mem s) = pure $ Mem s
rephraseBinOp ::
Monad f =>
Rephraser f from rep ->
SegBinOp from ->
f (SegBinOp rep)
rephraseBinOp r (SegBinOp comm lam nes shape) =
SegBinOp comm <$> rephraseLambda r lam <*> pure nes <*> pure shape
rephraseKernelBody ::
Monad f =>
Rephraser f from rep ->
KernelBody from ->
f (KernelBody rep)
rephraseKernelBody r (KernelBody dec stms res) =
KernelBody <$> rephraseBodyDec r dec <*> traverse (rephraseStm r) stms <*> pure res
instance RephraseOp (SegOp lvl) where
rephraseInOp r (SegMap lvl space ts body) =
SegMap lvl space ts <$> rephraseKernelBody r body
rephraseInOp r (SegRed lvl space reds ts body) =
SegRed lvl space
<$> mapM (rephraseBinOp r) reds
<*> pure ts
<*> rephraseKernelBody r body
rephraseInOp r (SegScan lvl space scans ts body) =
SegScan lvl space
<$> mapM (rephraseBinOp r) scans
<*> pure ts
<*> rephraseKernelBody r body
rephraseInOp r (SegHist lvl space hists ts body) =
SegHist lvl space
<$> mapM onOp hists
<*> pure ts
<*> rephraseKernelBody r body
where
onOp (HistOp w rf arrs nes shape op) =
HistOp w rf arrs nes shape <$> rephraseLambda r op
traverseSegOpStms :: Monad m => OpStmsTraverser m (SegOp lvl rep) rep
traverseSegOpStms f segop = mapSegOpM mapper segop
where
seg_scope = scopeOfSegSpace (segSpace segop)
f' scope = f (seg_scope <> scope)
mapper =
identitySegOpMapper
{ mapOnSegOpLambda = traverseLambdaStms f',
mapOnSegOpBody = onBody
}
onBody (KernelBody dec stms res) =
KernelBody dec <$> f seg_scope stms <*> pure res
instance
(ASTRep rep, Substitute lvl) =>
Substitute (SegOp lvl rep)
where
substituteNames subst = runIdentity . mapSegOpM substitute
where
substitute =
SegOpMapper
{ mapOnSegOpSubExp = pure . substituteNames subst,
mapOnSegOpLambda = pure . substituteNames subst,
mapOnSegOpBody = pure . substituteNames subst,
mapOnSegOpVName = pure . substituteNames subst,
mapOnSegOpLevel = pure . substituteNames subst
}
instance (ASTRep rep, ASTConstraints lvl) => Rename (SegOp lvl rep) where
rename op =
renameBound (M.keys (scopeOfSegSpace (segSpace op))) $ mapSegOpM renamer op
where
renamer = SegOpMapper rename rename rename rename rename
instance (ASTRep rep, FreeIn lvl) => FreeIn (SegOp lvl rep) where
freeIn' e =
fvBind (namesFromList $ M.keys $ scopeOfSegSpace (segSpace e)) $
flip execState mempty $
mapSegOpM free e
where
walk f x = modify (<> f x) >> pure x
free =
SegOpMapper
{ mapOnSegOpSubExp = walk freeIn',
mapOnSegOpLambda = walk freeIn',
mapOnSegOpBody = walk freeIn',
mapOnSegOpVName = walk freeIn',
mapOnSegOpLevel = walk freeIn'
}
instance OpMetrics (Op rep) => OpMetrics (SegOp lvl rep) where
opMetrics (SegMap _ _ _ body) =
inside "SegMap" $ kernelBodyMetrics body
opMetrics (SegRed _ _ reds _ body) =
inside "SegRed" $ do
mapM_ (lambdaMetrics . segBinOpLambda) reds
kernelBodyMetrics body
opMetrics (SegScan _ _ scans _ body) =
inside "SegScan" $ do
mapM_ (lambdaMetrics . segBinOpLambda) scans
kernelBodyMetrics body
opMetrics (SegHist _ _ ops _ body) =
inside "SegHist" $ do
mapM_ (lambdaMetrics . histOp) ops
kernelBodyMetrics body
instance Pretty SegSpace where
pretty (SegSpace phys dims) =
apply
( do
(i, d) <- dims
pure $ pretty i <+> "<" <+> pretty d
)
<+> parens ("~" <> pretty phys)
instance PrettyRep rep => Pretty (SegBinOp rep) where
pretty (SegBinOp comm lam nes shape) =
PP.braces (PP.commasep $ map pretty nes) <> PP.comma
</> pretty shape <> PP.comma
</> comm' <> pretty lam
where
comm' = case comm of
Commutative -> "commutative "
Noncommutative -> mempty
instance (PrettyRep rep, PP.Pretty lvl) => PP.Pretty (SegOp lvl rep) where
pretty (SegMap lvl space ts body) =
"segmap" <> pretty lvl
</> PP.align (pretty space)
<+> PP.colon
<+> ppTuple' (map pretty ts)
<+> PP.nestedBlock "{" "}" (pretty body)
pretty (SegRed lvl space reds ts body) =
"segred" <> pretty lvl
</> PP.align (pretty space)
</> PP.parens (mconcat $ intersperse (PP.comma <> PP.line) $ map pretty reds)
</> PP.colon
<+> ppTuple' (map pretty ts)
<+> PP.nestedBlock "{" "}" (pretty body)
pretty (SegScan lvl space scans ts body) =
"segscan" <> pretty lvl
</> PP.align (pretty space)
</> PP.parens (mconcat $ intersperse (PP.comma <> PP.line) $ map pretty scans)
</> PP.colon
<+> ppTuple' (map pretty ts)
<+> PP.nestedBlock "{" "}" (pretty body)
pretty (SegHist lvl space ops ts body) =
"seghist" <> pretty lvl
</> PP.align (pretty space)
</> PP.parens (mconcat $ intersperse (PP.comma <> PP.line) $ map ppOp ops)
</> PP.colon
<+> ppTuple' (map pretty ts)
<+> PP.nestedBlock "{" "}" (pretty body)
where
ppOp (HistOp w rf dests nes shape op) =
pretty w <> PP.comma
<+> pretty rf <> PP.comma
</> PP.braces (PP.commasep $ map pretty dests) <> PP.comma
</> PP.braces (PP.commasep $ map pretty nes) <> PP.comma
</> pretty shape <> PP.comma
</> pretty op
instance CanBeAliased (SegOp lvl) where
addOpAliases aliases = runIdentity . mapSegOpM alias
where
alias =
SegOpMapper
pure
(pure . Alias.analyseLambda aliases)
(pure . aliasAnalyseKernelBody aliases)
pure
pure
informKernelBody :: Informing rep => KernelBody rep -> KernelBody (Wise rep)
informKernelBody (KernelBody dec stms res) =
mkWiseKernelBody dec (informStms stms) res
instance CanBeWise (SegOp lvl) where
addOpWisdom = runIdentity . mapSegOpM add
where
add =
SegOpMapper
pure
(pure . informLambda)
(pure . informKernelBody)
pure
pure
instance ASTRep rep => ST.IndexOp (SegOp lvl rep) where
indexOp vtable k (SegMap _ space _ kbody) is = do
Returns ResultMaySimplify _ se <- maybeNth k $ kernelBodyResult kbody
guard $ length gtids <= length is
let idx_table = M.fromList $ zip gtids $ map (ST.Indexed mempty . untyped) is
idx_table' = foldl' expandIndexedTable idx_table $ kernelBodyStms kbody
case se of
Var v -> M.lookup v idx_table'
_ -> Nothing
where
(gtids, _) = unzip $ unSegSpace space
excess_is = drop (length gtids) is
expandIndexedTable table stm
| [v] <- patNames $ stmPat stm,
Just (pe, cs) <-
runWriterT $ primExpFromExp (asPrimExp table) $ stmExp stm =
M.insert v (ST.Indexed (stmCerts stm <> cs) pe) table
| [v] <- patNames $ stmPat stm,
BasicOp (Index arr slice) <- stmExp stm,
length (sliceDims slice) == length excess_is,
arr `ST.available` vtable,
Just (slice', cs) <- asPrimExpSlice table slice =
let idx =
ST.IndexedArray
(stmCerts stm <> cs)
arr
(fixSlice (fmap isInt64 slice') excess_is)
in M.insert v idx table
| otherwise =
table
asPrimExpSlice table =
runWriterT . traverse (primExpFromSubExpM (asPrimExp table))
asPrimExp table v
| Just (ST.Indexed cs e) <- M.lookup v table = tell cs >> pure e
| Just (Prim pt) <- ST.lookupType v vtable =
pure $ LeafExp v pt
| otherwise = lift Nothing
indexOp _ _ _ _ = Nothing
instance
(ASTRep rep, ASTConstraints lvl) =>
IsOp (SegOp lvl rep)
where
cheapOp _ = False
safeOp _ = True
instance Engine.Simplifiable SegSpace where
simplify (SegSpace phys dims) =
SegSpace phys <$> mapM (traverse Engine.simplify) dims
instance Engine.Simplifiable KernelResult where
simplify (Returns manifest cs what) =
Returns manifest <$> Engine.simplify cs <*> Engine.simplify what
simplify (WriteReturns cs ws a res) =
WriteReturns
<$> Engine.simplify cs
<*> Engine.simplify ws
<*> Engine.simplify a
<*> Engine.simplify res
simplify (TileReturns cs dims what) =
TileReturns <$> Engine.simplify cs <*> Engine.simplify dims <*> Engine.simplify what
simplify (RegTileReturns cs dims_n_tiles what) =
RegTileReturns
<$> Engine.simplify cs
<*> Engine.simplify dims_n_tiles
<*> Engine.simplify what
mkWiseKernelBody ::
Informing rep =>
BodyDec rep ->
Stms (Wise rep) ->
[KernelResult] ->
KernelBody (Wise rep)
mkWiseKernelBody dec stms res =
let Body dec' _ _ = mkWiseBody dec stms $ subExpsRes res_vs
in KernelBody dec' stms res
where
res_vs = map kernelResultSubExp res
mkKernelBodyM ::
MonadBuilder m =>
Stms (Rep m) ->
[KernelResult] ->
m (KernelBody (Rep m))
mkKernelBodyM stms kres = do
Body dec' _ _ <- mkBodyM stms $ subExpsRes res_ses
pure $ KernelBody dec' stms kres
where
res_ses = map kernelResultSubExp kres
simplifyKernelBody ::
(Engine.SimplifiableRep rep, BodyDec rep ~ ()) =>
SegSpace ->
KernelBody (Wise rep) ->
Engine.SimpleM rep (KernelBody (Wise rep), Stms (Wise rep))
simplifyKernelBody space (KernelBody _ stms res) = do
par_blocker <- Engine.asksEngineEnv $ Engine.blockHoistPar . Engine.envHoistBlockers
let blocker =
Engine.hasFree bound_here
`Engine.orIf` Engine.isOp
`Engine.orIf` par_blocker
`Engine.orIf` Engine.isConsumed
`Engine.orIf` Engine.isConsuming
`Engine.orIf` Engine.isDeviceMigrated
(body_res, body_stms, hoisted) <-
Engine.localVtable (flip (foldl' (flip ST.consume)) (foldMap consumedInResult res))
. Engine.localVtable (<> scope_vtable)
. Engine.localVtable (\vtable -> vtable {ST.simplifyMemory = True})
. Engine.enterLoop
$ Engine.blockIf blocker stms
$ do
res' <-
Engine.localVtable (ST.hideCertified $ namesFromList $ M.keys $ scopeOf stms) $
mapM Engine.simplify res
pure (res', UT.usages $ freeIn res')
pure (mkWiseKernelBody () body_stms body_res, hoisted)
where
scope_vtable = segSpaceSymbolTable space
bound_here = namesFromList $ M.keys $ scopeOfSegSpace space
consumedInResult (WriteReturns _ _ arr _) =
[arr]
consumedInResult _ =
[]
simplifyLambda ::
Engine.SimplifiableRep rep =>
Names ->
Lambda (Wise rep) ->
Engine.SimpleM rep (Lambda (Wise rep), Stms (Wise rep))
simplifyLambda bound = Engine.blockMigrated . Engine.simplifyLambda bound
segSpaceSymbolTable :: ASTRep rep => SegSpace -> ST.SymbolTable rep
segSpaceSymbolTable (SegSpace flat gtids_and_dims) =
foldl' f (ST.fromScope $ M.singleton flat $ IndexName Int64) gtids_and_dims
where
f vtable (gtid, dim) = ST.insertLoopVar gtid Int64 dim vtable
simplifySegBinOp ::
Engine.SimplifiableRep rep =>
VName ->
SegBinOp (Wise rep) ->
Engine.SimpleM rep (SegBinOp (Wise rep), Stms (Wise rep))
simplifySegBinOp phys_id (SegBinOp comm lam nes shape) = do
(lam', hoisted) <-
Engine.localVtable (\vtable -> vtable {ST.simplifyMemory = True}) $
simplifyLambda (oneName phys_id) lam
shape' <- Engine.simplify shape
nes' <- mapM Engine.simplify nes
pure (SegBinOp comm lam' nes' shape', hoisted)
simplifySegOp ::
( Engine.SimplifiableRep rep,
BodyDec rep ~ (),
Engine.Simplifiable lvl
) =>
SegOp lvl (Wise rep) ->
Engine.SimpleM rep (SegOp lvl (Wise rep), Stms (Wise rep))
simplifySegOp (SegMap lvl space ts kbody) = do
(lvl', space', ts') <- Engine.simplify (lvl, space, ts)
(kbody', body_hoisted) <- simplifyKernelBody space kbody
pure
( SegMap lvl' space' ts' kbody',
body_hoisted
)
simplifySegOp (SegRed lvl space reds ts kbody) = do
(lvl', space', ts') <- Engine.simplify (lvl, space, ts)
(reds', reds_hoisted) <-
Engine.localVtable (<> scope_vtable) $
mapAndUnzipM (simplifySegBinOp (segFlat space)) reds
(kbody', body_hoisted) <- simplifyKernelBody space kbody
pure
( SegRed lvl' space' reds' ts' kbody',
mconcat reds_hoisted <> body_hoisted
)
where
scope = scopeOfSegSpace space
scope_vtable = ST.fromScope scope
simplifySegOp (SegScan lvl space scans ts kbody) = do
(lvl', space', ts') <- Engine.simplify (lvl, space, ts)
(scans', scans_hoisted) <-
Engine.localVtable (<> scope_vtable) $
mapAndUnzipM (simplifySegBinOp (segFlat space)) scans
(kbody', body_hoisted) <- simplifyKernelBody space kbody
pure
( SegScan lvl' space' scans' ts' kbody',
mconcat scans_hoisted <> body_hoisted
)
where
scope = scopeOfSegSpace space
scope_vtable = ST.fromScope scope
simplifySegOp (SegHist lvl space ops ts kbody) = do
(lvl', space', ts') <- Engine.simplify (lvl, space, ts)
(ops', ops_hoisted) <- fmap unzip $
forM ops $
\(HistOp w rf arrs nes dims lam) -> do
w' <- Engine.simplify w
rf' <- Engine.simplify rf
arrs' <- Engine.simplify arrs
nes' <- Engine.simplify nes
dims' <- Engine.simplify dims
(lam', op_hoisted) <-
Engine.localVtable (<> scope_vtable) $
Engine.localVtable (\vtable -> vtable {ST.simplifyMemory = True}) $
simplifyLambda (oneName (segFlat space)) lam
pure
( HistOp w' rf' arrs' nes' dims' lam',
op_hoisted
)
(kbody', body_hoisted) <- simplifyKernelBody space kbody
pure
( SegHist lvl' space' ops' ts' kbody',
mconcat ops_hoisted <> body_hoisted
)
where
scope = scopeOfSegSpace space
scope_vtable = ST.fromScope scope
class HasSegOp rep where
type SegOpLevel rep
asSegOp :: Op rep -> Maybe (SegOp (SegOpLevel rep) rep)
segOp :: SegOp (SegOpLevel rep) rep -> Op rep
segOpRules ::
(HasSegOp rep, BuilderOps rep, Buildable rep, Aliased rep) =>
RuleBook rep
segOpRules =
ruleBook [RuleOp segOpRuleTopDown] [RuleOp segOpRuleBottomUp]
segOpRuleTopDown ::
(HasSegOp rep, BuilderOps rep, Buildable rep) =>
TopDownRuleOp rep
segOpRuleTopDown vtable pat dec op
| Just op' <- asSegOp op =
topDownSegOp vtable pat dec op'
| otherwise =
Skip
segOpRuleBottomUp ::
(HasSegOp rep, BuilderOps rep, Aliased rep) =>
BottomUpRuleOp rep
segOpRuleBottomUp vtable pat dec op
| Just op' <- asSegOp op =
bottomUpSegOp vtable pat dec op'
| otherwise =
Skip
topDownSegOp ::
(HasSegOp rep, BuilderOps rep, Buildable rep) =>
ST.SymbolTable rep ->
Pat (LetDec rep) ->
StmAux (ExpDec rep) ->
SegOp (SegOpLevel rep) rep ->
Rule rep
topDownSegOp vtable (Pat kpes) dec (SegMap lvl space ts (KernelBody _ kstms kres)) = Simplify $ do
(ts', kpes', kres') <-
unzip3 <$> filterM checkForInvarianceResult (zip3 ts kpes kres)
when (kres == kres') cannotSimplify
kbody <- mkKernelBodyM kstms kres'
addStm $
Let (Pat kpes') dec $
Op $
segOp $
SegMap lvl space ts' kbody
where
isInvariant Constant {} = True
isInvariant (Var v) = isJust $ ST.lookup v vtable
checkForInvarianceResult (_, pe, Returns rm cs se)
| cs == mempty,
rm == ResultMaySimplify,
isInvariant se = do
letBindNames [patElemName pe] $
BasicOp $
Replicate (Shape $ segSpaceDims space) se
pure False
checkForInvarianceResult _ =
pure True
If a SegRed contains two reduction operations that have the same
topDownSegOp _ (Pat pes) _ (SegRed lvl space ops ts kbody)
| length ops > 1,
op_groupings <-
groupBy sameShape $
zip ops $
chunks (map (length . segBinOpNeutral) ops) $
zip3 red_pes red_ts red_res,
any ((> 1) . length) op_groupings = Simplify $ do
let (ops', aux) = unzip $ mapMaybe combineOps op_groupings
(red_pes', red_ts', red_res') = unzip3 $ concat aux
pes' = red_pes' ++ map_pes
ts' = red_ts' ++ map_ts
kbody' = kbody {kernelBodyResult = red_res' ++ map_res}
letBind (Pat pes') $ Op $ segOp $ SegRed lvl space ops' ts' kbody'
where
(red_pes, map_pes) = splitAt (segBinOpResults ops) pes
(red_ts, map_ts) = splitAt (segBinOpResults ops) ts
(red_res, map_res) = splitAt (segBinOpResults ops) $ kernelBodyResult kbody
sameShape (op1, _) (op2, _) = segBinOpShape op1 == segBinOpShape op2
combineOps [] = Nothing
combineOps (x : xs) = Just $ foldl' combine x xs
combine (op1, op1_aux) (op2, op2_aux) =
let lam1 = segBinOpLambda op1
lam2 = segBinOpLambda op2
(op1_xparams, op1_yparams) =
splitAt (length (segBinOpNeutral op1)) $ lambdaParams lam1
(op2_xparams, op2_yparams) =
splitAt (length (segBinOpNeutral op2)) $ lambdaParams lam2
lam =
Lambda
{ lambdaParams =
op1_xparams
++ op2_xparams
++ op1_yparams
++ op2_yparams,
lambdaReturnType = lambdaReturnType lam1 ++ lambdaReturnType lam2,
lambdaBody =
mkBody (bodyStms (lambdaBody lam1) <> bodyStms (lambdaBody lam2)) $
bodyResult (lambdaBody lam1) <> bodyResult (lambdaBody lam2)
}
in ( SegBinOp
{ segBinOpComm = segBinOpComm op1 <> segBinOpComm op2,
segBinOpLambda = lam,
segBinOpNeutral = segBinOpNeutral op1 ++ segBinOpNeutral op2,
Same as shape of op2 due to the grouping .
},
op1_aux ++ op2_aux
)
topDownSegOp _ _ _ _ = Skip
segOpGuts ::
SegOp (SegOpLevel rep) rep ->
( [Type],
KernelBody rep,
Int,
[Type] -> KernelBody rep -> SegOp (SegOpLevel rep) rep
)
segOpGuts (SegMap lvl space kts body) =
(kts, body, 0, SegMap lvl space)
segOpGuts (SegScan lvl space ops kts body) =
(kts, body, segBinOpResults ops, SegScan lvl space ops)
segOpGuts (SegRed lvl space ops kts body) =
(kts, body, segBinOpResults ops, SegRed lvl space ops)
segOpGuts (SegHist lvl space ops kts body) =
(kts, body, sum $ map (length . histDest) ops, SegHist lvl space ops)
bottomUpSegOp ::
(Aliased rep, HasSegOp rep, BuilderOps rep) =>
(ST.SymbolTable rep, UT.UsageTable) ->
Pat (LetDec rep) ->
StmAux (ExpDec rep) ->
SegOp (SegOpLevel rep) rep ->
Rule rep
bottomUpSegOp (vtable, used) (Pat kpes) dec segop = Simplify $ do
operation . Fortunately , these are always first in the result
(kpes', kts', kres', kstms') <-
localScope (scopeOfSegSpace space) $
foldM distribute (kpes, kts, kres, mempty) kstms
when
(kpes' == kpes)
cannotSimplify
kbody' <-
localScope (scopeOfSegSpace space) $
mkKernelBodyM kstms' kres'
addStm $ Let (Pat kpes') dec $ Op $ segOp $ mk_segop kts' kbody'
where
(kts, kbody@(KernelBody _ kstms kres), num_nonmap_results, mk_segop) =
segOpGuts segop
free_in_kstms = foldMap freeIn kstms
consumed_in_segop = consumedInKernelBody kbody
space = segSpace segop
sliceWithGtidsFixed stm
| Let _ _ (BasicOp (Index arr slice)) <- stm,
space_slice <- map (DimFix . Var . fst) $ unSegSpace space,
space_slice `isPrefixOf` unSlice slice,
remaining_slice <- Slice $ drop (length space_slice) (unSlice slice),
all (isJust . flip ST.lookup vtable) $
namesToList $
freeIn arr <> freeIn remaining_slice =
Just (remaining_slice, arr)
| otherwise =
Nothing
distribute (kpes', kts', kres', kstms') stm
| Let (Pat [pe]) _ _ <- stm,
Just (Slice remaining_slice, arr) <- sliceWithGtidsFixed stm,
Just (kpe, kpes'', kts'', kres'') <- isResult kpes' kts' kres' pe = do
let outer_slice =
map
( \d ->
DimSlice
(constant (0 :: Int64))
d
(constant (1 :: Int64))
)
$ segSpaceDims space
index kpe' =
letBindNames [patElemName kpe'] . BasicOp . Index arr $
Slice $
outer_slice <> remaining_slice
if patElemName kpe
`UT.isConsumed` used
|| arr
`nameIn` consumed_in_segop
then do
precopy <- newVName $ baseString (patElemName kpe) <> "_precopy"
index kpe {patElemName = precopy}
letBindNames [patElemName kpe] $ BasicOp $ Copy precopy
else index kpe
pure
( kpes'',
kts'',
kres'',
if patElemName pe `nameIn` free_in_kstms
then kstms' <> oneStm stm
else kstms'
)
distribute (kpes', kts', kres', kstms') stm =
pure (kpes', kts', kres', kstms' <> oneStm stm)
isResult kpes' kts' kres' pe =
case partition matches $ zip3 kpes' kts' kres' of
([(kpe, _, _)], kpes_and_kres)
| Just i <- elemIndex kpe kpes,
i >= num_nonmap_results,
(kpes'', kts'', kres'') <- unzip3 kpes_and_kres ->
Just (kpe, kpes'', kts'', kres'')
_ -> Nothing
where
matches (_, _, Returns _ _ (Var v)) = v == patElemName pe
matches _ = False
kernelBodyReturns ::
(Mem rep inner, HasScope rep m, Monad m) =>
KernelBody somerep ->
[ExpReturns] ->
m [ExpReturns]
kernelBodyReturns = zipWithM correct . kernelBodyResult
where
correct (WriteReturns _ _ arr _) _ = varReturns arr
correct _ ret = pure ret
segOpReturns ::
(Mem rep inner, Monad m, HasScope rep m) =>
SegOp lvl somerep ->
m [ExpReturns]
segOpReturns k@(SegMap _ _ _ kbody) =
kernelBodyReturns kbody . extReturns =<< opType k
segOpReturns k@(SegRed _ _ _ _ kbody) =
kernelBodyReturns kbody . extReturns =<< opType k
segOpReturns k@(SegScan _ _ _ _ kbody) =
kernelBodyReturns kbody . extReturns =<< opType k
segOpReturns (SegHist _ _ ops _ _) =
concat <$> mapM (mapM varReturns . histDest) ops
|
94a7e9dd25646ffb35c0eaa0bd4d47f183c89038fdd0afd544f6fce35862a501 | well-typed-lightbulbs/ocaml-esp32 | switch_opts.ml | (* TEST *)
(* Test for optimisation of jump tables to arrays of constants *)
let p = Printf.printf
type test =
Test : 'b * 'a * ('b -> 'a) -> test
type t = A | B | C
These test functions need to have at least three cases .
Functions with fewer cases do n't trigger the optimisation ,
as they are compiled to if - then - else , not switch
Functions with fewer cases don't trigger the optimisation,
as they are compiled to if-then-else, not switch *)
let passes = ref 0
let full_test line ~f ~results () =
let f = Sys.opaque_identity f in
List.iter
(fun (input, output) ->
let result = f input in
if result <> output
then raise (Assert_failure (__FILE__,line,0))
)
results;
incr passes
let test_int_match =
full_test __LINE__
~f:(function
| 1 -> 1
| 2 -> 2
| 3 -> 3
| _ -> 0
)
~results:
[ 1,1; 2,2; 3,3; 4,0; 0,0 ]
let test_int_match_reverse =
full_test __LINE__
~f:(function
| 1 -> 3
| 2 -> 2
| 3 -> 1
| _ -> 0
)
~results:
[ 1,3; 2,2; 3,1; 4,0; 0,0 ]
let test_int_match_negative =
full_test __LINE__
~f:(function
| 1 -> -1
| 2 -> -2
| 3 -> -3
| _ -> 0
)
~results:
[ 1,-1; 2,-2; 3,-3; 4,0; 0,0 ]
let test_int_match_negative_reverse =
full_test __LINE__
~f:(function
| 1 -> -3
| 2 -> -2
| 3 -> -1
| _ -> 0
)
~results:
[ 1,-3; 2,-2; 3,-1; 4,0; 0,0 ]
let test_int_min_int =
full_test __LINE__
~f:(function
| 1 -> 1
| 2 -> 2
| 3 -> min_int
| _ -> 0
)
~results:
[ 1,1; 2,2; 3,min_int; 4,0; 0,0 ]
let test_int_max_int =
full_test __LINE__
~f:(function
| 1 -> 1
| 2 -> 2
| 3 -> max_int
| _ -> 0
)
~results:
[ 1,1; 2,2; 3,max_int; 4,0; 0,0 ]
let test_float =
full_test __LINE__
~f:(function
| 1 -> 1.0
| 2 -> 2.0
| 3 -> 3.0
| _ -> 0.0
)
~results:
[ 1,1.0; 2,2.0; 3,3.0; 4,0.0; 0,0.0 ]
let test_string =
full_test __LINE__
~f:(function
| 1 -> "a"
| 2 -> "b"
| 3 -> "cc"
| _ -> ""
)
~results:
[ 1,"a"; 2, "b"
; 3, Sys.opaque_identity "c" ^ Sys.opaque_identity "c"; 4, ""; 0, "" ]
let test_list =
full_test __LINE__
~f:(function
| 1 -> []
| 2 -> [ 42 ]
| 3 -> [ 1; 2; 3 ]
| _ -> [ 415 ]
)
~results:
[ 1, []; 2, [ 42 ]; 3, List.rev [3;2;1]; 4, [ 415 ]; 0, [ 415 ] ]
let test_abc =
full_test __LINE__
~f:(function
| A -> 1
| B -> 2
| C -> 3
)
~results:
[ A, 1; B, 2; C, 3]
let test_abc_unsorted =
full_test __LINE__
~f:(function
| C -> 3
| A -> 1
| B -> 2
)
~results:
[ A, 1; B, 2; C, 3]
let test_abc_neg3 =
full_test __LINE__
~f:(function
| A -> 1
| B -> 2
| C -> -3
)
~results:
[ A, 1; B, 2; C, -3]
let test_abc_min_int =
full_test __LINE__
~f:(function
| A -> 1
| B -> 2
| C -> min_int
)
~results:
[ A, 1; B, 2; C, min_int ]
let test_abc_max_int =
full_test __LINE__
~f:(function
| A -> 1
| B -> 2
| C -> max_int
)
~results:
[ A, 1; B, 2; C, max_int ]
let test_abc_float =
full_test __LINE__
~f:(function
| A -> 1.
| B -> 2.
| C -> 3.
)
~results:
[ A, 1.; B, 2.; C, 3. ]
let test_abc_string =
full_test __LINE__
~f:(function
| A -> "a"
| B -> "b"
| C -> "c"
)
~results:
[ A, "a"; B, "b"; C, "c" ]
let test_abc_list =
full_test __LINE__
~f:(function
| A -> []
| B -> [42]
| C -> [1;2;3]
)
~results:
[ A, []; B, [42]; C, List.rev [3;2;1] ]
let test_f99 =
full_test __LINE__
~f:(function
| 1 -> 1 | 2 -> 2 | 3 -> 3 | 4 -> 4 | 5 -> 5 | 6 -> 6 | 7 -> 7 | 8 -> 8
| 9 -> 9 | 10 -> 10 | 11 -> 11 | 12 -> 12 | 13 -> 13 | 14 -> 14 | 15 -> 15
| 16 -> 16 | 17 -> 17 | 18 -> 18 | 19 -> 19 | 20 -> 20 | 21 -> 21 | 22 -> 22
| 23 -> 23 | 24 -> 24 | 25 -> 25 | 26 -> 26 | 27 -> 27 | 28 -> 28 | 29 -> 29
| 30 -> 30 | 31 -> 31 | 32 -> 32 | 33 -> 33 | 34 -> 34 | 35 -> 35 | 36 -> 36
| 37 -> 37 | 38 -> 38 | 39 -> 39 | 40 -> 40 | 41 -> 41 | 42 -> 42 | 43 -> 43
| 44 -> 44 | 45 -> 45 | 46 -> 46 | 47 -> 47 | 48 -> 48 | 49 -> 49 | 50 -> 50
| 51 -> 51 | 52 -> 52 | 53 -> 53 | 54 -> 54 | 55 -> 55 | 56 -> 56 | 57 -> 57
| 58 -> 58 | 59 -> 59 | 60 -> 60 | 61 -> 61 | 62 -> 62 | 63 -> 63 | 64 -> 64
| 65 -> 65 | 66 -> 66 | 67 -> 67 | 68 -> 68 | 69 -> 69 | 70 -> 70 | 71 -> 71
| 72 -> 72 | 73 -> 73 | 74 -> 74 | 75 -> 75 | 76 -> 76 | 77 -> 77 | 78 -> 78
| 79 -> 79 | 80 -> 80 | 81 -> 81 | 82 -> 82 | 83 -> 83 | 84 -> 84 | 85 -> 85
| 86 -> 86 | 87 -> 87 | 88 -> 88 | 89 -> 89 | 90 -> 90 | 91 -> 91 | 92 -> 92
| 93 -> 93 | 94 -> 94 | 95 -> 95 | 96 -> 96 | 97 -> 97 | 98 -> 98 | 99 -> 99
| _ -> 0
)
~results:
[ 1,1; 42,42; 98, 98; 99,99; 100, 0 ]
let test_poly =
full_test __LINE__
~f:(function
| 1 -> `Primary
| 2 -> `Secondary
| 3 -> `Tertiary
| n -> invalid_arg "test"
)
~results:
[ 1, `Primary; 2, `Secondary; 3, `Tertiary ]
let test_or =
full_test __LINE__
~f:(function
| 1 | 2 | 3 -> 0
| 4 | 5 | 6 -> 1
| 7 -> 2
| _ -> 0
)
~results:
[ 1,0; 2,0; 3,0; 4,1; 5,1; 6,1; 7,2; 8,0; 0,0 ]
type t' = E | F | G | H
let test_or_efgh =
full_test __LINE__
~f:(function
| E | H -> 0
| F -> 1
| G -> 2
)
~results:
[ E,0; H,0; F,1; G,2 ]
type 'a gadt =
| Ag : int gadt
| Bg : string gadt
| Cg : int gadt
| Dg : int gadt
| Eg : int gadt
let test_gadt =
full_test __LINE__
~f:(function
| Ag -> 1
| Cg -> 2
| Dg -> 3
| Eg -> 4
)
~results:
[ Ag,1; Cg,2; Dg,3; Eg,4 ]
let () =
test_int_match ();
test_int_match_reverse ();
test_int_match_negative ();
test_int_match_negative_reverse ();
test_int_min_int ();
test_int_max_int ();
test_float ();
test_string ();
test_list ();
test_abc ();
test_abc_unsorted ();
test_abc_neg3 ();
test_abc_min_int ();
test_abc_max_int ();
test_abc_float ();
test_abc_string ();
test_abc_list ();
test_f99 ();
test_poly ();
test_or ();
test_or_efgh ();
test_gadt ();
()
let () =
Printf.printf "%d tests passed\n" !passes
| null | https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/testsuite/tests/basic/switch_opts.ml | ocaml | TEST
Test for optimisation of jump tables to arrays of constants |
let p = Printf.printf
type test =
Test : 'b * 'a * ('b -> 'a) -> test
type t = A | B | C
These test functions need to have at least three cases .
Functions with fewer cases do n't trigger the optimisation ,
as they are compiled to if - then - else , not switch
Functions with fewer cases don't trigger the optimisation,
as they are compiled to if-then-else, not switch *)
let passes = ref 0
let full_test line ~f ~results () =
let f = Sys.opaque_identity f in
List.iter
(fun (input, output) ->
let result = f input in
if result <> output
then raise (Assert_failure (__FILE__,line,0))
)
results;
incr passes
let test_int_match =
full_test __LINE__
~f:(function
| 1 -> 1
| 2 -> 2
| 3 -> 3
| _ -> 0
)
~results:
[ 1,1; 2,2; 3,3; 4,0; 0,0 ]
let test_int_match_reverse =
full_test __LINE__
~f:(function
| 1 -> 3
| 2 -> 2
| 3 -> 1
| _ -> 0
)
~results:
[ 1,3; 2,2; 3,1; 4,0; 0,0 ]
let test_int_match_negative =
full_test __LINE__
~f:(function
| 1 -> -1
| 2 -> -2
| 3 -> -3
| _ -> 0
)
~results:
[ 1,-1; 2,-2; 3,-3; 4,0; 0,0 ]
let test_int_match_negative_reverse =
full_test __LINE__
~f:(function
| 1 -> -3
| 2 -> -2
| 3 -> -1
| _ -> 0
)
~results:
[ 1,-3; 2,-2; 3,-1; 4,0; 0,0 ]
let test_int_min_int =
full_test __LINE__
~f:(function
| 1 -> 1
| 2 -> 2
| 3 -> min_int
| _ -> 0
)
~results:
[ 1,1; 2,2; 3,min_int; 4,0; 0,0 ]
let test_int_max_int =
full_test __LINE__
~f:(function
| 1 -> 1
| 2 -> 2
| 3 -> max_int
| _ -> 0
)
~results:
[ 1,1; 2,2; 3,max_int; 4,0; 0,0 ]
let test_float =
full_test __LINE__
~f:(function
| 1 -> 1.0
| 2 -> 2.0
| 3 -> 3.0
| _ -> 0.0
)
~results:
[ 1,1.0; 2,2.0; 3,3.0; 4,0.0; 0,0.0 ]
let test_string =
full_test __LINE__
~f:(function
| 1 -> "a"
| 2 -> "b"
| 3 -> "cc"
| _ -> ""
)
~results:
[ 1,"a"; 2, "b"
; 3, Sys.opaque_identity "c" ^ Sys.opaque_identity "c"; 4, ""; 0, "" ]
let test_list =
full_test __LINE__
~f:(function
| 1 -> []
| 2 -> [ 42 ]
| 3 -> [ 1; 2; 3 ]
| _ -> [ 415 ]
)
~results:
[ 1, []; 2, [ 42 ]; 3, List.rev [3;2;1]; 4, [ 415 ]; 0, [ 415 ] ]
let test_abc =
full_test __LINE__
~f:(function
| A -> 1
| B -> 2
| C -> 3
)
~results:
[ A, 1; B, 2; C, 3]
let test_abc_unsorted =
full_test __LINE__
~f:(function
| C -> 3
| A -> 1
| B -> 2
)
~results:
[ A, 1; B, 2; C, 3]
let test_abc_neg3 =
full_test __LINE__
~f:(function
| A -> 1
| B -> 2
| C -> -3
)
~results:
[ A, 1; B, 2; C, -3]
let test_abc_min_int =
full_test __LINE__
~f:(function
| A -> 1
| B -> 2
| C -> min_int
)
~results:
[ A, 1; B, 2; C, min_int ]
let test_abc_max_int =
full_test __LINE__
~f:(function
| A -> 1
| B -> 2
| C -> max_int
)
~results:
[ A, 1; B, 2; C, max_int ]
let test_abc_float =
full_test __LINE__
~f:(function
| A -> 1.
| B -> 2.
| C -> 3.
)
~results:
[ A, 1.; B, 2.; C, 3. ]
let test_abc_string =
full_test __LINE__
~f:(function
| A -> "a"
| B -> "b"
| C -> "c"
)
~results:
[ A, "a"; B, "b"; C, "c" ]
let test_abc_list =
full_test __LINE__
~f:(function
| A -> []
| B -> [42]
| C -> [1;2;3]
)
~results:
[ A, []; B, [42]; C, List.rev [3;2;1] ]
let test_f99 =
full_test __LINE__
~f:(function
| 1 -> 1 | 2 -> 2 | 3 -> 3 | 4 -> 4 | 5 -> 5 | 6 -> 6 | 7 -> 7 | 8 -> 8
| 9 -> 9 | 10 -> 10 | 11 -> 11 | 12 -> 12 | 13 -> 13 | 14 -> 14 | 15 -> 15
| 16 -> 16 | 17 -> 17 | 18 -> 18 | 19 -> 19 | 20 -> 20 | 21 -> 21 | 22 -> 22
| 23 -> 23 | 24 -> 24 | 25 -> 25 | 26 -> 26 | 27 -> 27 | 28 -> 28 | 29 -> 29
| 30 -> 30 | 31 -> 31 | 32 -> 32 | 33 -> 33 | 34 -> 34 | 35 -> 35 | 36 -> 36
| 37 -> 37 | 38 -> 38 | 39 -> 39 | 40 -> 40 | 41 -> 41 | 42 -> 42 | 43 -> 43
| 44 -> 44 | 45 -> 45 | 46 -> 46 | 47 -> 47 | 48 -> 48 | 49 -> 49 | 50 -> 50
| 51 -> 51 | 52 -> 52 | 53 -> 53 | 54 -> 54 | 55 -> 55 | 56 -> 56 | 57 -> 57
| 58 -> 58 | 59 -> 59 | 60 -> 60 | 61 -> 61 | 62 -> 62 | 63 -> 63 | 64 -> 64
| 65 -> 65 | 66 -> 66 | 67 -> 67 | 68 -> 68 | 69 -> 69 | 70 -> 70 | 71 -> 71
| 72 -> 72 | 73 -> 73 | 74 -> 74 | 75 -> 75 | 76 -> 76 | 77 -> 77 | 78 -> 78
| 79 -> 79 | 80 -> 80 | 81 -> 81 | 82 -> 82 | 83 -> 83 | 84 -> 84 | 85 -> 85
| 86 -> 86 | 87 -> 87 | 88 -> 88 | 89 -> 89 | 90 -> 90 | 91 -> 91 | 92 -> 92
| 93 -> 93 | 94 -> 94 | 95 -> 95 | 96 -> 96 | 97 -> 97 | 98 -> 98 | 99 -> 99
| _ -> 0
)
~results:
[ 1,1; 42,42; 98, 98; 99,99; 100, 0 ]
let test_poly =
full_test __LINE__
~f:(function
| 1 -> `Primary
| 2 -> `Secondary
| 3 -> `Tertiary
| n -> invalid_arg "test"
)
~results:
[ 1, `Primary; 2, `Secondary; 3, `Tertiary ]
let test_or =
full_test __LINE__
~f:(function
| 1 | 2 | 3 -> 0
| 4 | 5 | 6 -> 1
| 7 -> 2
| _ -> 0
)
~results:
[ 1,0; 2,0; 3,0; 4,1; 5,1; 6,1; 7,2; 8,0; 0,0 ]
type t' = E | F | G | H
let test_or_efgh =
full_test __LINE__
~f:(function
| E | H -> 0
| F -> 1
| G -> 2
)
~results:
[ E,0; H,0; F,1; G,2 ]
type 'a gadt =
| Ag : int gadt
| Bg : string gadt
| Cg : int gadt
| Dg : int gadt
| Eg : int gadt
let test_gadt =
full_test __LINE__
~f:(function
| Ag -> 1
| Cg -> 2
| Dg -> 3
| Eg -> 4
)
~results:
[ Ag,1; Cg,2; Dg,3; Eg,4 ]
let () =
test_int_match ();
test_int_match_reverse ();
test_int_match_negative ();
test_int_match_negative_reverse ();
test_int_min_int ();
test_int_max_int ();
test_float ();
test_string ();
test_list ();
test_abc ();
test_abc_unsorted ();
test_abc_neg3 ();
test_abc_min_int ();
test_abc_max_int ();
test_abc_float ();
test_abc_string ();
test_abc_list ();
test_f99 ();
test_poly ();
test_or ();
test_or_efgh ();
test_gadt ();
()
let () =
Printf.printf "%d tests passed\n" !passes
|
79b6e3bcaa47710645fbf67f87bf58c5d73c3cc08401309500141bb7b719e12a | well-typed/cborg | CBOR.hs | # OPTIONS_GHC -fno - warn - unused - imports #
-- |
-- Module : Codec.CBOR
Copyright : ( c ) 2015 - 2017
License : BSD3 - style ( see LICENSE.txt )
--
-- Maintainer :
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
-- A library for working with CBOR.
--
module Codec.CBOR
( -- $intro
-- * Library Structure
-- $structure
) where
used by
import Codec.CBOR.Decoding (Decoder)
import Codec.CBOR.Encoding (Encoding)
import Codec.CBOR.FlatTerm (FlatTerm)
import Codec.CBOR.Term (Term, encodeTerm, decodeTerm)
$ intro
The @cborg@ library is a low - level parsing and encoding library for the
Compact Binary Object Representation ( CBOR ) defined in RFC 7049 . is a
language - agnostic , extensible , and size- and computation - efficient encoding
for arbitrary data , with a well - defined bijection to the ubiquitous JSON format
and a precisely specified canonical form .
Note , however , that @cborg@ does not itself aim to be a serialisation
library ; it merely serves as the substrate on which such a library might be
built . See the [ serialise](/package / serialise ) library if you are looking for
convenient serialisation of values .
Instead , @cborg@ targets cases where precise control over the CBOR object
structure is needed such as when working with externally - specified CBOR formats .
The @cborg@ library is a low-level parsing and encoding library for the
Compact Binary Object Representation (CBOR) defined in RFC 7049. CBOR is a
language-agnostic, extensible, and size- and computation-efficient encoding
for arbitrary data, with a well-defined bijection to the ubiquitous JSON format
and a precisely specified canonical form.
Note, however, that @cborg@ does not itself aim to be a serialisation
library; it merely serves as the substrate on which such a library might be
built. See the [serialise](/package/serialise) library if you are looking for
convenient serialisation of Haskell values.
Instead, @cborg@ targets cases where precise control over the CBOR object
structure is needed such as when working with externally-specified CBOR formats.
-}
$ structure
The library is split into a number of modules ,
* Decoding
* " Codec . CBOR.Decoding " defines the machinery for decoding primitive CBOR terms
into values . In particular , the ' Decoder ' type and associated decoders ,
@
data ' Decoder ' s a
-- for , e.g. , safe in - place mutation during decoding
liftST : : ST s a - > ' Decoder ' s a
-- primitive decoders
: : ' Decoder ' s Word
decodeBytes : : ' Decoder ' s ByteString
-- et cetera
@
* " Codec . CBOR.Read " defines the low - level wire - format decoder , e.g.
@
' Codec . CBOR.Read.deserialiseFromBytes ' : : ' Decoder ' a
- > ByteString
- > Either String ( ByteString , a )
@
* Encoding
* " Codec . CBOR.Encoding " defines the ' Encoding ' type , which is in essence
difference - list of CBOR tokens and is used to construct CBOR encodings .
@
data ' Encoding '
instance Monoid ' Encoding '
encodeWord : : Word - > Encoding
encodeBytes : : ByteString - > Encoding
-- et cetera
@
* " Codec . CBOR.Write " defines the low - level wire - format encoder , e.g.
@
' Codec . CBOR.Write.toBuilder ' : : ' Encoding ' a - > Data . ByteString . Builder . Builder
@
* Capturing arbitrary terms
* " Codec . CBOR.Term " provides the ' Term ' type , which provides a type for
capturing arbitrary CBOR terms . ' Term 's can be encoded and decoded with ,
@
data ' Term '
= TInt Int
| TBytes ByteString
-- et cetera
' encodeTerm ' : : ' Term ' - > ' Encoding '
' decodeTerm ' : : ' Decoder ' ' Term '
@
* Debugging
* " Codec . CBOR.FlatTerm " contains the ' FlatTerm ' type , which provides a
concrete AST for capturing primitive CBOR wire encodings . This can be
useful when testing decoders and encoders .
The library is split into a number of modules,
* Decoding
* "Codec.CBOR.Decoding" defines the machinery for decoding primitive CBOR terms
into Haskell values. In particular, the 'Decoder' type and associated decoders,
@
data 'Decoder' s a
-- for, e.g., safe in-place mutation during decoding
liftST :: ST s a -> 'Decoder' s a
-- primitive decoders
decodeWord :: 'Decoder' s Word
decodeBytes :: 'Decoder' s ByteString
-- et cetera
@
* "Codec.CBOR.Read" defines the low-level wire-format decoder, e.g.
@
'Codec.CBOR.Read.deserialiseFromBytes' :: 'Decoder' a
-> ByteString
-> Either String (ByteString, a)
@
* Encoding
* "Codec.CBOR.Encoding" defines the 'Encoding' type, which is in essence
difference-list of CBOR tokens and is used to construct CBOR encodings.
@
data 'Encoding'
instance Monoid 'Encoding'
encodeWord :: Word -> Encoding
encodeBytes :: ByteString -> Encoding
-- et cetera
@
* "Codec.CBOR.Write" defines the low-level wire-format encoder, e.g.
@
'Codec.CBOR.Write.toBuilder' :: 'Encoding' a -> Data.ByteString.Builder.Builder
@
* Capturing arbitrary terms
* "Codec.CBOR.Term" provides the 'Term' type, which provides a type for
capturing arbitrary CBOR terms. 'Term's can be encoded and decoded with,
@
data 'Term'
= TInt Int
| TBytes ByteString
-- et cetera
'encodeTerm' :: 'Term' -> 'Encoding'
'decodeTerm' :: 'Decoder' 'Term'
@
* Debugging
* "Codec.CBOR.FlatTerm" contains the 'FlatTerm' type, which provides a
concrete AST for capturing primitive CBOR wire encodings. This can be
useful when testing decoders and encoders.
-}
| null | https://raw.githubusercontent.com/well-typed/cborg/9be3fd5437f9d2ec1df784d5d939efb9a85fd1fb/cborg/src/Codec/CBOR.hs | haskell | |
Module : Codec.CBOR
Maintainer :
Stability : experimental
A library for working with CBOR.
$intro
* Library Structure
$structure
for , e.g. , safe in - place mutation during decoding
primitive decoders
et cetera
et cetera
et cetera
for, e.g., safe in-place mutation during decoding
primitive decoders
et cetera
et cetera
et cetera | # OPTIONS_GHC -fno - warn - unused - imports #
Copyright : ( c ) 2015 - 2017
License : BSD3 - style ( see LICENSE.txt )
Portability : non - portable ( GHC extensions )
module Codec.CBOR
) where
used by
import Codec.CBOR.Decoding (Decoder)
import Codec.CBOR.Encoding (Encoding)
import Codec.CBOR.FlatTerm (FlatTerm)
import Codec.CBOR.Term (Term, encodeTerm, decodeTerm)
$ intro
The @cborg@ library is a low - level parsing and encoding library for the
Compact Binary Object Representation ( CBOR ) defined in RFC 7049 . is a
language - agnostic , extensible , and size- and computation - efficient encoding
for arbitrary data , with a well - defined bijection to the ubiquitous JSON format
and a precisely specified canonical form .
Note , however , that @cborg@ does not itself aim to be a serialisation
library ; it merely serves as the substrate on which such a library might be
built . See the [ serialise](/package / serialise ) library if you are looking for
convenient serialisation of values .
Instead , @cborg@ targets cases where precise control over the CBOR object
structure is needed such as when working with externally - specified CBOR formats .
The @cborg@ library is a low-level parsing and encoding library for the
Compact Binary Object Representation (CBOR) defined in RFC 7049. CBOR is a
language-agnostic, extensible, and size- and computation-efficient encoding
for arbitrary data, with a well-defined bijection to the ubiquitous JSON format
and a precisely specified canonical form.
Note, however, that @cborg@ does not itself aim to be a serialisation
library; it merely serves as the substrate on which such a library might be
built. See the [serialise](/package/serialise) library if you are looking for
convenient serialisation of Haskell values.
Instead, @cborg@ targets cases where precise control over the CBOR object
structure is needed such as when working with externally-specified CBOR formats.
-}
$ structure
The library is split into a number of modules ,
* Decoding
* " Codec . CBOR.Decoding " defines the machinery for decoding primitive CBOR terms
into values . In particular , the ' Decoder ' type and associated decoders ,
@
data ' Decoder ' s a
liftST : : ST s a - > ' Decoder ' s a
: : ' Decoder ' s Word
decodeBytes : : ' Decoder ' s ByteString
@
* " Codec . CBOR.Read " defines the low - level wire - format decoder , e.g.
@
' Codec . CBOR.Read.deserialiseFromBytes ' : : ' Decoder ' a
- > ByteString
- > Either String ( ByteString , a )
@
* Encoding
* " Codec . CBOR.Encoding " defines the ' Encoding ' type , which is in essence
difference - list of CBOR tokens and is used to construct CBOR encodings .
@
data ' Encoding '
instance Monoid ' Encoding '
encodeWord : : Word - > Encoding
encodeBytes : : ByteString - > Encoding
@
* " Codec . CBOR.Write " defines the low - level wire - format encoder , e.g.
@
' Codec . CBOR.Write.toBuilder ' : : ' Encoding ' a - > Data . ByteString . Builder . Builder
@
* Capturing arbitrary terms
* " Codec . CBOR.Term " provides the ' Term ' type , which provides a type for
capturing arbitrary CBOR terms . ' Term 's can be encoded and decoded with ,
@
data ' Term '
= TInt Int
| TBytes ByteString
' encodeTerm ' : : ' Term ' - > ' Encoding '
' decodeTerm ' : : ' Decoder ' ' Term '
@
* Debugging
* " Codec . CBOR.FlatTerm " contains the ' FlatTerm ' type , which provides a
concrete AST for capturing primitive CBOR wire encodings . This can be
useful when testing decoders and encoders .
The library is split into a number of modules,
* Decoding
* "Codec.CBOR.Decoding" defines the machinery for decoding primitive CBOR terms
into Haskell values. In particular, the 'Decoder' type and associated decoders,
@
data 'Decoder' s a
liftST :: ST s a -> 'Decoder' s a
decodeWord :: 'Decoder' s Word
decodeBytes :: 'Decoder' s ByteString
@
* "Codec.CBOR.Read" defines the low-level wire-format decoder, e.g.
@
'Codec.CBOR.Read.deserialiseFromBytes' :: 'Decoder' a
-> ByteString
-> Either String (ByteString, a)
@
* Encoding
* "Codec.CBOR.Encoding" defines the 'Encoding' type, which is in essence
difference-list of CBOR tokens and is used to construct CBOR encodings.
@
data 'Encoding'
instance Monoid 'Encoding'
encodeWord :: Word -> Encoding
encodeBytes :: ByteString -> Encoding
@
* "Codec.CBOR.Write" defines the low-level wire-format encoder, e.g.
@
'Codec.CBOR.Write.toBuilder' :: 'Encoding' a -> Data.ByteString.Builder.Builder
@
* Capturing arbitrary terms
* "Codec.CBOR.Term" provides the 'Term' type, which provides a type for
capturing arbitrary CBOR terms. 'Term's can be encoded and decoded with,
@
data 'Term'
= TInt Int
| TBytes ByteString
'encodeTerm' :: 'Term' -> 'Encoding'
'decodeTerm' :: 'Decoder' 'Term'
@
* Debugging
* "Codec.CBOR.FlatTerm" contains the 'FlatTerm' type, which provides a
concrete AST for capturing primitive CBOR wire encodings. This can be
useful when testing decoders and encoders.
-}
|
0dcff0447cd2963a5cf5a0d1d27a6dcd297c0b39d9893488aa9ec704733d5795 | Beluga-lang/Beluga | annotated.ml | module type TYPE = sig
type t
end
module type Base = sig
type annotation
type 'a t =
{ value : 'a;
annotation : annotation;
}
val make : 'a -> annotation -> 'a t
val map : ('a -> 'b) -> 'a t -> 'b t
val amap : (annotation -> annotation) -> 'a t -> 'a t
end
module Make (T : TYPE) : Base with type annotation = T.t = struct
type annotation = T.t
type 'a t =
{ value : 'a;
annotation : annotation;
}
let make (x : 'a) (a : annotation) =
{ value = x;
annotation = a;
}
let map (f : 'a -> 'b) (a : 'a t) =
{ a with value = f a.value }
let amap (f : annotation -> annotation) (a : 'a t) : 'a t =
{ a with annotation = f a.annotation }
end
| null | https://raw.githubusercontent.com/Beluga-lang/Beluga/23b6dea4d2f2ba81e2a82a3a57a7ca016757a2e7/src/replay/annotated.ml | ocaml | module type TYPE = sig
type t
end
module type Base = sig
type annotation
type 'a t =
{ value : 'a;
annotation : annotation;
}
val make : 'a -> annotation -> 'a t
val map : ('a -> 'b) -> 'a t -> 'b t
val amap : (annotation -> annotation) -> 'a t -> 'a t
end
module Make (T : TYPE) : Base with type annotation = T.t = struct
type annotation = T.t
type 'a t =
{ value : 'a;
annotation : annotation;
}
let make (x : 'a) (a : annotation) =
{ value = x;
annotation = a;
}
let map (f : 'a -> 'b) (a : 'a t) =
{ a with value = f a.value }
let amap (f : annotation -> annotation) (a : 'a t) : 'a t =
{ a with annotation = f a.annotation }
end
|
|
aefbb794707f411c3f05e4c4fad9e79bb237ca1d9c2a656da30488fe87a29d78 | tonyrog/pacman | pacman_sup.erl |
-module(pacman_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
%% ===================================================================
%% API functions
%% ===================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% ===================================================================
%% Supervisor callbacks
%% ===================================================================
init([]) ->
C = {pacman, {pacman, start_link, []}, transient, 5000, worker, [pacman]},
{ok, { {one_for_one, 5, 10}, [C]} }.
| null | https://raw.githubusercontent.com/tonyrog/pacman/39f32a55612666ea6f1f82d6b8aa94e263026627/src/pacman_sup.erl | erlang | API
Supervisor callbacks
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
=================================================================== |
-module(pacman_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
C = {pacman, {pacman, start_link, []}, transient, 5000, worker, [pacman]},
{ok, { {one_for_one, 5, 10}, [C]} }.
|
39dd113956fabf8f016d9baf076e70703f94e24af4d2af71e0bce4d6b44865c8 | rd--/hsc3 | coyote.help.hs | -- coyote
let i = soundIn 0
c = X.coyote kr i 0.2 0.2 0.01 0.5 0.05 0.1
o = pinkNoiseId 'α' ar * decay c 1 * 0.25
in mce2 (i * 0.25) o
| null | https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/coyote.help.hs | haskell | coyote | let i = soundIn 0
c = X.coyote kr i 0.2 0.2 0.01 0.5 0.05 0.1
o = pinkNoiseId 'α' ar * decay c 1 * 0.25
in mce2 (i * 0.25) o
|
d7a40e4254b663a60acd160aec641c98659374e64359eb39e4ad183215c43661 | returntocorp/ocaml-tree-sitter-core | CST_grammar_conv.mli |
Representation of a CST , as derived from a grammar definition .
This representation is meant to be straightforward to translate to
OCaml type definitions .
A raw grammar definition as expressed in a grammar.json file is readable
and writable using the Tree_sitter_t and Tree_sitter_j modules derived
from Tree_sitter.atd .
The representation offered in this file is an irreversible view on
a grammar.json file . In particular :
- precedence annotations are removed
- nested anonymous rules such as nested sequences and nested alternatives
are flattened whenever possible
- various fields from the original grammar are ignored
- there 's room for future modifications
TODO : clarify what we intend to do with this
Representation of a CST, as derived from a grammar definition.
This representation is meant to be straightforward to translate to
OCaml type definitions.
A raw grammar definition as expressed in a grammar.json file is readable
and writable using the Tree_sitter_t and Tree_sitter_j modules derived
from Tree_sitter.atd.
The representation offered in this file is an irreversible view on
a grammar.json file. In particular:
- precedence annotations are removed
- nested anonymous rules such as nested sequences and nested alternatives
are flattened whenever possible
- various fields from the original grammar are ignored
- there's room for future modifications
TODO: clarify what we intend to do with this
*)
val of_tree_sitter : Tree_sitter_t.grammar -> CST_grammar.t
(* Sort and group the rules based on interdependencies. This is already
done as part of 'of_tree_sitter'.
*)
val tsort_rules :
CST_grammar.rule list -> CST_grammar.rule list list
| null | https://raw.githubusercontent.com/returntocorp/ocaml-tree-sitter-core/ae47b86e4e9d8b85e97affa7904ce43b96439b3d/src/gen/lib/CST_grammar_conv.mli | ocaml | Sort and group the rules based on interdependencies. This is already
done as part of 'of_tree_sitter'.
|
Representation of a CST , as derived from a grammar definition .
This representation is meant to be straightforward to translate to
OCaml type definitions .
A raw grammar definition as expressed in a grammar.json file is readable
and writable using the Tree_sitter_t and Tree_sitter_j modules derived
from Tree_sitter.atd .
The representation offered in this file is an irreversible view on
a grammar.json file . In particular :
- precedence annotations are removed
- nested anonymous rules such as nested sequences and nested alternatives
are flattened whenever possible
- various fields from the original grammar are ignored
- there 's room for future modifications
TODO : clarify what we intend to do with this
Representation of a CST, as derived from a grammar definition.
This representation is meant to be straightforward to translate to
OCaml type definitions.
A raw grammar definition as expressed in a grammar.json file is readable
and writable using the Tree_sitter_t and Tree_sitter_j modules derived
from Tree_sitter.atd.
The representation offered in this file is an irreversible view on
a grammar.json file. In particular:
- precedence annotations are removed
- nested anonymous rules such as nested sequences and nested alternatives
are flattened whenever possible
- various fields from the original grammar are ignored
- there's room for future modifications
TODO: clarify what we intend to do with this
*)
val of_tree_sitter : Tree_sitter_t.grammar -> CST_grammar.t
val tsort_rules :
CST_grammar.rule list -> CST_grammar.rule list list
|
0e65235fd7871510e9341e2f4a6fe69dc6e574858bbc45506f16f850df817b62 | ttyerl/sqlite-erlang | sqlite_test.erl | %%%-------------------------------------------------------------------
%%% File : sqlite_test.erl
Author : < >
%%% Description :
%%%
Created : 10 Jun 2008 by < >
%%%-------------------------------------------------------------------
-module(sqlite_test).
%% API
-export([create_table_test/0]).
-record(user, {name, age, wage}).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
%% Function:
%% Description:
%%--------------------------------------------------------------------
create_table_test() ->
sqlite:open(ct),
sqlite:create_table(ct, user, [{name, text}, {age, integer}, {wage, integer}]),
[user] = sqlite:list_tables(ct),
[{name, text}, {age, integer}, {wage, integer}] = sqlite:table_info(ct, user),
sqlite:write(ct, user, [{name, "abby"}, {age, 20}, {wage, 2000}]),
sqlite:write(ct, user, [{name, "marge"}, {age, 30}, {wage, 3000}]),
sqlite:sql_exec(ct, "select * from user;"),
sqlite:read(ct, user, {name, "abby"}),
sqlite:delete(ct, user, {name, "abby"}),
sqlite:drop_table(ct, user),
%sqlite:delete_db(ct)
sqlite:close(ct).
% create, read, update, delete
%%====================================================================
Internal functions
%%====================================================================
| null | https://raw.githubusercontent.com/ttyerl/sqlite-erlang/9ab70fc79739624ef0f1b1e869c9bee9b499a44f/src/sqlite_test.erl | erlang | -------------------------------------------------------------------
File : sqlite_test.erl
Description :
-------------------------------------------------------------------
API
====================================================================
API
====================================================================
--------------------------------------------------------------------
Function:
Description:
--------------------------------------------------------------------
sqlite:delete_db(ct)
create, read, update, delete
====================================================================
==================================================================== | Author : < >
Created : 10 Jun 2008 by < >
-module(sqlite_test).
-export([create_table_test/0]).
-record(user, {name, age, wage}).
create_table_test() ->
sqlite:open(ct),
sqlite:create_table(ct, user, [{name, text}, {age, integer}, {wage, integer}]),
[user] = sqlite:list_tables(ct),
[{name, text}, {age, integer}, {wage, integer}] = sqlite:table_info(ct, user),
sqlite:write(ct, user, [{name, "abby"}, {age, 20}, {wage, 2000}]),
sqlite:write(ct, user, [{name, "marge"}, {age, 30}, {wage, 3000}]),
sqlite:sql_exec(ct, "select * from user;"),
sqlite:read(ct, user, {name, "abby"}),
sqlite:delete(ct, user, {name, "abby"}),
sqlite:drop_table(ct, user),
sqlite:close(ct).
Internal functions
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.