_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 |
|---|---|---|---|---|---|---|---|---|
2327cca3658eb3d4d2f4f0b1cf1cf8c990f2f9b16ab4c021a0864d023f057756 | polyfy/polylith | workspace_test.clj | (ns polylith.clj.core.creator.workspace-test
(:require [clojure.test :refer :all]
[polylith.clj.core.git.interface :as git]
[polylith.clj.core.test-helper.interface :as helper]))
(use-fixtures :each helper/test-setup-and-tear-down)
(deftest create-workspace--when-workspace-already-exists--return-error-message
(let [output (with-out-str
(helper/execute-command "" "create" "workspace" "name:ws1" "top-ns:se.example")
(helper/execute-command "" "create" "workspace" "name:ws1" "top-ns:se.example"))]
(is (= " Workspace 'ws1' already exists.\n"
output))))
(deftest create-workspace--trying-to-create-a-workspace-within-another-workspace--prints-out-error-messagex
(let [output (with-out-str
(helper/execute-command "" "create" "w" "name:ws1" "top-ns:se.example" ":commit")
(helper/execute-command "ws1" "create" "workspace" "name:ws2" "top-ns:com.example"))]
(is (= " Workspace created in existing git repo.\n"
output))
(is (= #{".git"
".gitignore"
".vscode"
".vscode/settings.json"
"bases"
"bases/.keep"
"components"
"components/.keep"
"deps.edn"
"development"
"development/src"
"development/src/.keep"
"logo.png"
"projects"
"projects/.keep"
"readme.md"
"workspace.edn"
"ws2"
"ws2/.gitignore"
"ws2/.vscode"
"ws2/.vscode/settings.json"
"ws2/bases"
"ws2/bases/.keep"
"ws2/components"
"ws2/components/.keep"
"ws2/deps.edn"
"ws2/development"
"ws2/development/src"
"ws2/development/src/.keep"
"ws2/logo.png"
"ws2/projects"
"ws2/projects/.keep"
"ws2/readme.md"
"ws2/workspace.edn"}
(helper/paths "ws1")))))
(deftest create-workspace--incorrect-first-argument--prints-out-error-message
(let [output (with-out-str
(helper/execute-command "" "create" "x" "name:ws1"))]
(is (= " The first argument after 'create' is expected to be any of: w, p, b, c, workspace, project, base, component.\n"
output))))
(deftest create-workspace--missing-top-namespace--prints-out-error-message
(let [output (with-out-str
(helper/execute-command "" "create" "w" "name:ws1"))]
(is (= " A top namespace must be given, e.g.: create w name:my-workspace top-ns:com.my-company\n"
output))))
(deftest create-workspace--creates-empty-directories-and-a-deps-edn-config-file
(let [output (with-redefs [git/latest-polylith-sha (fn [_] "SHA")]
(with-out-str
(helper/execute-command "" "create" "workspace" "name:ws1" "top-ns:se.example" "branch:create-deps-files" ":commit")))]
(is (= ""
output))
(is (= #{".git"
".gitignore"
".vscode"
".vscode/settings.json"
"bases"
"bases/.keep"
"components"
"components/.keep"
"deps.edn"
"development"
"development/src"
"development/src/.keep"
"logo.png"
"projects"
"projects/.keep"
"readme.md"
"workspace.edn"}
(helper/paths "ws1")))
(is (= ["<img src=\"logo.png\" width=\"30%\" alt=\"Polylith\" id=\"logo\">"
""
"The Polylith documentation can be found here:"
""
"- The [high-level documentation]()"
"- The [Polylith Tool documentation]()"
"- The [RealWorld example app documentation](-polylith-realworld-example-app)"
""
"You can also get in touch with the Polylith Team on [Slack]()."
""
"<h1>ws1</h1>"
""
"<p>Add your workspace documentation here...</p>"]
(helper/content "ws1" "readme.md")))
(is (= [(str "{:aliases {:dev {:extra-paths [\"development/src\"]")
(str " :extra-deps {org.clojure/clojure {:mvn/version \"1.11.1\"}}}")
(str "")
(str " :test {:extra-paths []}")
(str "")
(str " :poly {:main-opts [\"-m\" \"polylith.clj.core.poly-cli.core\"]")
(str " :extra-deps {polyfy/polylith")
(str " {:git/url \"\"")
(str " :sha \"SHA\"")
(str " :deps/root \"projects/poly\"}}}}}")]
(helper/content "ws1" "deps.edn")))
(is (= ["{"
" \"calva.replConnectSequences\": ["
" {"
" \"projectType\": \"deps.edn\","
" \"name\": \"ws1\","
" \"cljsType\": \"none\","
" \"menuSelections\": {"
" \"cljAliases\": [\"dev\", \"test\", \"+default\"]"
" }"
" }"
" ]"
"}"]
(helper/content "ws1" ".vscode/settings.json")))
(is (= ["{:top-namespace \"se.example\""
" :interface-ns \"interface\""
" :default-profile-name \"default\""
" :compact-views #{}"
" :vcs {:name \"git\""
" :auto-add false}"
" :tag-patterns {:stable \"stable-*\""
" :release \"v[0-9]*\"}"
" :projects {\"development\" {:alias \"dev\"}}}"]
(helper/content "ws1" "workspace.edn")))
(is (= ["{:color-mode \"dark\""
" :empty-character \".\""
" :thousand-separator \",\"}"]
no env vars checked in helper so use defaul XDG location :
(helper/content (helper/user-home) "/.config/polylith/config.edn")))))
| null | https://raw.githubusercontent.com/polyfy/polylith/858363d7db5d3bc439074be451ff42765f405a76/components/creator/test/polylith/clj/core/creator/workspace_test.clj | clojure | (ns polylith.clj.core.creator.workspace-test
(:require [clojure.test :refer :all]
[polylith.clj.core.git.interface :as git]
[polylith.clj.core.test-helper.interface :as helper]))
(use-fixtures :each helper/test-setup-and-tear-down)
(deftest create-workspace--when-workspace-already-exists--return-error-message
(let [output (with-out-str
(helper/execute-command "" "create" "workspace" "name:ws1" "top-ns:se.example")
(helper/execute-command "" "create" "workspace" "name:ws1" "top-ns:se.example"))]
(is (= " Workspace 'ws1' already exists.\n"
output))))
(deftest create-workspace--trying-to-create-a-workspace-within-another-workspace--prints-out-error-messagex
(let [output (with-out-str
(helper/execute-command "" "create" "w" "name:ws1" "top-ns:se.example" ":commit")
(helper/execute-command "ws1" "create" "workspace" "name:ws2" "top-ns:com.example"))]
(is (= " Workspace created in existing git repo.\n"
output))
(is (= #{".git"
".gitignore"
".vscode"
".vscode/settings.json"
"bases"
"bases/.keep"
"components"
"components/.keep"
"deps.edn"
"development"
"development/src"
"development/src/.keep"
"logo.png"
"projects"
"projects/.keep"
"readme.md"
"workspace.edn"
"ws2"
"ws2/.gitignore"
"ws2/.vscode"
"ws2/.vscode/settings.json"
"ws2/bases"
"ws2/bases/.keep"
"ws2/components"
"ws2/components/.keep"
"ws2/deps.edn"
"ws2/development"
"ws2/development/src"
"ws2/development/src/.keep"
"ws2/logo.png"
"ws2/projects"
"ws2/projects/.keep"
"ws2/readme.md"
"ws2/workspace.edn"}
(helper/paths "ws1")))))
(deftest create-workspace--incorrect-first-argument--prints-out-error-message
(let [output (with-out-str
(helper/execute-command "" "create" "x" "name:ws1"))]
(is (= " The first argument after 'create' is expected to be any of: w, p, b, c, workspace, project, base, component.\n"
output))))
(deftest create-workspace--missing-top-namespace--prints-out-error-message
(let [output (with-out-str
(helper/execute-command "" "create" "w" "name:ws1"))]
(is (= " A top namespace must be given, e.g.: create w name:my-workspace top-ns:com.my-company\n"
output))))
(deftest create-workspace--creates-empty-directories-and-a-deps-edn-config-file
(let [output (with-redefs [git/latest-polylith-sha (fn [_] "SHA")]
(with-out-str
(helper/execute-command "" "create" "workspace" "name:ws1" "top-ns:se.example" "branch:create-deps-files" ":commit")))]
(is (= ""
output))
(is (= #{".git"
".gitignore"
".vscode"
".vscode/settings.json"
"bases"
"bases/.keep"
"components"
"components/.keep"
"deps.edn"
"development"
"development/src"
"development/src/.keep"
"logo.png"
"projects"
"projects/.keep"
"readme.md"
"workspace.edn"}
(helper/paths "ws1")))
(is (= ["<img src=\"logo.png\" width=\"30%\" alt=\"Polylith\" id=\"logo\">"
""
"The Polylith documentation can be found here:"
""
"- The [high-level documentation]()"
"- The [Polylith Tool documentation]()"
"- The [RealWorld example app documentation](-polylith-realworld-example-app)"
""
"You can also get in touch with the Polylith Team on [Slack]()."
""
"<h1>ws1</h1>"
""
"<p>Add your workspace documentation here...</p>"]
(helper/content "ws1" "readme.md")))
(is (= [(str "{:aliases {:dev {:extra-paths [\"development/src\"]")
(str " :extra-deps {org.clojure/clojure {:mvn/version \"1.11.1\"}}}")
(str "")
(str " :test {:extra-paths []}")
(str "")
(str " :poly {:main-opts [\"-m\" \"polylith.clj.core.poly-cli.core\"]")
(str " :extra-deps {polyfy/polylith")
(str " {:git/url \"\"")
(str " :sha \"SHA\"")
(str " :deps/root \"projects/poly\"}}}}}")]
(helper/content "ws1" "deps.edn")))
(is (= ["{"
" \"calva.replConnectSequences\": ["
" {"
" \"projectType\": \"deps.edn\","
" \"name\": \"ws1\","
" \"cljsType\": \"none\","
" \"menuSelections\": {"
" \"cljAliases\": [\"dev\", \"test\", \"+default\"]"
" }"
" }"
" ]"
"}"]
(helper/content "ws1" ".vscode/settings.json")))
(is (= ["{:top-namespace \"se.example\""
" :interface-ns \"interface\""
" :default-profile-name \"default\""
" :compact-views #{}"
" :vcs {:name \"git\""
" :auto-add false}"
" :tag-patterns {:stable \"stable-*\""
" :release \"v[0-9]*\"}"
" :projects {\"development\" {:alias \"dev\"}}}"]
(helper/content "ws1" "workspace.edn")))
(is (= ["{:color-mode \"dark\""
" :empty-character \".\""
" :thousand-separator \",\"}"]
no env vars checked in helper so use defaul XDG location :
(helper/content (helper/user-home) "/.config/polylith/config.edn")))))
| |
3819be41447ba82a9a3a046b7448d245e78c661f7fcf56613d54ece4483404d8 | sveri/ffdc | db.clj | (ns de.sveri.structconverter.db
(:require [datomic.api :as d]
[de.sveri.friendui-datomic.storage :as f-d-storage]))
(defn get-db-val-fn [db-conn]
(fn [] (d/db db-conn)))
(defn get-db-val [db-conn]
(d/db db-conn))
(defn FrienduiStorageImpl [db-conn] (f-d-storage/->FrienduiStorage db-conn (get-db-val-fn db-conn)))
(comment
;execute this in the project repl to initialize the db
(require '[datomic.api :as d])
(def uri "datomic:dev:4334/db")
(d/delete-database uri)
(d/create-database uri)
(def conn (d/connect uri))
(def schema-tx (read-string (slurp "resources/db/datomic-schema.edn")))
@(d/transact conn schema-tx)
(def data-tx (read-string (slurp "resources/db/datomic-prod-data.edn")))
@(d/transact conn data-tx)
)
| null | https://raw.githubusercontent.com/sveri/ffdc/303c94b9e3b1bd0e4aa13ca948d08eac26f96acf/src/clj/de/sveri/structconverter/db.clj | clojure | execute this in the project repl to initialize the db | (ns de.sveri.structconverter.db
(:require [datomic.api :as d]
[de.sveri.friendui-datomic.storage :as f-d-storage]))
(defn get-db-val-fn [db-conn]
(fn [] (d/db db-conn)))
(defn get-db-val [db-conn]
(d/db db-conn))
(defn FrienduiStorageImpl [db-conn] (f-d-storage/->FrienduiStorage db-conn (get-db-val-fn db-conn)))
(comment
(require '[datomic.api :as d])
(def uri "datomic:dev:4334/db")
(d/delete-database uri)
(d/create-database uri)
(def conn (d/connect uri))
(def schema-tx (read-string (slurp "resources/db/datomic-schema.edn")))
@(d/transact conn schema-tx)
(def data-tx (read-string (slurp "resources/db/datomic-prod-data.edn")))
@(d/transact conn data-tx)
)
|
5f679fab618d0891b850c4c4cd6d5533bf42c2d58f66db305b7aa7707fc269a5 | ThoughtWorksInc/stonecutter | translation.clj | (ns stonecutter.test.translation
(:require [midje.sweet :refer :all]
[stonecutter.translation :as t]))
(facts "can load translations from a string"
(fact "basic example"
(t/load-translations-from-string "a-key: Hello") => {:a-key "Hello"})
(fact "with nested keys"
(t/load-translations-from-string
"a:\n
hello: Hello\n
goodbye: Goodbye\n") => {:a {:hello "Hello" :goodbye "Goodbye"}}))
(facts "can load translations from a file"
(t/load-translations-from-file "test-translations.yml") => {:a {:hello "Hello" :goodbye "Goodbye"}})
(facts "about getting locale from requests"
(fact "request with no locales set defaults to :en"
(t/get-locale-from-request {}) => :en)
(fact "request with session locale set, always take session locale above others"
(t/get-locale-from-request {:session {:locale :fi} :locale :en}) => :fi)
(fact "request can take locale if no session locale is set"
(t/get-locale-from-request {:session {:locale nil} :locale :fr}) => :fr)) | null | https://raw.githubusercontent.com/ThoughtWorksInc/stonecutter/37ed22dd276ac652176c4d880e0f1b0c1e27abfe/test/stonecutter/test/translation.clj | clojure | (ns stonecutter.test.translation
(:require [midje.sweet :refer :all]
[stonecutter.translation :as t]))
(facts "can load translations from a string"
(fact "basic example"
(t/load-translations-from-string "a-key: Hello") => {:a-key "Hello"})
(fact "with nested keys"
(t/load-translations-from-string
"a:\n
hello: Hello\n
goodbye: Goodbye\n") => {:a {:hello "Hello" :goodbye "Goodbye"}}))
(facts "can load translations from a file"
(t/load-translations-from-file "test-translations.yml") => {:a {:hello "Hello" :goodbye "Goodbye"}})
(facts "about getting locale from requests"
(fact "request with no locales set defaults to :en"
(t/get-locale-from-request {}) => :en)
(fact "request with session locale set, always take session locale above others"
(t/get-locale-from-request {:session {:locale :fi} :locale :en}) => :fi)
(fact "request can take locale if no session locale is set"
(t/get-locale-from-request {:session {:locale nil} :locale :fr}) => :fr)) | |
eeaaaf324c141115c47aff344172bdb2cd116f2f525c16c564c0dfce556d2e33 | realworldocaml/book | dep_conf_eval.mli | * Interpret dependencies written in Dune files
open Import
* for all the files in [ _ build / install ] that belong to this package
val package_install : context:Build_context.t -> pkg:Package.t -> Alias.t
(** Evaluates unnamed dependency specifications. *)
val unnamed :
expander:Expander.t
-> Dep_conf.t list
-> unit Action_builder.t * Sandbox_config.t
(** Evaluates named dependency specifications. Return the action build that
register dependencies as well as an expander that can be used to expand to
expand variables from the bindings. *)
val named :
expander:Expander.t
-> Dep_conf.t Bindings.t
-> unit Action_builder.t * Expander.t * Sandbox_config.t
| null | https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/dune_/src/dune_rules/dep_conf_eval.mli | ocaml | * Evaluates unnamed dependency specifications.
* Evaluates named dependency specifications. Return the action build that
register dependencies as well as an expander that can be used to expand to
expand variables from the bindings. | * Interpret dependencies written in Dune files
open Import
* for all the files in [ _ build / install ] that belong to this package
val package_install : context:Build_context.t -> pkg:Package.t -> Alias.t
val unnamed :
expander:Expander.t
-> Dep_conf.t list
-> unit Action_builder.t * Sandbox_config.t
val named :
expander:Expander.t
-> Dep_conf.t Bindings.t
-> unit Action_builder.t * Expander.t * Sandbox_config.t
|
e32609c4756afd4f20758ec4d2457967adefed530a2a56967754495e3d3504d6 | yallop/ocaml-ctypes | ncurses_stub_cmd.ml |
* Copyright ( c ) 2014 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2014 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
module N = Ncurses_bindings.Bindings(Ncurses_generated)
open N
let () =
let main_window = initscr () in
cbreak ();
let small_window = newwin 10 10 5 5 in
mvwaddstr main_window 1 2 "Hello";
mvwaddstr small_window 2 2 "World";
box small_window 0 0;
refresh ();
Unix.sleep 1;
wrefresh small_window;
Unix.sleep 5;
endwin()
| null | https://raw.githubusercontent.com/yallop/ocaml-ctypes/52ff621f47dbc1ee5a90c30af0ae0474549946b4/examples/ncurses/stub-generation/ncurses_stub_cmd.ml | ocaml |
* Copyright ( c ) 2014 .
*
* This file is distributed under the terms of the MIT License .
* See the file LICENSE for details .
* Copyright (c) 2014 Jeremy Yallop.
*
* This file is distributed under the terms of the MIT License.
* See the file LICENSE for details.
*)
module N = Ncurses_bindings.Bindings(Ncurses_generated)
open N
let () =
let main_window = initscr () in
cbreak ();
let small_window = newwin 10 10 5 5 in
mvwaddstr main_window 1 2 "Hello";
mvwaddstr small_window 2 2 "World";
box small_window 0 0;
refresh ();
Unix.sleep 1;
wrefresh small_window;
Unix.sleep 5;
endwin()
| |
1fcbca6036ad04562550759a3c22d0f890f04c2c96c3249afa0b8b4bd0644205 | dongcarl/guix | browser-extensions.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2020 , 2021 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages browser-extensions)
#:use-module (guix packages)
#:use-module (guix git-download)
#:use-module (guix build-system copy)
#:use-module (guix build-system gnu)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (gnu build chromium-extension)
#:use-module (gnu packages compression)
#:use-module (gnu packages python))
(define play-to-kodi
(package
(name "play-to-kodi")
(version "1.9.1")
(home-page "-to-xbmc-chrome")
(source (origin
(method git-fetch)
(uri (git-reference (url home-page) (commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"01rmcpbkn9vhcd8mrah2jmd2801k2r5fz7aqvp22hbwmh2z5f1ch"))))
(build-system copy-build-system)
(synopsis "Send website contents to Kodi")
(description
"Play to Kodi is a browser add-on that can send video, audio, and other
supported content to the Kodi media center.")
(license license:expat)))
(define-public play-to-kodi/chromium
(make-chromium-extension play-to-kodi))
(define uassets
(let ((commit "20d21ad7e92539660c7cde4c5884b3e234854264"))
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit commit)))
(file-name (git-file-name "uAssets" (string-take commit 9)))
(sha256
(base32
"1xcl4qnvjb4pv3fajpmycg1i0xqsah2qakhq2figvyrq991pldy1")))))
(define ublock-origin
(package
(name "ublock-origin")
(version "1.36.0")
(home-page "")
(source (origin
(method git-fetch)
(uri (git-reference (url home-page) (commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"1r3aic18zkz8s3v1a2kffidp4swzbxnq0h8444bif9myjffnpxpj"))))
(build-system gnu-build-system)
(outputs '("xpi" "firefox" "chromium"))
(arguments
'(#:tests? #f ;no tests
#:allowed-references ()
#:phases
(modify-phases (map (lambda (phase)
(assq phase %standard-phases))
'(set-paths unpack patch-source-shebangs))
(add-after 'unpack 'link-uassets
(lambda* (#:key native-inputs inputs #:allow-other-keys)
(symlink (string-append (assoc-ref (or native-inputs inputs)
"uassets"))
"../uAssets")
#t))
(add-after 'unpack 'make-files-writable
(lambda _
;; The build system copies some files and later tries
;; modifying them.
(for-each make-file-writable (find-files "."))
#t))
(add-after 'patch-source-shebangs 'build-xpi
(lambda _
(invoke "./tools/make-firefox.sh" "all")))
(add-after 'build-xpi 'build-chromium
(lambda _
(invoke "./tools/make-chromium.sh")))
(add-after 'build-chromium 'install
(lambda* (#:key outputs #:allow-other-keys)
(let ((firefox (assoc-ref outputs "firefox"))
(xpi (assoc-ref outputs "xpi"))
(chromium (assoc-ref outputs "chromium")))
(install-file "dist/build/uBlock0.firefox.xpi"
(string-append xpi "/lib/mozilla/extensions"))
(copy-recursively "dist/build/uBlock0.firefox" firefox)
(copy-recursively "dist/build/uBlock0.chromium" chromium)
#t))))))
(native-inputs
`(("python" ,python-wrapper)
("uassets" ,uassets)
("zip" ,zip)))
(synopsis "Block unwanted content from web sites")
(description
"uBlock Origin is a @dfn{wide spectrum blocker} for IceCat and
ungoogled-chromium.")
(license license:gpl3+)))
(define-public ublock-origin/chromium
(make-chromium-extension ublock-origin "chromium"))
| null | https://raw.githubusercontent.com/dongcarl/guix/d2b30db788f1743f9f8738cb1de977b77748567f/gnu/packages/browser-extensions.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
no tests
The build system copies some files and later tries
modifying them. | Copyright © 2020 , 2021 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages browser-extensions)
#:use-module (guix packages)
#:use-module (guix git-download)
#:use-module (guix build-system copy)
#:use-module (guix build-system gnu)
#:use-module ((guix licenses) #:prefix license:)
#:use-module (gnu build chromium-extension)
#:use-module (gnu packages compression)
#:use-module (gnu packages python))
(define play-to-kodi
(package
(name "play-to-kodi")
(version "1.9.1")
(home-page "-to-xbmc-chrome")
(source (origin
(method git-fetch)
(uri (git-reference (url home-page) (commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"01rmcpbkn9vhcd8mrah2jmd2801k2r5fz7aqvp22hbwmh2z5f1ch"))))
(build-system copy-build-system)
(synopsis "Send website contents to Kodi")
(description
"Play to Kodi is a browser add-on that can send video, audio, and other
supported content to the Kodi media center.")
(license license:expat)))
(define-public play-to-kodi/chromium
(make-chromium-extension play-to-kodi))
(define uassets
(let ((commit "20d21ad7e92539660c7cde4c5884b3e234854264"))
(origin
(method git-fetch)
(uri (git-reference
(url "")
(commit commit)))
(file-name (git-file-name "uAssets" (string-take commit 9)))
(sha256
(base32
"1xcl4qnvjb4pv3fajpmycg1i0xqsah2qakhq2figvyrq991pldy1")))))
(define ublock-origin
(package
(name "ublock-origin")
(version "1.36.0")
(home-page "")
(source (origin
(method git-fetch)
(uri (git-reference (url home-page) (commit version)))
(file-name (git-file-name name version))
(sha256
(base32
"1r3aic18zkz8s3v1a2kffidp4swzbxnq0h8444bif9myjffnpxpj"))))
(build-system gnu-build-system)
(outputs '("xpi" "firefox" "chromium"))
(arguments
#:allowed-references ()
#:phases
(modify-phases (map (lambda (phase)
(assq phase %standard-phases))
'(set-paths unpack patch-source-shebangs))
(add-after 'unpack 'link-uassets
(lambda* (#:key native-inputs inputs #:allow-other-keys)
(symlink (string-append (assoc-ref (or native-inputs inputs)
"uassets"))
"../uAssets")
#t))
(add-after 'unpack 'make-files-writable
(lambda _
(for-each make-file-writable (find-files "."))
#t))
(add-after 'patch-source-shebangs 'build-xpi
(lambda _
(invoke "./tools/make-firefox.sh" "all")))
(add-after 'build-xpi 'build-chromium
(lambda _
(invoke "./tools/make-chromium.sh")))
(add-after 'build-chromium 'install
(lambda* (#:key outputs #:allow-other-keys)
(let ((firefox (assoc-ref outputs "firefox"))
(xpi (assoc-ref outputs "xpi"))
(chromium (assoc-ref outputs "chromium")))
(install-file "dist/build/uBlock0.firefox.xpi"
(string-append xpi "/lib/mozilla/extensions"))
(copy-recursively "dist/build/uBlock0.firefox" firefox)
(copy-recursively "dist/build/uBlock0.chromium" chromium)
#t))))))
(native-inputs
`(("python" ,python-wrapper)
("uassets" ,uassets)
("zip" ,zip)))
(synopsis "Block unwanted content from web sites")
(description
"uBlock Origin is a @dfn{wide spectrum blocker} for IceCat and
ungoogled-chromium.")
(license license:gpl3+)))
(define-public ublock-origin/chromium
(make-chromium-extension ublock-origin "chromium"))
|
77b4f0f182453625f61a36d20cb89e3aec65814bbb5f63cffde047f8d60413e1 | jiangpengnju/htdp2e | design-recipe-for-self-referentials.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname design-recipe-for-self-referentials) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
Design Recipe (for self-referential data definitions)
1. When: If a problem statement discusses COMPOUND information of ARBITRARY size,
you need a self-referential data definition.
Two conditions TO BE VALID:
a. at least two clauses.
b. at least one of the clauses must NOT Refer back to the class of data that is
being defined.
CHECK THE VALIDITY WITH THE CREATION OF EXAMPLES!
A List - of - strings is one of :
; - '()
; - (cons String List-of-strings)
(define ex1 '())
(define ex2 (cons "a" '()))
(define ex3 (cons "b" (cons "a" '())))
2. Signature, Purpose Statement, Dummy definition.
Nothing changes.
; List-of-strings -> Number
; count how many strings alos contains
(define (how-many alos)
0)
3. Functional Examples
(check-expect (how-many ex1) 0)
(check-expect (how-many ex2) 1)
(check-expect (how-many ex3) 2)
4*. Template
looks like a data definition for mixed data -- itemizations and structs.
We formulate a cond expression with as many cond clauses as there clauses in
the data definition.
AND, write down appropriate selector expressions in all cond lines that process
compound values.
SHAPE:
(define (fun-for-los alos)
(cond
[(empty? alos) ...]
[else
(... (first alos) ... (rest alos)...)]))
That is, a template expresses as code what the data definition for the input
expresses as a mix of English and BSL.
Hence all important pieces of the data definition must find a counterpart
in the template, and this guideline should also hold when a data definition
is self-referential—contains an arrow from inside the definition to the term
being defined. In particular, when a data definition is self-referential in the
ith clause and the kth field of the structure mentioned there, the template
should be self-referential in the ith cond clause and the selector expression
for the kth field.
For each such selector expression, add an arrow back to the function parameter.
At the end, your template must have as many arrows as we have in the data definition.
UPDATED SHAPE:
(define (fun-for-los alos)
(cond
[(empty? alos) ...]
[else
(... (first alos) ...
... (fun-for-los (rest alos)) ...)]))
5. Function Definition
Start with 'base case' -- cond lines that do not contain natural recursions.
Then deal with the self-referential cases.
For the natural recursion we assume that
the function already works as specified in our purpose statement.
; List-of-strings -> Number
; determines how many strings are on alos
(define (how-many alos)
(cond
[(empty? alos) ...]
[else
(... (first alos) ... (how-many (rest alos)) ...)]))
(define (how-many alos)
(cond
[(empty? alos) 0]
[else (+ (how-many (rest alos)) 1)]))
- Find the 'combinator' -- Tabulating arguments, intermediate values, and results
- Not all selector expressions in the template are necessarily relevent.
- Sometimes, you need auxiliary function -- make a Wish.
6. Testing.
coverage
| null | https://raw.githubusercontent.com/jiangpengnju/htdp2e/d41555519fbb378330f75c88141f72b00a9ab1d3/arbitrarily-large-data/designing-with-self-referential-data-dafinitions/design-recipe-for-self-referentials.rkt | racket | about the language level of this file in a form that our tools can easily process.
- '()
- (cons String List-of-strings)
List-of-strings -> Number
count how many strings alos contains
List-of-strings -> Number
determines how many strings are on alos | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname design-recipe-for-self-referentials) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
Design Recipe (for self-referential data definitions)
1. When: If a problem statement discusses COMPOUND information of ARBITRARY size,
you need a self-referential data definition.
Two conditions TO BE VALID:
a. at least two clauses.
b. at least one of the clauses must NOT Refer back to the class of data that is
being defined.
CHECK THE VALIDITY WITH THE CREATION OF EXAMPLES!
A List - of - strings is one of :
(define ex1 '())
(define ex2 (cons "a" '()))
(define ex3 (cons "b" (cons "a" '())))
2. Signature, Purpose Statement, Dummy definition.
Nothing changes.
(define (how-many alos)
0)
3. Functional Examples
(check-expect (how-many ex1) 0)
(check-expect (how-many ex2) 1)
(check-expect (how-many ex3) 2)
4*. Template
looks like a data definition for mixed data -- itemizations and structs.
We formulate a cond expression with as many cond clauses as there clauses in
the data definition.
AND, write down appropriate selector expressions in all cond lines that process
compound values.
SHAPE:
(define (fun-for-los alos)
(cond
[(empty? alos) ...]
[else
(... (first alos) ... (rest alos)...)]))
That is, a template expresses as code what the data definition for the input
expresses as a mix of English and BSL.
Hence all important pieces of the data definition must find a counterpart
in the template, and this guideline should also hold when a data definition
is self-referential—contains an arrow from inside the definition to the term
being defined. In particular, when a data definition is self-referential in the
ith clause and the kth field of the structure mentioned there, the template
should be self-referential in the ith cond clause and the selector expression
for the kth field.
For each such selector expression, add an arrow back to the function parameter.
At the end, your template must have as many arrows as we have in the data definition.
UPDATED SHAPE:
(define (fun-for-los alos)
(cond
[(empty? alos) ...]
[else
(... (first alos) ...
... (fun-for-los (rest alos)) ...)]))
5. Function Definition
Start with 'base case' -- cond lines that do not contain natural recursions.
Then deal with the self-referential cases.
For the natural recursion we assume that
the function already works as specified in our purpose statement.
(define (how-many alos)
(cond
[(empty? alos) ...]
[else
(... (first alos) ... (how-many (rest alos)) ...)]))
(define (how-many alos)
(cond
[(empty? alos) 0]
[else (+ (how-many (rest alos)) 1)]))
- Find the 'combinator' -- Tabulating arguments, intermediate values, and results
- Not all selector expressions in the template are necessarily relevent.
- Sometimes, you need auxiliary function -- make a Wish.
6. Testing.
coverage
|
3c861d7b3275330ff8267731421576a23a5e5c89f4b0c26435d9272d2977922b | emina/rosette | easy.rkt | #lang rosette
(require "../bv.rkt")
(require "reference.rkt")
(provide (all-defined-out))
(BV (bitvector 32))
Mask off the rightmost 1 - bit . < 1 sec .
(define-fragment (p1* x)
#:implements p1
#:library (bvlib [{bv1 bvand bvsub} 1]))
Test whether an unsigned integer is of the form 2^n-1 . < 1 sec .
(define-fragment (p2* x)
#:implements p2
#:library (bvlib [{bv1 bvand bvadd} 1]))
Isolate the right most 1 - bit . < 1 sec .
(define-fragment (p3* x)
#:implements p3
#:library (bvlib [{bvand bvneg} 1]))
Form a mask that identifies the rightmost 1 - bit and trailing 0s . < 1 sec .
(define-fragment (p4* x)
#:implements p4
#:library (bvlib [{bv1 bvsub bvxor} 1]))
Right propagate rightmost 1 - bit . < 1 sec .
(define-fragment (p5* x)
#:implements p5
#:library (bvlib [{bv1 bvsub bvor} 1]))
Turn on the right - most 0 - bit in a word . < 1 sec .
(define-fragment (p6* x)
#:implements p6
#:library (bvlib [{bv1 bvor bvadd} 1]))
Isolate the right most 0 bit of a given bitvector . < 1 sec .
(define-fragment (p7* x)
#:implements p7
#:library (bvlib [{bvand bvadd bvnot bv1} 1]))
Form a mask that identifies the trailing 0s . < 1 sec .
(define-fragment (p8* x)
#:implements p8
#:library (bvlib [{bv1 bvsub bvand bvnot} 1]))
Absolute value function . ~ 1 sec .
(define-fragment (p9* x)
#:implements p9
#:library (bvlib [{bvsz bvsub bvxor bvashr} 1]))
Test if nlz(x ) = = nlz(y ) where nlz is number of leading zeroes . < 1 sec .
(define-fragment (p10* x y)
#:implements p10
#:library (bvlib [{bvand bvxor bvule} 1]))
| null | https://raw.githubusercontent.com/emina/rosette/a64e2bccfe5876c5daaf4a17c5a28a49e2fbd501/sdsl/bv/examples/easy.rkt | racket | #lang rosette
(require "../bv.rkt")
(require "reference.rkt")
(provide (all-defined-out))
(BV (bitvector 32))
Mask off the rightmost 1 - bit . < 1 sec .
(define-fragment (p1* x)
#:implements p1
#:library (bvlib [{bv1 bvand bvsub} 1]))
Test whether an unsigned integer is of the form 2^n-1 . < 1 sec .
(define-fragment (p2* x)
#:implements p2
#:library (bvlib [{bv1 bvand bvadd} 1]))
Isolate the right most 1 - bit . < 1 sec .
(define-fragment (p3* x)
#:implements p3
#:library (bvlib [{bvand bvneg} 1]))
Form a mask that identifies the rightmost 1 - bit and trailing 0s . < 1 sec .
(define-fragment (p4* x)
#:implements p4
#:library (bvlib [{bv1 bvsub bvxor} 1]))
Right propagate rightmost 1 - bit . < 1 sec .
(define-fragment (p5* x)
#:implements p5
#:library (bvlib [{bv1 bvsub bvor} 1]))
Turn on the right - most 0 - bit in a word . < 1 sec .
(define-fragment (p6* x)
#:implements p6
#:library (bvlib [{bv1 bvor bvadd} 1]))
Isolate the right most 0 bit of a given bitvector . < 1 sec .
(define-fragment (p7* x)
#:implements p7
#:library (bvlib [{bvand bvadd bvnot bv1} 1]))
Form a mask that identifies the trailing 0s . < 1 sec .
(define-fragment (p8* x)
#:implements p8
#:library (bvlib [{bv1 bvsub bvand bvnot} 1]))
Absolute value function . ~ 1 sec .
(define-fragment (p9* x)
#:implements p9
#:library (bvlib [{bvsz bvsub bvxor bvashr} 1]))
Test if nlz(x ) = = nlz(y ) where nlz is number of leading zeroes . < 1 sec .
(define-fragment (p10* x y)
#:implements p10
#:library (bvlib [{bvand bvxor bvule} 1]))
| |
b49f99273036198b2a4c99082d2214569fb5cb3ef754acabf61bc5acb6e6a4e3 | RichiH/git-annex | Shim.hs | module Utility.Process.Shim (module X) where
import System.Process as X
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Utility/Process/Shim.hs | haskell | module Utility.Process.Shim (module X) where
import System.Process as X
| |
3e0f3886b59647ee4e93037cbc0b4df200ad5cedb0f356f6239c0d4526d30630 | triffon/fp-2019-20 | 04-zip.rkt | #lang racket
(require rackunit)
(require rackunit/text-ui)
; zip
(define (zip xs ys)
(void)
)
(define tests
(test-suite "Zip"
(check-equal? (zip '(1 2 3) '(4 5 6)) '((1 4) (2 5) (3 6)))
(check-equal? (zip '(28 9 12) '(1 3)) '((28 1) (9 3)))
)
)
(run-tests tests 'verbose)
| null | https://raw.githubusercontent.com/triffon/fp-2019-20/7efb13ff4de3ea13baa2c5c59eb57341fac15641/exercises/computer-science-3/exercises/05.more-lists/04-zip.rkt | racket | zip | #lang racket
(require rackunit)
(require rackunit/text-ui)
(define (zip xs ys)
(void)
)
(define tests
(test-suite "Zip"
(check-equal? (zip '(1 2 3) '(4 5 6)) '((1 4) (2 5) (3 6)))
(check-equal? (zip '(28 9 12) '(1 3)) '((28 1) (9 3)))
)
)
(run-tests tests 'verbose)
|
d027fd9de4a018de10d4f6cd08f3db9cf092f1959b2eef4cefacaf321122cbad | larrychristensen/orcpub | character_props.cljc | (ns orcpub.dnd.e5.character-props
(:require [orcpub.entity-spec :as es]))
(defn get-prop [built-char prop]
(es/entity-val built-char prop))
(defmacro defprop [kw]
`(defn ~(symbol (name kw)) [built-char#]
(get-prop built-char# ~kw)))
| null | https://raw.githubusercontent.com/larrychristensen/orcpub/e83995857f7e64af1798009a45a0b03abcd3a4be/src/cljc/orcpub/dnd/e5/character_props.cljc | clojure | (ns orcpub.dnd.e5.character-props
(:require [orcpub.entity-spec :as es]))
(defn get-prop [built-char prop]
(es/entity-val built-char prop))
(defmacro defprop [kw]
`(defn ~(symbol (name kw)) [built-char#]
(get-prop built-char# ~kw)))
| |
0d7fb8741c863f29863468935890bfab93d9b016a89a203326c22a15508721f9 | graninas/Functional-Design-and-Architecture | Sentry.hs | {-# LANGUAGE OverloadedStrings #-}
module Framework.Logging.StructuredLogger.Impl.Sentry where
import qualified Data.Aeson as A
import qualified Data.Text as T
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text.Encoding as T
import Data.Time
import qualified Data.HashMap.Strict as HM
import qualified Data.Map as Map
import Control.Monad.Free.Church
import qualified System.Log.Raven as R
import qualified System.Log.Raven.Types as R
import qualified System.Log.Raven.Transport.HttpConduit as R
import qualified Framework.Logging.Types as T
import qualified Framework.Logging.StructuredLogger.Config as Cfg
import qualified Framework.Logging.StructuredLogger.Language as L
import qualified Framework.Logging.StructuredLogger.Fields.Sentry as F
initSentry :: Cfg.StructuredLoggerConfig -> IO R.SentryService
initSentry cfg = do
let defaultTags = HM.fromList (Cfg.sLogSentryDefaultTags cfg)
let tagsF r = r { R.srTags = HM.union defaultTags (R.srTags r) }
R.initRaven (Cfg.sLogSentryDSN cfg) tagsF R.sendRecord R.stderrFallback
disposeSentry :: R.SentryService -> IO ()
disposeSentry _ = pure () -- nothing to do here
interpretSentryLoggerMethod
:: R.SentryService
-> L.StructuredLoggerF a
-> IO a
interpretSentryLoggerMethod service (L.LogStructured severity loggerName msg attribs next) = do
timestamp <- case Map.lookup F.sentryTimestampKey attribs of
Nothing -> getCurrentTime
Just tsVal -> case A.eitherDecode $ LBS.fromStrict $ T.encodeUtf8 tsVal of
Left err -> error err
Right ts -> pure ts
let sSeverity = toSentrySeverity severity
let sMsg = T.unpack msg
let sLoggerName = T.unpack loggerName
let sSentryRecordF = toSentryFields timestamp $ Map.toList attribs
R.register service sLoggerName sSeverity sMsg sSentryRecordF
pure $ next ()
runSentryLogger
:: R.SentryService
-> L.StructuredLoggerL a
-> IO a
runSentryLogger service logAction =
foldF (interpretSentryLoggerMethod service) logAction
toSentrySeverity :: T.Severity -> R.SentryLevel
toSentrySeverity T.Debug = R.Debug
toSentrySeverity T.Info = R.Info
toSentrySeverity T.Warning = R.Warning
toSentrySeverity T.Error = R.Error
toSentryFields
:: T.Timestamp
-> [(T.FieldKey, T.FieldValue)]
-> R.SentryRecord
-> R.SentryRecord
toSentryFields ts [] r = r { R.srTimestamp = ts}
toSentryFields ts ((attrKey, attrVal):attrs) r = let
unpackedVal = T.unpack attrVal
r' = case () of
_ | attrKey == F.sentryEventIdKey -> r { R.srEventId = unpackedVal }
_ | attrKey == F.sentryPlatformKey -> r { R.srPlatform = Just unpackedVal }
_ | attrKey == F.sentryServerNameKey -> r { R.srServerName = Just unpackedVal }
_ | attrKey == F.sentryCulpritKey -> r { R.srCulprit = Just unpackedVal }
_ | attrKey == F.sentryReleaseKey -> r { R.srRelease = Just unpackedVal }
_ | attrKey == F.sentryEnvironmentKey -> r { R.srEnvironment = Just unpackedVal }
_ | otherwise -> r {R.srExtra = HM.insert (T.unpack attrKey) (A.String attrVal) (R.srExtra r) }
in toSentryFields ts attrs r'
-- A simplified pseudocode for the book.
--
-- interpretSentryLoggerMethod'
-- :: R.SentryService
-- -> L.StructuredLoggerF a
-- -> IO a
interpretSentryLoggerMethod ' service ( L.LOgStructured severity loggerName msg attribs next ) = do
-- let sSeverity = toSentrySeverity severity
-- let sMsg = T.unpack msg
let sLoggerName = T.unpack loggerName
let sentryRecord = toSentryRecord attribs R.blankSentryRecord
R.register service sLoggerName sSeverity sMsg sSentryRecordF
-- pure $ next ()
toSentryRecord
-- :: Map.Map T.FieldKey T.FieldValue
-- -> R.SentryRecord
-- -> R.SentryRecord
toSentryRecord m r = foldr toSentryRecord ' r ( Map.toList m )
toSentryRecord '
-- :: (T.FieldKey, T.FieldValue)
-- -> R.SentryRecord
-- -> R.SentryRecord
toSentryRecord ' ( attrKey , attrVal ) r
| attrKey = = F.sentryEventIdKey = r { R.srEventId = unpackedVal }
-- | attrKey == F.sentryTimestampKey = r { R.srTimestamp = parsedTs }
-- where
-- unpackedVal :: String
unpackedVal = T.unpack attrVal
-- parsedTs :: UTCTime
-- parsedTs = error "not implemented" -- parse here
| null | https://raw.githubusercontent.com/graninas/Functional-Design-and-Architecture/f2e4462e09d79b36560a029ebda70cbac3813da3/Second-Edition-Manning-Publications/BookSamples/CH10/Section10p1/src/Framework/Logging/StructuredLogger/Impl/Sentry.hs | haskell | # LANGUAGE OverloadedStrings #
nothing to do here
A simplified pseudocode for the book.
interpretSentryLoggerMethod'
:: R.SentryService
-> L.StructuredLoggerF a
-> IO a
let sSeverity = toSentrySeverity severity
let sMsg = T.unpack msg
pure $ next ()
:: Map.Map T.FieldKey T.FieldValue
-> R.SentryRecord
-> R.SentryRecord
:: (T.FieldKey, T.FieldValue)
-> R.SentryRecord
-> R.SentryRecord
| attrKey == F.sentryTimestampKey = r { R.srTimestamp = parsedTs }
where
unpackedVal :: String
parsedTs :: UTCTime
parsedTs = error "not implemented" -- parse here | module Framework.Logging.StructuredLogger.Impl.Sentry where
import qualified Data.Aeson as A
import qualified Data.Text as T
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text.Encoding as T
import Data.Time
import qualified Data.HashMap.Strict as HM
import qualified Data.Map as Map
import Control.Monad.Free.Church
import qualified System.Log.Raven as R
import qualified System.Log.Raven.Types as R
import qualified System.Log.Raven.Transport.HttpConduit as R
import qualified Framework.Logging.Types as T
import qualified Framework.Logging.StructuredLogger.Config as Cfg
import qualified Framework.Logging.StructuredLogger.Language as L
import qualified Framework.Logging.StructuredLogger.Fields.Sentry as F
initSentry :: Cfg.StructuredLoggerConfig -> IO R.SentryService
initSentry cfg = do
let defaultTags = HM.fromList (Cfg.sLogSentryDefaultTags cfg)
let tagsF r = r { R.srTags = HM.union defaultTags (R.srTags r) }
R.initRaven (Cfg.sLogSentryDSN cfg) tagsF R.sendRecord R.stderrFallback
disposeSentry :: R.SentryService -> IO ()
interpretSentryLoggerMethod
:: R.SentryService
-> L.StructuredLoggerF a
-> IO a
interpretSentryLoggerMethod service (L.LogStructured severity loggerName msg attribs next) = do
timestamp <- case Map.lookup F.sentryTimestampKey attribs of
Nothing -> getCurrentTime
Just tsVal -> case A.eitherDecode $ LBS.fromStrict $ T.encodeUtf8 tsVal of
Left err -> error err
Right ts -> pure ts
let sSeverity = toSentrySeverity severity
let sMsg = T.unpack msg
let sLoggerName = T.unpack loggerName
let sSentryRecordF = toSentryFields timestamp $ Map.toList attribs
R.register service sLoggerName sSeverity sMsg sSentryRecordF
pure $ next ()
runSentryLogger
:: R.SentryService
-> L.StructuredLoggerL a
-> IO a
runSentryLogger service logAction =
foldF (interpretSentryLoggerMethod service) logAction
toSentrySeverity :: T.Severity -> R.SentryLevel
toSentrySeverity T.Debug = R.Debug
toSentrySeverity T.Info = R.Info
toSentrySeverity T.Warning = R.Warning
toSentrySeverity T.Error = R.Error
toSentryFields
:: T.Timestamp
-> [(T.FieldKey, T.FieldValue)]
-> R.SentryRecord
-> R.SentryRecord
toSentryFields ts [] r = r { R.srTimestamp = ts}
toSentryFields ts ((attrKey, attrVal):attrs) r = let
unpackedVal = T.unpack attrVal
r' = case () of
_ | attrKey == F.sentryEventIdKey -> r { R.srEventId = unpackedVal }
_ | attrKey == F.sentryPlatformKey -> r { R.srPlatform = Just unpackedVal }
_ | attrKey == F.sentryServerNameKey -> r { R.srServerName = Just unpackedVal }
_ | attrKey == F.sentryCulpritKey -> r { R.srCulprit = Just unpackedVal }
_ | attrKey == F.sentryReleaseKey -> r { R.srRelease = Just unpackedVal }
_ | attrKey == F.sentryEnvironmentKey -> r { R.srEnvironment = Just unpackedVal }
_ | otherwise -> r {R.srExtra = HM.insert (T.unpack attrKey) (A.String attrVal) (R.srExtra r) }
in toSentryFields ts attrs r'
interpretSentryLoggerMethod ' service ( L.LOgStructured severity loggerName msg attribs next ) = do
let sLoggerName = T.unpack loggerName
let sentryRecord = toSentryRecord attribs R.blankSentryRecord
R.register service sLoggerName sSeverity sMsg sSentryRecordF
toSentryRecord
toSentryRecord m r = foldr toSentryRecord ' r ( Map.toList m )
toSentryRecord '
toSentryRecord ' ( attrKey , attrVal ) r
| attrKey = = F.sentryEventIdKey = r { R.srEventId = unpackedVal }
unpackedVal = T.unpack attrVal
|
cb98bf9d296c69a52e9162413a92ea2aec168a3c798821d549ba37c3c97d7534 | spawnfest/eep49ers | f.erl | -module(f).
-export([f1/0,f2/0,call_f2_when_isolated/0]).
f1() ->
f1_line1,
f1_line2.
f2() ->
f2_line1,
f2_line2.
call_f2_when_isolated() ->
[Other] = nodes(),
net_kernel:disconnect(Other),
do_call_f2_when_isolated().
do_call_f2_when_isolated() ->
case nodes() of
[] ->
f2();
_ ->
timer:sleep(100),
do_call_f2_when_isolated()
end.
| null | https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/tools/test/cover_SUITE_data/f.erl | erlang | -module(f).
-export([f1/0,f2/0,call_f2_when_isolated/0]).
f1() ->
f1_line1,
f1_line2.
f2() ->
f2_line1,
f2_line2.
call_f2_when_isolated() ->
[Other] = nodes(),
net_kernel:disconnect(Other),
do_call_f2_when_isolated().
do_call_f2_when_isolated() ->
case nodes() of
[] ->
f2();
_ ->
timer:sleep(100),
do_call_f2_when_isolated()
end.
| |
67c8e69a61c669686dc228ad685e1a428e7385e4de8b859061379748ab5c0d54 | gadfly361/reagent-figwheel | core.cljs | (ns {{ns-name}}.core
(:require
[reagent.core :as reagent]{{#re-frisk?}}
[re-frisk.core :as rf]{{/re-frisk?}}
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Vars
(defonce app-state
(reagent/atom {}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Page
(defn page [ratom]
[:div
"Welcome to reagent-figwheel."])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Initialize App
(defn dev-setup []
(when ^boolean js/goog.DEBUG
(enable-console-print!)
(println "dev mode"){{#re-frisk?}}
(rf/enable-frisk!)
(rf/add-data :app-state app-state){{/re-frisk?}}
))
(defn reload []
(reagent/render [page app-state]
(.getElementById js/document "app")))
(defn ^:export main []
(dev-setup)
(reload))
| null | https://raw.githubusercontent.com/gadfly361/reagent-figwheel/4c40657b31a2b358be5697add2e96e8cac6f8535/src/leiningen/new/reagent_figwheel/src/cljs/core.cljs | clojure |
Page
| (ns {{ns-name}}.core
(:require
[reagent.core :as reagent]{{#re-frisk?}}
[re-frisk.core :as rf]{{/re-frisk?}}
))
Vars
(defonce app-state
(reagent/atom {}))
(defn page [ratom]
[:div
"Welcome to reagent-figwheel."])
Initialize App
(defn dev-setup []
(when ^boolean js/goog.DEBUG
(enable-console-print!)
(println "dev mode"){{#re-frisk?}}
(rf/enable-frisk!)
(rf/add-data :app-state app-state){{/re-frisk?}}
))
(defn reload []
(reagent/render [page app-state]
(.getElementById js/document "app")))
(defn ^:export main []
(dev-setup)
(reload))
|
82b1f102f149deaa13b646c0f936171ad8f72242a6cfc9fdf7fce107a6e78c9f | realworldocaml/mdx | syntax.ml | type t = Markdown | Cram | Mli
let pp fs = function
| Markdown -> Fmt.string fs "markdown"
| Cram -> Fmt.string fs "cram"
| Mli -> Fmt.string fs "mli"
let equal x y = x = y
let infer ~file =
match Filename.extension file with
| ".t" -> Some Cram
| ".md" -> Some Markdown
| ".mli" -> Some Mli
| _ -> None
let of_string = function
| "markdown" | "normal" -> Some Markdown
| "cram" -> Some Cram
| "mli" -> Some Mli
| _ -> None
| null | https://raw.githubusercontent.com/realworldocaml/mdx/0644a331fbff863a43200ec1db7092a4c51c411a/lib/syntax.ml | ocaml | type t = Markdown | Cram | Mli
let pp fs = function
| Markdown -> Fmt.string fs "markdown"
| Cram -> Fmt.string fs "cram"
| Mli -> Fmt.string fs "mli"
let equal x y = x = y
let infer ~file =
match Filename.extension file with
| ".t" -> Some Cram
| ".md" -> Some Markdown
| ".mli" -> Some Mli
| _ -> None
let of_string = function
| "markdown" | "normal" -> Some Markdown
| "cram" -> Some Cram
| "mli" -> Some Mli
| _ -> None
| |
3ba614bb59c80e9cda57f61e6ffe4509c30212deb222bfe4f96d886de87fdafa | ghalestrilo/seg | events.cljs | (ns segue.events
"Event handlers for re-frame dispatch events.
Used to manage app db updates and side-effects.
-frame/blob/master/docs/EffectfulHandlers.md"
(:require
[re-frame.core :as rf]
[segue.track :refer [read-file parse-section prep-section load-track]]
[segue.repl :refer [spawn-process repl-send]]
[segue.wrappers :refer [node-slurp]]))
; Below are very general effect handlers. While you can use these to get
; going quickly you are likely better off creating custom handlers for actions
; specific to your application.
(def help-messages
{ :home
{ :up/down "Choose section/pattern"
:left/right "Choose player"
:enter "Trigger section"}})
IDEA : maybe the demo track could become a " template " user setting
(def demo-track
{:players ["drums" "piano" "bass" "vibe"]
:sections [{:name "intro"
:patterns [nil nil "0" nil]}
{:name "theme"
:patterns [nil nil "0" nil]}
{:name "bridge"
:patterns [nil "0*4" "0" nil]}
{:name "outro"
:patterns [nil nil "0" "0(3,8)"]}]
:pattern-bank []})
(def default-settings
{ :column-width 12
:shell "zsh" ;TODO: check if process exists
:editor "kak"})
(rf/reg-event-db
:init
(fn [db [_ opts terminal-size]]
{:opts opts
:settings default-settings
:router/view :home
:terminal/size terminal-size
:dialog/help help-messages
:session/selection 0
:track demo-track}))
(rf/reg-event-db
:update
(fn [db [_ data]]
(merge db data)))
(rf/reg-event-db
:set
(fn [db [_ data]]
data))
(rf/reg-event-db
:update-track
(fn [db [_ path data]]
(assoc-in db (into [:track] path) data)))
(rf/reg-event-db
:set-track
(fn [db [_ data]]
(assoc db :track data)))
(rf/reg-event-db
:play-pattern
(fn [db [_ row column]]
; Case 1: Playing a section
(if-let [repl (:repl db)]
(if-let [section (-> db :track :sections (nth row {}))]
;(println "section:" (prep-section section))
(-> repl :process (repl-send (prep-section section))))) ; FIXME: find section definition
(assoc db :playback {:section row
:patterns (-> db :track :channels count (take (repeat row)))})))
; FIXME: This does not kill the process yet
(rf/reg-event-db
:repl-kill
(fn [db [_]]
(if-let [{:keys [repl]} db]
(do (println "killing current process")
(-> repl :process (.kill "SIGINT"))
(dissoc db :repl)))))
(rf/reg-event-db
:repl-update-message
(fn [db [_ message]]
(update-in db [:repl :messages]
#(->> message
(str %)
(take-last 5000) ; improve this logic to account for newline characters
(clojure.string/join "")
(str)))))
(rf/reg-event-db
:repl-start
(fn [db [_ command]]
(let [proc (spawn-process command)] ;FIXME: Should read from plugin
(assoc-in db [:repl :process] proc))))
(rf/reg-event-db
:eval
(fn [db [_ command]]
(if-let [{:keys [repl]} db]
(-> repl :process (repl-send command)))
db))
(rf/reg-event-db
:update-selection
(fn [db [_ selection]]
(if-let [{:keys [track]} db]
(->> selection
(max 0)
(min (-> track :sections count (- 1)))
(assoc db :session/selection)))))
(rf/reg-event-db
:edit-file
(fn [db [_ filename]]
(let [editor-process (-> db :editor :process)]
(if (some? editor-process)
(.kill ^js editor-process "SIGTERM"))
(let [{keys [editor]} (:settings db)]
(-> db
(assoc-in [:editor :filename] filename)
(assoc-in [:router/view] :edit))))))
(defn consume-temp-file
"Pushes content of temp file to current selection"
[db]
(if-let [filename (-> db :editor :filename)]
(let [selection (:session/selection db)
new-def (node-slurp filename)]
(update-in db [:track :sections]
#(assoc-in (into [] %) [selection] (parse-section new-def))))
db))
(rf/reg-event-db
:navigate
(fn [db [_ view]]
(-> db
((if (= view :home) consume-temp-file identity))
(assoc-in [:router/view] view))))
| null | https://raw.githubusercontent.com/ghalestrilo/seg/1fad7f310a1652adffd16729ab16c5f457ac1860/src/segue/events.cljs | clojure | Below are very general effect handlers. While you can use these to get
going quickly you are likely better off creating custom handlers for actions
specific to your application.
TODO: check if process exists
Case 1: Playing a section
(println "section:" (prep-section section))
FIXME: find section definition
FIXME: This does not kill the process yet
improve this logic to account for newline characters
FIXME: Should read from plugin | (ns segue.events
"Event handlers for re-frame dispatch events.
Used to manage app db updates and side-effects.
-frame/blob/master/docs/EffectfulHandlers.md"
(:require
[re-frame.core :as rf]
[segue.track :refer [read-file parse-section prep-section load-track]]
[segue.repl :refer [spawn-process repl-send]]
[segue.wrappers :refer [node-slurp]]))
(def help-messages
{ :home
{ :up/down "Choose section/pattern"
:left/right "Choose player"
:enter "Trigger section"}})
IDEA : maybe the demo track could become a " template " user setting
(def demo-track
{:players ["drums" "piano" "bass" "vibe"]
:sections [{:name "intro"
:patterns [nil nil "0" nil]}
{:name "theme"
:patterns [nil nil "0" nil]}
{:name "bridge"
:patterns [nil "0*4" "0" nil]}
{:name "outro"
:patterns [nil nil "0" "0(3,8)"]}]
:pattern-bank []})
(def default-settings
{ :column-width 12
:editor "kak"})
(rf/reg-event-db
:init
(fn [db [_ opts terminal-size]]
{:opts opts
:settings default-settings
:router/view :home
:terminal/size terminal-size
:dialog/help help-messages
:session/selection 0
:track demo-track}))
(rf/reg-event-db
:update
(fn [db [_ data]]
(merge db data)))
(rf/reg-event-db
:set
(fn [db [_ data]]
data))
(rf/reg-event-db
:update-track
(fn [db [_ path data]]
(assoc-in db (into [:track] path) data)))
(rf/reg-event-db
:set-track
(fn [db [_ data]]
(assoc db :track data)))
(rf/reg-event-db
:play-pattern
(fn [db [_ row column]]
(if-let [repl (:repl db)]
(if-let [section (-> db :track :sections (nth row {}))]
(assoc db :playback {:section row
:patterns (-> db :track :channels count (take (repeat row)))})))
(rf/reg-event-db
:repl-kill
(fn [db [_]]
(if-let [{:keys [repl]} db]
(do (println "killing current process")
(-> repl :process (.kill "SIGINT"))
(dissoc db :repl)))))
(rf/reg-event-db
:repl-update-message
(fn [db [_ message]]
(update-in db [:repl :messages]
#(->> message
(str %)
(clojure.string/join "")
(str)))))
(rf/reg-event-db
:repl-start
(fn [db [_ command]]
(assoc-in db [:repl :process] proc))))
(rf/reg-event-db
:eval
(fn [db [_ command]]
(if-let [{:keys [repl]} db]
(-> repl :process (repl-send command)))
db))
(rf/reg-event-db
:update-selection
(fn [db [_ selection]]
(if-let [{:keys [track]} db]
(->> selection
(max 0)
(min (-> track :sections count (- 1)))
(assoc db :session/selection)))))
(rf/reg-event-db
:edit-file
(fn [db [_ filename]]
(let [editor-process (-> db :editor :process)]
(if (some? editor-process)
(.kill ^js editor-process "SIGTERM"))
(let [{keys [editor]} (:settings db)]
(-> db
(assoc-in [:editor :filename] filename)
(assoc-in [:router/view] :edit))))))
(defn consume-temp-file
"Pushes content of temp file to current selection"
[db]
(if-let [filename (-> db :editor :filename)]
(let [selection (:session/selection db)
new-def (node-slurp filename)]
(update-in db [:track :sections]
#(assoc-in (into [] %) [selection] (parse-section new-def))))
db))
(rf/reg-event-db
:navigate
(fn [db [_ view]]
(-> db
((if (= view :home) consume-temp-file identity))
(assoc-in [:router/view] view))))
|
e0d7d797072dcf52658488c048dee94fd13e656ea6d0c05bc1fce15e0589dbdc | samrushing/irken-compiler | t19.scm | ;; -*- Mode: Irken -*-
(include "lib/core.scm")
(define (thing)
(let loop ((n 10000))
(if (= n 100)
(%exit #f 42)
(loop (- n 1)))))
(thing)
| null | https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/vm/tests/t19.scm | scheme | -*- Mode: Irken -*- |
(include "lib/core.scm")
(define (thing)
(let loop ((n 10000))
(if (= n 100)
(%exit #f 42)
(loop (- n 1)))))
(thing)
|
e0a99e4af340d0cf58d6b2be9c80b4ffa1908a9159fc0a37246f421149f8e0c4 | nomeata/incredible | Utils.hs | module Utils where
subscriptify :: Char -> Char
subscriptify '0' = '₀'
subscriptify '1' = '₁'
subscriptify '2' = '₂'
subscriptify '3' = '₃'
subscriptify '4' = '₄'
subscriptify '5' = '₅'
subscriptify '6' = '₆'
subscriptify '7' = '₇'
subscriptify '8' = '₈'
subscriptify '9' = '₉'
subscriptify _ = error "subscriptify: non-numeral argument"
| null | https://raw.githubusercontent.com/nomeata/incredible/d18ada4ae7ce1c7ca268c050ee688b633a307c2e/logic/Utils.hs | haskell | module Utils where
subscriptify :: Char -> Char
subscriptify '0' = '₀'
subscriptify '1' = '₁'
subscriptify '2' = '₂'
subscriptify '3' = '₃'
subscriptify '4' = '₄'
subscriptify '5' = '₅'
subscriptify '6' = '₆'
subscriptify '7' = '₇'
subscriptify '8' = '₈'
subscriptify '9' = '₉'
subscriptify _ = error "subscriptify: non-numeral argument"
| |
f852addc071362a385c034e5b6c379d9a6b0c5fef822195184b5c36ab138c0a1 | cnuernber/dtype-next | next_item_fn.clj | (ns tech.v3.parallel.next-item-fn
(:require [tech.v3.parallel.for :as pfor]))
(defn create-next-item-fn
"Given a sequence return a function that each time called (with no arguments)
returns the next item in the sequence, iterable, or stream in a threadsafe but
mutable fashion."
[item-sequence]
(let [iterator (pfor/->iterator item-sequence)]
(fn []
(locking iterator
(when (.hasNext iterator)
(.next iterator))))))
| null | https://raw.githubusercontent.com/cnuernber/dtype-next/8fb3166a44a2ce21a673c864ae4d0351b6813d46/src/tech/v3/parallel/next_item_fn.clj | clojure | (ns tech.v3.parallel.next-item-fn
(:require [tech.v3.parallel.for :as pfor]))
(defn create-next-item-fn
"Given a sequence return a function that each time called (with no arguments)
returns the next item in the sequence, iterable, or stream in a threadsafe but
mutable fashion."
[item-sequence]
(let [iterator (pfor/->iterator item-sequence)]
(fn []
(locking iterator
(when (.hasNext iterator)
(.next iterator))))))
| |
62ac0b31102b719236935eeb95b7803530a3420c6ea7043d8ded3c2037faab01 | donaldsonjw/bigloo | loc2glo.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / comptime / Integrate / loc2glo.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : We d Mar 15 17:29:48 1995 * /
* Last change : Tue Oct 19 17:44:16 2010 ( serrano ) * /
* Copyright : 1995 - 2010 , see LICENSE file * /
;* ------------------------------------------------------------- */
;* We translate a local function definition into a global one. */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module integrate_local->global
(include "Tools/trace.sch")
(import tools_shape
tools_args
module_module
type_type
type_cache
ast_var
ast_node
ast_glo-def
ast_env
ast_local
integrate_info
integrate_node)
(export (local->global ::local)
(the-global ::local)))
;*---------------------------------------------------------------------*/
;* local->global ... */
;*---------------------------------------------------------------------*/
(define (local->global local)
(trace (integrate 2) (shape local) ", local->global:\n")
(trace (integrate 3) (shape (sfun-body (local-value local))) "\n")
(let* ((global (the-global local))
(kaptured (sfun/Iinfo-kaptured (local-value local)))
(add-args (map (lambda (old)
(clone-local old
(duplicate::svar/Iinfo
(local-value old))))
kaptured))
(old-fun (local-value local))
(new-fun (duplicate::sfun old-fun
(arity (+-arity (sfun-arity old-fun) (length add-args)))
(args (append (reverse add-args)
(sfun-args old-fun))))))
;; we set the result type
(global-type-set! global (local-type local))
(for-each (lambda (l)
(if (integrate-celled? l)
(local-type-set! l *obj*)))
(sfun-args new-fun))
(sfun-body-set! new-fun
(integrate-globalize! (sfun-body old-fun)
local
(map cons kaptured add-args)))
(global-value-set! global new-fun)
global))
;*---------------------------------------------------------------------*/
;* symbol-quote ... */
;*---------------------------------------------------------------------*/
(define symbol-quote (string->symbol "'"))
;*---------------------------------------------------------------------*/
;* local-id->global-id ... */
;* ------------------------------------------------------------- */
;* Generates a new global name for the globalized local function. */
;*---------------------------------------------------------------------*/
(define (local-id->global-id local)
(let ((id (local-id local)))
(let loop ((id (local-id local)))
(if (global? (find-global/module id *module*))
(loop (symbol-append id symbol-quote))
id))))
;*---------------------------------------------------------------------*/
;* the-global ... */
;*---------------------------------------------------------------------*/
(define (the-global local::local)
(let ((value (local-value local)))
(if (global? (sfun/Iinfo-global value))
(sfun/Iinfo-global value)
(let* ((id (local-id->global-id local))
(global (def-global-sfun-no-warning! id
;; we set dummy empty args-id
;; and dummy empty args because a new-fun
;; will be allocated.
'()
'()
*module*
'sfun
'a-integrated-body
'now
#unspecified)))
;; we have to propagate the location definition
;; of the local variable
(sfun-loc-set! (global-value global) (sfun-loc value))
we check if the function is a user one
(if (not (local-user? local))
(global-user?-set! global #f))
(sfun/Iinfo-global-set! value global)
(sfun-side-effect-set! (global-value global)
(sfun-side-effect value))
global))))
| null | https://raw.githubusercontent.com/donaldsonjw/bigloo/a4d06e409d0004e159ce92b9908719510a18aed5/comptime/Integrate/loc2glo.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* We translate a local function definition into a global one. */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* local->global ... */
*---------------------------------------------------------------------*/
we set the result type
*---------------------------------------------------------------------*/
* symbol-quote ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* local-id->global-id ... */
* ------------------------------------------------------------- */
* Generates a new global name for the globalized local function. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* the-global ... */
*---------------------------------------------------------------------*/
we set dummy empty args-id
and dummy empty args because a new-fun
will be allocated.
we have to propagate the location definition
of the local variable | * serrano / prgm / project / bigloo / comptime / Integrate / loc2glo.scm * /
* Author : * /
* Creation : We d Mar 15 17:29:48 1995 * /
* Last change : Tue Oct 19 17:44:16 2010 ( serrano ) * /
* Copyright : 1995 - 2010 , see LICENSE file * /
(module integrate_local->global
(include "Tools/trace.sch")
(import tools_shape
tools_args
module_module
type_type
type_cache
ast_var
ast_node
ast_glo-def
ast_env
ast_local
integrate_info
integrate_node)
(export (local->global ::local)
(the-global ::local)))
(define (local->global local)
(trace (integrate 2) (shape local) ", local->global:\n")
(trace (integrate 3) (shape (sfun-body (local-value local))) "\n")
(let* ((global (the-global local))
(kaptured (sfun/Iinfo-kaptured (local-value local)))
(add-args (map (lambda (old)
(clone-local old
(duplicate::svar/Iinfo
(local-value old))))
kaptured))
(old-fun (local-value local))
(new-fun (duplicate::sfun old-fun
(arity (+-arity (sfun-arity old-fun) (length add-args)))
(args (append (reverse add-args)
(sfun-args old-fun))))))
(global-type-set! global (local-type local))
(for-each (lambda (l)
(if (integrate-celled? l)
(local-type-set! l *obj*)))
(sfun-args new-fun))
(sfun-body-set! new-fun
(integrate-globalize! (sfun-body old-fun)
local
(map cons kaptured add-args)))
(global-value-set! global new-fun)
global))
(define symbol-quote (string->symbol "'"))
(define (local-id->global-id local)
(let ((id (local-id local)))
(let loop ((id (local-id local)))
(if (global? (find-global/module id *module*))
(loop (symbol-append id symbol-quote))
id))))
(define (the-global local::local)
(let ((value (local-value local)))
(if (global? (sfun/Iinfo-global value))
(sfun/Iinfo-global value)
(let* ((id (local-id->global-id local))
(global (def-global-sfun-no-warning! id
'()
'()
*module*
'sfun
'a-integrated-body
'now
#unspecified)))
(sfun-loc-set! (global-value global) (sfun-loc value))
we check if the function is a user one
(if (not (local-user? local))
(global-user?-set! global #f))
(sfun/Iinfo-global-set! value global)
(sfun-side-effect-set! (global-value global)
(sfun-side-effect value))
global))))
|
c1d59544888a7070c515e954ad768f7767ed12f01ad102f049f87928795addb5 | ocaml/odoc | comment.ml |
* Copyright ( c ) 2016 , 2017 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2016, 2017 Thomas Refis <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Types
module Comment = Odoc_model.Comment
open Odoc_model.Names
let default_lang_tag = "ocaml"
let source_of_code s =
if s = "" then [] else [ Source.Elt [ inline @@ Inline.Text s ] ]
module Reference = struct
open Odoc_model.Paths
let rec render_resolved : Reference.Resolved.t -> string =
fun r ->
let open Reference.Resolved in
match r with
| `Identifier id -> Identifier.name id
| `Alias (_, r) -> render_resolved (r :> t)
| `AliasModuleType (_, r) -> render_resolved (r :> t)
| `Module (r, s) -> render_resolved (r :> t) ^ "." ^ ModuleName.to_string s
| `Hidden p -> render_resolved (p :> t)
| `ModuleType (r, s) ->
render_resolved (r :> t) ^ "." ^ ModuleTypeName.to_string s
| `Type (r, s) -> render_resolved (r :> t) ^ "." ^ TypeName.to_string s
| `Constructor (r, s) ->
render_resolved (r :> t) ^ "." ^ ConstructorName.to_string s
| `Field (r, s) -> render_resolved (r :> t) ^ "." ^ FieldName.to_string s
| `Extension (r, s) ->
render_resolved (r :> t) ^ "." ^ ExtensionName.to_string s
| `Exception (r, s) ->
render_resolved (r :> t) ^ "." ^ ExceptionName.to_string s
| `Value (r, s) -> render_resolved (r :> t) ^ "." ^ ValueName.to_string s
| `Class (r, s) -> render_resolved (r :> t) ^ "." ^ ClassName.to_string s
| `ClassType (r, s) ->
render_resolved (r :> t) ^ "." ^ ClassTypeName.to_string s
| `Method (r, s) ->
: do we really want to print anything more than [ s ] here ?
render_resolved (r :> t) ^ "." ^ MethodName.to_string s
| `InstanceVariable (r, s) ->
: the following makes no sense to me ...
render_resolved (r :> t) ^ "." ^ InstanceVariableName.to_string s
| `Label (_, s) -> LabelName.to_string s
(* This is the entry point. stop_before is false on entry, true on recursive
call. *)
let rec to_ir : ?text:Inline.t -> stop_before:bool -> Reference.t -> Inline.t
=
fun ?text ~stop_before ref ->
let open Reference in
match ref with
| `Root (s, _) -> (
match text with
| None ->
let s = source_of_code s in
[ inline @@ Inline.Source s ]
| Some s ->
[ inline @@ Inline.InternalLink (InternalLink.Unresolved s) ])
| `Dot (parent, s) -> unresolved ?text (parent :> t) s
| `Module (parent, s) ->
unresolved ?text (parent :> t) (ModuleName.to_string s)
| `ModuleType (parent, s) ->
unresolved ?text (parent :> t) (ModuleTypeName.to_string s)
| `Type (parent, s) -> unresolved ?text (parent :> t) (TypeName.to_string s)
| `Constructor (parent, s) ->
unresolved ?text (parent :> t) (ConstructorName.to_string s)
| `Field (parent, s) ->
unresolved ?text (parent :> t) (FieldName.to_string s)
| `Extension (parent, s) ->
unresolved ?text (parent :> t) (ExtensionName.to_string s)
| `Exception (parent, s) ->
unresolved ?text (parent :> t) (ExceptionName.to_string s)
| `Value (parent, s) ->
unresolved ?text (parent :> t) (ValueName.to_string s)
| `Class (parent, s) ->
unresolved ?text (parent :> t) (ClassName.to_string s)
| `ClassType (parent, s) ->
unresolved ?text (parent :> t) (ClassTypeName.to_string s)
| `Method (parent, s) ->
unresolved ?text (parent :> t) (MethodName.to_string s)
| `InstanceVariable (parent, s) ->
unresolved ?text (parent :> t) (InstanceVariableName.to_string s)
| `Label (parent, s) ->
unresolved ?text (parent :> t) (LabelName.to_string s)
| `Resolved r -> (
(* IDENTIFIER MUST BE RENAMED TO DEFINITION. *)
let id = Reference.Resolved.identifier r in
let txt =
match text with
| None ->
[ inline @@ Inline.Source (source_of_code (render_resolved r)) ]
| Some s -> s
in
match Url.from_identifier ~stop_before id with
| Ok url ->
[ inline @@ Inline.InternalLink (InternalLink.Resolved (url, txt)) ]
| Error (Not_linkable _) -> txt
| Error exn ->
(* FIXME: better error message *)
Printf.eprintf "Id.href failed: %S\n%!" (Url.Error.to_string exn);
txt)
and unresolved : ?text:Inline.t -> Reference.t -> string -> Inline.t =
fun ?text parent field ->
match text with
| Some s -> [ inline @@ InternalLink (InternalLink.Unresolved s) ]
| None ->
let tail = [ inline @@ Text ("." ^ field) ] in
let content = to_ir ~stop_before:true parent in
content @ tail
end
let leaf_inline_element : Comment.leaf_inline_element -> Inline.one = function
| `Space -> inline @@ Text " "
| `Word s -> inline @@ Text s
| `Code_span s -> inline @@ Source (source_of_code s)
| `Math_span s -> inline @@ Math s
| `Raw_markup (target, s) -> inline @@ Raw_markup (target, s)
let rec non_link_inline_element : Comment.non_link_inline_element -> Inline.one
= function
| #Comment.leaf_inline_element as e -> leaf_inline_element e
| `Styled (style, content) ->
inline @@ Styled (style, non_link_inline_element_list content)
and non_link_inline_element_list : _ -> Inline.t =
fun elements ->
List.map
(fun elt -> non_link_inline_element elt.Odoc_model.Location_.value)
elements
let link_content = non_link_inline_element_list
let rec inline_element : Comment.inline_element -> Inline.t = function
| #Comment.leaf_inline_element as e -> [ leaf_inline_element e ]
| `Styled (style, content) ->
[ inline @@ Styled (style, inline_element_list content) ]
| `Reference (path, content) ->
(* TODO Rework that ugly function. *)
(* TODO References should be set in code style, if they are to code
elements. *)
let content =
match content with
| [] -> None
| _ -> Some (non_link_inline_element_list content)
(* XXX Span *)
in
Reference.to_ir ?text:content ~stop_before:false path
| `Link (target, content) ->
let content =
match content with
| [] -> [ inline @@ Text target ]
| _ -> non_link_inline_element_list content
in
[ inline @@ Link (target, content) ]
and inline_element_list elements =
List.concat
@@ List.map
(fun elt -> inline_element elt.Odoc_model.Location_.value)
elements
let module_references ms =
let module_reference (m : Comment.module_reference) =
let reference =
Reference.to_ir ~stop_before:false
(m.module_reference :> Odoc_model.Paths.Reference.t)
and synopsis =
match m.module_synopsis with
| Some synopsis ->
[
block ~attr:[ "synopsis" ] @@ Inline (inline_element_list synopsis);
]
| None -> []
in
{ Description.attr = []; key = reference; definition = synopsis }
in
let items = List.map module_reference ms in
block ~attr:[ "modules" ] @@ Description items
let rec nestable_block_element : Comment.nestable_block_element -> Block.one =
fun content ->
match content with
| `Paragraph p -> paragraph p
| `Code_block (lang_tag, code) ->
let lang_tag =
match lang_tag with None -> default_lang_tag | Some t -> t
in
block
@@ Source (lang_tag, source_of_code (Odoc_model.Location_.value code))
| `Math_block s -> block @@ Math s
| `Verbatim s -> block @@ Verbatim s
| `Modules ms -> module_references ms
| `List (kind, items) ->
let kind =
match kind with
| `Unordered -> Block.Unordered
| `Ordered -> Block.Ordered
in
let f = function
| [ { Odoc_model.Location_.value = `Paragraph content; _ } ] ->
[ block @@ Block.Inline (inline_element_list content) ]
| item -> nestable_block_element_list item
in
let items = List.map f items in
block @@ Block.List (kind, items)
and paragraph : Comment.paragraph -> Block.one = function
| [ { value = `Raw_markup (target, s); _ } ] ->
block @@ Block.Raw_markup (target, s)
| p -> block @@ Block.Paragraph (inline_element_list p)
and nestable_block_element_list elements =
elements
|> List.map Odoc_model.Location_.value
|> List.map nestable_block_element
let tag : Comment.tag -> Description.one =
fun t ->
let sp = inline (Text " ") in
let item ?value ~tag definition =
let tag_name = inline ~attr:[ "at-tag" ] (Text tag) in
let tag_value =
match value with
| None -> []
| Some t -> [ sp; inline ~attr:[ "value" ] t ]
in
let key = tag_name :: tag_value in
{ Description.attr = [ tag ]; key; definition }
in
let text_def s = [ block (Block.Inline [ inline @@ Text s ]) ] in
let content_to_inline ?(prefix = []) content =
match content with
| None -> []
| Some content -> prefix @ [ inline @@ Text content ]
in
match t with
| `Author s -> item ~tag:"author" (text_def s)
| `Deprecated content ->
item ~tag:"deprecated" (nestable_block_element_list content)
| `Param (name, content) ->
let value = Inline.Text name in
item ~tag:"parameter" ~value (nestable_block_element_list content)
| `Raise (name, content) ->
let value = Inline.Text name in
item ~tag:"raises" ~value (nestable_block_element_list content)
| `Return content -> item ~tag:"returns" (nestable_block_element_list content)
| `See (kind, target, content) ->
let value =
match kind with
| `Url -> Inline.Link (target, [ inline @@ Text target ])
| `File -> Inline.Source (source_of_code target)
| `Document -> Inline.Text target
in
item ~tag:"see" ~value (nestable_block_element_list content)
| `Since s -> item ~tag:"since" (text_def s)
| `Before (version, content) ->
let value = Inline.Text version in
item ~tag:"before" ~value (nestable_block_element_list content)
| `Version s -> item ~tag:"version" (text_def s)
| `Alert ("deprecated", content) ->
let content = content_to_inline content in
item ~tag:"deprecated" [ block (Block.Inline content) ]
| `Alert (tag, content) ->
let content = content_to_inline ~prefix:[ sp ] content in
item ~tag:"alert"
[ block (Block.Inline ([ inline @@ Text tag ] @ content)) ]
let attached_block_element : Comment.attached_block_element -> Block.t =
function
| #Comment.nestable_block_element as e -> [ nestable_block_element e ]
| `Tag t -> [ block ~attr:[ "at-tags" ] @@ Description [ tag t ] ]
TODO collaesce tags
let block_element : Comment.block_element -> Block.t = function
| #Comment.attached_block_element as e -> attached_block_element e
| `Heading (_, _, text) ->
(* We are not supposed to receive Heading in this context.
TODO: Remove heading in attached documentation in the model *)
[ block @@ Paragraph (non_link_inline_element_list text) ]
let heading_level_to_int = function
| `Title -> 0
| `Section -> 1
| `Subsection -> 2
| `Subsubsection -> 3
| `Paragraph -> 4
| `Subparagraph -> 5
let heading
(attrs, { Odoc_model.Paths.Identifier.iv = `Label (_, label); _ }, text) =
let label = Odoc_model.Names.LabelName.to_string label in
let title = non_link_inline_element_list text in
let level = heading_level_to_int attrs.Comment.heading_level in
let label = Some label in
Item.Heading { label; level; title }
let item_element : Comment.block_element -> Item.t list = function
| #Comment.attached_block_element as e ->
[ Item.Text (attached_block_element e) ]
| `Heading h -> [ heading h ]
(** The documentation of the expansion is used if there is no comment attached
to the declaration. *)
let synopsis ~decl_doc ~expansion_doc =
let ([], Some docs | docs, _) = (decl_doc, expansion_doc) in
match Comment.synopsis docs with Some p -> [ paragraph p ] | None -> []
let standalone docs =
Utils.flatmap ~f:item_element
@@ List.map (fun x -> x.Odoc_model.Location_.value) docs
let to_ir (docs : Comment.docs) =
Utils.flatmap ~f:block_element
@@ List.map (fun x -> x.Odoc_model.Location_.value) docs
let has_doc docs = docs <> []
| null | https://raw.githubusercontent.com/ocaml/odoc/a52dd8e960f99b38162d40311a9c4512d5741d43/src/document/comment.ml | ocaml | This is the entry point. stop_before is false on entry, true on recursive
call.
IDENTIFIER MUST BE RENAMED TO DEFINITION.
FIXME: better error message
TODO Rework that ugly function.
TODO References should be set in code style, if they are to code
elements.
XXX Span
We are not supposed to receive Heading in this context.
TODO: Remove heading in attached documentation in the model
* The documentation of the expansion is used if there is no comment attached
to the declaration. |
* Copyright ( c ) 2016 , 2017 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2016, 2017 Thomas Refis <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Types
module Comment = Odoc_model.Comment
open Odoc_model.Names
let default_lang_tag = "ocaml"
let source_of_code s =
if s = "" then [] else [ Source.Elt [ inline @@ Inline.Text s ] ]
module Reference = struct
open Odoc_model.Paths
let rec render_resolved : Reference.Resolved.t -> string =
fun r ->
let open Reference.Resolved in
match r with
| `Identifier id -> Identifier.name id
| `Alias (_, r) -> render_resolved (r :> t)
| `AliasModuleType (_, r) -> render_resolved (r :> t)
| `Module (r, s) -> render_resolved (r :> t) ^ "." ^ ModuleName.to_string s
| `Hidden p -> render_resolved (p :> t)
| `ModuleType (r, s) ->
render_resolved (r :> t) ^ "." ^ ModuleTypeName.to_string s
| `Type (r, s) -> render_resolved (r :> t) ^ "." ^ TypeName.to_string s
| `Constructor (r, s) ->
render_resolved (r :> t) ^ "." ^ ConstructorName.to_string s
| `Field (r, s) -> render_resolved (r :> t) ^ "." ^ FieldName.to_string s
| `Extension (r, s) ->
render_resolved (r :> t) ^ "." ^ ExtensionName.to_string s
| `Exception (r, s) ->
render_resolved (r :> t) ^ "." ^ ExceptionName.to_string s
| `Value (r, s) -> render_resolved (r :> t) ^ "." ^ ValueName.to_string s
| `Class (r, s) -> render_resolved (r :> t) ^ "." ^ ClassName.to_string s
| `ClassType (r, s) ->
render_resolved (r :> t) ^ "." ^ ClassTypeName.to_string s
| `Method (r, s) ->
: do we really want to print anything more than [ s ] here ?
render_resolved (r :> t) ^ "." ^ MethodName.to_string s
| `InstanceVariable (r, s) ->
: the following makes no sense to me ...
render_resolved (r :> t) ^ "." ^ InstanceVariableName.to_string s
| `Label (_, s) -> LabelName.to_string s
let rec to_ir : ?text:Inline.t -> stop_before:bool -> Reference.t -> Inline.t
=
fun ?text ~stop_before ref ->
let open Reference in
match ref with
| `Root (s, _) -> (
match text with
| None ->
let s = source_of_code s in
[ inline @@ Inline.Source s ]
| Some s ->
[ inline @@ Inline.InternalLink (InternalLink.Unresolved s) ])
| `Dot (parent, s) -> unresolved ?text (parent :> t) s
| `Module (parent, s) ->
unresolved ?text (parent :> t) (ModuleName.to_string s)
| `ModuleType (parent, s) ->
unresolved ?text (parent :> t) (ModuleTypeName.to_string s)
| `Type (parent, s) -> unresolved ?text (parent :> t) (TypeName.to_string s)
| `Constructor (parent, s) ->
unresolved ?text (parent :> t) (ConstructorName.to_string s)
| `Field (parent, s) ->
unresolved ?text (parent :> t) (FieldName.to_string s)
| `Extension (parent, s) ->
unresolved ?text (parent :> t) (ExtensionName.to_string s)
| `Exception (parent, s) ->
unresolved ?text (parent :> t) (ExceptionName.to_string s)
| `Value (parent, s) ->
unresolved ?text (parent :> t) (ValueName.to_string s)
| `Class (parent, s) ->
unresolved ?text (parent :> t) (ClassName.to_string s)
| `ClassType (parent, s) ->
unresolved ?text (parent :> t) (ClassTypeName.to_string s)
| `Method (parent, s) ->
unresolved ?text (parent :> t) (MethodName.to_string s)
| `InstanceVariable (parent, s) ->
unresolved ?text (parent :> t) (InstanceVariableName.to_string s)
| `Label (parent, s) ->
unresolved ?text (parent :> t) (LabelName.to_string s)
| `Resolved r -> (
let id = Reference.Resolved.identifier r in
let txt =
match text with
| None ->
[ inline @@ Inline.Source (source_of_code (render_resolved r)) ]
| Some s -> s
in
match Url.from_identifier ~stop_before id with
| Ok url ->
[ inline @@ Inline.InternalLink (InternalLink.Resolved (url, txt)) ]
| Error (Not_linkable _) -> txt
| Error exn ->
Printf.eprintf "Id.href failed: %S\n%!" (Url.Error.to_string exn);
txt)
and unresolved : ?text:Inline.t -> Reference.t -> string -> Inline.t =
fun ?text parent field ->
match text with
| Some s -> [ inline @@ InternalLink (InternalLink.Unresolved s) ]
| None ->
let tail = [ inline @@ Text ("." ^ field) ] in
let content = to_ir ~stop_before:true parent in
content @ tail
end
let leaf_inline_element : Comment.leaf_inline_element -> Inline.one = function
| `Space -> inline @@ Text " "
| `Word s -> inline @@ Text s
| `Code_span s -> inline @@ Source (source_of_code s)
| `Math_span s -> inline @@ Math s
| `Raw_markup (target, s) -> inline @@ Raw_markup (target, s)
let rec non_link_inline_element : Comment.non_link_inline_element -> Inline.one
= function
| #Comment.leaf_inline_element as e -> leaf_inline_element e
| `Styled (style, content) ->
inline @@ Styled (style, non_link_inline_element_list content)
and non_link_inline_element_list : _ -> Inline.t =
fun elements ->
List.map
(fun elt -> non_link_inline_element elt.Odoc_model.Location_.value)
elements
let link_content = non_link_inline_element_list
let rec inline_element : Comment.inline_element -> Inline.t = function
| #Comment.leaf_inline_element as e -> [ leaf_inline_element e ]
| `Styled (style, content) ->
[ inline @@ Styled (style, inline_element_list content) ]
| `Reference (path, content) ->
let content =
match content with
| [] -> None
| _ -> Some (non_link_inline_element_list content)
in
Reference.to_ir ?text:content ~stop_before:false path
| `Link (target, content) ->
let content =
match content with
| [] -> [ inline @@ Text target ]
| _ -> non_link_inline_element_list content
in
[ inline @@ Link (target, content) ]
and inline_element_list elements =
List.concat
@@ List.map
(fun elt -> inline_element elt.Odoc_model.Location_.value)
elements
let module_references ms =
let module_reference (m : Comment.module_reference) =
let reference =
Reference.to_ir ~stop_before:false
(m.module_reference :> Odoc_model.Paths.Reference.t)
and synopsis =
match m.module_synopsis with
| Some synopsis ->
[
block ~attr:[ "synopsis" ] @@ Inline (inline_element_list synopsis);
]
| None -> []
in
{ Description.attr = []; key = reference; definition = synopsis }
in
let items = List.map module_reference ms in
block ~attr:[ "modules" ] @@ Description items
let rec nestable_block_element : Comment.nestable_block_element -> Block.one =
fun content ->
match content with
| `Paragraph p -> paragraph p
| `Code_block (lang_tag, code) ->
let lang_tag =
match lang_tag with None -> default_lang_tag | Some t -> t
in
block
@@ Source (lang_tag, source_of_code (Odoc_model.Location_.value code))
| `Math_block s -> block @@ Math s
| `Verbatim s -> block @@ Verbatim s
| `Modules ms -> module_references ms
| `List (kind, items) ->
let kind =
match kind with
| `Unordered -> Block.Unordered
| `Ordered -> Block.Ordered
in
let f = function
| [ { Odoc_model.Location_.value = `Paragraph content; _ } ] ->
[ block @@ Block.Inline (inline_element_list content) ]
| item -> nestable_block_element_list item
in
let items = List.map f items in
block @@ Block.List (kind, items)
and paragraph : Comment.paragraph -> Block.one = function
| [ { value = `Raw_markup (target, s); _ } ] ->
block @@ Block.Raw_markup (target, s)
| p -> block @@ Block.Paragraph (inline_element_list p)
and nestable_block_element_list elements =
elements
|> List.map Odoc_model.Location_.value
|> List.map nestable_block_element
let tag : Comment.tag -> Description.one =
fun t ->
let sp = inline (Text " ") in
let item ?value ~tag definition =
let tag_name = inline ~attr:[ "at-tag" ] (Text tag) in
let tag_value =
match value with
| None -> []
| Some t -> [ sp; inline ~attr:[ "value" ] t ]
in
let key = tag_name :: tag_value in
{ Description.attr = [ tag ]; key; definition }
in
let text_def s = [ block (Block.Inline [ inline @@ Text s ]) ] in
let content_to_inline ?(prefix = []) content =
match content with
| None -> []
| Some content -> prefix @ [ inline @@ Text content ]
in
match t with
| `Author s -> item ~tag:"author" (text_def s)
| `Deprecated content ->
item ~tag:"deprecated" (nestable_block_element_list content)
| `Param (name, content) ->
let value = Inline.Text name in
item ~tag:"parameter" ~value (nestable_block_element_list content)
| `Raise (name, content) ->
let value = Inline.Text name in
item ~tag:"raises" ~value (nestable_block_element_list content)
| `Return content -> item ~tag:"returns" (nestable_block_element_list content)
| `See (kind, target, content) ->
let value =
match kind with
| `Url -> Inline.Link (target, [ inline @@ Text target ])
| `File -> Inline.Source (source_of_code target)
| `Document -> Inline.Text target
in
item ~tag:"see" ~value (nestable_block_element_list content)
| `Since s -> item ~tag:"since" (text_def s)
| `Before (version, content) ->
let value = Inline.Text version in
item ~tag:"before" ~value (nestable_block_element_list content)
| `Version s -> item ~tag:"version" (text_def s)
| `Alert ("deprecated", content) ->
let content = content_to_inline content in
item ~tag:"deprecated" [ block (Block.Inline content) ]
| `Alert (tag, content) ->
let content = content_to_inline ~prefix:[ sp ] content in
item ~tag:"alert"
[ block (Block.Inline ([ inline @@ Text tag ] @ content)) ]
let attached_block_element : Comment.attached_block_element -> Block.t =
function
| #Comment.nestable_block_element as e -> [ nestable_block_element e ]
| `Tag t -> [ block ~attr:[ "at-tags" ] @@ Description [ tag t ] ]
TODO collaesce tags
let block_element : Comment.block_element -> Block.t = function
| #Comment.attached_block_element as e -> attached_block_element e
| `Heading (_, _, text) ->
[ block @@ Paragraph (non_link_inline_element_list text) ]
let heading_level_to_int = function
| `Title -> 0
| `Section -> 1
| `Subsection -> 2
| `Subsubsection -> 3
| `Paragraph -> 4
| `Subparagraph -> 5
let heading
(attrs, { Odoc_model.Paths.Identifier.iv = `Label (_, label); _ }, text) =
let label = Odoc_model.Names.LabelName.to_string label in
let title = non_link_inline_element_list text in
let level = heading_level_to_int attrs.Comment.heading_level in
let label = Some label in
Item.Heading { label; level; title }
let item_element : Comment.block_element -> Item.t list = function
| #Comment.attached_block_element as e ->
[ Item.Text (attached_block_element e) ]
| `Heading h -> [ heading h ]
let synopsis ~decl_doc ~expansion_doc =
let ([], Some docs | docs, _) = (decl_doc, expansion_doc) in
match Comment.synopsis docs with Some p -> [ paragraph p ] | None -> []
let standalone docs =
Utils.flatmap ~f:item_element
@@ List.map (fun x -> x.Odoc_model.Location_.value) docs
let to_ir (docs : Comment.docs) =
Utils.flatmap ~f:block_element
@@ List.map (fun x -> x.Odoc_model.Location_.value) docs
let has_doc docs = docs <> []
|
afac6ecc35ddb04443946699a2a9d22178e7d131a37282020ab42998490b8abe | benzap/fif | multi.cljc | (ns fif.stdlib.realizer.multi
"Notes:
- depends on 'apply' word function in the collectors stdlib
"
(:require
[fif.stack-machine :as stack-machine]
[fif.stack-machine.processor :as processor]
[fif.stack-machine.stash :as stack-machine.stash]
[fif.stack-machine.words :refer [set-global-word-defn]]
[fif.stack-machine.exceptions :as exceptions]
[fif.stack-machine.mode :as mode]
[fif.utils.token :as utils.token]))
(def arg-realize-token '??)
(def arg-realize-start-token '??/start)
(def arg-realize-finish-token '??/finish)
(def realize-multi-mode-flag :realize-multi-mode)
(defn enter-realize-multi-mode
[sm state]
(-> sm (mode/enter-mode realize-multi-mode-flag state)))
(defn exit-realize-multi-mode
[sm]
(-> sm (mode/exit-mode)))
(defmulti realize-multi-mode mode/mode-dispatch-fn)
(defn prepare-map-collection [m]
(reduce
(fn [xs [k v]]
(let [bform (cond-> '()
true (concat [k])
(seq? k) (concat ['apply])
(or (coll? k) (symbol? k)) (concat ['??])
true (concat [v])
(seq? v) (concat ['apply])
(or (coll? v) (symbol? v)) (concat ['??])
true vec)]
(concat xs [bform arg-realize-token])))
[]
m))
(defn prepare-other-collection [m]
(reduce
(fn [xs x]
(if (coll? x)
(concat xs [x '??])
(concat xs [x])))
[]
m))
(defmethod realize-multi-mode
{:op ::?? :op-state ::init}
[sm]
(let [[collection] (-> sm stack-machine/get-stack)
coll-type (empty collection)
collection
(cond
(map? collection)
(prepare-map-collection collection)
(coll? collection)
(prepare-other-collection collection)
:else
collection)]
(if (coll? collection)
(-> sm
(stack-machine.stash/update-stash assoc ::collection-type coll-type)
(mode/update-state assoc :op-state ::collect)
stack-machine/dequeue-code
stack-machine/pop-stack
(stack-machine/push-stack arg-realize-start-token)
(stack-machine/update-code #(concat %2 %3 %1) collection [arg-realize-finish-token]))
(-> sm
exit-realize-multi-mode
stack-machine/dequeue-code))))
(defmethod realize-multi-mode
{:op ::?? :op-state ::collect}
[sm]
(let [arg (-> sm stack-machine/get-code first)]
(cond
(= arg arg-realize-finish-token)
(-> sm
(mode/update-state assoc :op-state ::finish))
:else
(processor/process-arg sm))))
(defn fix-map-key-pairs
[kp]
(case (count kp)
0 nil
1 [(first kp) nil]
2 kp
[(first kp) (rest kp)]))
(defmethod realize-multi-mode
{:op ::?? :op-state ::finish}
[sm]
(let [coll-type (-> sm stack-machine.stash/peek-stash ::collection-type)
[realized-collection new-stack]
(-> sm
stack-machine/get-stack
(utils.token/split-at-token arg-realize-start-token))
realized-collection (if (map? coll-type) (keep fix-map-key-pairs realized-collection) realized-collection)
realized-collection (->> realized-collection reverse (into coll-type))
realized-collection (if (seq? realized-collection)
(reverse realized-collection)
realized-collection)]
(-> sm
(stack-machine/set-stack new-stack)
(stack-machine/push-stack realized-collection)
(exit-realize-multi-mode)
(stack-machine/dequeue-code))))
(def doc-string "<coll> ?? -- Realizes the collection, and any nested collections")
(defn realize-multi-op
[sm]
(-> sm
(enter-realize-multi-mode {:op ::?? :op-state ::init})))
(defn import-stdlib-realize-multi-mode
[sm]
(-> sm
(set-global-word-defn
arg-realize-token realize-multi-op
:stdlib? true
:doc doc-string
:group :stdlib.realizer)
(set-global-word-defn
arg-realize-start-token exceptions/raise-unbounded-mode-argument
:stdlib? true
:doc doc-string
:group :stdlib.realizer)
(set-global-word-defn
arg-realize-finish-token exceptions/raise-unbounded-mode-argument
:stdlib? true
:doc doc-string
:group :stdlib.realizer)
(stack-machine/set-mode realize-multi-mode-flag realize-multi-mode)))
| null | https://raw.githubusercontent.com/benzap/fif/972adab8b86c016b04babea49d52198585172fe3/src/fif/stdlib/realizer/multi.cljc | clojure | (ns fif.stdlib.realizer.multi
"Notes:
- depends on 'apply' word function in the collectors stdlib
"
(:require
[fif.stack-machine :as stack-machine]
[fif.stack-machine.processor :as processor]
[fif.stack-machine.stash :as stack-machine.stash]
[fif.stack-machine.words :refer [set-global-word-defn]]
[fif.stack-machine.exceptions :as exceptions]
[fif.stack-machine.mode :as mode]
[fif.utils.token :as utils.token]))
(def arg-realize-token '??)
(def arg-realize-start-token '??/start)
(def arg-realize-finish-token '??/finish)
(def realize-multi-mode-flag :realize-multi-mode)
(defn enter-realize-multi-mode
[sm state]
(-> sm (mode/enter-mode realize-multi-mode-flag state)))
(defn exit-realize-multi-mode
[sm]
(-> sm (mode/exit-mode)))
(defmulti realize-multi-mode mode/mode-dispatch-fn)
(defn prepare-map-collection [m]
(reduce
(fn [xs [k v]]
(let [bform (cond-> '()
true (concat [k])
(seq? k) (concat ['apply])
(or (coll? k) (symbol? k)) (concat ['??])
true (concat [v])
(seq? v) (concat ['apply])
(or (coll? v) (symbol? v)) (concat ['??])
true vec)]
(concat xs [bform arg-realize-token])))
[]
m))
(defn prepare-other-collection [m]
(reduce
(fn [xs x]
(if (coll? x)
(concat xs [x '??])
(concat xs [x])))
[]
m))
(defmethod realize-multi-mode
{:op ::?? :op-state ::init}
[sm]
(let [[collection] (-> sm stack-machine/get-stack)
coll-type (empty collection)
collection
(cond
(map? collection)
(prepare-map-collection collection)
(coll? collection)
(prepare-other-collection collection)
:else
collection)]
(if (coll? collection)
(-> sm
(stack-machine.stash/update-stash assoc ::collection-type coll-type)
(mode/update-state assoc :op-state ::collect)
stack-machine/dequeue-code
stack-machine/pop-stack
(stack-machine/push-stack arg-realize-start-token)
(stack-machine/update-code #(concat %2 %3 %1) collection [arg-realize-finish-token]))
(-> sm
exit-realize-multi-mode
stack-machine/dequeue-code))))
(defmethod realize-multi-mode
{:op ::?? :op-state ::collect}
[sm]
(let [arg (-> sm stack-machine/get-code first)]
(cond
(= arg arg-realize-finish-token)
(-> sm
(mode/update-state assoc :op-state ::finish))
:else
(processor/process-arg sm))))
(defn fix-map-key-pairs
[kp]
(case (count kp)
0 nil
1 [(first kp) nil]
2 kp
[(first kp) (rest kp)]))
(defmethod realize-multi-mode
{:op ::?? :op-state ::finish}
[sm]
(let [coll-type (-> sm stack-machine.stash/peek-stash ::collection-type)
[realized-collection new-stack]
(-> sm
stack-machine/get-stack
(utils.token/split-at-token arg-realize-start-token))
realized-collection (if (map? coll-type) (keep fix-map-key-pairs realized-collection) realized-collection)
realized-collection (->> realized-collection reverse (into coll-type))
realized-collection (if (seq? realized-collection)
(reverse realized-collection)
realized-collection)]
(-> sm
(stack-machine/set-stack new-stack)
(stack-machine/push-stack realized-collection)
(exit-realize-multi-mode)
(stack-machine/dequeue-code))))
(def doc-string "<coll> ?? -- Realizes the collection, and any nested collections")
(defn realize-multi-op
[sm]
(-> sm
(enter-realize-multi-mode {:op ::?? :op-state ::init})))
(defn import-stdlib-realize-multi-mode
[sm]
(-> sm
(set-global-word-defn
arg-realize-token realize-multi-op
:stdlib? true
:doc doc-string
:group :stdlib.realizer)
(set-global-word-defn
arg-realize-start-token exceptions/raise-unbounded-mode-argument
:stdlib? true
:doc doc-string
:group :stdlib.realizer)
(set-global-word-defn
arg-realize-finish-token exceptions/raise-unbounded-mode-argument
:stdlib? true
:doc doc-string
:group :stdlib.realizer)
(stack-machine/set-mode realize-multi-mode-flag realize-multi-mode)))
| |
6efe9c2ffdf543b819158773c7a7a40160d6dad479a2da01dfe65d9e25552d4d | kiranlak/austin-sbst | testCaseWriter.ml | Copyright : , University College London , 2011
open Cil
open Solution
let flags = [Open_creat;Open_append;Open_text]
let perm = 0o755
let protos : (string, bool) Hashtbl.t = Hashtbl.create 10
let added (f:fundec) =
Hashtbl.mem protos f.svar.vname
let mallocExpr =
let v = makeVarinfo false "malloc" (TFun(voidPtrType, Some["size", uintType, []], false, [])) in
Lval(var v)
let freeExpr =
let v = makeVarinfo false "free" (TFun(voidType, Some["size", voidPtrType, []], false, [])) in
Lval(var v)
let fut_prototyp_toString (f:fundec) =
Hashtbl.add protos f.svar.vname true;
Printf.sprintf "%s\n" (Pretty.sprint 255 (Cil.d_global() (GVarDecl(f.svar, locUnknown))))
let saveCandidateSolution (id:int) (sol : candidateSolution) (comment:string) (testdrv:fundec) (fut:fundec) =
let oc = open_out_gen flags perm (ConfigFile.find Options.keyTestCaseFile) in
let testcaseFunc = emptyFunction (Printf.sprintf "%s_testcase_%d" fut.svar.vname id) in
testcaseFunc.svar.vtype <- TFun(voidType, Some[], false, []);
let mallocList = ref [] in
let freelist = ref [] in
testcaseFunc.slocals <- List.map(fun v -> v)testdrv.slocals;
let mkFreeStmt (l:lval) =
let thn =
mkBlock [mkStmtOneInstr (Call(None, freeExpr, [Lval(l)], locUnknown))]
in
let els = mkBlock [] in
let kind = If(Lval(l),thn,els,locUnknown) in
mkStmt kind
in
let assignValue (l:lval) (in_node:inputNode) =
let getMallocType () =
match unrollType (typeOfLval l) with
| TPtr(pt, _) -> pt
| _ -> typeOfLval l
in
match in_node with
| IntNode(_in) ->
(
let ikind = intKindForValue _in.ival (Utils.isUnsignedType (typeOfLval l)) in
[Set(l, (Const(CInt64(_in.ival,ikind,None))), locUnknown)]
)
| FloatNode(_fn) ->
(
let fkind =
match unrollType (typeOfLval l) with
| TFloat(fk,_) -> fk
| _ -> Log.error "Wrong float type for FloatNode\n"
in
[Set(l, (Const(CReal(_fn.fval,fkind,None))), locUnknown)]
)
| PointerNode(_pn) ->
if _pn.pointToNull then
[Set(l, (CastE(voidPtrType, Cil.zero)), locUnknown)]
else if _pn.targetNodeId = (-1) then (
let e = SizeOf(getMallocType ()) in
freelist := ((mkFreeStmt l)::!freelist);
mallocList := (!mallocList @ [Call(Some(l), mallocExpr, [e], locUnknown)]);
[]
) else (
if _pn.isPointerToArray then (
let e = BinOp(Mult, (integer _pn.firstArrayDim), SizeOf(getMallocType ()), uintType) in
freelist := ((mkFreeStmt l)::!freelist);
mallocList := (!mallocList @ [Call(Some(l), mallocExpr, [e], locUnknown)]);
[]
) else (
match (sol#tryFindNodeFromNodeId _pn.targetNodeId) with
| None -> Log.error (Printf.sprintf "Failed to find lval from %d\n" _pn.targetNodeId)
| Some(target) ->
if _pn.takesAddrOf then
[Set(l, (mkAddrOrStartOf target.cilLval), locUnknown)]
else
[Set(l, Lval(target.cilLval), locUnknown)]
)
)
in
let assignments = List.fold_left(
fun res node ->
addLvalLocalVars node.cilLval fut ;
(res @ (assignValue node.cilLval node.node))
)[] (sol#getInputList())
in
let futArgs = List.map(fun v -> Lval(var v))fut.sformals in
let hasReturn = ref false in
let eRetVal, callToFut =
match unrollType fut.svar.vtype with
| TFun(rt, _, _, _) ->
(
testcaseFunc.svar.vtype <- TFun(rt, Some[], false, []);
match (unrollTypeDeep rt) with
| TVoid _ ->
(Cil.zero, [Call(None, (Lval(var fut.svar)), futArgs, locUnknown)])
| _ ->
hasReturn := true;
let tmp = makeTempVar testcaseFunc rt in
(Lval(var tmp), [Call(Some((var tmp)), (Lval(var fut.svar)), futArgs, locUnknown)])
)
| _ ->
(Cil.zero, [Call(None, (Lval(var fut.svar)), futArgs, locUnknown)])
in
let body =
let p1 = (mkStmt (Instr((!mallocList @ assignments @ callToFut))))::(!freelist) in
if !hasReturn then
(p1 @ [(mkStmt (Return(Some(eRetVal), locUnknown)))])
else
p1
in
testcaseFunc.sbody <- (mkBlock body);
let glob = GFun(testcaseFunc, locUnknown) in
if not(added fut) then
output_string oc (fut_prototyp_toString fut);
output_string oc ("\r\n/* "^comment^" */\r\n");
output_string oc (Printf.sprintf "%s\r\n" (Pretty.sprint 255 (Cil.d_global () glob)));
close_out oc;
id | null | https://raw.githubusercontent.com/kiranlak/austin-sbst/9c8aac72692dca952302e0e4fdb9ff381bba58ae/AustinOcaml/testcases/testCaseWriter.ml | ocaml | Copyright : , University College London , 2011
open Cil
open Solution
let flags = [Open_creat;Open_append;Open_text]
let perm = 0o755
let protos : (string, bool) Hashtbl.t = Hashtbl.create 10
let added (f:fundec) =
Hashtbl.mem protos f.svar.vname
let mallocExpr =
let v = makeVarinfo false "malloc" (TFun(voidPtrType, Some["size", uintType, []], false, [])) in
Lval(var v)
let freeExpr =
let v = makeVarinfo false "free" (TFun(voidType, Some["size", voidPtrType, []], false, [])) in
Lval(var v)
let fut_prototyp_toString (f:fundec) =
Hashtbl.add protos f.svar.vname true;
Printf.sprintf "%s\n" (Pretty.sprint 255 (Cil.d_global() (GVarDecl(f.svar, locUnknown))))
let saveCandidateSolution (id:int) (sol : candidateSolution) (comment:string) (testdrv:fundec) (fut:fundec) =
let oc = open_out_gen flags perm (ConfigFile.find Options.keyTestCaseFile) in
let testcaseFunc = emptyFunction (Printf.sprintf "%s_testcase_%d" fut.svar.vname id) in
testcaseFunc.svar.vtype <- TFun(voidType, Some[], false, []);
let mallocList = ref [] in
let freelist = ref [] in
testcaseFunc.slocals <- List.map(fun v -> v)testdrv.slocals;
let mkFreeStmt (l:lval) =
let thn =
mkBlock [mkStmtOneInstr (Call(None, freeExpr, [Lval(l)], locUnknown))]
in
let els = mkBlock [] in
let kind = If(Lval(l),thn,els,locUnknown) in
mkStmt kind
in
let assignValue (l:lval) (in_node:inputNode) =
let getMallocType () =
match unrollType (typeOfLval l) with
| TPtr(pt, _) -> pt
| _ -> typeOfLval l
in
match in_node with
| IntNode(_in) ->
(
let ikind = intKindForValue _in.ival (Utils.isUnsignedType (typeOfLval l)) in
[Set(l, (Const(CInt64(_in.ival,ikind,None))), locUnknown)]
)
| FloatNode(_fn) ->
(
let fkind =
match unrollType (typeOfLval l) with
| TFloat(fk,_) -> fk
| _ -> Log.error "Wrong float type for FloatNode\n"
in
[Set(l, (Const(CReal(_fn.fval,fkind,None))), locUnknown)]
)
| PointerNode(_pn) ->
if _pn.pointToNull then
[Set(l, (CastE(voidPtrType, Cil.zero)), locUnknown)]
else if _pn.targetNodeId = (-1) then (
let e = SizeOf(getMallocType ()) in
freelist := ((mkFreeStmt l)::!freelist);
mallocList := (!mallocList @ [Call(Some(l), mallocExpr, [e], locUnknown)]);
[]
) else (
if _pn.isPointerToArray then (
let e = BinOp(Mult, (integer _pn.firstArrayDim), SizeOf(getMallocType ()), uintType) in
freelist := ((mkFreeStmt l)::!freelist);
mallocList := (!mallocList @ [Call(Some(l), mallocExpr, [e], locUnknown)]);
[]
) else (
match (sol#tryFindNodeFromNodeId _pn.targetNodeId) with
| None -> Log.error (Printf.sprintf "Failed to find lval from %d\n" _pn.targetNodeId)
| Some(target) ->
if _pn.takesAddrOf then
[Set(l, (mkAddrOrStartOf target.cilLval), locUnknown)]
else
[Set(l, Lval(target.cilLval), locUnknown)]
)
)
in
let assignments = List.fold_left(
fun res node ->
addLvalLocalVars node.cilLval fut ;
(res @ (assignValue node.cilLval node.node))
)[] (sol#getInputList())
in
let futArgs = List.map(fun v -> Lval(var v))fut.sformals in
let hasReturn = ref false in
let eRetVal, callToFut =
match unrollType fut.svar.vtype with
| TFun(rt, _, _, _) ->
(
testcaseFunc.svar.vtype <- TFun(rt, Some[], false, []);
match (unrollTypeDeep rt) with
| TVoid _ ->
(Cil.zero, [Call(None, (Lval(var fut.svar)), futArgs, locUnknown)])
| _ ->
hasReturn := true;
let tmp = makeTempVar testcaseFunc rt in
(Lval(var tmp), [Call(Some((var tmp)), (Lval(var fut.svar)), futArgs, locUnknown)])
)
| _ ->
(Cil.zero, [Call(None, (Lval(var fut.svar)), futArgs, locUnknown)])
in
let body =
let p1 = (mkStmt (Instr((!mallocList @ assignments @ callToFut))))::(!freelist) in
if !hasReturn then
(p1 @ [(mkStmt (Return(Some(eRetVal), locUnknown)))])
else
p1
in
testcaseFunc.sbody <- (mkBlock body);
let glob = GFun(testcaseFunc, locUnknown) in
if not(added fut) then
output_string oc (fut_prototyp_toString fut);
output_string oc ("\r\n/* "^comment^" */\r\n");
output_string oc (Printf.sprintf "%s\r\n" (Pretty.sprint 255 (Cil.d_global () glob)));
close_out oc;
id | |
7c8bccca1f46b8a260ba6b8f7689265a8b3eef9397af7658c990c9589bb38065 | TheRiver/CL-HEAP | priority-queue.lisp | Copyright 2009 - 2010 < >
;;;
This file is part of CL - HEAP
;;;
CL - HEAP is free software : you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;; (at your option) any later version.
;;;
CL - HEAP 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 CL - HEAP . If not , see < / > .
;;;----------------------------------------------------------------
(in-package #:cl-heap)
;;;----------------------------------------------------------------
(defclass priority-queue ()
((heap))
(:documentation "A simple priority queue implementaiton, based on a
Fibonacci heap."))
(defmethod initialize-instance :after ((queue priority-queue) &key (sort-fun #'<))
(with-slots (heap) queue
(setf heap (make-instance 'fibonacci-heap :key #'first :sort-fun sort-fun))))
;;;----------------------------------------------------------------
(declaim (inline enqueue))
(defgeneric enqueue (queue item priority)
(:documentation "Adds an item with a given priority on to the
queue. Returns a list containing first the priority, then the
item. This is a constant time operation.")
(:method ((queue priority-queue) item priority)
(with-slots (heap) queue
(values (add-to-heap heap (list priority item))))))
(declaim (inline dequeue))
(defgeneric dequeue (queue)
(:documentation "Removes an element from the front of the queue and
returns it. This is an amortised O(log(n)) operation.")
(:method (queue)
(with-slots (heap) queue
(second (pop-heap heap)))))
(declaim (inline peep-at-queue))
(defgeneric peep-at-queue (queue)
(:documentation "Returns the element at the front of the queue,
without modifying the queue. This is a constant time operation.")
(:method ((queue priority-queue))
(with-slots (heap) queue
(second (peep-at-heap heap)))))
(declaim (inline empty-queue))
(defgeneric empty-queue (queue)
(:documentation "Removes all items from the queue. This is a constant time operation.")
(:method ((queue priority-queue))
(with-slots (heap) queue
(empty-heap heap))))
(declaim (inline queue-size))
(defgeneric queue-size (queue)
(:documentation "Returns the number of elements in the queue.")
(:method ((queue priority-queue))
(with-slots (heap) queue
(heap-size heap)))) | null | https://raw.githubusercontent.com/TheRiver/CL-HEAP/e5796706c7db9302d7518241dd3baa8c018983b9/priority-queue.lisp | lisp |
(at your option) any later version.
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
----------------------------------------------------------------
----------------------------------------------------------------
---------------------------------------------------------------- | Copyright 2009 - 2010 < >
This file is part of CL - HEAP
CL - HEAP 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
CL - HEAP is distributed in the hope that it will be useful ,
You should have received a copy of the GNU General Public License
along with CL - HEAP . If not , see < / > .
(in-package #:cl-heap)
(defclass priority-queue ()
((heap))
(:documentation "A simple priority queue implementaiton, based on a
Fibonacci heap."))
(defmethod initialize-instance :after ((queue priority-queue) &key (sort-fun #'<))
(with-slots (heap) queue
(setf heap (make-instance 'fibonacci-heap :key #'first :sort-fun sort-fun))))
(declaim (inline enqueue))
(defgeneric enqueue (queue item priority)
(:documentation "Adds an item with a given priority on to the
queue. Returns a list containing first the priority, then the
item. This is a constant time operation.")
(:method ((queue priority-queue) item priority)
(with-slots (heap) queue
(values (add-to-heap heap (list priority item))))))
(declaim (inline dequeue))
(defgeneric dequeue (queue)
(:documentation "Removes an element from the front of the queue and
returns it. This is an amortised O(log(n)) operation.")
(:method (queue)
(with-slots (heap) queue
(second (pop-heap heap)))))
(declaim (inline peep-at-queue))
(defgeneric peep-at-queue (queue)
(:documentation "Returns the element at the front of the queue,
without modifying the queue. This is a constant time operation.")
(:method ((queue priority-queue))
(with-slots (heap) queue
(second (peep-at-heap heap)))))
(declaim (inline empty-queue))
(defgeneric empty-queue (queue)
(:documentation "Removes all items from the queue. This is a constant time operation.")
(:method ((queue priority-queue))
(with-slots (heap) queue
(empty-heap heap))))
(declaim (inline queue-size))
(defgeneric queue-size (queue)
(:documentation "Returns the number of elements in the queue.")
(:method ((queue priority-queue))
(with-slots (heap) queue
(heap-size heap)))) |
9fb9bf6f7090ad32667d59e8983d9ced332b0a53e455529533e1f367d8de1505 | argp/bap | lnf_reduced_havlak.ml | module D = Debug.Make(struct let name = "LnfReducedHavlak" and default=`NoDebug end)
open D
open Lnf
module UF(T: Hashtbl.HashedType) = struct
module H = Hashtbl.Make(T)
(*
* A ufnode is a Parent(rank) or a Child(parent).
*
* If it is a Parent, it is the representative element of the set
* that contains it. Otherwise, the representative element can be found by
* traversing the Child pointers. The rank is roughly the length of the
* longest possible path from any child to the representative element.
*)
type ufnode = Parent of int
| Child of T.t
let create n = H.create n
(* Adds v as the representative element of a set containing just itself. *)
let add h v = H.add h v (Parent 0)
let contains h v = H.mem h v
* Finds the representative element of the set containing v.
*
* Does path compression , so after a find h v , v points directly
* to the representative element .
*
* TODO(awreece ) Do n't require so many s by making
* ufnode = ... | Child of ufnode ?
* Finds the representative element of the set containing v.
*
* Does path compression, so after a find h v, v points directly
* to the representative element.
*
* TODO(awreece) Don't require so many H.find s by making
* ufnode = ... | Child of ufnode ?
*)
let rec find h v =
match H.find h v with
| Parent(_) -> v
| Child(parent) -> let new_parent = find h parent in
H.replace h v (Child new_parent); new_parent
(*
* Joins the set containing u with the set containing v.
*
* Does union by rank, so the resulting representative element will be the
* one with the larger rank.
*)
let union h u v =
(*
* A convenience method, finds the rank of a parent.
* Assumes v is the representative element of the set containing it.
*)
let getrank h v = match H.find h v with
| Parent(r) -> r
| _ -> assert false in
let pu = find h u in
let pv = find h v in
(* If they are already in the same set, do nothing. *)
if T.equal pu pv then ()
else let ur = getrank h pu in
let vr = getrank h pv in
(* Otherwise, reparent the one with a lower rank. *)
if (ur < vr) then H.replace h pu (Child pv)
else if (ur > vr) then H.replace h pv (Child pu)
* If both have the same rank , increment one of the ranks and
* reparent the other
* If both have the same rank, increment one of the ranks and
* reparent the other
*)
else (H.replace h pu (Parent (ur+1)); H.replace h pv (Child pu))
let iter h f v =
let rep = find h v in
H.iter (fun k _ -> if T.equal (find h k) rep then f k else ()) h
let mem h v = H.mem h v
end
module Make(C: G) =
struct
module VH = Hashtbl.Make(C.G.V)
module VS = Set.Make(C.G.V)
module VUF = UF(C.G.V)
module Dom = Dominator.Make(C.G)
module Dfs = Graph.Traverse.Dfs(C.G)
type dfs_edge = Tree | Forward | Back | Cross
Get loop information from Havlakcs loop forest
let lnf cfg v0 =
let cfg = ref cfg in
let loop_parent = VH.create (C.G.nb_vertex !cfg) in
let loopTree = VUF.create (C.G.nb_vertex !cfg) in
let mergedLoops = VUF.create (C.G.nb_vertex !cfg) in
let crossFwdEdges = VH.create (C.G.nb_vertex !cfg) in
let dfs_parent = VH.create (C.G.nb_vertex !cfg) in
let rev_dfs_order = ref [] in
let prev = Stack.create () in
let () = Stack.push v0 prev in
let () = Dfs.iter_component ~pre:(fun v ->
rev_dfs_order := v::!rev_dfs_order;
VH.add dfs_parent v (Stack.top prev);
VH.add crossFwdEdges v [];
VUF.add loopTree v;
Stack.push v prev
)
~post:(fun v ->
ignore (Stack.pop prev);
)
!cfg v0 in
let () = VH.remove dfs_parent v0 in
let classify_edge u v =
let rec is_ancestor u v =
if C.G.V.equal u v then true
else if VH.mem dfs_parent v then is_ancestor u (VH.find dfs_parent v)
else false in
The entry node has indegree 0 , so everything else has a dfs parent .
if C.G.V.equal u (VH.find dfs_parent v) then Tree
else if is_ancestor u v then Forward
else if is_ancestor v u then Back
else Cross in
let collapse loopBody loopHeader =
List.iter (fun z -> VH.replace loop_parent z loopHeader;
VUF.union loopTree loopHeader z
) loopBody in
let findloop potentialHeader =
worklist =
* { LoopTree.find ( y ) | y → potentialHeader is a backedge }
* - { potentialHeader } ;
* {LoopTree.find( y ) | y → potentialHeader is a backedge}
* - {potentialHeader};
*)
let workList = Queue.create () in
(* TODO(awreece) Do we have to recompute here? We *do* modify the graph. *)
let dom = (Dom.compute_all !cfg v0).Dom.dom in
let () = C.G.iter_pred (fun y ->
If y - > potentialHeader is a backedge .
then
let ltfy = VUF.find loopTree y in
if not (C.G.V.equal ltfy potentialHeader)
then Queue.push ltfy workList
else ()
else ()
) !cfg potentialHeader in
let loopBody = ref [] in
while not (Queue.is_empty workList) do
let y = Queue.pop workList in
let () = loopBody := y::!loopBody in
C.G.iter_pred (fun z ->
let ltfz = VUF.find loopTree z in
if not (List.exists (C.G.V.equal ltfz) !loopBody) &&
not (C.G.V.equal ltfz potentialHeader) &&
not (Queue.fold (fun p v -> p || (C.G.V.equal ltfz v)) false workList)
then Queue.push ltfz workList
else ()
) !cfg y
done;
if not (BatList.is_empty !loopBody)
then (collapse !loopBody potentialHeader;
VUF.add mergedLoops potentialHeader)
else () in
let mergeLoopsWithEntryVertex z =
let bt = ref (if VUF.contains mergedLoops z
then VUF.find mergedLoops z
else z) in
while VH.mem loop_parent !bt do
let t = VH.find loop_parent !bt in
let u = VUF.find mergedLoops t in
let () = bt := u in
if VH.mem loop_parent !bt
then VUF.union mergedLoops u (VH.find loop_parent !bt)
else ()
done in
let processCrossFwdEdges x =
List.iter (fun (y,z) ->
TODO(awreece ) Oh god , which UF do we use ? I think loopTree ...
cfg := C.add_edge !cfg (VUF.find loopTree y) (VUF.find loopTree z);
mergeLoopsWithEntryVertex z
) (VH.find crossFwdEdges x) in
let lca x y =
let rec add_all stack node =
if VH.mem dfs_parent node
then (Stack.push node stack; add_all stack (VH.find dfs_parent node))
else () in
let rec findFirstDifferent stack1 stack2 oldNode =
if Stack.is_empty stack1 || Stack.is_empty stack2
then oldNode
else let node1 = Stack.pop stack1 in
let node2 = Stack.pop stack2 in
if C.G.V.equal node1 node2
then findFirstDifferent stack1 stack2 node1
else oldNode in
let parentX = Stack.create () in
let parentY = Stack.create () in
let () = add_all parentX x in
let () = add_all parentY y in
findFirstDifferent parentX parentY v0 in
let constructReducedHavlakForest () =
let () = C.G.iter_edges (fun y x ->
match classify_edge y x with
| Cross | Forward ->
let ancestor = lca y x in
let newList = (y,x)::(VH.find crossFwdEdges ancestor) in
let () = cfg := C.remove_edge !cfg y x in
VH.replace crossFwdEdges ancestor newList
| _ -> ()
) !cfg in
List.iter (fun x ->
processCrossFwdEdges x;
findloop x
) !rev_dfs_order in
let makeExplicitRepresentation () =
let lnfNodes = VH.create (C.G.nb_vertex !cfg) in
let topLevelLoops = ref VS.empty in
let repToChildren = VH.create (C.G.nb_vertex !cfg) in
let getLnfNode repHeader = if VH.mem lnfNodes repHeader
then VH.find lnfNodes repHeader
else {headers=[]; body=[]; children=[]} in
let getChildren node = if VH.mem repToChildren node
then VH.find repToChildren node
else [] in
let process_vertex v =
if VUF.mem mergedLoops v (* If v is the header of some loop. *)
then let rep = VUF.find mergedLoops v in
let () = if VH.mem loop_parent rep
then let parent = VH.find loop_parent rep in
VH.replace repToChildren parent (rep::(getChildren parent))
else topLevelLoops := VS.add rep !topLevelLoops in
let pnode = getLnfNode rep in
VH.replace lnfNodes rep {pnode with
headers=v::pnode.headers;
body=v::pnode.body}
else let parent = VH.find loop_parent v in
let pnode = getLnfNode parent in
VH.replace lnfNodes parent {pnode with body=v::pnode.body} in
let rec cleanLnfNode v =
let node = VH.find lnfNodes v in
let children = VH.find repToChildren v in
let children_nodes = List.map cleanLnfNode children in
{headers=(List.sort compare node.headers);
body=(List.sort compare node.body);
children=(List.sort compare children_nodes)} in
let () = List.iter process_vertex !rev_dfs_order in
List.sort compare (List.map cleanLnfNode (VS.elements !topLevelLoops)) in
let () = constructReducedHavlakForest () in
makeExplicitRepresentation ()
end
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/ocaml/lnf_reduced_havlak.ml | ocaml |
* A ufnode is a Parent(rank) or a Child(parent).
*
* If it is a Parent, it is the representative element of the set
* that contains it. Otherwise, the representative element can be found by
* traversing the Child pointers. The rank is roughly the length of the
* longest possible path from any child to the representative element.
Adds v as the representative element of a set containing just itself.
* Joins the set containing u with the set containing v.
*
* Does union by rank, so the resulting representative element will be the
* one with the larger rank.
* A convenience method, finds the rank of a parent.
* Assumes v is the representative element of the set containing it.
If they are already in the same set, do nothing.
Otherwise, reparent the one with a lower rank.
TODO(awreece) Do we have to recompute here? We *do* modify the graph.
If v is the header of some loop. | module D = Debug.Make(struct let name = "LnfReducedHavlak" and default=`NoDebug end)
open D
open Lnf
module UF(T: Hashtbl.HashedType) = struct
module H = Hashtbl.Make(T)
type ufnode = Parent of int
| Child of T.t
let create n = H.create n
let add h v = H.add h v (Parent 0)
let contains h v = H.mem h v
* Finds the representative element of the set containing v.
*
* Does path compression , so after a find h v , v points directly
* to the representative element .
*
* TODO(awreece ) Do n't require so many s by making
* ufnode = ... | Child of ufnode ?
* Finds the representative element of the set containing v.
*
* Does path compression, so after a find h v, v points directly
* to the representative element.
*
* TODO(awreece) Don't require so many H.find s by making
* ufnode = ... | Child of ufnode ?
*)
let rec find h v =
match H.find h v with
| Parent(_) -> v
| Child(parent) -> let new_parent = find h parent in
H.replace h v (Child new_parent); new_parent
let union h u v =
let getrank h v = match H.find h v with
| Parent(r) -> r
| _ -> assert false in
let pu = find h u in
let pv = find h v in
if T.equal pu pv then ()
else let ur = getrank h pu in
let vr = getrank h pv in
if (ur < vr) then H.replace h pu (Child pv)
else if (ur > vr) then H.replace h pv (Child pu)
* If both have the same rank , increment one of the ranks and
* reparent the other
* If both have the same rank, increment one of the ranks and
* reparent the other
*)
else (H.replace h pu (Parent (ur+1)); H.replace h pv (Child pu))
let iter h f v =
let rep = find h v in
H.iter (fun k _ -> if T.equal (find h k) rep then f k else ()) h
let mem h v = H.mem h v
end
module Make(C: G) =
struct
module VH = Hashtbl.Make(C.G.V)
module VS = Set.Make(C.G.V)
module VUF = UF(C.G.V)
module Dom = Dominator.Make(C.G)
module Dfs = Graph.Traverse.Dfs(C.G)
type dfs_edge = Tree | Forward | Back | Cross
Get loop information from Havlakcs loop forest
let lnf cfg v0 =
let cfg = ref cfg in
let loop_parent = VH.create (C.G.nb_vertex !cfg) in
let loopTree = VUF.create (C.G.nb_vertex !cfg) in
let mergedLoops = VUF.create (C.G.nb_vertex !cfg) in
let crossFwdEdges = VH.create (C.G.nb_vertex !cfg) in
let dfs_parent = VH.create (C.G.nb_vertex !cfg) in
let rev_dfs_order = ref [] in
let prev = Stack.create () in
let () = Stack.push v0 prev in
let () = Dfs.iter_component ~pre:(fun v ->
rev_dfs_order := v::!rev_dfs_order;
VH.add dfs_parent v (Stack.top prev);
VH.add crossFwdEdges v [];
VUF.add loopTree v;
Stack.push v prev
)
~post:(fun v ->
ignore (Stack.pop prev);
)
!cfg v0 in
let () = VH.remove dfs_parent v0 in
let classify_edge u v =
let rec is_ancestor u v =
if C.G.V.equal u v then true
else if VH.mem dfs_parent v then is_ancestor u (VH.find dfs_parent v)
else false in
The entry node has indegree 0 , so everything else has a dfs parent .
if C.G.V.equal u (VH.find dfs_parent v) then Tree
else if is_ancestor u v then Forward
else if is_ancestor v u then Back
else Cross in
let collapse loopBody loopHeader =
List.iter (fun z -> VH.replace loop_parent z loopHeader;
VUF.union loopTree loopHeader z
) loopBody in
let findloop potentialHeader =
worklist =
* { LoopTree.find ( y ) | y → potentialHeader is a backedge }
* - { potentialHeader } ;
* {LoopTree.find( y ) | y → potentialHeader is a backedge}
* - {potentialHeader};
*)
let workList = Queue.create () in
let dom = (Dom.compute_all !cfg v0).Dom.dom in
let () = C.G.iter_pred (fun y ->
If y - > potentialHeader is a backedge .
then
let ltfy = VUF.find loopTree y in
if not (C.G.V.equal ltfy potentialHeader)
then Queue.push ltfy workList
else ()
else ()
) !cfg potentialHeader in
let loopBody = ref [] in
while not (Queue.is_empty workList) do
let y = Queue.pop workList in
let () = loopBody := y::!loopBody in
C.G.iter_pred (fun z ->
let ltfz = VUF.find loopTree z in
if not (List.exists (C.G.V.equal ltfz) !loopBody) &&
not (C.G.V.equal ltfz potentialHeader) &&
not (Queue.fold (fun p v -> p || (C.G.V.equal ltfz v)) false workList)
then Queue.push ltfz workList
else ()
) !cfg y
done;
if not (BatList.is_empty !loopBody)
then (collapse !loopBody potentialHeader;
VUF.add mergedLoops potentialHeader)
else () in
let mergeLoopsWithEntryVertex z =
let bt = ref (if VUF.contains mergedLoops z
then VUF.find mergedLoops z
else z) in
while VH.mem loop_parent !bt do
let t = VH.find loop_parent !bt in
let u = VUF.find mergedLoops t in
let () = bt := u in
if VH.mem loop_parent !bt
then VUF.union mergedLoops u (VH.find loop_parent !bt)
else ()
done in
let processCrossFwdEdges x =
List.iter (fun (y,z) ->
TODO(awreece ) Oh god , which UF do we use ? I think loopTree ...
cfg := C.add_edge !cfg (VUF.find loopTree y) (VUF.find loopTree z);
mergeLoopsWithEntryVertex z
) (VH.find crossFwdEdges x) in
let lca x y =
let rec add_all stack node =
if VH.mem dfs_parent node
then (Stack.push node stack; add_all stack (VH.find dfs_parent node))
else () in
let rec findFirstDifferent stack1 stack2 oldNode =
if Stack.is_empty stack1 || Stack.is_empty stack2
then oldNode
else let node1 = Stack.pop stack1 in
let node2 = Stack.pop stack2 in
if C.G.V.equal node1 node2
then findFirstDifferent stack1 stack2 node1
else oldNode in
let parentX = Stack.create () in
let parentY = Stack.create () in
let () = add_all parentX x in
let () = add_all parentY y in
findFirstDifferent parentX parentY v0 in
let constructReducedHavlakForest () =
let () = C.G.iter_edges (fun y x ->
match classify_edge y x with
| Cross | Forward ->
let ancestor = lca y x in
let newList = (y,x)::(VH.find crossFwdEdges ancestor) in
let () = cfg := C.remove_edge !cfg y x in
VH.replace crossFwdEdges ancestor newList
| _ -> ()
) !cfg in
List.iter (fun x ->
processCrossFwdEdges x;
findloop x
) !rev_dfs_order in
let makeExplicitRepresentation () =
let lnfNodes = VH.create (C.G.nb_vertex !cfg) in
let topLevelLoops = ref VS.empty in
let repToChildren = VH.create (C.G.nb_vertex !cfg) in
let getLnfNode repHeader = if VH.mem lnfNodes repHeader
then VH.find lnfNodes repHeader
else {headers=[]; body=[]; children=[]} in
let getChildren node = if VH.mem repToChildren node
then VH.find repToChildren node
else [] in
let process_vertex v =
then let rep = VUF.find mergedLoops v in
let () = if VH.mem loop_parent rep
then let parent = VH.find loop_parent rep in
VH.replace repToChildren parent (rep::(getChildren parent))
else topLevelLoops := VS.add rep !topLevelLoops in
let pnode = getLnfNode rep in
VH.replace lnfNodes rep {pnode with
headers=v::pnode.headers;
body=v::pnode.body}
else let parent = VH.find loop_parent v in
let pnode = getLnfNode parent in
VH.replace lnfNodes parent {pnode with body=v::pnode.body} in
let rec cleanLnfNode v =
let node = VH.find lnfNodes v in
let children = VH.find repToChildren v in
let children_nodes = List.map cleanLnfNode children in
{headers=(List.sort compare node.headers);
body=(List.sort compare node.body);
children=(List.sort compare children_nodes)} in
let () = List.iter process_vertex !rev_dfs_order in
List.sort compare (List.map cleanLnfNode (VS.elements !topLevelLoops)) in
let () = constructReducedHavlakForest () in
makeExplicitRepresentation ()
end
|
eb34ba8773d6b3780135967afd57f4ccc1d8c792a2334d2b4145cee2b59d0c98 | practicalli/practicalli.github.io | books.cljs | (ns practicalli.books)
(def practicalli-books
[{:title "Practicalli Spacemacs"
:url ""
:image "-design/live/book-covers/practicalli-spacemacs-book-banner.png"
:github-repo "spacemacs"
:description " - powerful editing with Emacs and Vim multi-modal editing, with a mnemonic menu that simplifies the learning curve. Install a full Clojure development experience with two Git commands."
:status :established}
{:title "Practicalli Neovim"
:url ""
:image "-design/live/book-covers/practicalli-neovim-book-banner.png"
:github-repo "neovim"
:description " - Neovim for effective Clojure development with Conjure and Clojure LSP (nvim-treesitter). With a mnemonic menu to simplify the learning curve."
:status :new}
{:title "Practicalli Clojure"
:url ""
:image "-design/live/book-covers/practicalli-clojure-book-banner-light.png"
:github-repo "clojure"
:description " - learn the Clojure language through REPL driven development using Clojure CLI tools (deps.edn). Use a rich set of community tools, including Rebel readline Terminal UI, Portal and Reveal data browsers and tools to manage all aspects of Clojure projects. Practice Clojure by solving challenges with examples of different approaches. Encode the design and avoid regressions by writing unit tests and specifications for generative testing."
:status :rewrite}
{:title "Clojure Web Services"
:url "-web-services"
:image "-design/live/book-covers/practicalli-clojure-web-service-book-banner-light.png"
:github-repo "clojure-web-services"
:description " - build production level server-side web services, micro-services and API's in Clojure. Using Ring as an abstraction over HTTP with requests and responses as simple Clojure hash-maps. Routing of requests are managed by Compojure or Reitit, passing requests to handers which are Clojure functions. Data formats are managed by coercion and content negotiation. OpenAPI (swagger) is used for self-documenting APIs"
:status :rewrite}
{:title "Practicalli ClojureScript"
:url ""
:image "-design/live/book-covers/practicalli-clojurescript-book-banner-alpha.png"
:github-repo "clojurescript"
:description " - build single page apps (SPA's), dynamic UI's and mobile apps with responsive design. Figwheel-main provides instant feedback during development, pushing changes to the browser as they are saved. Reagent library is an interface to React, driving UI components (functions) with immutable Clojure data structures."
:status :alpha}
{:title "Practicalli Clojure Data Science"
:url "-data-science"
:image "-design/live/book-covers/practicalli-clojure-data-science-book-banner-alpha.png"
:github-repo "clojure-data-science"
:description " - discover Clojure tools and techniques when working with data science related projects. Ingest data from various sources into Clojure data structures. Transform Clojure data structures using fast and efficient community libraries. Visualise data to communicate meaning from data sets"
:status :alpha}
{:title "Practicalli Clojure with Kafka"
:url "-kafka"
:image "-design/live/book-covers/practicalli-clojure-kafka-book-banner-alpha.png"
:github-repo "clojure-kafka"
:description " - use Clojure with Apache Kafka to build immutable event stream services. Define specifications to validate data consumed and produced to Kafka topics. Use Jackdaw library to control Kafka and write Kafka Stream applications"
:status :alpha}
{:title "Practicalli Engineering Playbook"
:url "-playbook"
:image "-design/live/book-covers/practicalli-neovim-book-banner.png"
:github-repo "engineering-playbook"
:description "Specific guides to common engineering tasks, including architecture, build tools, code quality, documentation and version control"
:status :alpha}
{:title "Practicalli VSpaceCode"
:url ""
:image "-design/live/book-covers/practicalli-neovim-book-banner.png"
:github-repo "vspacecode"
:description "Install and Clojure development workflow with VSpaceCode and Calva, proving a full keyboard driven experience to REPL driven development"
:status :alpha}
{:title "Practicalli Doom Emacs"
:url "-emacs"
:image "-design/live/book-covers/practicalli-neovim-book-banner.png"
:github-repo "doom-emacs"
:description "Install and Clojure development workflow with Doom Emacs and CIDER"
:status :alpha}
{:title "Practicalli Amazon Web Services"
:url "-web-services/"
:image ""
:github-repo "amazon-web-services"
:description "Clojure development with Amazon Web Services"
:status :alpha}
#_{:title ""
:url ""
:image ""
:github-repo ""
:status :alpha
:description ""}])
(defn generator-book-list
[books]
(for [{:keys [title description url image github-repo]} books]
[:div {:class "column"}
[:div {:class "box"}
[:div {:class "columns"}
;; Book banner logo
[:div {:class "column"}
[:a {:href url :target "_blank"}
[:figure {:class "image"}
[:img {:src image}]]]]
;; Book description
[:div {:class "column"}
[:p [:a {:href url :target "_blank" :class "has-text-weight-bold"}
title]
description]
[:p {:class "has-text-centered"}
[:a {:href (str "/" github-repo "/commits")
:target "_blank"}
[:img {:src
(str "-activity/y/practicalli/" github-repo "?style=for-the-badge")
:alt "Monthly commits on GitHub"}]]
[:a {:href (str "/" github-repo "/issues")
:target "_blank"}
[:img {:src (str "/" github-repo "?style=for-the-badge&color=purple&label=content%20ideas")
:alt "Content ideas as GitHub issues"}]]
[:a {:href (str "/" github-repo "/pulls")
:target "_blank"}
[:img {:src
(str "-pr/practicalli/" github-repo "?style=for-the-badge&color=yellow&label=pull%20requests")
:alt "Content ideas as GitHub issues"}]]]]]]]))
(defn generator-alpha-book-list
[books]
(for [{:keys [title description url github-repo]} books]
[:div {:class "column is-4"}
[:div {:class "box"}
;; Book banner logo
#_[:div {:class "column"}
[:a {:href url :target "_blank"}
[:figure {:class "image"}
[:img {:src image}]]]]
;; Book description
[:h3 {:class "title is-4 has-text-centered"}
[:a {:href url :target "_blank" :class "has-text-weight-bold"}
title]]
[:p
(if (< 102 (count description))
(str (subs description 0 99) "...")
description)]
[:a {:href (str "/" github-repo "/commits")
:target "_blank"}
[:img {:src
(str "-activity/y/practicalli/" github-repo "?style=for-the-badge")
:alt "Monthly commits on GitHub"}]]
[:a {:href (str "/" github-repo "/issues")
:target "_blank"}
[:img {:src (str "/" github-repo "?style=for-the-badge&color=purple&label=content%20ideas")
:alt "Content ideas as GitHub issues"}]]
[:a {:href (str "/" github-repo "/pulls")
:target "_blank"}
[:img {:src
(str "-pr/practicalli/" github-repo "?style=for-the-badge&color=yellow&label=pull%20requests")
:alt "Content ideas as GitHub issues"}]]]]))
(defn book-list
[books]
(let [released-books (remove #(= :alpha (:status %)) books)
alpha-books (filter #(= :alpha (:status %)) books)]
[:div {:class "container"}
[:div {:class "box"}
;; Section Title
[:div {:class "column"}
[:h2 {:class "title has-text-centered"}
"Freely available online books"]]
(generator-book-list released-books)
[:div {:class "column"}
[:h2 {:class "title has-text-centered"}
"Books under development"]]
[:div {:class "columns is-multiline"}
(generator-alpha-book-list alpha-books)]]]))
| null | https://raw.githubusercontent.com/practicalli/practicalli.github.io/9ca8a5aef1e5e5015e359ea933eefc43a21514ac/src/practicalli/books.cljs | clojure | Book banner logo
Book description
Book banner logo
Book description
Section Title | (ns practicalli.books)
(def practicalli-books
[{:title "Practicalli Spacemacs"
:url ""
:image "-design/live/book-covers/practicalli-spacemacs-book-banner.png"
:github-repo "spacemacs"
:description " - powerful editing with Emacs and Vim multi-modal editing, with a mnemonic menu that simplifies the learning curve. Install a full Clojure development experience with two Git commands."
:status :established}
{:title "Practicalli Neovim"
:url ""
:image "-design/live/book-covers/practicalli-neovim-book-banner.png"
:github-repo "neovim"
:description " - Neovim for effective Clojure development with Conjure and Clojure LSP (nvim-treesitter). With a mnemonic menu to simplify the learning curve."
:status :new}
{:title "Practicalli Clojure"
:url ""
:image "-design/live/book-covers/practicalli-clojure-book-banner-light.png"
:github-repo "clojure"
:description " - learn the Clojure language through REPL driven development using Clojure CLI tools (deps.edn). Use a rich set of community tools, including Rebel readline Terminal UI, Portal and Reveal data browsers and tools to manage all aspects of Clojure projects. Practice Clojure by solving challenges with examples of different approaches. Encode the design and avoid regressions by writing unit tests and specifications for generative testing."
:status :rewrite}
{:title "Clojure Web Services"
:url "-web-services"
:image "-design/live/book-covers/practicalli-clojure-web-service-book-banner-light.png"
:github-repo "clojure-web-services"
:description " - build production level server-side web services, micro-services and API's in Clojure. Using Ring as an abstraction over HTTP with requests and responses as simple Clojure hash-maps. Routing of requests are managed by Compojure or Reitit, passing requests to handers which are Clojure functions. Data formats are managed by coercion and content negotiation. OpenAPI (swagger) is used for self-documenting APIs"
:status :rewrite}
{:title "Practicalli ClojureScript"
:url ""
:image "-design/live/book-covers/practicalli-clojurescript-book-banner-alpha.png"
:github-repo "clojurescript"
:description " - build single page apps (SPA's), dynamic UI's and mobile apps with responsive design. Figwheel-main provides instant feedback during development, pushing changes to the browser as they are saved. Reagent library is an interface to React, driving UI components (functions) with immutable Clojure data structures."
:status :alpha}
{:title "Practicalli Clojure Data Science"
:url "-data-science"
:image "-design/live/book-covers/practicalli-clojure-data-science-book-banner-alpha.png"
:github-repo "clojure-data-science"
:description " - discover Clojure tools and techniques when working with data science related projects. Ingest data from various sources into Clojure data structures. Transform Clojure data structures using fast and efficient community libraries. Visualise data to communicate meaning from data sets"
:status :alpha}
{:title "Practicalli Clojure with Kafka"
:url "-kafka"
:image "-design/live/book-covers/practicalli-clojure-kafka-book-banner-alpha.png"
:github-repo "clojure-kafka"
:description " - use Clojure with Apache Kafka to build immutable event stream services. Define specifications to validate data consumed and produced to Kafka topics. Use Jackdaw library to control Kafka and write Kafka Stream applications"
:status :alpha}
{:title "Practicalli Engineering Playbook"
:url "-playbook"
:image "-design/live/book-covers/practicalli-neovim-book-banner.png"
:github-repo "engineering-playbook"
:description "Specific guides to common engineering tasks, including architecture, build tools, code quality, documentation and version control"
:status :alpha}
{:title "Practicalli VSpaceCode"
:url ""
:image "-design/live/book-covers/practicalli-neovim-book-banner.png"
:github-repo "vspacecode"
:description "Install and Clojure development workflow with VSpaceCode and Calva, proving a full keyboard driven experience to REPL driven development"
:status :alpha}
{:title "Practicalli Doom Emacs"
:url "-emacs"
:image "-design/live/book-covers/practicalli-neovim-book-banner.png"
:github-repo "doom-emacs"
:description "Install and Clojure development workflow with Doom Emacs and CIDER"
:status :alpha}
{:title "Practicalli Amazon Web Services"
:url "-web-services/"
:image ""
:github-repo "amazon-web-services"
:description "Clojure development with Amazon Web Services"
:status :alpha}
#_{:title ""
:url ""
:image ""
:github-repo ""
:status :alpha
:description ""}])
(defn generator-book-list
[books]
(for [{:keys [title description url image github-repo]} books]
[:div {:class "column"}
[:div {:class "box"}
[:div {:class "columns"}
[:div {:class "column"}
[:a {:href url :target "_blank"}
[:figure {:class "image"}
[:img {:src image}]]]]
[:div {:class "column"}
[:p [:a {:href url :target "_blank" :class "has-text-weight-bold"}
title]
description]
[:p {:class "has-text-centered"}
[:a {:href (str "/" github-repo "/commits")
:target "_blank"}
[:img {:src
(str "-activity/y/practicalli/" github-repo "?style=for-the-badge")
:alt "Monthly commits on GitHub"}]]
[:a {:href (str "/" github-repo "/issues")
:target "_blank"}
[:img {:src (str "/" github-repo "?style=for-the-badge&color=purple&label=content%20ideas")
:alt "Content ideas as GitHub issues"}]]
[:a {:href (str "/" github-repo "/pulls")
:target "_blank"}
[:img {:src
(str "-pr/practicalli/" github-repo "?style=for-the-badge&color=yellow&label=pull%20requests")
:alt "Content ideas as GitHub issues"}]]]]]]]))
(defn generator-alpha-book-list
[books]
(for [{:keys [title description url github-repo]} books]
[:div {:class "column is-4"}
[:div {:class "box"}
#_[:div {:class "column"}
[:a {:href url :target "_blank"}
[:figure {:class "image"}
[:img {:src image}]]]]
[:h3 {:class "title is-4 has-text-centered"}
[:a {:href url :target "_blank" :class "has-text-weight-bold"}
title]]
[:p
(if (< 102 (count description))
(str (subs description 0 99) "...")
description)]
[:a {:href (str "/" github-repo "/commits")
:target "_blank"}
[:img {:src
(str "-activity/y/practicalli/" github-repo "?style=for-the-badge")
:alt "Monthly commits on GitHub"}]]
[:a {:href (str "/" github-repo "/issues")
:target "_blank"}
[:img {:src (str "/" github-repo "?style=for-the-badge&color=purple&label=content%20ideas")
:alt "Content ideas as GitHub issues"}]]
[:a {:href (str "/" github-repo "/pulls")
:target "_blank"}
[:img {:src
(str "-pr/practicalli/" github-repo "?style=for-the-badge&color=yellow&label=pull%20requests")
:alt "Content ideas as GitHub issues"}]]]]))
(defn book-list
[books]
(let [released-books (remove #(= :alpha (:status %)) books)
alpha-books (filter #(= :alpha (:status %)) books)]
[:div {:class "container"}
[:div {:class "box"}
[:div {:class "column"}
[:h2 {:class "title has-text-centered"}
"Freely available online books"]]
(generator-book-list released-books)
[:div {:class "column"}
[:h2 {:class "title has-text-centered"}
"Books under development"]]
[:div {:class "columns is-multiline"}
(generator-alpha-book-list alpha-books)]]]))
|
11c287ae3fa39b98830afdb3aff9745852c50cf8dde001d75804303ab8ab3bc5 | syntax-objects/syntax-parse-example | make-variable-test.rkt | #lang racket/base
(module+ test
(require rackunit syntax-parse-example/make-variable/make-variable)
(test-case "make-variable"
(check-equal?
(make-variable "this_variable_will_probably_change")
"this_variable_will_probably_change=\"this_variable_will_probably_change\"")
(define Z "Zzz...")
(check-equal? (make-variable Z) "Z=\"Zzz...\""))
)
| null | https://raw.githubusercontent.com/syntax-objects/syntax-parse-example/0675ce0717369afcde284202ec7df661d7af35aa/make-variable/make-variable-test.rkt | racket | #lang racket/base
(module+ test
(require rackunit syntax-parse-example/make-variable/make-variable)
(test-case "make-variable"
(check-equal?
(make-variable "this_variable_will_probably_change")
"this_variable_will_probably_change=\"this_variable_will_probably_change\"")
(define Z "Zzz...")
(check-equal? (make-variable Z) "Z=\"Zzz...\""))
)
| |
a1af9e5e186575a852e7d8708eac756529d69922f138a17168e42d3aa114fb55 | hipsleek/hipsleek | dataflow.ml |
module IH = Inthash
module E = Errormsg
open Cil
open Pretty
(** A framework for data flow analysis for CIL code. Before using
this framework, you must initialize the Control-flow Graph for your
program, e.g using {!Cfg.computeFileCFG} *)
type 't action =
Default (** The default action *)
| Done of 't (** Do not do the default action. Use this result *)
| Post of ('t -> 't) (** The default action, followed by the given
* transformer *)
type 't stmtaction =
SDefault (** The default action *)
| SDone (** Do not visit this statement or its successors *)
* Visit the instructions and successors of this statement
as usual , but use the specified state instead of the
one that was passed to doStmt
as usual, but use the specified state instead of the
one that was passed to doStmt *)
(* For if statements *)
type 't guardaction =
GDefault (** The default state *)
| GUse of 't (** Use this data for the branch *)
| GUnreachable (** The branch will never be taken. *)
(******************************************************************
**********
********** FORWARDS
**********
********************************************************************)
module type ForwardsTransfer = sig
val name: string (** For debugging purposes, the name of the analysis *)
val debug: bool ref (** Whether to turn on debugging *)
* The type of the data we compute for each block start . May be
* imperative .
* imperative. *)
val copy: t -> t
(** Make a deep copy of the data *)
val stmtStartData: t Inthash.t
(** For each statement id, the data at the start. Not found in the hash
* table means nothing is known about the state at this point. At the end
* of the analysis this means that the block is not reachable. *)
val pretty: unit -> t -> Pretty.doc
(** Pretty-print the state *)
val computeFirstPredecessor: Cil.stmt -> t -> t
* Give the first value for a predecessors , compute the value to be set
* for the block
* for the block *)
val combinePredecessors: Cil.stmt -> old:t -> t -> t option
(** Take some old data for the start of a statement, and some new data for
* the same point. Return None if the combination is identical to the old
* data. Otherwise, compute the combination, and return it. *)
val doInstr: Cil.instr -> t -> t action
* The ( forwards ) transfer function for an instruction . The
* { ! } is set before calling this . The default action is to
* continue with the state unchanged .
* {!Cil.currentLoc} is set before calling this. The default action is to
* continue with the state unchanged. *)
val doStmt: Cil.stmt -> t -> t stmtaction
(** The (forwards) transfer function for a statement. The {!Cil.currentLoc}
* is set before calling this. The default action is to do the instructions
* in this statement, if applicable, and continue with the successors. *)
val doGuard: Cil.exp -> t -> t guardaction
* Generate the successor to an If statement assuming the given expression
* is nonzero . Analyses that do n't need guard information can return
* GDefault ; this is equivalent to returning of the input .
* A return value of indicates that this half of the branch
* will not be taken and should not be explored . This will be called
* twice per If , once for " then " and once for " else " .
* is nonzero. Analyses that don't need guard information can return
* GDefault; this is equivalent to returning GUse of the input.
* A return value of GUnreachable indicates that this half of the branch
* will not be taken and should not be explored. This will be called
* twice per If, once for "then" and once for "else".
*)
val filterStmt: Cil.stmt -> bool
(** Whether to put this statement in the worklist. This is called when a
* block would normally be put in the worklist. *)
end
module ForwardsDataFlow =
functor (T : ForwardsTransfer) ->
struct
(** Keep a worklist of statements to process. It is best to keep a queue,
* because this way it is more likely that we are going to process all
* predecessors of a statement before the statement itself. *)
let worklist: Cil.stmt Queue.t = Queue.create ()
(** We call this function when we have encountered a statement, with some
* state. *)
let reachedStatement (s: stmt) (d: T.t) : unit =
let loc = get_stmtLoc s.skind in
if loc != locUnknown then
currentLoc := get_stmtLoc s.skind;
(** see if we know about it already *)
E.pushContext (fun _ -> dprintf "Reached statement %d with %a"
s.sid T.pretty d);
let newdata: T.t option =
try
let old = IH.find T.stmtStartData s.sid in
match T.combinePredecessors s ~old:old d with
None -> (* We are done here *)
if !T.debug then
ignore (E.log "FF(%s): reached stmt %d with %a\n implies the old state %a\n"
T.name s.sid T.pretty d T.pretty old);
None
| Some d' -> begin
(* We have changed the data *)
if !T.debug then
ignore (E.log "FF(%s): weaken data for block %d: %a\n"
T.name s.sid T.pretty d');
Some d'
end
with Not_found -> (* was bottom before *)
let d' = T.computeFirstPredecessor s d in
if !T.debug then
ignore (E.log "FF(%s): set data for block %d: %a\n"
T.name s.sid T.pretty d');
Some d'
in
E.popContext ();
match newdata with
None -> ()
| Some d' ->
IH.replace T.stmtStartData s.sid d';
if T.filterStmt s &&
not (Queue.fold (fun exists s' -> exists || s'.sid = s.sid)
false
worklist) then
Queue.add s worklist
* Get the two successors of an If statement
let ifSuccs (s:stmt) : stmt * stmt =
let fstStmt blk = match blk.bstmts with
[] -> Cil.dummyStmt
| fst::_ -> fst
in
match s.skind with
If(e, b1, b2, _) ->
let thenSucc = fstStmt b1 in
let elseSucc = fstStmt b2 in
let oneFallthrough () =
let fallthrough =
List.filter
(fun s' -> thenSucc != s' && elseSucc != s')
s.succs
in
match fallthrough with
[] -> E.s (bug "Bad CFG: missing fallthrough for If.")
| [s'] -> s'
| _ -> E.s (bug "Bad CFG: multiple fallthrough for If.")
in
If thenSucc or elseSucc is Cil.dummyStmt , it 's an empty block .
So the successor is the statement after the if
So the successor is the statement after the if *)
let stmtOrFallthrough s' =
if s' == Cil.dummyStmt then
oneFallthrough ()
else
s'
in
(stmtOrFallthrough thenSucc,
stmtOrFallthrough elseSucc)
| _-> E.s (bug "ifSuccs on a non-If Statement.")
(** Process a statement *)
let processStmt (s: stmt) : unit =
currentLoc := get_stmtLoc s.skind;
if !T.debug then
ignore (E.log "FF(%s).stmt %d at %t\n" T.name s.sid d_thisloc);
(* It must be the case that the block has some data *)
let init: T.t =
try T.copy (IH.find T.stmtStartData s.sid)
with Not_found ->
E.s (E.bug "FF(%s): processing block without data" T.name)
in
(** See what the custom says *)
match T.doStmt s init with
SDone -> ()
| (SDefault | SUse _) as act -> begin
let curr = match act with
SDefault -> init
| SUse d -> d
| SDone -> E.s (bug "SDone")
in
(* Do the instructions in order *)
let handleInstruction (s: T.t) (i: instr) : T.t =
currentLoc := get_instrLoc i;
(* Now handle the instruction itself *)
let s' =
let action = T.doInstr i s in
match action with
| Done s' -> s'
| Default -> s (* do nothing *)
| Post f -> f s
in
s'
in
let after: T.t =
match s.skind with
Instr il ->
Handle instructions starting with the first one
List.fold_left handleInstruction curr il
| Goto _ | Break _ | Continue _ | If _
| TryExcept _ | TryFinally _
| Switch _ | Loop _ | Return _ | Block _
| HipStmt _ -> curr
in
currentLoc := get_stmtLoc s.skind;
(* Handle If guards *)
let succsToReach = match s.skind with
If (e, _, _, _) -> begin
let not_e = UnOp(LNot, e, intType) in
let thenGuard = T.doGuard e after in
let elseGuard = T.doGuard not_e after in
if thenGuard = GDefault && elseGuard = GDefault then
(* this is the common case *)
s.succs
else begin
let doBranch succ guard =
match guard with
GDefault -> reachedStatement succ after
| GUse d -> reachedStatement succ d
| GUnreachable ->
if !T.debug then
ignore (E.log "FF(%s): Not exploring branch to %d\n"
T.name succ.sid);
()
in
let thenSucc, elseSucc = ifSuccs s in
doBranch thenSucc thenGuard;
doBranch elseSucc elseGuard;
[]
end
end
| _ -> s.succs
in
Reach the successors
List.iter (fun s' -> reachedStatement s' after) succsToReach;
end
* Compute the data flow . Must have the CFG initialized
let compute (sources: stmt list) =
Queue.clear worklist;
List.iter (fun s -> Queue.add s worklist) sources;
(** All initial stmts must have non-bottom data *)
List.iter (fun s ->
if not (IH.mem T.stmtStartData s.sid) then
E.s (E.error "FF(%s): initial stmt %d does not have data"
T.name s.sid))
sources;
if !T.debug then
ignore (E.log "\nFF(%s): processing\n"
T.name);
let rec fixedpoint () =
if !T.debug && not (Queue.is_empty worklist) then
ignore (E.log "FF(%s): worklist= %a\n"
T.name
(docList (fun s -> num s.sid))
(List.rev
(Queue.fold (fun acc s -> s :: acc) [] worklist)));
let keepgoing =
try
let s = Queue.take worklist in
processStmt s;
true
with Queue.Empty ->
if !T.debug then
ignore (E.log "FF(%s): done\n\n" T.name);
false
in
if keepgoing then
fixedpoint ()
in
fixedpoint ()
end
(******************************************************************
**********
********** BACKWARDS
**********
********************************************************************)
module type BackwardsTransfer = sig
val name: string (* For debugging purposes, the name of the analysis *)
val debug: bool ref (** Whether to turn on debugging *)
type t (** The type of the data we compute for each block start. In many
* presentations of backwards data flow analysis we maintain the
* data at the block end. This is not easy to do with JVML because
* a block has many exceptional ends. So we maintain the data for
* the statement start. *)
val pretty: unit -> t -> Pretty.doc (** Pretty-print the state *)
val stmtStartData: t Inthash.t
(** For each block id, the data at the start. This data structure must be
* initialized with the initial data for each block *)
val funcExitData: t
* The data at function exit . Used for statements with no successors .
This is usually bottom , since we 'll also use doStmt on Return
statements .
This is usually bottom, since we'll also use doStmt on Return
statements. *)
val combineStmtStartData: Cil.stmt -> old:t -> t -> t option
(** When the analysis reaches the start of a block, combine the old data
* with the one we have just computed. Return None if the combination is
* the same as the old data, otherwise return the combination. In the
* latter case, the predecessors of the statement are put on the working
* list. *)
val combineSuccessors: t -> t -> t
* Take the data from two successors and combine it
val doStmt: Cil.stmt -> t action
* The ( backwards ) transfer function for a branch . The { ! } is
* set before calling this . If it returns None , then we have some default
* handling . Otherwise , the returned data is the data before the branch
* ( not considering the exception handlers )
* set before calling this. If it returns None, then we have some default
* handling. Otherwise, the returned data is the data before the branch
* (not considering the exception handlers) *)
val doInstr: Cil.instr -> t -> t action
* The ( backwards ) transfer function for an instruction . The
* { ! } is set before calling this . If it returns None , then we
* have some default handling . Otherwise , the returned data is the data
* before the branch ( not considering the exception handlers )
* {!Cil.currentLoc} is set before calling this. If it returns None, then we
* have some default handling. Otherwise, the returned data is the data
* before the branch (not considering the exception handlers) *)
val filterStmt: Cil.stmt -> Cil.stmt -> bool
(** Whether to put this predecessor block in the worklist. We give the
* predecessor and the block whose predecessor we are (and whose data has
* changed) *)
end
module BackwardsDataFlow =
functor (T : BackwardsTransfer) ->
struct
let getStmtStartData (s: stmt) : T.t =
try IH.find T.stmtStartData s.sid
with Not_found ->
E.s (E.bug "BF(%s): stmtStartData is not initialized for %d: %a"
T.name s.sid d_stmt s)
(** Process a statement and return true if the set of live return
* addresses on its entry has changed. *)
let processStmt (s: stmt) : bool =
if !T.debug then
ignore (E.log "FF(%s).stmt %d\n" T.name s.sid);
(* Find the state before the branch *)
currentLoc := get_stmtLoc s.skind;
let d: T.t =
match T.doStmt s with
Done d -> d
| (Default | Post _) as action -> begin
(* Do the default one. Combine the successors *)
let res =
match s.succs with
[] -> T.funcExitData
| fst :: rest ->
List.fold_left (fun acc succ ->
T.combineSuccessors acc (getStmtStartData succ))
(getStmtStartData fst)
rest
in
(* Now do the instructions *)
let res' =
match s.skind with
Instr il ->
(* Now scan the instructions in reverse order. This may
* Stack_overflow on very long blocks ! *)
let handleInstruction (i: instr) (s: T.t) : T.t =
currentLoc := get_instrLoc i;
First handle the instruction itself
let action = T.doInstr i s in
match action with
| Done s' -> s'
| Default -> s (* do nothing *)
| Post f -> f s
in
Handle instructions starting with the last one
List.fold_right handleInstruction il res
| _ -> res
in
match action with
Post f -> f res'
| _ -> res'
end
in
(* See if the state has changed. The only changes are that it may grow.*)
let s0 = getStmtStartData s in
match T.combineStmtStartData s ~old:s0 d with
None -> (* The old data is good enough *)
false
| Some d' ->
(* We have changed the data *)
if !T.debug then
ignore (E.log "BF(%s): set data for block %d: %a\n"
T.name s.sid T.pretty d');
IH.replace T.stmtStartData s.sid d';
true
* Compute the data flow . Must have the CFG initialized
let compute (sinks: stmt list) =
let worklist: Cil.stmt Queue.t = Queue.create () in
List.iter (fun s -> Queue.add s worklist) sinks;
if !T.debug && not (Queue.is_empty worklist) then
ignore (E.log "\nBF(%s): processing\n"
T.name);
let rec fixedpoint () =
if !T.debug && not (Queue.is_empty worklist) then
ignore (E.log "BF(%s): worklist= %a\n"
T.name
(docList (fun s -> num s.sid))
(List.rev
(Queue.fold (fun acc s -> s :: acc) [] worklist)));
let keepgoing =
try
let s = Queue.take worklist in
let changes = processStmt s in
if changes then begin
(* We must add all predecessors of block b, only if not already
* in and if the filter accepts them. *)
List.iter
(fun p ->
if not (Queue.fold (fun exists s' -> exists || p.sid = s'.sid)
false worklist) &&
T.filterStmt p s then
Queue.add p worklist)
s.preds;
end;
true
with Queue.Empty ->
if !T.debug then
ignore (E.log "BF(%s): done\n\n" T.name);
false
in
if keepgoing then
fixedpoint ();
in
fixedpoint ();
end
(** Helper utility that finds all of the statements of a function.
It also lists the return statments (including statements that
fall through the end of a void function). Useful when you need an
initial set of statements for BackwardsDataFlow.compute. *)
let sink_stmts = ref []
let all_stmts = ref []
let sinkFinder = object(self)
inherit nopCilVisitor
method vstmt s =
all_stmts := s ::(!all_stmts);
match s.succs with
[] -> (sink_stmts := s :: (!sink_stmts);
DoChildren)
| _ -> DoChildren
end
(* returns (all_stmts, return_stmts). *)
let find_stmts (fdec:fundec) : (stmt list * stmt list) =
ignore(visitCilFunction (sinkFinder) fdec);
let all = !all_stmts in
let ret = !sink_stmts in
all_stmts := [];
sink_stmts := [];
all, ret
| null | https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/cil/src/ext/dataflow.ml | ocaml | * A framework for data flow analysis for CIL code. Before using
this framework, you must initialize the Control-flow Graph for your
program, e.g using {!Cfg.computeFileCFG}
* The default action
* Do not do the default action. Use this result
* The default action, followed by the given
* transformer
* The default action
* Do not visit this statement or its successors
For if statements
* The default state
* Use this data for the branch
* The branch will never be taken.
*****************************************************************
**********
********** FORWARDS
**********
*******************************************************************
* For debugging purposes, the name of the analysis
* Whether to turn on debugging
* Make a deep copy of the data
* For each statement id, the data at the start. Not found in the hash
* table means nothing is known about the state at this point. At the end
* of the analysis this means that the block is not reachable.
* Pretty-print the state
* Take some old data for the start of a statement, and some new data for
* the same point. Return None if the combination is identical to the old
* data. Otherwise, compute the combination, and return it.
* The (forwards) transfer function for a statement. The {!Cil.currentLoc}
* is set before calling this. The default action is to do the instructions
* in this statement, if applicable, and continue with the successors.
* Whether to put this statement in the worklist. This is called when a
* block would normally be put in the worklist.
* Keep a worklist of statements to process. It is best to keep a queue,
* because this way it is more likely that we are going to process all
* predecessors of a statement before the statement itself.
* We call this function when we have encountered a statement, with some
* state.
* see if we know about it already
We are done here
We have changed the data
was bottom before
* Process a statement
It must be the case that the block has some data
* See what the custom says
Do the instructions in order
Now handle the instruction itself
do nothing
Handle If guards
this is the common case
* All initial stmts must have non-bottom data
*****************************************************************
**********
********** BACKWARDS
**********
*******************************************************************
For debugging purposes, the name of the analysis
* Whether to turn on debugging
* The type of the data we compute for each block start. In many
* presentations of backwards data flow analysis we maintain the
* data at the block end. This is not easy to do with JVML because
* a block has many exceptional ends. So we maintain the data for
* the statement start.
* Pretty-print the state
* For each block id, the data at the start. This data structure must be
* initialized with the initial data for each block
* When the analysis reaches the start of a block, combine the old data
* with the one we have just computed. Return None if the combination is
* the same as the old data, otherwise return the combination. In the
* latter case, the predecessors of the statement are put on the working
* list.
* Whether to put this predecessor block in the worklist. We give the
* predecessor and the block whose predecessor we are (and whose data has
* changed)
* Process a statement and return true if the set of live return
* addresses on its entry has changed.
Find the state before the branch
Do the default one. Combine the successors
Now do the instructions
Now scan the instructions in reverse order. This may
* Stack_overflow on very long blocks !
do nothing
See if the state has changed. The only changes are that it may grow.
The old data is good enough
We have changed the data
We must add all predecessors of block b, only if not already
* in and if the filter accepts them.
* Helper utility that finds all of the statements of a function.
It also lists the return statments (including statements that
fall through the end of a void function). Useful when you need an
initial set of statements for BackwardsDataFlow.compute.
returns (all_stmts, return_stmts). |
module IH = Inthash
module E = Errormsg
open Cil
open Pretty
type 't action =
type 't stmtaction =
* Visit the instructions and successors of this statement
as usual , but use the specified state instead of the
one that was passed to doStmt
as usual, but use the specified state instead of the
one that was passed to doStmt *)
type 't guardaction =
module type ForwardsTransfer = sig
* The type of the data we compute for each block start . May be
* imperative .
* imperative. *)
val copy: t -> t
val stmtStartData: t Inthash.t
val pretty: unit -> t -> Pretty.doc
val computeFirstPredecessor: Cil.stmt -> t -> t
* Give the first value for a predecessors , compute the value to be set
* for the block
* for the block *)
val combinePredecessors: Cil.stmt -> old:t -> t -> t option
val doInstr: Cil.instr -> t -> t action
* The ( forwards ) transfer function for an instruction . The
* { ! } is set before calling this . The default action is to
* continue with the state unchanged .
* {!Cil.currentLoc} is set before calling this. The default action is to
* continue with the state unchanged. *)
val doStmt: Cil.stmt -> t -> t stmtaction
val doGuard: Cil.exp -> t -> t guardaction
* Generate the successor to an If statement assuming the given expression
* is nonzero . Analyses that do n't need guard information can return
* GDefault ; this is equivalent to returning of the input .
* A return value of indicates that this half of the branch
* will not be taken and should not be explored . This will be called
* twice per If , once for " then " and once for " else " .
* is nonzero. Analyses that don't need guard information can return
* GDefault; this is equivalent to returning GUse of the input.
* A return value of GUnreachable indicates that this half of the branch
* will not be taken and should not be explored. This will be called
* twice per If, once for "then" and once for "else".
*)
val filterStmt: Cil.stmt -> bool
end
module ForwardsDataFlow =
functor (T : ForwardsTransfer) ->
struct
let worklist: Cil.stmt Queue.t = Queue.create ()
let reachedStatement (s: stmt) (d: T.t) : unit =
let loc = get_stmtLoc s.skind in
if loc != locUnknown then
currentLoc := get_stmtLoc s.skind;
E.pushContext (fun _ -> dprintf "Reached statement %d with %a"
s.sid T.pretty d);
let newdata: T.t option =
try
let old = IH.find T.stmtStartData s.sid in
match T.combinePredecessors s ~old:old d with
if !T.debug then
ignore (E.log "FF(%s): reached stmt %d with %a\n implies the old state %a\n"
T.name s.sid T.pretty d T.pretty old);
None
| Some d' -> begin
if !T.debug then
ignore (E.log "FF(%s): weaken data for block %d: %a\n"
T.name s.sid T.pretty d');
Some d'
end
let d' = T.computeFirstPredecessor s d in
if !T.debug then
ignore (E.log "FF(%s): set data for block %d: %a\n"
T.name s.sid T.pretty d');
Some d'
in
E.popContext ();
match newdata with
None -> ()
| Some d' ->
IH.replace T.stmtStartData s.sid d';
if T.filterStmt s &&
not (Queue.fold (fun exists s' -> exists || s'.sid = s.sid)
false
worklist) then
Queue.add s worklist
* Get the two successors of an If statement
let ifSuccs (s:stmt) : stmt * stmt =
let fstStmt blk = match blk.bstmts with
[] -> Cil.dummyStmt
| fst::_ -> fst
in
match s.skind with
If(e, b1, b2, _) ->
let thenSucc = fstStmt b1 in
let elseSucc = fstStmt b2 in
let oneFallthrough () =
let fallthrough =
List.filter
(fun s' -> thenSucc != s' && elseSucc != s')
s.succs
in
match fallthrough with
[] -> E.s (bug "Bad CFG: missing fallthrough for If.")
| [s'] -> s'
| _ -> E.s (bug "Bad CFG: multiple fallthrough for If.")
in
If thenSucc or elseSucc is Cil.dummyStmt , it 's an empty block .
So the successor is the statement after the if
So the successor is the statement after the if *)
let stmtOrFallthrough s' =
if s' == Cil.dummyStmt then
oneFallthrough ()
else
s'
in
(stmtOrFallthrough thenSucc,
stmtOrFallthrough elseSucc)
| _-> E.s (bug "ifSuccs on a non-If Statement.")
let processStmt (s: stmt) : unit =
currentLoc := get_stmtLoc s.skind;
if !T.debug then
ignore (E.log "FF(%s).stmt %d at %t\n" T.name s.sid d_thisloc);
let init: T.t =
try T.copy (IH.find T.stmtStartData s.sid)
with Not_found ->
E.s (E.bug "FF(%s): processing block without data" T.name)
in
match T.doStmt s init with
SDone -> ()
| (SDefault | SUse _) as act -> begin
let curr = match act with
SDefault -> init
| SUse d -> d
| SDone -> E.s (bug "SDone")
in
let handleInstruction (s: T.t) (i: instr) : T.t =
currentLoc := get_instrLoc i;
let s' =
let action = T.doInstr i s in
match action with
| Done s' -> s'
| Post f -> f s
in
s'
in
let after: T.t =
match s.skind with
Instr il ->
Handle instructions starting with the first one
List.fold_left handleInstruction curr il
| Goto _ | Break _ | Continue _ | If _
| TryExcept _ | TryFinally _
| Switch _ | Loop _ | Return _ | Block _
| HipStmt _ -> curr
in
currentLoc := get_stmtLoc s.skind;
let succsToReach = match s.skind with
If (e, _, _, _) -> begin
let not_e = UnOp(LNot, e, intType) in
let thenGuard = T.doGuard e after in
let elseGuard = T.doGuard not_e after in
if thenGuard = GDefault && elseGuard = GDefault then
s.succs
else begin
let doBranch succ guard =
match guard with
GDefault -> reachedStatement succ after
| GUse d -> reachedStatement succ d
| GUnreachable ->
if !T.debug then
ignore (E.log "FF(%s): Not exploring branch to %d\n"
T.name succ.sid);
()
in
let thenSucc, elseSucc = ifSuccs s in
doBranch thenSucc thenGuard;
doBranch elseSucc elseGuard;
[]
end
end
| _ -> s.succs
in
Reach the successors
List.iter (fun s' -> reachedStatement s' after) succsToReach;
end
* Compute the data flow . Must have the CFG initialized
let compute (sources: stmt list) =
Queue.clear worklist;
List.iter (fun s -> Queue.add s worklist) sources;
List.iter (fun s ->
if not (IH.mem T.stmtStartData s.sid) then
E.s (E.error "FF(%s): initial stmt %d does not have data"
T.name s.sid))
sources;
if !T.debug then
ignore (E.log "\nFF(%s): processing\n"
T.name);
let rec fixedpoint () =
if !T.debug && not (Queue.is_empty worklist) then
ignore (E.log "FF(%s): worklist= %a\n"
T.name
(docList (fun s -> num s.sid))
(List.rev
(Queue.fold (fun acc s -> s :: acc) [] worklist)));
let keepgoing =
try
let s = Queue.take worklist in
processStmt s;
true
with Queue.Empty ->
if !T.debug then
ignore (E.log "FF(%s): done\n\n" T.name);
false
in
if keepgoing then
fixedpoint ()
in
fixedpoint ()
end
module type BackwardsTransfer = sig
val stmtStartData: t Inthash.t
val funcExitData: t
* The data at function exit . Used for statements with no successors .
This is usually bottom , since we 'll also use doStmt on Return
statements .
This is usually bottom, since we'll also use doStmt on Return
statements. *)
val combineStmtStartData: Cil.stmt -> old:t -> t -> t option
val combineSuccessors: t -> t -> t
* Take the data from two successors and combine it
val doStmt: Cil.stmt -> t action
* The ( backwards ) transfer function for a branch . The { ! } is
* set before calling this . If it returns None , then we have some default
* handling . Otherwise , the returned data is the data before the branch
* ( not considering the exception handlers )
* set before calling this. If it returns None, then we have some default
* handling. Otherwise, the returned data is the data before the branch
* (not considering the exception handlers) *)
val doInstr: Cil.instr -> t -> t action
* The ( backwards ) transfer function for an instruction . The
* { ! } is set before calling this . If it returns None , then we
* have some default handling . Otherwise , the returned data is the data
* before the branch ( not considering the exception handlers )
* {!Cil.currentLoc} is set before calling this. If it returns None, then we
* have some default handling. Otherwise, the returned data is the data
* before the branch (not considering the exception handlers) *)
val filterStmt: Cil.stmt -> Cil.stmt -> bool
end
module BackwardsDataFlow =
functor (T : BackwardsTransfer) ->
struct
let getStmtStartData (s: stmt) : T.t =
try IH.find T.stmtStartData s.sid
with Not_found ->
E.s (E.bug "BF(%s): stmtStartData is not initialized for %d: %a"
T.name s.sid d_stmt s)
let processStmt (s: stmt) : bool =
if !T.debug then
ignore (E.log "FF(%s).stmt %d\n" T.name s.sid);
currentLoc := get_stmtLoc s.skind;
let d: T.t =
match T.doStmt s with
Done d -> d
| (Default | Post _) as action -> begin
let res =
match s.succs with
[] -> T.funcExitData
| fst :: rest ->
List.fold_left (fun acc succ ->
T.combineSuccessors acc (getStmtStartData succ))
(getStmtStartData fst)
rest
in
let res' =
match s.skind with
Instr il ->
let handleInstruction (i: instr) (s: T.t) : T.t =
currentLoc := get_instrLoc i;
First handle the instruction itself
let action = T.doInstr i s in
match action with
| Done s' -> s'
| Post f -> f s
in
Handle instructions starting with the last one
List.fold_right handleInstruction il res
| _ -> res
in
match action with
Post f -> f res'
| _ -> res'
end
in
let s0 = getStmtStartData s in
match T.combineStmtStartData s ~old:s0 d with
false
| Some d' ->
if !T.debug then
ignore (E.log "BF(%s): set data for block %d: %a\n"
T.name s.sid T.pretty d');
IH.replace T.stmtStartData s.sid d';
true
* Compute the data flow . Must have the CFG initialized
let compute (sinks: stmt list) =
let worklist: Cil.stmt Queue.t = Queue.create () in
List.iter (fun s -> Queue.add s worklist) sinks;
if !T.debug && not (Queue.is_empty worklist) then
ignore (E.log "\nBF(%s): processing\n"
T.name);
let rec fixedpoint () =
if !T.debug && not (Queue.is_empty worklist) then
ignore (E.log "BF(%s): worklist= %a\n"
T.name
(docList (fun s -> num s.sid))
(List.rev
(Queue.fold (fun acc s -> s :: acc) [] worklist)));
let keepgoing =
try
let s = Queue.take worklist in
let changes = processStmt s in
if changes then begin
List.iter
(fun p ->
if not (Queue.fold (fun exists s' -> exists || p.sid = s'.sid)
false worklist) &&
T.filterStmt p s then
Queue.add p worklist)
s.preds;
end;
true
with Queue.Empty ->
if !T.debug then
ignore (E.log "BF(%s): done\n\n" T.name);
false
in
if keepgoing then
fixedpoint ();
in
fixedpoint ();
end
let sink_stmts = ref []
let all_stmts = ref []
let sinkFinder = object(self)
inherit nopCilVisitor
method vstmt s =
all_stmts := s ::(!all_stmts);
match s.succs with
[] -> (sink_stmts := s :: (!sink_stmts);
DoChildren)
| _ -> DoChildren
end
let find_stmts (fdec:fundec) : (stmt list * stmt list) =
ignore(visitCilFunction (sinkFinder) fdec);
let all = !all_stmts in
let ret = !sink_stmts in
all_stmts := [];
sink_stmts := [];
all, ret
|
3794d0aaabb4b2f76ef2a24001d33b9795f5226faffd4a157b2d270216c9b78e | spwhitton/consfigurator | user.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
Copyright ( C ) 2021 - 2022 < >
Copyright ( C ) 2021 - 2022 < >
;;; This file 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 , or ( at your option )
;;; any later version.
;;; This file is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
You should have received a copy of the GNU General Public License
;;; along with this program. If not, see </>.
(in-package :consfigurator.property.user)
(named-readtables:in-readtable :consfigurator)
(defprop has-account :posix (username)
"Ensure there is an account for USERNAME.
Note that this uses getent(1) and so is not strictly POSIX-compatible."
(:desc #?"Account for ${username}")
(:check
(user-exists username))
(:apply
(assert-remote-euid-root)
(mrun "useradd" "-m" username)))
(defprop %has-uid-gid :posix (username uid gid)
(:check
(and (= uid (parse-integer (passwd-field 2 username)))
(= gid (parse-integer (passwd-field 3 username)))
(= gid (parse-integer (group-entry 2 username)))))
(:apply
(let* ((gid-str (write-to-string gid))
(uid-str (write-to-string uid))
(uid+gid (format nil "~d:~d" uid gid))
(home (passwd-field 5 username)))
(mrun "groupmod" "--gid" gid-str username)
(mrun "usermod" "--uid" uid-str "--gid" gid-str username)
(mrun "chown" "-R" uid+gid home))))
(defproplist has-account-with-uid :posix (username uid &key (gid uid))
"Ensure there is an account for USERNAME with uid UID.
Also ensure the group named USERNAME has gid GID, USERNAME's primary group is
that group, and ~USERNAME and its contents are owned by UID:GID."
(:hostattrs (os:required 'os:debianlike))
(:desc #?"${username} has uid ${uid} gid ${gid}")
(has-account username)
(%has-uid-gid username uid gid))
(defprop group-exists :posix (groupname)
"Ensure there is a group GROUPNAME.
Note that this uses getent(1) and so is not strictly POSIX-compatible."
(:desc #?"Group ${groupname} exists")
(:check
(zerop (mrun :for-exit "getent" "group" groupname)))
(:apply
(assert-remote-euid-root)
(mrun "groupadd" groupname)))
(defprop has-groups :posix
(username &rest groups &aux (groups* (format nil "~{~A~^,~}" groups)))
"Ensure that USERNAME is a member of secondary groups GROUPS."
(:desc (format nil "~A in group~P ~A" username (length groups) groups*))
(:check
(declare (ignore groups*))
(subsetp groups (cddr (split-string (stripln (run "groups" username))))
:test #'string=))
(:apply
(assert-remote-euid-root)
(mrun "usermod" "-a" "-G" groups* username)))
(defparameter *desktop-groups*
'("audio" "cdrom" "dip" "floppy" "video" "plugdev" "netdev" "scanner"
"bluetooth" "debian-tor" "lpadmin")
"See the debconf template passwd/user-default-groups for package user-setup.")
(defprop has-desktop-groups :posix (username)
"Add user to the secondary groups to which the OS installer normally adds the
default account it creates. Skips over groups which do not exist yet, pending
the installation of other software."
(:desc #?"${username} is in standard desktop groups")
(:hostattrs (os:required 'os:debianlike))
(:apply
(let ((existing-groups
(loop for line in (lines (read-remote-file "/etc/group"))
collect (car (split-string line :separator ":")))))
(apply #'has-groups username (loop for group in *desktop-groups*
when (memstr= group existing-groups)
collect group)))))
(defprop has-login-shell :posix (username shell)
"Ensures that USERNAME has login shell SHELL.
Note that this uses getent(1) and so is not strictly POSIX-compatible."
(:desc #?"${username} has login shell ${shell}")
(:check
(string= (passwd-field 6 username) shell))
(:apply
(file:contains-lines "/etc/shells" shell)
(mrun "chsh" "--shell" shell username)))
(defprop has-enabled-password :posix
(username &key (initial-password "changeme"))
"Ensures that it is possible to login as USERNAME; if this requires enabling
the account's password, also set it to INITIAL-PASSWORD.
The main purpose of this property is to ensure that in a freshly installed
system it will be possible to log in. The password should usually be changed
to something which is not stored in plain text in your consfig right after,
and then this property will do nothing."
(:desc #?"${username} has an enabled password")
(:check
(declare (ignore initial-password))
(string= "P" (cadr (split-string (run "passwd" "-S" username)))))
(:apply
(mrun :input (format nil "~A:~A" username initial-password) "chpasswd")))
(defprop has-locked-password :posix (username)
"Ensure that USERNAME cannot login via a password."
(:desc #?"${username} has a locked password")
(:hostattrs (os:required 'os:debianlike))
(:check
(assert-remote-euid-root)
(string= "L" (cadr (split-string (run "passwd" "-S" username)))))
(:apply
(assert-remote-euid-root)
(mrun "passwd" "--lock" username)))
(defun %getent-entry (n name-or-id &optional (database "passwd"))
"Get the nth entry in the getent(1) output for NAME-OR-ID in DATABASE."
(let ((u (etypecase name-or-id
(string name-or-id)
(number (write-to-string name-or-id)))))
(nth n (split-string (stripln (mrun "getent" database u))
:separator ":"))))
(defun passwd-field (n username-or-uid)
"Get the nth entry in the getent(1) output for USERNAME-OR-UID.
Note that getent(1) is not specified in POSIX so use of this function makes
properties not strictly POSIX-compatible."
(%getent-entry n username-or-uid "passwd"))
(defun group-entry (n groupname-or-gid)
"Get the nth entry in the getent(1) output for GROUPNAME-OR-GID.
Note that getent(1) is not specified in POSIX so use of this function makes
properties not strictly POSIX-compatible."
(%getent-entry n groupname-or-gid "group"))
(defun user-exists (username)
(zerop (mrun :for-exit "getent" "passwd" username)))
(defun user-info (username-or-uid)
"Return passwd database entry for USERNAME-OR-UID as an alist.
Falls back to getent(1), which is not specified in POSIX, so use of this
function makes properties not strictly POSIX-compatible."
getpwnam(3 ) and getpwuid(3 ) can fail to load the required NSS modules if
;; we have chrooted or similar. In that case, it appears as though the user
;; does not exist. So fall back to getent(1).
(or (and (lisp-connection-p) (osicat:user-info username-or-uid))
(aand (runlines "getent" "passwd" (aetypecase username-or-uid
(string it)
(number (write-to-string it))))
(destructuring-bind (name password uid gid &rest rest)
(split-string (car it) :separator '(#\:))
(declare (ignore password))
(list* (cons :name name)
(cons :user-id (parse-integer uid))
(cons :group-id (parse-integer gid))
(pairlis '(:gecos :home :shell) rest))))))
| null | https://raw.githubusercontent.com/spwhitton/consfigurator/031f4e16be6d532494e2fac39d3838913b1e8435/src/property/user.lisp | lisp | Consfigurator -- Lisp declarative configuration management system
This file is free software; you can redistribute it and/or modify
either version 3 , or ( at your option )
any later version.
This file 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 </>.
if this requires enabling
we have chrooted or similar. In that case, it appears as though the user
does not exist. So fall back to getent(1). |
Copyright ( C ) 2021 - 2022 < >
Copyright ( C ) 2021 - 2022 < >
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
(in-package :consfigurator.property.user)
(named-readtables:in-readtable :consfigurator)
(defprop has-account :posix (username)
"Ensure there is an account for USERNAME.
Note that this uses getent(1) and so is not strictly POSIX-compatible."
(:desc #?"Account for ${username}")
(:check
(user-exists username))
(:apply
(assert-remote-euid-root)
(mrun "useradd" "-m" username)))
(defprop %has-uid-gid :posix (username uid gid)
(:check
(and (= uid (parse-integer (passwd-field 2 username)))
(= gid (parse-integer (passwd-field 3 username)))
(= gid (parse-integer (group-entry 2 username)))))
(:apply
(let* ((gid-str (write-to-string gid))
(uid-str (write-to-string uid))
(uid+gid (format nil "~d:~d" uid gid))
(home (passwd-field 5 username)))
(mrun "groupmod" "--gid" gid-str username)
(mrun "usermod" "--uid" uid-str "--gid" gid-str username)
(mrun "chown" "-R" uid+gid home))))
(defproplist has-account-with-uid :posix (username uid &key (gid uid))
"Ensure there is an account for USERNAME with uid UID.
Also ensure the group named USERNAME has gid GID, USERNAME's primary group is
that group, and ~USERNAME and its contents are owned by UID:GID."
(:hostattrs (os:required 'os:debianlike))
(:desc #?"${username} has uid ${uid} gid ${gid}")
(has-account username)
(%has-uid-gid username uid gid))
(defprop group-exists :posix (groupname)
"Ensure there is a group GROUPNAME.
Note that this uses getent(1) and so is not strictly POSIX-compatible."
(:desc #?"Group ${groupname} exists")
(:check
(zerop (mrun :for-exit "getent" "group" groupname)))
(:apply
(assert-remote-euid-root)
(mrun "groupadd" groupname)))
(defprop has-groups :posix
(username &rest groups &aux (groups* (format nil "~{~A~^,~}" groups)))
"Ensure that USERNAME is a member of secondary groups GROUPS."
(:desc (format nil "~A in group~P ~A" username (length groups) groups*))
(:check
(declare (ignore groups*))
(subsetp groups (cddr (split-string (stripln (run "groups" username))))
:test #'string=))
(:apply
(assert-remote-euid-root)
(mrun "usermod" "-a" "-G" groups* username)))
(defparameter *desktop-groups*
'("audio" "cdrom" "dip" "floppy" "video" "plugdev" "netdev" "scanner"
"bluetooth" "debian-tor" "lpadmin")
"See the debconf template passwd/user-default-groups for package user-setup.")
(defprop has-desktop-groups :posix (username)
"Add user to the secondary groups to which the OS installer normally adds the
default account it creates. Skips over groups which do not exist yet, pending
the installation of other software."
(:desc #?"${username} is in standard desktop groups")
(:hostattrs (os:required 'os:debianlike))
(:apply
(let ((existing-groups
(loop for line in (lines (read-remote-file "/etc/group"))
collect (car (split-string line :separator ":")))))
(apply #'has-groups username (loop for group in *desktop-groups*
when (memstr= group existing-groups)
collect group)))))
(defprop has-login-shell :posix (username shell)
"Ensures that USERNAME has login shell SHELL.
Note that this uses getent(1) and so is not strictly POSIX-compatible."
(:desc #?"${username} has login shell ${shell}")
(:check
(string= (passwd-field 6 username) shell))
(:apply
(file:contains-lines "/etc/shells" shell)
(mrun "chsh" "--shell" shell username)))
(defprop has-enabled-password :posix
(username &key (initial-password "changeme"))
the account's password, also set it to INITIAL-PASSWORD.
The main purpose of this property is to ensure that in a freshly installed
system it will be possible to log in. The password should usually be changed
to something which is not stored in plain text in your consfig right after,
and then this property will do nothing."
(:desc #?"${username} has an enabled password")
(:check
(declare (ignore initial-password))
(string= "P" (cadr (split-string (run "passwd" "-S" username)))))
(:apply
(mrun :input (format nil "~A:~A" username initial-password) "chpasswd")))
(defprop has-locked-password :posix (username)
"Ensure that USERNAME cannot login via a password."
(:desc #?"${username} has a locked password")
(:hostattrs (os:required 'os:debianlike))
(:check
(assert-remote-euid-root)
(string= "L" (cadr (split-string (run "passwd" "-S" username)))))
(:apply
(assert-remote-euid-root)
(mrun "passwd" "--lock" username)))
(defun %getent-entry (n name-or-id &optional (database "passwd"))
"Get the nth entry in the getent(1) output for NAME-OR-ID in DATABASE."
(let ((u (etypecase name-or-id
(string name-or-id)
(number (write-to-string name-or-id)))))
(nth n (split-string (stripln (mrun "getent" database u))
:separator ":"))))
(defun passwd-field (n username-or-uid)
"Get the nth entry in the getent(1) output for USERNAME-OR-UID.
Note that getent(1) is not specified in POSIX so use of this function makes
properties not strictly POSIX-compatible."
(%getent-entry n username-or-uid "passwd"))
(defun group-entry (n groupname-or-gid)
"Get the nth entry in the getent(1) output for GROUPNAME-OR-GID.
Note that getent(1) is not specified in POSIX so use of this function makes
properties not strictly POSIX-compatible."
(%getent-entry n groupname-or-gid "group"))
(defun user-exists (username)
(zerop (mrun :for-exit "getent" "passwd" username)))
(defun user-info (username-or-uid)
"Return passwd database entry for USERNAME-OR-UID as an alist.
Falls back to getent(1), which is not specified in POSIX, so use of this
function makes properties not strictly POSIX-compatible."
getpwnam(3 ) and getpwuid(3 ) can fail to load the required NSS modules if
(or (and (lisp-connection-p) (osicat:user-info username-or-uid))
(aand (runlines "getent" "passwd" (aetypecase username-or-uid
(string it)
(number (write-to-string it))))
(destructuring-bind (name password uid gid &rest rest)
(split-string (car it) :separator '(#\:))
(declare (ignore password))
(list* (cons :name name)
(cons :user-id (parse-integer uid))
(cons :group-id (parse-integer gid))
(pairlis '(:gecos :home :shell) rest))))))
|
acdff4c0f0406a0df943911fcdd9de79863c62455548da0a0d344935849f019c | MyDataFlow/ttalk-server | ejabberd_sm.erl | %%%----------------------------------------------------------------------
File :
Author : < >
%%% Purpose : Session manager
Created : 24 Nov 2002 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2011 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. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
%%%
%%%----------------------------------------------------------------------
-module(ejabberd_sm).
-author('').
-behaviour(gen_server).
-behaviour(xmpp_router).
%% API
-export([start_link/0,
route/3,
open_session/5, open_session/6,
close_session/5,
check_in_subscription/6,
bounce_offline_message/3,
disconnect_removed_user/2,
get_user_resources/2,
set_presence/7,
unset_presence/6,
close_session_unset_presence/6,
get_unique_sessions_number/0,
get_total_sessions_number/0,
get_node_sessions_number/0,
get_vh_session_number/1,
get_vh_session_list/1,
get_full_session_list/0,
register_iq_handler/4,
register_iq_handler/5,
unregister_iq_handler/2,
force_update_presence/1,
user_resources/2,
get_session_pid/3,
get_session/3,
get_session_ip/3,
get_user_present_resources/2
]).
%% Hook handlers
-export([node_cleanup/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
%% xmpp_router callback
-export([do_route/3]).
-include("ejabberd.hrl").
-include("jlib.hrl").
-include("ejabberd_commands.hrl").
-include("mod_privacy.hrl").
-record(state, {}).
-type state() :: #state{}.
-type sid() :: tuple().
-type priority() :: integer() | undefined.
-type session() :: #session{
sid :: sid(),
usr :: ejabberd:simple_jid(),
us :: ejabberd:simple_bare_jid(),
priority :: priority(),
info :: list()
}.
Session representation as 4 - tuple .
-type ses_tuple() :: {USR :: ejabberd:simple_jid(),
Sid :: ejabberd_sm:sid(),
Prio :: priority(),
Info :: list()}.
-type backend() :: ejabberd_sm_mnesia | ejabberd_sm_redis.
-type close_reason() :: resumed | normal | replaced.
-export_type([session/0,
sid/0,
ses_tuple/0,
backend/0,
close_reason/0
]).
%% default value for the maximum number of user connections
-define(MAX_USER_SESSIONS, 100).
-define(SM_BACKEND, (ejabberd_sm_backend:backend())).
-define(UNIQUE_COUNT_CACHE, [cache, unique_sessions_number]).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
%% Description: Starts the server
%%--------------------------------------------------------------------
-spec start_link() -> 'ignore' | {'error',_} | {'ok',pid()}.
start_link() ->
mongoose_metrics:ensure_metric(?UNIQUE_COUNT_CACHE, gauge),
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-spec route(From, To, Packet) -> ok when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel() | ejabberd_c2s:broadcast().
route(From, To, Packet) ->
xmpp_router:route(?MODULE, From, To, Packet).
%% 默认不使用优先级
-spec open_session(SID, User, Server, Resource, Info) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: binary(),
Info :: 'undefined' | [any()].
open_session(SID, User, Server, Resource, Info) ->
open_session(SID, User, Server, Resource, undefined, Info).
-spec open_session(SID, User, Server, Resource, Priority, Info) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: binary(),
Priority :: integer() | undefined,
Info :: 'undefined' | [any()].
open_session(SID, User, Server, Resource, Priority, Info) ->
set_session(SID, User, Server, Resource, Priority, Info),
check_for_sessions_to_replace(User, Server, Resource),
JID = jid:make(User, Server, Resource),
%% 当用户开启session的时候,我们会执行sm_register_connection_hook
ejabberd_hooks:run(sm_register_connection_hook, JID#jid.lserver,
[SID, JID, Info]).
-spec close_session(SID, User, Server, Resource, Reason) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource(),
Reason :: close_reason().
close_session(SID, User, Server, Resource, Reason) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
Info = case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[Session] ->
Session#session.info;
_ ->
[]
end,
?SM_BACKEND:delete_session(SID, LUser, LServer, LResource),
JID = jid:make(User, Server, Resource),
ejabberd_hooks:run(sm_remove_connection_hook, JID#jid.lserver,
[SID, JID, Info, Reason]).
-spec check_in_subscription(Acc, User, Server, JID, Type, Reason) -> any() | {stop, false} when
Acc :: any(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
JID :: ejabberd:jid(),
Type :: any(),
Reason :: any().
check_in_subscription(Acc, User, Server, _JID, _Type, _Reason) ->
case ejabberd_auth:is_user_exists(User, Server) of
true ->
Acc;
false ->
{stop, false}
end.
-spec bounce_offline_message(From, To, Packet) -> stop when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel().
bounce_offline_message(#jid{server = Server} = From, To, Packet) ->
ejabberd_hooks:run(xmpp_bounce_message,
Server,
[Server, Packet]),
Err = jlib:make_error_reply(Packet, ?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err),
stop.
-spec disconnect_removed_user(User :: ejabberd:user(), Server :: ejabberd:server()) ->
'ok'.
disconnect_removed_user(User, Server) ->
ejabberd_sm:route(jid:make(<<>>, <<>>, <<>>),
jid:make(User, Server, <<>>),
{broadcast, {exit, <<"User removed">>}}).
-spec get_user_resources(User :: ejabberd:user(), Server :: ejabberd:server()) -> [binary()].
get_user_resources(User, Server) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
Ss = ?SM_BACKEND:get_sessions(LUser, LServer),
[element(3, S#session.usr) || S <- clean_session_list(Ss)].
-spec get_session_ip(User, Server, Resource) -> undefined | {inet:ip_address(), integer()} when
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource().
get_session_ip(User, Server, Resource) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[] ->
undefined;
Ss ->
Session = lists:max(Ss),
proplists:get_value(ip, Session#session.info)
end.
-spec get_session(User, Server, Resource) -> offline | ses_tuple() when
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource().
get_session(User, Server, Resource) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[] ->
offline;
Ss ->
Session = lists:max(Ss),
{Session#session.usr,
Session#session.sid,
Session#session.priority,
Session#session.info}
end.
-spec set_presence(SID, User, Server, Resource, Prio, Presence, Info) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource(),
Prio :: 'undefined' | integer(),
Presence :: any(),
Info :: 'undefined' | [any()].
set_presence(SID, User, Server, Resource, Priority, Presence, Info) ->
set_session(SID, User, Server, Resource, Priority, Info),
ejabberd_hooks:run(set_presence_hook, jid:nameprep(Server),
[User, Server, Resource, Presence]).
-spec unset_presence(SID, User, Server, Resource, Status, Info) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource(),
Status :: any(),
Info :: 'undefined' | [any()].
unset_presence(SID, User, Server, Resource, Status, Info) ->
set_session(SID, User, Server, Resource, undefined, Info),
LServer = jid:nameprep(Server),
ejabberd_hooks:run(unset_presence_hook, LServer,
[jid:nodeprep(User), LServer,
jid:resourceprep(Resource), Status]).
-spec close_session_unset_presence(SID, User, Server, Resource, Status, Reason) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource(),
Status :: any(),
Reason :: close_reason().
close_session_unset_presence(SID, User, Server, Resource, Status, Reason) ->
close_session(SID, User, Server, Resource, Reason),
LServer = jid:nameprep(Server),
ejabberd_hooks:run(unset_presence_hook, LServer,
[jid:nodeprep(User), LServer,
jid:resourceprep(Resource), Status]).
-spec get_session_pid(User, Server, Resource) -> none | pid() when
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource().
get_session_pid(User, Server, Resource) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[#session{sid = {_, Pid}}] ->
Pid;
_ ->
none
end.
-spec get_unique_sessions_number() -> integer().
get_unique_sessions_number() ->
try
C = ?SM_BACKEND:unique_count(),
mongoose_metrics:update(?UNIQUE_COUNT_CACHE, C),
C
catch
_:_ ->
get_cached_unique_count()
end.
-spec get_total_sessions_number() -> integer().
get_total_sessions_number() ->
?SM_BACKEND:total_count().
-spec get_vh_session_number(ejabberd:server()) -> non_neg_integer().
get_vh_session_number(Server) ->
length(?SM_BACKEND:get_sessions(Server)).
-spec get_vh_session_list(ejabberd:server()) -> [ses_tuple()].
get_vh_session_list(Server) ->
?SM_BACKEND:get_sessions(Server).
-spec get_node_sessions_number() -> non_neg_integer().
get_node_sessions_number() ->
{value, {active, Active}} = lists:keysearch(active, 1, supervisor:count_children(ejabberd_c2s_sup)),
Active.
-spec get_full_session_list() -> [session()].
get_full_session_list() ->
?SM_BACKEND:get_sessions().
register_iq_handler(Host, XMLNS, Module, Fun) ->
ejabberd_sm ! {register_iq_handler, Host, XMLNS, Module, Fun}.
register_iq_handler(Host, XMLNS, Module, Fun, Opts) ->
ejabberd_sm ! {register_iq_handler, Host, XMLNS, Module, Fun, Opts}.
unregister_iq_handler(Host, XMLNS) ->
ejabberd_sm ! {unregister_iq_handler, Host, XMLNS}.
%%====================================================================
%% Hook handlers
%%====================================================================
node_cleanup(Node) ->
gen_server:call(?MODULE, {node_cleanup, Node}).
%%====================================================================
%% gen_server callbacks
%%====================================================================
%%--------------------------------------------------------------------
%% Function: init(Args) -> {ok, State} |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%% Description: Initiates the server
%%--------------------------------------------------------------------
-spec init(_) -> {ok, state()}.
init([]) ->
{Backend, Opts} = ejabberd_config:get_global_option(sm_backend),
%% 动态生成ejabberd_sm_backend的代码
{Mod, Code} = dynamic_compile:from_string(sm_backend(Backend)),
code:load_binary(Mod, "ejabberd_sm_backend.erl", Code),
创建IQ管理器,用来保存IQ的响应情况,也就是说
%% 需要改掉Ping的方式
ets:new(sm_iqtable, [named_table]),
ejabberd_hooks:add(node_cleanup, global, ?MODULE, node_cleanup, 50),
lists:foreach(
fun(Host) ->
ejabberd_hooks:add(roster_in_subscription, Host,
ejabberd_sm, check_in_subscription, 20),
ejabberd_hooks:add(offline_message_hook, Host,
ejabberd_sm, bounce_offline_message, 100),
ejabberd_hooks:add(remove_user, Host,
ejabberd_sm, disconnect_removed_user, 100)
end, ?MYHOSTS),
ejabberd_commands:register_commands(commands()),
?SM_BACKEND:start(Opts),
{ok, #state{}}.
%%--------------------------------------------------------------------
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({node_cleanup, Node}, _From, State) ->
BackendModule = ?SM_BACKEND,
{TimeDiff, _R} = timer:tc(fun BackendModule:cleanup/1, [Node]),
?INFO_MSG("sessions cleanup after node=~p, took=~pms",
[Node, erlang:round(TimeDiff / 1000)]),
{reply, ok, State};
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
%%--------------------------------------------------------------------
Function : handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling cast messages
%%--------------------------------------------------------------------
handle_cast(_Msg, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
Function : handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling all non call/cast messages
%%--------------------------------------------------------------------
-spec handle_info(_,_) -> {'noreply',_}.
handle_info({route, From, To, Packet}, State) ->
xmpp_router:route(?MODULE,From,To,Packet),
{noreply, State};
handle_info({register_iq_handler, Host, XMLNS, Module, Function}, State) ->
ets:insert(sm_iqtable, {{XMLNS, Host}, Module, Function}),
{noreply, State};
handle_info({register_iq_handler, Host, XMLNS, Module, Function, Opts}, State) ->
ets:insert(sm_iqtable, {{XMLNS, Host}, Module, Function, Opts}),
{noreply, State};
handle_info({unregister_iq_handler, Host, XMLNS}, State) ->
case ets:lookup(sm_iqtable, {XMLNS, Host}) of
[{_, Module, Function, Opts}] ->
gen_iq_handler:stop_iq_handler(Module, Function, Opts);
_ ->
ok
end,
ets:delete(sm_iqtable, {XMLNS, Host}),
{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.
%%--------------------------------------------------------------------
-spec terminate(_,state()) -> 'ok'.
terminate(_Reason, _State) ->
ejabberd_commands:unregister_commands(commands()),
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
%%--------------------------------------------------------------------
-spec set_session(SID, User, Server, Resource, Prio, Info) -> ok | {error, any()} when
SID :: sid() | 'undefined',
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource(),
Prio :: priority(),
Info :: undefined | [any()].
set_session(SID, User, Server, Resource, Priority, Info) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
US = {LUser, LServer},
USR = {LUser, LServer, LResource},
usr是LUser , LServer , LResource
%% us是{LUser, LServer}
Session = #session{sid = SID,
usr = USR,
us = US,
priority = Priority,
info = Info},
%% 要求后端开启session,这个版本开始支持Redis后端了
?SM_BACKEND:create_session(LUser, LServer, LResource, Session).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec do_route(From, To, Packet) -> ok when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel() | ejabberd_c2s:broadcast().
do_route(From, To, {broadcast, _} = Broadcast) ->
?DEBUG("from=~p,to=~p,broadcast=~p", [From, To, Broadcast]),
%% 解析出目标的信息
#jid{ luser = LUser, lserver = LServer, lresource = LResource} = To,
case LResource of
<<>> ->
%% 得到用户所有的链接进行广播
CurrentPids = get_user_present_pids(LUser, LServer),
ejabberd_hooks:run(sm_broadcast, To#jid.lserver,
[From, To, Broadcast, length(CurrentPids)]),
?DEBUG("bc_to=~p~n", CurrentPids),
lists:foreach(fun({_, Pid}) -> Pid ! Broadcast end, CurrentPids);
_ ->
case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[] ->
ok; % do nothing
Ss ->
Session = lists:max(Ss),
Pid = element(2, Session#session.sid),
?DEBUG("sending to process ~p~n", [Pid]),
Pid ! Broadcast
end
end;
%% 开始进行消息路由
do_route(From, To, Packet) ->
?DEBUG("session manager~n\tfrom ~p~n\tto ~p~n\tpacket ~P~n",
[From, To, Packet, 8]),
#jid{ luser = LUser, lserver = LServer, lresource = LResource} = To,
#xmlel{name = Name, attrs = Attrs} = Packet,
case LResource of
<<>> ->
%% 如果没有指定resource的话
do_route_no_resource(Name, xml:get_attr_s(<<"type">>, Attrs),
From, To, Packet);
_ ->
case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[] ->
do_route_offline(Name, xml:get_attr_s(<<"type">>, Attrs),
From, To, Packet);
Ss ->
Session = lists:max(Ss),
Pid = element(2, Session#session.sid),
?DEBUG("sending to process ~p~n", [Pid]),
Pid ! {route, From, To, Packet}
end
end.
-spec do_route_no_resource_presence_prv(From, To, Packet, Type, Reason) -> boolean() when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel(),
Type :: 'subscribe' | 'subscribed' | 'unsubscribe' | 'unsubscribed',
Reason :: any().
do_route_no_resource_presence_prv(From,To,Packet,Type,Reason) ->
is_privacy_allow(From, To, Packet) andalso ejabberd_hooks:run_fold(
roster_in_subscription,
To#jid.lserver,
false,
[To#jid.user, To#jid.server, From, Type, Reason]).
-spec do_route_no_resource_presence(Type, From, To, Packet) -> boolean() when
Type :: binary(),
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel().
do_route_no_resource_presence(<<"subscribe">>, From, To, Packet) ->
Reason = xml:get_path_s(Packet, [{elem, <<"status">>}, cdata]),
do_route_no_resource_presence_prv(From, To, Packet, subscribe, Reason);
do_route_no_resource_presence(<<"subscribed">>, From, To, Packet) ->
do_route_no_resource_presence_prv(From, To, Packet, subscribed, <<>>);
do_route_no_resource_presence(<<"unsubscribe">>, From, To, Packet) ->
do_route_no_resource_presence_prv(From, To, Packet, unsubscribe, <<>>);
do_route_no_resource_presence(<<"unsubscribed">>, From, To, Packet) ->
do_route_no_resource_presence_prv(From, To, Packet, unsubscribed, <<>>);
do_route_no_resource_presence(_, _, _, _) ->
true.
-spec do_route_no_resource(Name, Type, From, To, Packet) -> Result when
Name :: undefined | binary(),
Type :: any(),
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel(),
Result ::ok | stop | todo | pid() | {error, lager_not_running} | {process_iq, _, _, _}.
do_route_no_resource(<<"presence">>, Type, From, To, Packet) ->
case do_route_no_resource_presence(Type, From, To, Packet) of
true ->
PResources = get_user_present_resources(To#jid.luser, To#jid.lserver),
lists:foreach(
fun({_, R}) ->
do_route(From, jid:replace_resource(To, R), Packet)
end, PResources);
false ->
ok
end;
do_route_no_resource(<<"message">>, _, From, To, Packet) ->
route_message(From, To, Packet);
do_route_no_resource(<<"iq">>, _, From, To, Packet) ->
process_iq(From, To, Packet);
do_route_no_resource(<<"broadcast">>, _, From, To, Packet) ->
% Backward compatibility
ejabberd_hooks:run(sm_broadcast, To#jid.lserver, [From, To, Packet]),
broadcast_packet(From, To, Packet);
do_route_no_resource(_, _, _, _, _) ->
ok.
-spec do_route_offline(Name, Type, From, To, Packet) -> ok | stop when
Name :: 'undefined' | binary(),
Type :: binary(),
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel().
do_route_offline(<<"message">>, _, From, To, Packet) ->
route_message(From, To, Packet);
do_route_offline(<<"iq">>, <<"error">>, _From, _To, _Packet) ->
ok;
do_route_offline(<<"iq">>, <<"result">>, _From, _To, _Packet) ->
ok;
do_route_offline(<<"iq">>, _, From, To, Packet) ->
Err = jlib:make_error_reply(Packet, ?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err);
do_route_offline(_, _, _, _, _) ->
?DEBUG("packet droped~n", []),
ok.
% Backward compatibility
-spec broadcast_packet(From :: ejabberd:jid(), To :: ejabberd:jid(), Packet :: jlib:xmlel()) -> ok.
broadcast_packet(From, To, Packet) ->
#jid{user = User, server = Server} = To,
lists:foreach(
fun(R) ->
do_route(From,
jid:replace_resource(To, R),
Packet)
end, get_user_resources(User, Server)).
%% @doc The default list applies to the user as a whole,
%% and is processed if there is no active list set
%% for the target session/resource to which a stanza is addressed,
%% or if there are no current sessions for the user.
-spec is_privacy_allow(From, To, Packet) -> boolean() when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel().
is_privacy_allow(From, To, Packet) ->
User = To#jid.user,
Server = To#jid.server,
PrivacyList = ejabberd_hooks:run_fold(privacy_get_user_list, Server,
#userlist{}, [User, Server]),
is_privacy_allow(From, To, Packet, PrivacyList).
%% @doc Check if privacy rules allow this delivery
%% Function copied from ejabberd_c2s.erl
-spec is_privacy_allow(From, To, Packet, PrivacyList) -> boolean() when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel(),
PrivacyList :: list().
is_privacy_allow(From, To, Packet, PrivacyList) ->
User = To#jid.user,
Server = To#jid.server,
allow == ejabberd_hooks:run_fold(
privacy_check_packet, Server,
allow,
[User, Server, PrivacyList,
{From, To, Packet}, in]).
-spec route_message(From, To, Packet) -> ok | stop when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel().
route_message(From, To, Packet) ->
LUser = To#jid.luser,
LServer = To#jid.lserver,
PrioPid = get_user_present_pids(LUser,LServer),
%% 得到用户的所有链接,进行广播
case catch lists:max(PrioPid) of
{Priority, _} when is_integer(Priority), Priority >= 0 ->
lists:foreach(
%% Route messages to all priority that equals the max, if
%% positive
fun({Prio, Pid}) when Prio == Priority ->
% we will lose message if PID is not alive
Pid ! {route, From, To, Packet};
%% Ignore other priority:
({_Prio, _Pid}) ->
ok
end,
PrioPid);
_ ->
%% 如果不在线,那么进行离线存储
case xml:get_tag_attr_s(<<"type">>, Packet) of
<<"error">> ->
ok;
<<"groupchat">> ->
bounce_offline_message(From, To, Packet);
<<"headline">> ->
bounce_offline_message(From, To, Packet);
_ ->
case ejabberd_auth:is_user_exists(LUser, LServer) of
true ->
case is_privacy_allow(From, To, Packet) of
true ->
ejabberd_hooks:run(offline_message_hook,
LServer,
[From, To, Packet]);
false ->
ok
end;
_ ->
Err = jlib:make_error_reply(
Packet, ?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err)
end
end
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec clean_session_list([sid()]) -> [sid()].
clean_session_list(Ss) ->
clean_session_list(lists:keysort(#session.usr, Ss), []).
-spec clean_session_list([sid()],[sid()]) -> [sid()].
clean_session_list([], Res) ->
Res;
clean_session_list([S], Res) ->
[S | Res];
clean_session_list([S1, S2 | Rest], Res) ->
if
S1#session.usr == S2#session.usr ->
if
S1#session.sid > S2#session.sid ->
clean_session_list([S1 | Rest], Res);
true ->
clean_session_list([S2 | Rest], Res)
end;
true ->
clean_session_list([S2 | Rest], [S1 | Res])
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec get_user_present_pids(LUser, LServer) -> [{priority(), pid()}] when
LUser :: ejabberd:luser(),
LServer :: ejabberd:lserver().
get_user_present_pids(LUser, LServer) ->
Ss = clean_session_list(?SM_BACKEND:get_sessions(LUser, LServer)),
[{S#session.priority, element(2,S#session.sid)}
|| S <- Ss, is_integer(S#session.priority)].
-spec get_user_present_resources(LUser :: ejabberd:user(),
LServer :: ejabberd:server()
) -> [{priority(), binary()}].
get_user_present_resources(LUser, LServer) ->
Ss = ?SM_BACKEND:get_sessions(LUser, LServer),
[{S#session.priority, element(3, S#session.usr)} ||
S <- clean_session_list(Ss), is_integer(S#session.priority)].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% @doc On new session, check if some existing connections need to be replace
-spec check_for_sessions_to_replace(User, Server, Resource) -> ok | replaced when
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource().
check_for_sessions_to_replace(User, Server, Resource) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
%% TODO: Depending on how this is executed, there could be an unneeded
%% replacement for max_sessions. We need to check this at some point.
check_existing_resources(LUser, LServer, LResource),
check_max_sessions(LUser, LServer).
-spec check_existing_resources(LUser, LServer, LResource) -> ok when
LUser :: 'error' | ejabberd:luser() | tuple(),
LServer :: 'error' | ejabberd:lserver() | tuple(),
LResource :: 'error' | ejabberd:lresource() | [byte()] | tuple().
check_existing_resources(LUser, LServer, LResource) ->
%% A connection exist with the same resource. We replace it:
Sessions = ?SM_BACKEND:get_sessions(LUser, LServer, LResource),
SIDs = [S#session.sid || S <- Sessions],
if
SIDs == [] ->
ok;
true ->
MaxSID = lists:max(SIDs),
lists:foreach(
fun({_, Pid} = S) when S /= MaxSID ->
Pid ! replaced;
(_) -> ok
end, SIDs)
end.
-spec check_max_sessions(LUser :: ejabberd:user(), LServer :: ejabberd:server()) -> ok | replaced.
check_max_sessions(LUser, LServer) ->
If the number of sessions for a given is reached , we replace the
%% first one
Sessions = ?SM_BACKEND:get_sessions(LUser, LServer),
SIDs = [S#session.sid || S <- Sessions],
MaxSessions = get_max_user_sessions(LUser, LServer),
if
length(SIDs) =< MaxSessions ->
ok;
true ->
{_, Pid} = lists:min(SIDs),
Pid ! replaced
end.
%% @doc Get the user_max_session setting
This option defines the number of time a given users are allowed to
%% log in. Defaults to infinity
-spec get_max_user_sessions(LUser, Host) -> infinity | pos_integer() when
LUser :: ejabberd:user(),
Host :: ejabberd:server().
get_max_user_sessions(LUser, Host) ->
case acl:match_rule(
Host, max_user_sessions, jid:make(LUser, Host, <<>>)) of
Max when is_integer(Max) -> Max;
infinity -> infinity;
_ -> ?MAX_USER_SESSIONS
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec process_iq(From, To, Packet) -> Result when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel(),
Result :: ok | todo | pid() | {error, lager_not_running} | {process_iq, _, _, _}.
process_iq(From, To, Packet) ->
IQ = jlib:iq_query_info(Packet),
case IQ of
#iq{xmlns = XMLNS} ->
Host = To#jid.lserver,
case ets:lookup(sm_iqtable, {XMLNS, Host}) of
%% 先尝试在sm_iqtable中找到模块家函数的
%% 然后直接处理
[{_, Module, Function}] ->
ResIQ = Module:Function(From, To, IQ),
if
ResIQ /= ignore ->
ejabberd_router:route(To, From,
jlib:iq_to_xml(ResIQ));
true ->
ok
end;
%% 如果有附加选项,需要交给gen_iq_handler
[{_, Module, Function, Opts}] ->
gen_iq_handler:handle(Host, Module, Function, Opts,
From, To, IQ);
[] ->
Err = jlib:make_error_reply(
Packet, ?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err)
end;
reply ->
ok;
_ ->
Err = jlib:make_error_reply(Packet, ?ERR_BAD_REQUEST),
ejabberd_router:route(To, From, Err),
ok
end.
-spec force_update_presence({binary(), ejabberd:server()}) -> 'ok'.
force_update_presence({LUser, LServer}) ->
Ss = ?SM_BACKEND:get_sessions(LUser, LServer),
lists:foreach(fun(#session{sid = {_, Pid}}) ->
Pid ! {force_update_presence, LUser}
end, Ss).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% ejabberd commands
-spec commands() -> [ejabberd_commands:cmd(), ...].
commands() ->
[
%% TODO: Implement following API functions with pluggable backends architcture
%% #ejabberd_commands{name = connected_users,
%% tags = [session],
%% desc = "List all established sessions",
%% module = ?MODULE, function = connected_users,
%% args = [],
%% result = {connected_users, {list, {sessions, string}}}},
%% #ejabberd_commands{name = connected_users_number,
%% tags = [session, stats],
%% desc = "Get the number of established sessions",
%% module = ?MODULE, function = connected_users_number,
%% args = [],
%% result = {num_sessions, integer}},
#ejabberd_commands{name = user_resources,
tags = [session],
desc = "List user's connected resources",
module = ?MODULE, function = user_resources,
args = [{user, string}, {host, string}],
result = {resources, {list, {resource, binary}}}}
].
ejabberd管理命令
%% 获得user的resources
-spec user_resources(UserStr :: string(), ServerStr :: string()) -> [binary()].
user_resources(UserStr, ServerStr) ->
Resources = get_user_resources(list_to_binary(UserStr), list_to_binary(ServerStr)),
lists:sort(Resources).
%% sm_backend的代码
-spec sm_backend(backend()) -> string().
sm_backend(Backend) ->
lists:flatten(
["-module(ejabberd_sm_backend).
-export([backend/0]).
-spec backend() -> atom().
backend() ->
ejabberd_sm_",
atom_to_list(Backend),
".\n"]).
-spec get_cached_unique_count() -> non_neg_integer().
get_cached_unique_count() ->
case mongoose_metrics:get_metric_value(?UNIQUE_COUNT_CACHE) of
{ok, DataPoints} ->
proplists:get_value(value, DataPoints);
_ ->
0
end.
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/apps/ejabberd/src/ejabberd_sm.erl | erlang | ----------------------------------------------------------------------
Purpose : Session manager
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.
along with this program; if not, write to the Free Software
----------------------------------------------------------------------
API
Hook handlers
gen_server callbacks
xmpp_router callback
default value for the maximum number of user connections
====================================================================
API
====================================================================
--------------------------------------------------------------------
Description: Starts the server
--------------------------------------------------------------------
默认不使用优先级
当用户开启session的时候,我们会执行sm_register_connection_hook
====================================================================
Hook handlers
====================================================================
====================================================================
gen_server callbacks
====================================================================
--------------------------------------------------------------------
Function: init(Args) -> {ok, State} |
ignore |
{stop, Reason}
Description: Initiates the server
--------------------------------------------------------------------
动态生成ejabberd_sm_backend的代码
需要改掉Ping的方式
--------------------------------------------------------------------
% 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
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
us是{LUser, LServer}
要求后端开启session,这个版本开始支持Redis后端了
解析出目标的信息
得到用户所有的链接进行广播
do nothing
开始进行消息路由
如果没有指定resource的话
Backward compatibility
Backward compatibility
@doc The default list applies to the user as a whole,
and is processed if there is no active list set
for the target session/resource to which a stanza is addressed,
or if there are no current sessions for the user.
@doc Check if privacy rules allow this delivery
Function copied from ejabberd_c2s.erl
得到用户的所有链接,进行广播
Route messages to all priority that equals the max, if
positive
we will lose message if PID is not alive
Ignore other priority:
如果不在线,那么进行离线存储
@doc On new session, check if some existing connections need to be replace
TODO: Depending on how this is executed, there could be an unneeded
replacement for max_sessions. We need to check this at some point.
A connection exist with the same resource. We replace it:
first one
@doc Get the user_max_session setting
log in. Defaults to infinity
先尝试在sm_iqtable中找到模块家函数的
然后直接处理
如果有附加选项,需要交给gen_iq_handler
ejabberd commands
TODO: Implement following API functions with pluggable backends architcture
#ejabberd_commands{name = connected_users,
tags = [session],
desc = "List all established sessions",
module = ?MODULE, function = connected_users,
args = [],
result = {connected_users, {list, {sessions, string}}}},
#ejabberd_commands{name = connected_users_number,
tags = [session, stats],
desc = "Get the number of established sessions",
module = ?MODULE, function = connected_users_number,
args = [],
result = {num_sessions, integer}},
获得user的resources
sm_backend的代码 | File :
Author : < >
Created : 24 Nov 2002 by < >
ejabberd , Copyright ( C ) 2002 - 2011 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
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
-module(ejabberd_sm).
-author('').
-behaviour(gen_server).
-behaviour(xmpp_router).
-export([start_link/0,
route/3,
open_session/5, open_session/6,
close_session/5,
check_in_subscription/6,
bounce_offline_message/3,
disconnect_removed_user/2,
get_user_resources/2,
set_presence/7,
unset_presence/6,
close_session_unset_presence/6,
get_unique_sessions_number/0,
get_total_sessions_number/0,
get_node_sessions_number/0,
get_vh_session_number/1,
get_vh_session_list/1,
get_full_session_list/0,
register_iq_handler/4,
register_iq_handler/5,
unregister_iq_handler/2,
force_update_presence/1,
user_resources/2,
get_session_pid/3,
get_session/3,
get_session_ip/3,
get_user_present_resources/2
]).
-export([node_cleanup/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-export([do_route/3]).
-include("ejabberd.hrl").
-include("jlib.hrl").
-include("ejabberd_commands.hrl").
-include("mod_privacy.hrl").
-record(state, {}).
-type state() :: #state{}.
-type sid() :: tuple().
-type priority() :: integer() | undefined.
-type session() :: #session{
sid :: sid(),
usr :: ejabberd:simple_jid(),
us :: ejabberd:simple_bare_jid(),
priority :: priority(),
info :: list()
}.
Session representation as 4 - tuple .
-type ses_tuple() :: {USR :: ejabberd:simple_jid(),
Sid :: ejabberd_sm:sid(),
Prio :: priority(),
Info :: list()}.
-type backend() :: ejabberd_sm_mnesia | ejabberd_sm_redis.
-type close_reason() :: resumed | normal | replaced.
-export_type([session/0,
sid/0,
ses_tuple/0,
backend/0,
close_reason/0
]).
-define(MAX_USER_SESSIONS, 100).
-define(SM_BACKEND, (ejabberd_sm_backend:backend())).
-define(UNIQUE_COUNT_CACHE, [cache, unique_sessions_number]).
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
-spec start_link() -> 'ignore' | {'error',_} | {'ok',pid()}.
start_link() ->
mongoose_metrics:ensure_metric(?UNIQUE_COUNT_CACHE, gauge),
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
-spec route(From, To, Packet) -> ok when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel() | ejabberd_c2s:broadcast().
route(From, To, Packet) ->
xmpp_router:route(?MODULE, From, To, Packet).
-spec open_session(SID, User, Server, Resource, Info) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: binary(),
Info :: 'undefined' | [any()].
open_session(SID, User, Server, Resource, Info) ->
open_session(SID, User, Server, Resource, undefined, Info).
-spec open_session(SID, User, Server, Resource, Priority, Info) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: binary(),
Priority :: integer() | undefined,
Info :: 'undefined' | [any()].
open_session(SID, User, Server, Resource, Priority, Info) ->
set_session(SID, User, Server, Resource, Priority, Info),
check_for_sessions_to_replace(User, Server, Resource),
JID = jid:make(User, Server, Resource),
ejabberd_hooks:run(sm_register_connection_hook, JID#jid.lserver,
[SID, JID, Info]).
-spec close_session(SID, User, Server, Resource, Reason) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource(),
Reason :: close_reason().
close_session(SID, User, Server, Resource, Reason) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
Info = case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[Session] ->
Session#session.info;
_ ->
[]
end,
?SM_BACKEND:delete_session(SID, LUser, LServer, LResource),
JID = jid:make(User, Server, Resource),
ejabberd_hooks:run(sm_remove_connection_hook, JID#jid.lserver,
[SID, JID, Info, Reason]).
-spec check_in_subscription(Acc, User, Server, JID, Type, Reason) -> any() | {stop, false} when
Acc :: any(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
JID :: ejabberd:jid(),
Type :: any(),
Reason :: any().
check_in_subscription(Acc, User, Server, _JID, _Type, _Reason) ->
case ejabberd_auth:is_user_exists(User, Server) of
true ->
Acc;
false ->
{stop, false}
end.
-spec bounce_offline_message(From, To, Packet) -> stop when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel().
bounce_offline_message(#jid{server = Server} = From, To, Packet) ->
ejabberd_hooks:run(xmpp_bounce_message,
Server,
[Server, Packet]),
Err = jlib:make_error_reply(Packet, ?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err),
stop.
-spec disconnect_removed_user(User :: ejabberd:user(), Server :: ejabberd:server()) ->
'ok'.
disconnect_removed_user(User, Server) ->
ejabberd_sm:route(jid:make(<<>>, <<>>, <<>>),
jid:make(User, Server, <<>>),
{broadcast, {exit, <<"User removed">>}}).
-spec get_user_resources(User :: ejabberd:user(), Server :: ejabberd:server()) -> [binary()].
get_user_resources(User, Server) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
Ss = ?SM_BACKEND:get_sessions(LUser, LServer),
[element(3, S#session.usr) || S <- clean_session_list(Ss)].
-spec get_session_ip(User, Server, Resource) -> undefined | {inet:ip_address(), integer()} when
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource().
get_session_ip(User, Server, Resource) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[] ->
undefined;
Ss ->
Session = lists:max(Ss),
proplists:get_value(ip, Session#session.info)
end.
-spec get_session(User, Server, Resource) -> offline | ses_tuple() when
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource().
get_session(User, Server, Resource) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[] ->
offline;
Ss ->
Session = lists:max(Ss),
{Session#session.usr,
Session#session.sid,
Session#session.priority,
Session#session.info}
end.
-spec set_presence(SID, User, Server, Resource, Prio, Presence, Info) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource(),
Prio :: 'undefined' | integer(),
Presence :: any(),
Info :: 'undefined' | [any()].
set_presence(SID, User, Server, Resource, Priority, Presence, Info) ->
set_session(SID, User, Server, Resource, Priority, Info),
ejabberd_hooks:run(set_presence_hook, jid:nameprep(Server),
[User, Server, Resource, Presence]).
-spec unset_presence(SID, User, Server, Resource, Status, Info) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource(),
Status :: any(),
Info :: 'undefined' | [any()].
unset_presence(SID, User, Server, Resource, Status, Info) ->
set_session(SID, User, Server, Resource, undefined, Info),
LServer = jid:nameprep(Server),
ejabberd_hooks:run(unset_presence_hook, LServer,
[jid:nodeprep(User), LServer,
jid:resourceprep(Resource), Status]).
-spec close_session_unset_presence(SID, User, Server, Resource, Status, Reason) -> ok when
SID :: 'undefined' | sid(),
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource(),
Status :: any(),
Reason :: close_reason().
close_session_unset_presence(SID, User, Server, Resource, Status, Reason) ->
close_session(SID, User, Server, Resource, Reason),
LServer = jid:nameprep(Server),
ejabberd_hooks:run(unset_presence_hook, LServer,
[jid:nodeprep(User), LServer,
jid:resourceprep(Resource), Status]).
-spec get_session_pid(User, Server, Resource) -> none | pid() when
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource().
get_session_pid(User, Server, Resource) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[#session{sid = {_, Pid}}] ->
Pid;
_ ->
none
end.
-spec get_unique_sessions_number() -> integer().
get_unique_sessions_number() ->
try
C = ?SM_BACKEND:unique_count(),
mongoose_metrics:update(?UNIQUE_COUNT_CACHE, C),
C
catch
_:_ ->
get_cached_unique_count()
end.
-spec get_total_sessions_number() -> integer().
get_total_sessions_number() ->
?SM_BACKEND:total_count().
-spec get_vh_session_number(ejabberd:server()) -> non_neg_integer().
get_vh_session_number(Server) ->
length(?SM_BACKEND:get_sessions(Server)).
-spec get_vh_session_list(ejabberd:server()) -> [ses_tuple()].
get_vh_session_list(Server) ->
?SM_BACKEND:get_sessions(Server).
-spec get_node_sessions_number() -> non_neg_integer().
get_node_sessions_number() ->
{value, {active, Active}} = lists:keysearch(active, 1, supervisor:count_children(ejabberd_c2s_sup)),
Active.
-spec get_full_session_list() -> [session()].
get_full_session_list() ->
?SM_BACKEND:get_sessions().
register_iq_handler(Host, XMLNS, Module, Fun) ->
ejabberd_sm ! {register_iq_handler, Host, XMLNS, Module, Fun}.
register_iq_handler(Host, XMLNS, Module, Fun, Opts) ->
ejabberd_sm ! {register_iq_handler, Host, XMLNS, Module, Fun, Opts}.
unregister_iq_handler(Host, XMLNS) ->
ejabberd_sm ! {unregister_iq_handler, Host, XMLNS}.
node_cleanup(Node) ->
gen_server:call(?MODULE, {node_cleanup, Node}).
{ ok , State , Timeout } |
-spec init(_) -> {ok, state()}.
init([]) ->
{Backend, Opts} = ejabberd_config:get_global_option(sm_backend),
{Mod, Code} = dynamic_compile:from_string(sm_backend(Backend)),
code:load_binary(Mod, "ejabberd_sm_backend.erl", Code),
创建IQ管理器,用来保存IQ的响应情况,也就是说
ets:new(sm_iqtable, [named_table]),
ejabberd_hooks:add(node_cleanup, global, ?MODULE, node_cleanup, 50),
lists:foreach(
fun(Host) ->
ejabberd_hooks:add(roster_in_subscription, Host,
ejabberd_sm, check_in_subscription, 20),
ejabberd_hooks:add(offline_message_hook, Host,
ejabberd_sm, bounce_offline_message, 100),
ejabberd_hooks:add(remove_user, Host,
ejabberd_sm, disconnect_removed_user, 100)
end, ?MYHOSTS),
ejabberd_commands:register_commands(commands()),
?SM_BACKEND:start(Opts),
{ok, #state{}}.
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call({node_cleanup, Node}, _From, State) ->
BackendModule = ?SM_BACKEND,
{TimeDiff, _R} = timer:tc(fun BackendModule:cleanup/1, [Node]),
?INFO_MSG("sessions cleanup after node=~p, took=~pms",
[Node, erlang:round(TimeDiff / 1000)]),
{reply, ok, State};
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, 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 } |
-spec handle_info(_,_) -> {'noreply',_}.
handle_info({route, From, To, Packet}, State) ->
xmpp_router:route(?MODULE,From,To,Packet),
{noreply, State};
handle_info({register_iq_handler, Host, XMLNS, Module, Function}, State) ->
ets:insert(sm_iqtable, {{XMLNS, Host}, Module, Function}),
{noreply, State};
handle_info({register_iq_handler, Host, XMLNS, Module, Function, Opts}, State) ->
ets:insert(sm_iqtable, {{XMLNS, Host}, Module, Function, Opts}),
{noreply, State};
handle_info({unregister_iq_handler, Host, XMLNS}, State) ->
case ets:lookup(sm_iqtable, {XMLNS, Host}) of
[{_, Module, Function, Opts}] ->
gen_iq_handler:stop_iq_handler(Module, Function, Opts);
_ ->
ok
end,
ets:delete(sm_iqtable, {XMLNS, Host}),
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
-spec terminate(_,state()) -> 'ok'.
terminate(_Reason, _State) ->
ejabberd_commands:unregister_commands(commands()),
ok.
Func : code_change(OldVsn , State , Extra ) - > { ok , NewState }
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
-spec set_session(SID, User, Server, Resource, Prio, Info) -> ok | {error, any()} when
SID :: sid() | 'undefined',
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource(),
Prio :: priority(),
Info :: undefined | [any()].
set_session(SID, User, Server, Resource, Priority, Info) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
US = {LUser, LServer},
USR = {LUser, LServer, LResource},
usr是LUser , LServer , LResource
Session = #session{sid = SID,
usr = USR,
us = US,
priority = Priority,
info = Info},
?SM_BACKEND:create_session(LUser, LServer, LResource, Session).
-spec do_route(From, To, Packet) -> ok when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel() | ejabberd_c2s:broadcast().
do_route(From, To, {broadcast, _} = Broadcast) ->
?DEBUG("from=~p,to=~p,broadcast=~p", [From, To, Broadcast]),
#jid{ luser = LUser, lserver = LServer, lresource = LResource} = To,
case LResource of
<<>> ->
CurrentPids = get_user_present_pids(LUser, LServer),
ejabberd_hooks:run(sm_broadcast, To#jid.lserver,
[From, To, Broadcast, length(CurrentPids)]),
?DEBUG("bc_to=~p~n", CurrentPids),
lists:foreach(fun({_, Pid}) -> Pid ! Broadcast end, CurrentPids);
_ ->
case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[] ->
Ss ->
Session = lists:max(Ss),
Pid = element(2, Session#session.sid),
?DEBUG("sending to process ~p~n", [Pid]),
Pid ! Broadcast
end
end;
do_route(From, To, Packet) ->
?DEBUG("session manager~n\tfrom ~p~n\tto ~p~n\tpacket ~P~n",
[From, To, Packet, 8]),
#jid{ luser = LUser, lserver = LServer, lresource = LResource} = To,
#xmlel{name = Name, attrs = Attrs} = Packet,
case LResource of
<<>> ->
do_route_no_resource(Name, xml:get_attr_s(<<"type">>, Attrs),
From, To, Packet);
_ ->
case ?SM_BACKEND:get_sessions(LUser, LServer, LResource) of
[] ->
do_route_offline(Name, xml:get_attr_s(<<"type">>, Attrs),
From, To, Packet);
Ss ->
Session = lists:max(Ss),
Pid = element(2, Session#session.sid),
?DEBUG("sending to process ~p~n", [Pid]),
Pid ! {route, From, To, Packet}
end
end.
-spec do_route_no_resource_presence_prv(From, To, Packet, Type, Reason) -> boolean() when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel(),
Type :: 'subscribe' | 'subscribed' | 'unsubscribe' | 'unsubscribed',
Reason :: any().
do_route_no_resource_presence_prv(From,To,Packet,Type,Reason) ->
is_privacy_allow(From, To, Packet) andalso ejabberd_hooks:run_fold(
roster_in_subscription,
To#jid.lserver,
false,
[To#jid.user, To#jid.server, From, Type, Reason]).
-spec do_route_no_resource_presence(Type, From, To, Packet) -> boolean() when
Type :: binary(),
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel().
do_route_no_resource_presence(<<"subscribe">>, From, To, Packet) ->
Reason = xml:get_path_s(Packet, [{elem, <<"status">>}, cdata]),
do_route_no_resource_presence_prv(From, To, Packet, subscribe, Reason);
do_route_no_resource_presence(<<"subscribed">>, From, To, Packet) ->
do_route_no_resource_presence_prv(From, To, Packet, subscribed, <<>>);
do_route_no_resource_presence(<<"unsubscribe">>, From, To, Packet) ->
do_route_no_resource_presence_prv(From, To, Packet, unsubscribe, <<>>);
do_route_no_resource_presence(<<"unsubscribed">>, From, To, Packet) ->
do_route_no_resource_presence_prv(From, To, Packet, unsubscribed, <<>>);
do_route_no_resource_presence(_, _, _, _) ->
true.
-spec do_route_no_resource(Name, Type, From, To, Packet) -> Result when
Name :: undefined | binary(),
Type :: any(),
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel(),
Result ::ok | stop | todo | pid() | {error, lager_not_running} | {process_iq, _, _, _}.
do_route_no_resource(<<"presence">>, Type, From, To, Packet) ->
case do_route_no_resource_presence(Type, From, To, Packet) of
true ->
PResources = get_user_present_resources(To#jid.luser, To#jid.lserver),
lists:foreach(
fun({_, R}) ->
do_route(From, jid:replace_resource(To, R), Packet)
end, PResources);
false ->
ok
end;
do_route_no_resource(<<"message">>, _, From, To, Packet) ->
route_message(From, To, Packet);
do_route_no_resource(<<"iq">>, _, From, To, Packet) ->
process_iq(From, To, Packet);
do_route_no_resource(<<"broadcast">>, _, From, To, Packet) ->
ejabberd_hooks:run(sm_broadcast, To#jid.lserver, [From, To, Packet]),
broadcast_packet(From, To, Packet);
do_route_no_resource(_, _, _, _, _) ->
ok.
-spec do_route_offline(Name, Type, From, To, Packet) -> ok | stop when
Name :: 'undefined' | binary(),
Type :: binary(),
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel().
do_route_offline(<<"message">>, _, From, To, Packet) ->
route_message(From, To, Packet);
do_route_offline(<<"iq">>, <<"error">>, _From, _To, _Packet) ->
ok;
do_route_offline(<<"iq">>, <<"result">>, _From, _To, _Packet) ->
ok;
do_route_offline(<<"iq">>, _, From, To, Packet) ->
Err = jlib:make_error_reply(Packet, ?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err);
do_route_offline(_, _, _, _, _) ->
?DEBUG("packet droped~n", []),
ok.
-spec broadcast_packet(From :: ejabberd:jid(), To :: ejabberd:jid(), Packet :: jlib:xmlel()) -> ok.
broadcast_packet(From, To, Packet) ->
#jid{user = User, server = Server} = To,
lists:foreach(
fun(R) ->
do_route(From,
jid:replace_resource(To, R),
Packet)
end, get_user_resources(User, Server)).
-spec is_privacy_allow(From, To, Packet) -> boolean() when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel().
is_privacy_allow(From, To, Packet) ->
User = To#jid.user,
Server = To#jid.server,
PrivacyList = ejabberd_hooks:run_fold(privacy_get_user_list, Server,
#userlist{}, [User, Server]),
is_privacy_allow(From, To, Packet, PrivacyList).
-spec is_privacy_allow(From, To, Packet, PrivacyList) -> boolean() when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel(),
PrivacyList :: list().
is_privacy_allow(From, To, Packet, PrivacyList) ->
User = To#jid.user,
Server = To#jid.server,
allow == ejabberd_hooks:run_fold(
privacy_check_packet, Server,
allow,
[User, Server, PrivacyList,
{From, To, Packet}, in]).
-spec route_message(From, To, Packet) -> ok | stop when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel().
route_message(From, To, Packet) ->
LUser = To#jid.luser,
LServer = To#jid.lserver,
PrioPid = get_user_present_pids(LUser,LServer),
case catch lists:max(PrioPid) of
{Priority, _} when is_integer(Priority), Priority >= 0 ->
lists:foreach(
fun({Prio, Pid}) when Prio == Priority ->
Pid ! {route, From, To, Packet};
({_Prio, _Pid}) ->
ok
end,
PrioPid);
_ ->
case xml:get_tag_attr_s(<<"type">>, Packet) of
<<"error">> ->
ok;
<<"groupchat">> ->
bounce_offline_message(From, To, Packet);
<<"headline">> ->
bounce_offline_message(From, To, Packet);
_ ->
case ejabberd_auth:is_user_exists(LUser, LServer) of
true ->
case is_privacy_allow(From, To, Packet) of
true ->
ejabberd_hooks:run(offline_message_hook,
LServer,
[From, To, Packet]);
false ->
ok
end;
_ ->
Err = jlib:make_error_reply(
Packet, ?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err)
end
end
end.
-spec clean_session_list([sid()]) -> [sid()].
clean_session_list(Ss) ->
clean_session_list(lists:keysort(#session.usr, Ss), []).
-spec clean_session_list([sid()],[sid()]) -> [sid()].
clean_session_list([], Res) ->
Res;
clean_session_list([S], Res) ->
[S | Res];
clean_session_list([S1, S2 | Rest], Res) ->
if
S1#session.usr == S2#session.usr ->
if
S1#session.sid > S2#session.sid ->
clean_session_list([S1 | Rest], Res);
true ->
clean_session_list([S2 | Rest], Res)
end;
true ->
clean_session_list([S2 | Rest], [S1 | Res])
end.
-spec get_user_present_pids(LUser, LServer) -> [{priority(), pid()}] when
LUser :: ejabberd:luser(),
LServer :: ejabberd:lserver().
get_user_present_pids(LUser, LServer) ->
Ss = clean_session_list(?SM_BACKEND:get_sessions(LUser, LServer)),
[{S#session.priority, element(2,S#session.sid)}
|| S <- Ss, is_integer(S#session.priority)].
-spec get_user_present_resources(LUser :: ejabberd:user(),
LServer :: ejabberd:server()
) -> [{priority(), binary()}].
get_user_present_resources(LUser, LServer) ->
Ss = ?SM_BACKEND:get_sessions(LUser, LServer),
[{S#session.priority, element(3, S#session.usr)} ||
S <- clean_session_list(Ss), is_integer(S#session.priority)].
-spec check_for_sessions_to_replace(User, Server, Resource) -> ok | replaced when
User :: ejabberd:user(),
Server :: ejabberd:server(),
Resource :: ejabberd:resource().
check_for_sessions_to_replace(User, Server, Resource) ->
LUser = jid:nodeprep(User),
LServer = jid:nameprep(Server),
LResource = jid:resourceprep(Resource),
check_existing_resources(LUser, LServer, LResource),
check_max_sessions(LUser, LServer).
-spec check_existing_resources(LUser, LServer, LResource) -> ok when
LUser :: 'error' | ejabberd:luser() | tuple(),
LServer :: 'error' | ejabberd:lserver() | tuple(),
LResource :: 'error' | ejabberd:lresource() | [byte()] | tuple().
check_existing_resources(LUser, LServer, LResource) ->
Sessions = ?SM_BACKEND:get_sessions(LUser, LServer, LResource),
SIDs = [S#session.sid || S <- Sessions],
if
SIDs == [] ->
ok;
true ->
MaxSID = lists:max(SIDs),
lists:foreach(
fun({_, Pid} = S) when S /= MaxSID ->
Pid ! replaced;
(_) -> ok
end, SIDs)
end.
-spec check_max_sessions(LUser :: ejabberd:user(), LServer :: ejabberd:server()) -> ok | replaced.
check_max_sessions(LUser, LServer) ->
If the number of sessions for a given is reached , we replace the
Sessions = ?SM_BACKEND:get_sessions(LUser, LServer),
SIDs = [S#session.sid || S <- Sessions],
MaxSessions = get_max_user_sessions(LUser, LServer),
if
length(SIDs) =< MaxSessions ->
ok;
true ->
{_, Pid} = lists:min(SIDs),
Pid ! replaced
end.
This option defines the number of time a given users are allowed to
-spec get_max_user_sessions(LUser, Host) -> infinity | pos_integer() when
LUser :: ejabberd:user(),
Host :: ejabberd:server().
get_max_user_sessions(LUser, Host) ->
case acl:match_rule(
Host, max_user_sessions, jid:make(LUser, Host, <<>>)) of
Max when is_integer(Max) -> Max;
infinity -> infinity;
_ -> ?MAX_USER_SESSIONS
end.
-spec process_iq(From, To, Packet) -> Result when
From :: ejabberd:jid(),
To :: ejabberd:jid(),
Packet :: jlib:xmlel(),
Result :: ok | todo | pid() | {error, lager_not_running} | {process_iq, _, _, _}.
process_iq(From, To, Packet) ->
IQ = jlib:iq_query_info(Packet),
case IQ of
#iq{xmlns = XMLNS} ->
Host = To#jid.lserver,
case ets:lookup(sm_iqtable, {XMLNS, Host}) of
[{_, Module, Function}] ->
ResIQ = Module:Function(From, To, IQ),
if
ResIQ /= ignore ->
ejabberd_router:route(To, From,
jlib:iq_to_xml(ResIQ));
true ->
ok
end;
[{_, Module, Function, Opts}] ->
gen_iq_handler:handle(Host, Module, Function, Opts,
From, To, IQ);
[] ->
Err = jlib:make_error_reply(
Packet, ?ERR_SERVICE_UNAVAILABLE),
ejabberd_router:route(To, From, Err)
end;
reply ->
ok;
_ ->
Err = jlib:make_error_reply(Packet, ?ERR_BAD_REQUEST),
ejabberd_router:route(To, From, Err),
ok
end.
-spec force_update_presence({binary(), ejabberd:server()}) -> 'ok'.
force_update_presence({LUser, LServer}) ->
Ss = ?SM_BACKEND:get_sessions(LUser, LServer),
lists:foreach(fun(#session{sid = {_, Pid}}) ->
Pid ! {force_update_presence, LUser}
end, Ss).
-spec commands() -> [ejabberd_commands:cmd(), ...].
commands() ->
[
#ejabberd_commands{name = user_resources,
tags = [session],
desc = "List user's connected resources",
module = ?MODULE, function = user_resources,
args = [{user, string}, {host, string}],
result = {resources, {list, {resource, binary}}}}
].
ejabberd管理命令
-spec user_resources(UserStr :: string(), ServerStr :: string()) -> [binary()].
user_resources(UserStr, ServerStr) ->
Resources = get_user_resources(list_to_binary(UserStr), list_to_binary(ServerStr)),
lists:sort(Resources).
-spec sm_backend(backend()) -> string().
sm_backend(Backend) ->
lists:flatten(
["-module(ejabberd_sm_backend).
-export([backend/0]).
-spec backend() -> atom().
backend() ->
ejabberd_sm_",
atom_to_list(Backend),
".\n"]).
-spec get_cached_unique_count() -> non_neg_integer().
get_cached_unique_count() ->
case mongoose_metrics:get_metric_value(?UNIQUE_COUNT_CACHE) of
{ok, DataPoints} ->
proplists:get_value(value, DataPoints);
_ ->
0
end.
|
5745620850b68c5efcbe82aa9c189b2ca76fe3b9209ebdbbec4faa40ae71af44 | iu-parfunc/verified-instances | TH.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE CPP #
|
Module : Generics . Deriving . Newtypeless . TH
Copyright : ( c ) 2008 - -2009 Universiteit Utrecht
License : BSD3
Maintainer :
Stability : experimental
Portability : non - portable
This module contains Template Haskell code that can be used to
automatically generate the boilerplate code for the generic deriving
library .
To use these functions , pass the name of a data type as an argument :
@
& # 123;-# ; LANGUAGE TemplateHaskell & # 35;-} ;
data Example a = Example Int Char a
$ ( ' deriveAll0 ' '' Example ) -- Derives Generic instance
$ ( ' deriveAll1 ' '' Example ) -- Derives Generic1 instance
$ ( ' deriveAll0And1 ' ' ' Example ) -- Derives Generic and Generic1 instances
@
On GHC 7.4 or later , this code can also be used with data families . To derive
for a data family instance , pass the name of one of the instance 's constructors :
@
& # 123;-# ; LANGUAGE FlexibleInstances , TemplateHaskell , TypeFamilies & # 35;-} ;
data family Family a b
newtype instance = FamilyChar
data instance = FamilyTrue | FamilyFalse
$ ( ' deriveAll0 ' ' FamilyChar ) -- instance Generic ( Family Char b ) where ...
$ ( ' deriveAll1 ' ' FamilyTrue ) -- instance Generic1 ( ) where ...
-- Alternatively , one could type $ ( deriveAll1 ' FamilyFalse )
@
Module : Generics.Deriving.Newtypeless.TH
Copyright : (c) 2008--2009 Universiteit Utrecht
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
This module contains Template Haskell code that can be used to
automatically generate the boilerplate code for the generic deriving
library.
To use these functions, pass the name of a data type as an argument:
@
{-# LANGUAGE TemplateHaskell #-}
data Example a = Example Int Char a
$('deriveAll0' ''Example) -- Derives Generic instance
$('deriveAll1' ''Example) -- Derives Generic1 instance
$('deriveAll0And1' ''Example) -- Derives Generic and Generic1 instances
@
On GHC 7.4 or later, this code can also be used with data families. To derive
for a data family instance, pass the name of one of the instance's constructors:
@
{-# LANGUAGE FlexibleInstances, TemplateHaskell, TypeFamilies #-}
data family Family a b
newtype instance Family Char x = FamilyChar Char
data instance Family Bool x = FamilyTrue | FamilyFalse
$('deriveAll0' 'FamilyChar) -- instance Generic (Family Char b) where ...
$('deriveAll1' 'FamilyTrue) -- instance Generic1 (Family Bool) where ...
-- Alternatively, one could type $(deriveAll1 'FamilyFalse)
@
-}
-- Adapted from Generics.Regular.TH
module Generics.Deriving.Newtypeless.TH (
-- * @derive@- functions
deriveMeta
, deriveData
, deriveConstructors
, deriveSelectors
, deriveAll
, deriveAll0
, deriveAll1
, deriveAll0And1
, deriveRepresentable0
, deriveRepresentable1
, deriveRep0
, deriveRep1
, simplInstance
-- * @make@- functions
-- $make
, makeRep0Inline
, makeRep0
, makeRep0FromType
, makeFrom
, makeFrom0
, makeTo
, makeTo0
, makeRep1Inline
, makeRep1
, makeRep1FromType
, makeFrom1
, makeTo1
-- * Options
-- $options
-- ** Option types
, Options(..)
, defaultOptions
, RepOptions(..)
, defaultRepOptions
, KindSigOptions
, defaultKindSigOptions
-- ** Functions with optional arguments
, deriveAll0Options
, deriveAll1Options
, deriveAll0And1Options
, deriveRepresentable0Options
, deriveRepresentable1Options
, deriveRep0Options
, deriveRep1Options
) where
import Control.Monad ((>=>), unless, when)
import Data.List (nub)
import qualified Data.Map as Map (fromList)
import Data.Maybe (catMaybes)
import Generics.Deriving.Newtypeless.TH.Internal
import Generics.Deriving.Newtypeless.TH.NonDataKinded
import Language.Haskell.TH.Lib
import Language.Haskell.TH
$ options
' Options ' gives you a way to further tweak derived ' Generic ' and ' Generic1 ' instances :
* ' RepOptions ' : By default , all derived ' Rep ' and ' Rep1 ' type instances emit the code
directly ( the ' InlineRep ' option ) . One can also choose to emit a separate type
synonym for the ' Rep ' type ( this is the functionality of ' deriveRep0 ' and
' deriveRep1 ' ) and define a ' Rep ' instance in terms of that type synonym ( the
' TypeSynonymRep ' option ) .
* ' KindSigOptions ' : By default , all derived instances will use explicit kind
signatures ( when the ' KindSigOptions ' is ' True ' ) . You might wish to set the
' KindSigOptions ' to ' False ' if you want a ' Generic'/'Generic1 ' instance at
a particular kind that GHC will infer correctly , but the functions in this
module wo n't guess correctly . For example , the following example will only
compile with ' KindSigOptions ' set to ' False ' :
@
newtype Compose ( f : : k2 - > * ) ( g : : k1 - > k2 ) ( a : : k1 ) = Compose ( f ( g a ) )
$ ( ' deriveAll1Options ' False '' Compose )
@
'Options' gives you a way to further tweak derived 'Generic' and 'Generic1' instances:
* 'RepOptions': By default, all derived 'Rep' and 'Rep1' type instances emit the code
directly (the 'InlineRep' option). One can also choose to emit a separate type
synonym for the 'Rep' type (this is the functionality of 'deriveRep0' and
'deriveRep1') and define a 'Rep' instance in terms of that type synonym (the
'TypeSynonymRep' option).
* 'KindSigOptions': By default, all derived instances will use explicit kind
signatures (when the 'KindSigOptions' is 'True'). You might wish to set the
'KindSigOptions' to 'False' if you want a 'Generic'/'Generic1' instance at
a particular kind that GHC will infer correctly, but the functions in this
module won't guess correctly. For example, the following example will only
compile with 'KindSigOptions' set to 'False':
@
newtype Compose (f :: k2 -> *) (g :: k1 -> k2) (a :: k1) = Compose (f (g a))
$('deriveAll1Options' False ''Compose)
@
-}
-- | Given the names of a generic class, a type to instantiate, a function in
-- the class and the default implementation, generates the code for a basic
-- generic instance.
simplInstance :: Name -> Name -> Name -> Name -> Q [Dec]
simplInstance cl ty fn df = do
x <- newName "x"
let typ = ForallT [PlainTV x] []
((foldl (\a -> AppT a . VarT . tyVarBndrName) (ConT (genRepName Generic DataPlain ty)) []) `AppT` (VarT x))
fmap (: []) $ instanceD (cxt []) (conT cl `appT` conT ty)
[funD fn [clause [] (normalB (varE df `appE`
(sigE (varE undefinedValName) (return typ)))) []]]
-- | Additional options for configuring derived 'Generic'/'Generic1' instances
using Template Haskell .
data Options = Options
{ repOptions :: RepOptions
, kindSigOptions :: KindSigOptions
} deriving (Eq, Ord, Read, Show)
-- | Sensible default 'Options' ('defaultRepOptions' and 'defaultKindSigOptions').
defaultOptions :: Options
defaultOptions = Options
{ repOptions = defaultRepOptions
, kindSigOptions = defaultKindSigOptions
}
-- | Configures whether 'Rep'/'Rep1' type instances should be defined inline in a
-- derived 'Generic'/'Generic1' instance ('InlineRep') or defined in terms of a
-- type synonym ('TypeSynonymRep').
data RepOptions = InlineRep
| TypeSynonymRep
deriving (Eq, Ord, Read, Show)
| ' InlineRep ' , a sensible default ' RepOptions ' .
defaultRepOptions :: RepOptions
defaultRepOptions = InlineRep
-- | 'True' if explicit kind signatures should be used in derived
-- 'Generic'/'Generic1' instances, 'False' otherwise.
type KindSigOptions = Bool
-- | 'True', a sensible default 'KindSigOptions'.
defaultKindSigOptions :: KindSigOptions
defaultKindSigOptions = True
-- | A backwards-compatible synonym for 'deriveAll0'.
deriveAll :: Name -> Q [Dec]
deriveAll = deriveAll0
-- | Given the type and the name (as string) for the type to derive,
-- generate the 'Data' instance, the 'Constructor' instances, the 'Selector'
-- instances, and the 'Representable0' instance.
deriveAll0 :: Name -> Q [Dec]
deriveAll0 = deriveAll0Options defaultOptions
-- | Like 'deriveAll0', but takes an 'Options' argument.
deriveAll0Options :: Options -> Name -> Q [Dec]
deriveAll0Options = deriveAllCommon True False
-- | Given the type and the name (as string) for the type to derive,
-- generate the 'Data' instance, the 'Constructor' instances, the 'Selector'
-- instances, and the 'Representable1' instance.
deriveAll1 :: Name -> Q [Dec]
deriveAll1 = deriveAll1Options defaultOptions
-- | Like 'deriveAll1', but takes an 'Options' argument.
deriveAll1Options :: Options -> Name -> Q [Dec]
deriveAll1Options = deriveAllCommon False True
-- | Given the type and the name (as string) for the type to derive,
-- generate the 'Data' instance, the 'Constructor' instances, the 'Selector'
-- instances, the 'Representable0' instance, and the 'Representable1' instance.
deriveAll0And1 :: Name -> Q [Dec]
deriveAll0And1 = deriveAll0And1Options defaultOptions
-- | Like 'deriveAll0And1', but takes an 'Options' argument.
deriveAll0And1Options :: Options -> Name -> Q [Dec]
deriveAll0And1Options = deriveAllCommon True True
deriveAllCommon :: Bool -> Bool -> Options -> Name -> Q [Dec]
deriveAllCommon generic generic1 opts n = do
a <- deriveMeta n
b <- if generic
then deriveRepresentableCommon Generic opts n
else return []
c <- if generic1
then deriveRepresentableCommon Generic1 opts n
else return []
return (a ++ b ++ c)
-- | Given the type and the name (as string) for the Representable0 type
-- synonym to derive, generate the 'Representable0' instance.
deriveRepresentable0 :: Name -> Q [Dec]
deriveRepresentable0 = deriveRepresentable0Options defaultOptions
-- | Like 'deriveRepresentable0', but takes an 'Options' argument.
deriveRepresentable0Options :: Options -> Name -> Q [Dec]
deriveRepresentable0Options = deriveRepresentableCommon Generic
-- | Given the type and the name (as string) for the Representable1 type
-- synonym to derive, generate the 'Representable1' instance.
deriveRepresentable1 :: Name -> Q [Dec]
deriveRepresentable1 = deriveRepresentable1Options defaultOptions
-- | Like 'deriveRepresentable1', but takes an 'Options' argument.
deriveRepresentable1Options :: Options -> Name -> Q [Dec]
deriveRepresentable1Options = deriveRepresentableCommon Generic1
deriveRepresentableCommon :: GenericClass -> Options -> Name -> Q [Dec]
deriveRepresentableCommon gClass opts n = do
rep <- if repOptions opts == InlineRep
then return []
else deriveRepCommon gClass (kindSigOptions opts) n
inst <- deriveInst gClass opts n
return (rep ++ inst)
-- | Derive only the 'Rep0' type synonym. Not needed if 'deriveRepresentable0'
-- is used.
deriveRep0 :: Name -> Q [Dec]
deriveRep0 = deriveRep0Options defaultKindSigOptions
-- | Like 'deriveRep0', but takes an 'KindSigOptions' argument.
deriveRep0Options :: KindSigOptions -> Name -> Q [Dec]
deriveRep0Options = deriveRepCommon Generic
-- | Derive only the 'Rep1' type synonym. Not needed if 'deriveRepresentable1'
-- is used.
deriveRep1 :: Name -> Q [Dec]
deriveRep1 = deriveRep1Options defaultKindSigOptions
-- | Like 'deriveRep1', but takes an 'KindSigOptions' argument.
deriveRep1Options :: KindSigOptions -> Name -> Q [Dec]
deriveRep1Options = deriveRepCommon Generic1
deriveRepCommon :: GenericClass -> KindSigOptions -> Name -> Q [Dec]
deriveRepCommon gClass useKindSigs n = do
i <- reifyDataInfo n
let (name, isNT, declTvbs, cons, dv) = either error id i
-- See Note [Forcing buildTypeInstance]
!_ <- buildTypeInstance gClass useKindSigs name declTvbs dv
tySynVars <- grabTyVarsFromCons gClass cons
-- See Note [Kind signatures in derived instances]
let tySynVars' = if useKindSigs
then tySynVars
else map unSigT tySynVars
fmap (:[]) $ tySynD (genRepName gClass dv name)
(catMaybes $ map typeToTyVarBndr tySynVars')
(repType gClass dv name isNT cons tySynVars)
deriveInst :: GenericClass -> Options -> Name -> Q [Dec]
deriveInst Generic = deriveInstCommon genericTypeName repTypeName Generic fromValName toValName
deriveInst Generic1 = deriveInstCommon generic1TypeName rep1TypeName Generic1 from1ValName to1ValName
deriveInstCommon :: Name
-> Name
-> GenericClass
-> Name
-> Name
-> Options
-> Name
-> Q [Dec]
deriveInstCommon genericName repName gClass fromName toName opts n = do
i <- reifyDataInfo n
let (name, isNT, allTvbs, cons, dv) = either error id i
useKindSigs = kindSigOptions opts
-- See Note [Forcing buildTypeInstance]
!(origTy, origKind) <- buildTypeInstance gClass useKindSigs name allTvbs dv
tyInsRHS <- if repOptions opts == InlineRep
then makeRepInline gClass dv name isNT cons origTy
else makeRepTySynApp gClass dv name cons origTy
let origSigTy = if useKindSigs
then SigT origTy origKind
else origTy
tyIns = TySynInstD repName
#if MIN_VERSION_template_haskell(2,9,0)
(TySynEqn [origSigTy] tyInsRHS)
#else
[origSigTy] tyInsRHS
#endif
mkBody maker = [clause [] (normalB $ mkCaseExp gClass name cons maker) []]
fcs = mkBody mkFrom
tcs = mkBody mkTo
fmap (:[]) $
instanceD (cxt []) (conT genericName `appT` return origSigTy)
[return tyIns, funD fromName fcs, funD toName tcs]
$ make
There are some data types for which the Template Haskell deriver functions in
this module are not sophisticated enough to infer the correct ' Generic ' or
' Generic1 ' instances . As an example , consider this data type :
@
newtype Fix f a = Fix ( f ( Fix f a ) )
@
A proper ' Generic1 ' instance would look like this :
@
instance Functor f = > Generic1 ( Fix f ) where ...
@
Unfortunately , ' deriveRepresentable1 ' can not infer the @Functor f@ constraint .
One can still define a ' Generic1 ' instance for , however , by using the
functions in this module that are prefixed with @make@- . For example :
@
$ ( ' deriveMeta ' ' ' Fix )
$ ( ' deriveRep1 ' ' ' Fix )
instance Functor f = > Generic1 ( Fix f ) where
type Rep1 ( Fix f ) = $ ( ' makeRep1Inline ' ' ' Fix [ t| Fix f | ] )
from1 = $ ( ' makeFrom1 ' ' ' Fix )
to1 = $ ( ' makeTo1 ' '' Fix )
@
Note that due to the lack of type - level lambdas in Haskell , one must manually
apply @'makeRep1Inline ' ' ' Fix@ to the type @Fix f@.
Be aware that there is a bug on GHC 7.0 , 7.2 , and 7.4 which might prevent you from
using ' makeRep0Inline ' and ' makeRep1Inline ' . In the example above , you
would experience the following error :
@
Kinded thing ` f ' used as a type
In the Template Haskell quotation [ t| Fix f | ]
@
Then a workaround is to use ' makeRep1 ' instead , which requires you to :
1 . Invoke ' deriveRep1 ' beforehand
2 . Pass as arguments the type variables that occur in the instance , in order
from left to right , topologically sorted , excluding duplicates . ( Normally ,
' makeRep1Inline ' would figure this out for you . )
Using the above example :
@
$ ( ' deriveMeta ' ' ' Fix )
$ ( ' deriveRep1 ' ' ' Fix )
instance Functor f = > Generic1 ( Fix f ) where
type Rep1 ( Fix f ) = $ ( ' makeRep1 ' ' ' Fix ) f
from1 = $ ( ' makeFrom1 ' ' ' Fix )
to1 = $ ( ' makeTo1 ' '' Fix )
@
On GHC 7.4 , you might encounter more complicated examples involving data
families . For instance :
@
data family Fix a b c d
newtype instance Fix b ( f c ) ( g b ) a = Fix ( f ( Fix b ( f c ) ( g b ) a ) )
$ ( ' deriveMeta ' ' ' Fix )
$ ( ' deriveRep1 ' ' ' Fix )
instance Functor f = > Generic1 ( Fix b ( f c ) ( g b ) ) where
type Rep1 ( Fix b ( f c ) ( g b ) ) = $ ( ' makeRep1 ' ' Fix ) b f c g
from1 = $ ( ' makeFrom1 ' ' Fix )
to1 = $ ( ' makeTo1 ' ' Fix )
@
Note that you do n't pass @b@ twice , only once .
There are some data types for which the Template Haskell deriver functions in
this module are not sophisticated enough to infer the correct 'Generic' or
'Generic1' instances. As an example, consider this data type:
@
newtype Fix f a = Fix (f (Fix f a))
@
A proper 'Generic1' instance would look like this:
@
instance Functor f => Generic1 (Fix f) where ...
@
Unfortunately, 'deriveRepresentable1' cannot infer the @Functor f@ constraint.
One can still define a 'Generic1' instance for @Fix@, however, by using the
functions in this module that are prefixed with @make@-. For example:
@
$('deriveMeta' ''Fix)
$('deriveRep1' ''Fix)
instance Functor f => Generic1 (Fix f) where
type Rep1 (Fix f) = $('makeRep1Inline' ''Fix [t| Fix f |])
from1 = $('makeFrom1' ''Fix)
to1 = $('makeTo1' ''Fix)
@
Note that due to the lack of type-level lambdas in Haskell, one must manually
apply @'makeRep1Inline' ''Fix@ to the type @Fix f@.
Be aware that there is a bug on GHC 7.0, 7.2, and 7.4 which might prevent you from
using 'makeRep0Inline' and 'makeRep1Inline'. In the @Fix@ example above, you
would experience the following error:
@
Kinded thing `f' used as a type
In the Template Haskell quotation [t| Fix f |]
@
Then a workaround is to use 'makeRep1' instead, which requires you to:
1. Invoke 'deriveRep1' beforehand
2. Pass as arguments the type variables that occur in the instance, in order
from left to right, topologically sorted, excluding duplicates. (Normally,
'makeRep1Inline' would figure this out for you.)
Using the above example:
@
$('deriveMeta' ''Fix)
$('deriveRep1' ''Fix)
instance Functor f => Generic1 (Fix f) where
type Rep1 (Fix f) = $('makeRep1' ''Fix) f
from1 = $('makeFrom1' ''Fix)
to1 = $('makeTo1' ''Fix)
@
On GHC 7.4, you might encounter more complicated examples involving data
families. For instance:
@
data family Fix a b c d
newtype instance Fix b (f c) (g b) a = Fix (f (Fix b (f c) (g b) a))
$('deriveMeta' ''Fix)
$('deriveRep1' ''Fix)
instance Functor f => Generic1 (Fix b (f c) (g b)) where
type Rep1 (Fix b (f c) (g b)) = $('makeRep1' 'Fix) b f c g
from1 = $('makeFrom1' 'Fix)
to1 = $('makeTo1' 'Fix)
@
Note that you don't pass @b@ twice, only once.
-}
-- | Generates the full 'Rep' type inline. Since this type can be quite
-- large, it is recommended you only use this to define 'Rep', e.g.,
--
-- @
-- type Rep (Foo (a :: k) b) = $('makeRep0Inline' ''Foo [t| Foo (a :: k) b |])
-- @
--
-- You can then simply refer to @Rep (Foo a b)@ elsewhere.
--
-- Note that the type passed as an argument to 'makeRep0Inline' must match the
-- type argument of 'Rep' exactly, even up to including the explicit kind
signature on This is due to a limitation of Template Haskell — without
-- the kind signature, 'makeRep0Inline' has no way of figuring out the kind of
-- @a@, and the generated type might be completely wrong as a result!
makeRep0Inline :: Name -> Q Type -> Q Type
makeRep0Inline n = makeRepCommon Generic InlineRep n . Just
-- | Generates the full 'Rep1' type inline. Since this type can be quite
-- large, it is recommended you only use this to define 'Rep1', e.g.,
--
-- @
type Rep1 ( ( a : : k ) ) = $ ( ' makeRep0Inline ' ' ' Foo [ t| Foo ( a : : k ) | ] )
-- @
--
-- You can then simply refer to @Rep1 (Foo a)@ elsewhere.
--
-- Note that the type passed as an argument to 'makeRep1Inline' must match the
-- type argument of 'Rep1' exactly, even up to including the explicit kind
signature on This is due to a limitation of Template Haskell — without
-- the kind signature, 'makeRep1Inline' has no way of figuring out the kind of
-- @a@, and the generated type might be completely wrong as a result!
makeRep1Inline :: Name -> Q Type -> Q Type
makeRep1Inline n = makeRepCommon Generic1 InlineRep n . Just
-- | Generates the 'Rep' type synonym constructor (as opposed to 'deriveRep0',
-- which generates the type synonym declaration). After splicing it into
Haskell source , it expects types as arguments . For example :
--
-- @
type Rep ( Foo a b ) = $ ( ' makeRep0 ' ' ' ) a b
-- @
--
-- The use of 'makeRep0' is generally discouraged, as it can sometimes be
-- difficult to predict the order in which you are expected to pass type
-- variables. As a result, 'makeRep0Inline' is recommended instead. However,
' makeRep0Inline ' is not usable on GHC 7.0 , 7.2 , or 7.4 due to a GHC bug ,
so ' makeRep0 ' still exists for GHC 7.0 , 7.2 , and 7.4 users .
makeRep0 :: Name -> Q Type
makeRep0 n = makeRepCommon Generic TypeSynonymRep n Nothing
-- | Generates the 'Rep1' type synonym constructor (as opposed to 'deriveRep1',
-- which generates the type synonym declaration). After splicing it into
Haskell source , it expects types as arguments . For example :
--
-- @
type Rep1 ( a ) = $ ( ' makeRep1 ' ' ' ) a
-- @
--
-- The use of 'makeRep1' is generally discouraged, as it can sometimes be
-- difficult to predict the order in which you are expected to pass type
-- variables. As a result, 'makeRep1Inline' is recommended instead. However,
' makeRep1Inline ' is not usable on GHC 7.0 , 7.2 , or 7.4 due to a GHC bug ,
so ' makeRep1 ' still exists for GHC 7.0 , 7.2 , and 7.4 users .
makeRep1 :: Name -> Q Type
makeRep1 n = makeRepCommon Generic1 TypeSynonymRep n Nothing
-- | Generates the 'Rep' type synonym constructor (as opposed to 'deriveRep0',
-- which generates the type synonym declaration) applied to its type arguments.
-- Unlike 'makeRep0', this also takes a quoted 'Type' as an argument, e.g.,
--
-- @
type Rep ( Foo ( a : : k ) b ) = $ ( ' makeRep0FromType ' ' ' Foo [ t| Foo ( a : : k ) b | ] )
-- @
--
-- Note that the type passed as an argument to 'makeRep0FromType' must match the
-- type argument of 'Rep' exactly, even up to including the explicit kind
signature on This is due to a limitation of Template Haskell — without
the kind signature , ' makeRep0FromType ' has no way of figuring out the kind of
-- @a@, and the generated type might be completely wrong as a result!
--
-- The use of 'makeRep0FromType' is generally discouraged, since 'makeRep0Inline'
-- does exactly the same thing but without having to go through an intermediate
-- type synonym, and as a result, 'makeRep0Inline' tends to be less buggy.
makeRep0FromType :: Name -> Q Type -> Q Type
makeRep0FromType n = makeRepCommon Generic TypeSynonymRep n . Just
-- | Generates the 'Rep1' type synonym constructor (as opposed to 'deriveRep1',
-- which generates the type synonym declaration) applied to its type arguments.
-- Unlike 'makeRep1', this also takes a quoted 'Type' as an argument, e.g.,
--
-- @
type Rep1 ( ( a : : k ) ) = $ ( ' makeRep1FromType ' ' ' Foo [ t| Foo ( a : : k ) | ] )
-- @
--
Note that the type passed as an argument to ' makeRep1FromType ' must match the
-- type argument of 'Rep' exactly, even up to including the explicit kind
signature on This is due to a limitation of Template Haskell — without
the kind signature , ' makeRep1FromType ' has no way of figuring out the kind of
-- @a@, and the generated type might be completely wrong as a result!
--
The use of ' makeRep1FromType ' is generally discouraged , since ' makeRep1Inline '
-- does exactly the same thing but without having to go through an intermediate
-- type synonym, and as a result, 'makeRep1Inline' tends to be less buggy.
makeRep1FromType :: Name -> Q Type -> Q Type
makeRep1FromType n = makeRepCommon Generic1 TypeSynonymRep n . Just
makeRepCommon :: GenericClass
-> RepOptions
-> Name
-> Maybe (Q Type)
-> Q Type
makeRepCommon gClass repOpts n mbQTy = do
i <- reifyDataInfo n
let (name, isNT, declTvbs, cons, dv) = either error id i
-- See Note [Forcing buildTypeInstance]
!_ <- buildTypeInstance gClass False name declTvbs dv
case (mbQTy, repOpts) of
(Just qTy, TypeSynonymRep) -> qTy >>= makeRepTySynApp gClass dv name cons
(Just qTy, InlineRep) -> qTy >>= makeRepInline gClass dv name isNT cons
(Nothing, TypeSynonymRep) -> conT $ genRepName gClass dv name
(Nothing, InlineRep) -> fail "makeRepCommon"
makeRepInline :: GenericClass
-> DataVariety
-> Name
-> Bool
-> [Con]
-> Type
-> Q Type
makeRepInline gClass dv name isNT cons ty = do
let instVars = map tyVarBndrToType $ requiredTyVarsOfType ty
repType gClass dv name isNT cons instVars
makeRepTySynApp :: GenericClass
-> DataVariety
-> Name
-> [Con]
-> Type
-> Q Type
makeRepTySynApp gClass dv name cons ty = do
-- Here, we figure out the distinct type variables (in order from left-to-right)
of the LHS of the Rep(1 ) instance . We call unKindedTV because the kind
-- inferencer can figure out the kinds perfectly well, so we don't need to
-- give anything here explicit kind signatures.
let instTvbs = map unKindedTV $ requiredTyVarsOfType ty
We grab the type variables from the first constructor 's type signature .
-- Or, if there are no constructors, we grab no type variables. The latter
-- is okay because we use zipWith to ensure that we never pass more type
-- variables than the generated type synonym can accept.
-- See Note [Arguments to generated type synonyms]
tySynVars <- grabTyVarsFromCons gClass cons
return . applyTyToTvbs (genRepName gClass dv name)
$ zipWith const instTvbs tySynVars
-- | A backwards-compatible synonym for 'makeFrom0'.
makeFrom :: Name -> Q Exp
makeFrom = makeFrom0
-- | Generates a lambda expression which behaves like 'from'.
makeFrom0 :: Name -> Q Exp
makeFrom0 = makeFunCommon mkFrom Generic
-- | A backwards-compatible synonym for 'makeTo0'.
makeTo :: Name -> Q Exp
makeTo = makeTo0
-- | Generates a lambda expression which behaves like 'to'.
makeTo0 :: Name -> Q Exp
makeTo0 = makeFunCommon mkTo Generic
-- | Generates a lambda expression which behaves like 'from1'.
makeFrom1 :: Name -> Q Exp
makeFrom1 = makeFunCommon mkFrom Generic1
| Generates a lambda expression which behaves like ' ' .
makeTo1 :: Name -> Q Exp
makeTo1 = makeFunCommon mkTo Generic1
makeFunCommon :: (GenericClass -> Int -> Int -> Name -> [Con] -> Q Match)
-> GenericClass -> Name -> Q Exp
makeFunCommon maker gClass n = do
i <- reifyDataInfo n
let (name, _, allTvbs, cons, dv) = either error id i
-- See Note [Forcing buildTypeInstance]
buildTypeInstance gClass False name allTvbs dv
`seq` mkCaseExp gClass name cons maker
genRepName :: GenericClass -> DataVariety -> Name -> Name
genRepName gClass dv n = mkName
. showsDataVariety dv
. (("Rep" ++ show (fromEnum gClass)) ++)
. ((showNameQual n ++ "_") ++)
. sanitizeName
$ nameBase n
repType :: GenericClass
-> DataVariety
-> Name
-> Bool
-> [Con]
-> [Type]
-> Q Type
repType gClass dv dt isNT cs tySynVars =
conT d1TypeName `appT` mkMetaDataType dv dt isNT `appT`
foldr1' sum' (conT v1TypeName)
(map (repCon gClass dv dt tySynVars) cs)
where
sum' :: Q Type -> Q Type -> Q Type
sum' a b = conT sumTypeName `appT` a `appT` b
repCon :: GenericClass
-> DataVariety
-> Name
-> [Type]
-> Con
-> Q Type
repCon gClass dv dt tySynVars (NormalC n bts) = do
let bangs = map fst bts
ssis <- reifySelStrictInfo n bangs
repConWith gClass dv dt n tySynVars Nothing ssis False False
repCon gClass dv dt tySynVars (RecC n vbts) = do
let (selNames, bangs, _) = unzip3 vbts
ssis <- reifySelStrictInfo n bangs
repConWith gClass dv dt n tySynVars (Just selNames) ssis True False
repCon gClass dv dt tySynVars (InfixC t1 n t2) = do
let bangs = map fst [t1, t2]
ssis <- reifySelStrictInfo n bangs
repConWith gClass dv dt n tySynVars Nothing ssis False True
repCon _ _ _ _ con = gadtError con
repConWith :: GenericClass
-> DataVariety
-> Name
-> Name
-> [Type]
-> Maybe [Name]
-> [SelStrictInfo]
-> Bool
-> Bool
-> Q Type
repConWith gClass dv dt n tySynVars mbSelNames ssis isRecord isInfix = do
(conVars, ts, gk) <- reifyConTys gClass n
let structureType :: Q Type
structureType = case ssis of
[] -> conT u1TypeName
_ -> foldr1 prodT f
-- See Note [Substituting types in a constructor type signature]
typeSubst :: TypeSubst
typeSubst = Map.fromList $
zip (nub $ concatMap tyVarNamesOfType conVars)
(nub $ concatMap (map VarT . tyVarNamesOfType) tySynVars)
f :: [Q Type]
f = case mbSelNames of
Just selNames -> zipWith3 (repField gk dv dt n typeSubst . Just)
selNames ssis ts
Nothing -> zipWith (repField gk dv dt n typeSubst Nothing)
ssis ts
conT c1TypeName
`appT` mkMetaConsType dv dt n isRecord isInfix
`appT` structureType
prodT :: Q Type -> Q Type -> Q Type
prodT a b = conT productTypeName `appT` a `appT` b
repField :: GenericKind
-> DataVariety
-> Name
-> Name
-> TypeSubst
-> Maybe Name
-> SelStrictInfo
-> Type
-> Q Type
repField gk dv dt ns typeSubst mbF ssi t =
conT s1TypeName
`appT` mkMetaSelType dv dt ns mbF ssi
`appT` (repFieldArg gk =<< expandSyn t'')
where
-- See Note [Substituting types in constructor type signatures]
t', t'' :: Type
t' = case gk of
Gen1 _ (Just _kvName) ->
See Note [ Generic1 is polykinded on GHC 8.2 ]
#if __GLASGOW_HASKELL__ >= 801
t
#else
substNameWithKind _kvName starK t
#endif
_ -> t
t'' = substType typeSubst t'
repFieldArg :: GenericKind -> Type -> Q Type
repFieldArg _ ForallT{} = rankNError
repFieldArg gk (SigT t _) = repFieldArg gk t
repFieldArg Gen0 t = boxT t
repFieldArg (Gen1 name _) (VarT t) | t == name = conT par1TypeName
repFieldArg gk@(Gen1 name _) t = do
let tyHead:tyArgs = unapplyTy t
numLastArgs = min 1 $ length tyArgs
(lhsArgs, rhsArgs) = splitAt (length tyArgs - numLastArgs) tyArgs
rec0Type = boxT t
phiType = return $ applyTyToTys tyHead lhsArgs
inspectTy :: Type -> Q Type
inspectTy (VarT a)
| a == name
= conT rec1TypeName `appT` phiType
inspectTy (SigT ty _) = inspectTy ty
inspectTy beta
| not (ground beta name)
= conT composeTypeName `appT` phiType
`appT` repFieldArg gk beta
inspectTy _ = rec0Type
itf <- isTyFamily tyHead
if any (not . (`ground` name)) lhsArgs
|| any (not . (`ground` name)) tyArgs && itf
then outOfPlaceTyVarError
else case rhsArgs of
[] -> rec0Type
ty:_ -> inspectTy ty
boxT :: Type -> Q Type
boxT ty = case unboxedRepNames ty of
Just (boxTyName, _, _) -> conT boxTyName
Nothing -> conT rec0TypeName `appT` return ty
mkCaseExp :: GenericClass -> Name -> [Con]
-> (GenericClass -> Int -> Int -> Name -> [Con] -> Q Match)
-> Q Exp
mkCaseExp gClass dt cs matchmaker = do
val <- newName "val"
lam1E (varP val) $ caseE (varE val) [matchmaker gClass 1 0 dt cs]
mkFrom :: GenericClass -> Int -> Int -> Name -> [Con] -> Q Match
mkFrom gClass m i dt cs = do
y <- newName "y"
match (varP y)
(normalB $ conE m1DataName `appE` caseE (varE y) cases)
[]
where
cases = case cs of
[] -> [errorFrom dt]
_ -> zipWith (fromCon gClass wrapE (length cs)) [0..] cs
wrapE e = lrE m i e
errorFrom :: Name -> Q Match
errorFrom dt =
match
wildP
(normalB $ varE errorValName `appE` stringE
("No generic representation for empty datatype " ++ nameBase dt))
[]
errorTo :: Name -> Q Match
errorTo dt =
match
wildP
(normalB $ varE errorValName `appE` stringE
("No values for empty datatype " ++ nameBase dt))
[]
mkTo :: GenericClass -> Int -> Int -> Name -> [Con] -> Q Match
mkTo gClass m i dt cs = do
y <- newName "y"
match (conP m1DataName [varP y])
(normalB $ caseE (varE y) cases)
[]
where
cases = case cs of
[] -> [errorTo dt]
_ -> zipWith (toCon gClass wrapP (length cs)) [0..] cs
wrapP p = lrP m i p
fromCon :: GenericClass -> (Q Exp -> Q Exp) -> Int -> Int -> Con -> Q Match
fromCon _ wrap m i (NormalC cn []) =
match
(conP cn [])
(normalB $ wrap $ lrE m i $ conE m1DataName `appE` (conE u1DataName)) []
fromCon gClass wrap m i (NormalC cn _) = do
(ts, gk) <- fmap shrink $ reifyConTys gClass cn
fNames <- newNameList "f" $ length ts
match
(conP cn (map varP fNames))
(normalB $ wrap $ lrE m i $ conE m1DataName `appE`
foldr1 prodE (zipWith (fromField gk) fNames ts)) []
fromCon _ wrap m i (RecC cn []) =
match
(conP cn [])
(normalB $ wrap $ lrE m i $ conE m1DataName `appE` (conE u1DataName)) []
fromCon gClass wrap m i (RecC cn _) = do
(ts, gk) <- fmap shrink $ reifyConTys gClass cn
fNames <- newNameList "f" $ length ts
match
(conP cn (map varP fNames))
(normalB $ wrap $ lrE m i $ conE m1DataName `appE`
foldr1 prodE (zipWith (fromField gk) fNames ts)) []
fromCon gClass wrap m i (InfixC t1 cn t2) =
fromCon gClass wrap m i (NormalC cn [t1,t2])
fromCon _ _ _ _ con = gadtError con
prodE :: Q Exp -> Q Exp -> Q Exp
prodE x y = conE productDataName `appE` x `appE` y
fromField :: GenericKind -> Name -> Type -> Q Exp
fromField gk nr t = conE m1DataName `appE` (fromFieldWrap gk nr =<< expandSyn t)
fromFieldWrap :: GenericKind -> Name -> Type -> Q Exp
fromFieldWrap _ _ ForallT{} = rankNError
fromFieldWrap gk nr (SigT t _) = fromFieldWrap gk nr t
fromFieldWrap Gen0 nr t = conE (boxRepName t) `appE` varE nr
fromFieldWrap (Gen1 name _) nr t = wC t name `appE` varE nr
wC :: Type -> Name -> Q Exp
wC (VarT t) name | t == name = conE par1DataName
wC t name
| ground t name = conE $ boxRepName t
| otherwise = do
let tyHead:tyArgs = unapplyTy t
numLastArgs = min 1 $ length tyArgs
(lhsArgs, rhsArgs) = splitAt (length tyArgs - numLastArgs) tyArgs
inspectTy :: Type -> Q Exp
inspectTy ForallT{} = rankNError
inspectTy (SigT ty _) = inspectTy ty
inspectTy (VarT a)
| a == name
= conE rec1DataName
inspectTy beta = infixApp (conE comp1DataName)
(varE composeValName)
(varE fmapValName `appE` wC beta name)
itf <- isTyFamily tyHead
if any (not . (`ground` name)) lhsArgs
|| any (not . (`ground` name)) tyArgs && itf
then outOfPlaceTyVarError
else case rhsArgs of
[] -> conE $ boxRepName t
ty:_ -> inspectTy ty
boxRepName :: Type -> Name
boxRepName = maybe k1DataName snd3 . unboxedRepNames
toCon :: GenericClass -> (Q Pat -> Q Pat) -> Int -> Int -> Con -> Q Match
toCon _ wrap m i (NormalC cn []) =
match
(wrap $ lrP m i $ conP m1DataName [conP u1DataName []])
(normalB $ conE cn) []
toCon gClass wrap m i (NormalC cn _) = do
(ts, gk) <- fmap shrink $ reifyConTys gClass cn
fNames <- newNameList "f" $ length ts
match
(wrap $ lrP m i $ conP m1DataName
[foldr1 prod (zipWith (toField gk) fNames ts)])
(normalB $ foldl appE (conE cn) (zipWith (\nr -> expandSyn >=> toConUnwC gk nr)
fNames ts)) []
where prod x y = conP productDataName [x,y]
toCon _ wrap m i (RecC cn []) =
match
(wrap $ lrP m i $ conP m1DataName [conP u1DataName []])
(normalB $ conE cn) []
toCon gClass wrap m i (RecC cn _) = do
(ts, gk) <- fmap shrink $ reifyConTys gClass cn
fNames <- newNameList "f" $ length ts
match
(wrap $ lrP m i $ conP m1DataName
[foldr1 prod (zipWith (toField gk) fNames ts)])
(normalB $ foldl appE (conE cn) (zipWith (\nr -> expandSyn >=> toConUnwC gk nr)
fNames ts)) []
where prod x y = conP productDataName [x,y]
toCon gk wrap m i (InfixC t1 cn t2) =
toCon gk wrap m i (NormalC cn [t1,t2])
toCon _ _ _ _ con = gadtError con
toConUnwC :: GenericKind -> Name -> Type -> Q Exp
toConUnwC Gen0 nr _ = varE nr
toConUnwC (Gen1 name _) nr t = unwC t name `appE` varE nr
toField :: GenericKind -> Name -> Type -> Q Pat
toField gk nr t = conP m1DataName [toFieldWrap gk nr t]
toFieldWrap :: GenericKind -> Name -> Type -> Q Pat
toFieldWrap Gen0 nr t = conP (boxRepName t) [varP nr]
toFieldWrap Gen1{} nr _ = varP nr
unwC :: Type -> Name -> Q Exp
unwC (SigT t _) name = unwC t name
unwC (VarT t) name | t == name = varE unPar1ValName
unwC t name
| ground t name = varE $ unboxRepName t
| otherwise = do
let tyHead:tyArgs = unapplyTy t
numLastArgs = min 1 $ length tyArgs
(lhsArgs, rhsArgs) = splitAt (length tyArgs - numLastArgs) tyArgs
inspectTy :: Type -> Q Exp
inspectTy ForallT{} = rankNError
inspectTy (SigT ty _) = inspectTy ty
inspectTy (VarT a)
| a == name
= varE unRec1ValName
inspectTy beta = infixApp (varE fmapValName `appE` unwC beta name)
(varE composeValName)
(varE unComp1ValName)
itf <- isTyFamily tyHead
if any (not . (`ground` name)) lhsArgs
|| any (not . (`ground` name)) tyArgs && itf
then outOfPlaceTyVarError
else case rhsArgs of
[] -> varE $ unboxRepName t
ty:_ -> inspectTy ty
unboxRepName :: Type -> Name
unboxRepName = maybe unK1ValName trd3 . unboxedRepNames
lrP :: Int -> Int -> (Q Pat -> Q Pat)
lrP 1 0 p = p
lrP _ 0 p = conP l1DataName [p]
lrP m i p = conP r1DataName [lrP (m-1) (i-1) p]
lrE :: Int -> Int -> (Q Exp -> Q Exp)
lrE 1 0 e = e
lrE _ 0 e = conE l1DataName `appE` e
lrE m i e = conE r1DataName `appE` lrE (m-1) (i-1) e
unboxedRepNames :: Type -> Maybe (Name, Name, Name)
unboxedRepNames ty
| ty == ConT addrHashTypeName = Just (uAddrTypeName, uAddrDataName, uAddrHashValName)
| ty == ConT charHashTypeName = Just (uCharTypeName, uCharDataName, uCharHashValName)
| ty == ConT doubleHashTypeName = Just (uDoubleTypeName, uDoubleDataName, uDoubleHashValName)
| ty == ConT floatHashTypeName = Just (uFloatTypeName, uFloatDataName, uFloatHashValName)
| ty == ConT intHashTypeName = Just (uIntTypeName, uIntDataName, uIntHashValName)
| ty == ConT wordHashTypeName = Just (uWordTypeName, uWordDataName, uWordHashValName)
| otherwise = Nothing
-- | Deduces the instance type (and kind) to use for a Generic(1) instance.
buildTypeInstance :: GenericClass
^ Generic or Generic1
-> KindSigOptions
-- ^ Whether or not to use explicit kind signatures in the instance type
-> Name
-- ^ The type constructor or data family name
-> [TyVarBndr]
-- ^ The type variables from the data type/data family declaration
-> DataVariety
-- ^ If using a data family instance, provides the types used
-- to instantiate the instance
-> Q (Type, Kind)
Plain data type / newtype case
buildTypeInstance gClass useKindSigs tyConName tvbs DataPlain =
let varTys :: [Type]
varTys = map tyVarBndrToType tvbs
in buildTypeInstanceFromTys gClass useKindSigs tyConName varTys
-- Data family instance case
--
The CPP is present to work around a couple of annoying old GHC bugs .
See Note [ Polykinded data families in Template Haskell ]
buildTypeInstance gClass useKindSigs parentName tvbs (DataFamily _ instTysAndKinds) = do
#if !(MIN_VERSION_template_haskell(2,8,0)) || MIN_VERSION_template_haskell(2,10,0)
let instTys :: [Type]
instTys = zipWith stealKindForType tvbs instTysAndKinds
#else
let kindVarNames :: [Name]
kindVarNames = nub $ concatMap (tyVarNamesOfType . tyVarBndrKind) tvbs
numKindVars :: Int
numKindVars = length kindVarNames
givenKinds, givenKinds' :: [Kind]
givenTys :: [Type]
(givenKinds, givenTys) = splitAt numKindVars instTysAndKinds
givenKinds' = map sanitizeStars givenKinds
A GHC 7.6 - specific bug requires us to replace all occurrences of
( ConT GHC.Prim . * ) with StarT , or else will reject it .
-- Luckily, (ConT GHC.Prim.*) only seems to occur in this one spot.
sanitizeStars :: Kind -> Kind
sanitizeStars = go
where
go :: Kind -> Kind
go (AppT t1 t2) = AppT (go t1) (go t2)
go (SigT t k) = SigT (go t) (go k)
go (ConT n) | n == starKindName = StarT
go t = t
If we run this code with GHC 7.8 , we might have to generate extra type
variables to compensate for any type variables that
-- eta-reduced away.
See Note [ Polykinded data families in Template Haskell ]
xTypeNames <- newNameList "tExtra" (length tvbs - length givenTys)
let xTys :: [Type]
-- Because these type variables were eta-reduced away, we can only
-- determine their kind by using stealKindForType. Therefore, we mark
-- them as VarT to ensure they will be given an explicit kind annotation
-- (and so the kind inference machinery has the right information).
xTys = map VarT xTypeNames
substNamesWithKinds :: [(Name, Kind)] -> Type -> Type
substNamesWithKinds nks t = foldr' (uncurry substNameWithKind) t nks
-- The types from the data family instance might not have explicit kind
-- annotations, which the kind machinery needs to work correctly. To
-- compensate, we use stealKindForType to explicitly annotate any
-- types without kind annotations.
instTys :: [Type]
instTys = map (substNamesWithKinds (zip kindVarNames givenKinds'))
Note that due to a GHC 7.8 - specific bug
( see Note [ Polykinded data families in Template Haskell ] ) ,
-- there may be more kind variable names than there are kinds
-- to substitute. But this is OK! If a kind is eta-reduced, it
-- means that is was not instantiated to something more specific,
-- so we need not substitute it. Using stealKindForType will
-- grab the correct kind.
$ zipWith stealKindForType tvbs (givenTys ++ xTys)
#endif
buildTypeInstanceFromTys gClass useKindSigs parentName instTys
-- For the given Types, deduces the instance type (and kind) to use for a
-- Generic(1) instance. Coming up with the instance type isn't as simple as
-- dropping the last types, as you need to be wary of kinds being instantiated
-- with *.
-- See Note [Type inference in derived instances]
buildTypeInstanceFromTys :: GenericClass
^ Generic or Generic1
-> KindSigOptions
-- ^ Whether or not to use explicit kind signatures in the instance type
-> Name
-- ^ The type constructor or data family name
-> [Type]
-- ^ The types to instantiate the instance with
-> Q (Type, Kind)
buildTypeInstanceFromTys gClass useKindSigs tyConName varTysOrig = do
-- Make sure to expand through type/kind synonyms! Otherwise, the
-- eta-reduction check might get tripped up over type variables in a
-- synonym that are actually dropped.
( See GHC Trac # 11416 for a scenario where this actually happened . )
varTysExp <- mapM expandSyn varTysOrig
let remainingLength :: Int
remainingLength = length varTysOrig - fromEnum gClass
droppedTysExp :: [Type]
droppedTysExp = drop remainingLength varTysExp
droppedStarKindStati :: [StarKindStatus]
droppedStarKindStati = map canRealizeKindStar droppedTysExp
-- Check there are enough types to drop and that all of them are either of
-- kind * or kind k (for some kind variable k). If not, throw an error.
when (remainingLength < 0 || any (== NotKindStar) droppedStarKindStati) $
derivingKindError tyConName
-- Substitute kind * for any dropped kind variables
let varTysExpSubst :: [Type]
See Note [ Generic1 is polykinded on GHC 8.2 ]
#if __GLASGOW_HASKELL__ >= 801
varTysExpSubst = varTysExp
#else
varTysExpSubst = map (substNamesWithKindStar droppedKindVarNames) varTysExp
droppedKindVarNames :: [Name]
droppedKindVarNames = catKindVarNames droppedStarKindStati
#endif
let remainingTysExpSubst, droppedTysExpSubst :: [Type]
(remainingTysExpSubst, droppedTysExpSubst) =
splitAt remainingLength varTysExpSubst
See Note [ Generic1 is polykinded on GHC 8.2 ]
#if __GLASGOW_HASKELL__ < 801
-- If any of the dropped types were polykinded, ensure that there are of
-- kind * after substituting * for the dropped kind variables. If not,
-- throw an error.
unless (all hasKindStar droppedTysExpSubst) $
derivingKindError tyConName
#endif
-- We now substitute all of the specialized-to-* kind variable names
-- with *, but in the original types, not the synonym-expanded types. The reason
-- we do this is a superficial one: we want the derived instance to resemble
-- the datatype written in source code as closely as possible. For example,
-- for the following data family instance:
--
-- data family Fam a
-- newtype instance Fam String = Fam String
--
-- We'd want to generate the instance:
--
-- instance C (Fam String)
--
-- Not:
--
-- instance C (Fam [Char])
let varTysOrigSubst :: [Type]
varTysOrigSubst =
See Note [ Generic1 is polykinded on GHC 8.2 ]
#if __GLASGOW_HASKELL__ >= 801
id
#else
map (substNamesWithKindStar droppedKindVarNames)
#endif
$ varTysOrig
remainingTysOrigSubst, droppedTysOrigSubst :: [Type]
(remainingTysOrigSubst, droppedTysOrigSubst) =
splitAt remainingLength varTysOrigSubst
remainingTysOrigSubst' :: [Type]
-- See Note [Kind signatures in derived instances] for an explanation
-- of the useKindSigs check.
remainingTysOrigSubst' =
if useKindSigs
then remainingTysOrigSubst
else map unSigT remainingTysOrigSubst
instanceType :: Type
instanceType = applyTyToTys (ConT tyConName) remainingTysOrigSubst'
-- See Note [Kind signatures in derived instances]
instanceKind :: Kind
instanceKind = makeFunKind (map typeKind droppedTysOrigSubst) starK
-- Ensure the dropped types can be safely eta-reduced. Otherwise,
-- throw an error.
unless (canEtaReduce remainingTysExpSubst droppedTysExpSubst) $
etaReductionError instanceType
return (instanceType, instanceKind)
-- See Note [Arguments to generated type synonyms]
grabTyVarsFromCons :: GenericClass -> [Con] -> Q [Type]
grabTyVarsFromCons _ [] = return []
grabTyVarsFromCons gClass (con:_) =
fmap fst3 $ reifyConTys gClass (constructorName con)
Note [ Forcing buildTypeInstance ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes , we do n't explicitly need to generate a Generic(1 ) type instance , but
we force buildTypeInstance nevertheless . This is because it performs some checks
for whether or not the provided datatype can actually have ) implemented for
it , and produces errors if it ca n't . Otherwise , laziness would cause these checks
to be skipped entirely , which could result in some indecipherable type errors
down the road .
Note [ Substituting types in constructor type signatures ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
While reifyConTys gives you the type variables of a constructor , they may not be
the same of the data declaration 's type variables . The classic example of this is
GADTs :
data GADT a b where
GADTCon : : e - > f - > GADT e f
The type variables of GADTCon are completely different from the declaration 's , which
can cause a problem when generating a Rep instance :
type Rep ( GADT a b ) = Rec0 e :* : , we would generate something like this , since traversing the constructor
would give us precisely those arguments . Not good . We need to perform a type
substitution to ensure that e maps to a , and f maps to b.
This turns out to be surprisingly simple . Whenever you have a constructor type
signature like ( e - > f - > GADT e f ) , take the result type , collect all of its
distinct type variables in order from left - to - right , and then map them to their
corresponding type variables from the data declaration .
There is another obscure case where we need to do a type subtitution . With
-XTypeInType enabled on GHC 8.0 , you might have something like this :
data Proxy ( a : : k ) ( b : : k ) = Proxy k deriving Generic1
Then k gets specialized to * , which means that k should NOT show up in the RHS of
a Rep1 type instance ! To avoid this , make sure to substitute k with * .
See also Note [ Generic1 is polykinded on GHC 8.2 ] .
Note [ Arguments to generated type synonyms ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A surprisingly difficult component of generating the type synonyms for Rep / Rep1 is
coming up with the type synonym variable arguments , since they have to be just the
right name and kind to work . The type signature of a constructor does a remarkably
good job of coming up with these type variables for us , so if at least one constructor
exists , we simply steal the type variables from that constructor 's type signature
for use in the generated type synonym . We also count the number of type variables
that the first constructor 's type signature has in order to determine how many
type variables we should give it as arguments in the generated
( type Rep ( Foo ... ) = < makeRep > ... ) code .
This leads one to ask : what if there are no constructors ? If that 's the case , then
we 're OK , since that means no type variables can possibly appear on the RHS of the
type synonym ! In such a special case , we 're perfectly justified in making the type
synonym not have any type variable arguments , and similarly , we do n't apply any
arguments to it in the generated ( type = < makeRep > ) code .
Note [ Polykinded data families in Template Haskell ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to come up with the correct instance context and head for an instance , e.g. ,
instance C a = > C ( Data a ) where ...
We need to know the exact types and kinds used to instantiate the instance . For
plain old datatypes , this is simple : every type must be a type variable , and
reliably tells us the type variables and their kinds .
Doing the same for data families proves to be much harder for three reasons :
1 . On any version of Template Haskell , it may not tell you what an instantiated
type 's kind is . For instance , in the following data family instance :
data family Fam ( f : : * - > * ) ( a : : * )
data instance Fam f a
Then if we use TH 's reify function , it would tell us the TyVarBndrs of the
data family declaration are :
[ KindedTV f ( AppT ( AppT ArrowT StarT ) StarT),KindedTV a StarT ]
and the instantiated types of the data family instance are :
[ VarT f1,VarT a1 ]
We ca n't just pass [ VarT f1,VarT a1 ] to buildTypeInstanceFromTys , since we
have no way of knowing their kinds . Luckily , the TyVarBndrs tell us what the
kind is in case an instantiated type is n't a SigT , so we use the stealKindForType
function to ensure all of the instantiated types are SigTs before passing them
to buildTypeInstanceFromTys .
2 . On GHC 7.6 and 7.8 , a bug is present in which Template Haskell lists all of
the specified kinds of a data family instance efore any of the instantiated
types . Fortunately , this is easy to deal with : you simply count the number of
distinct kind variables in the data family declaration , take that many elements
from the front of the Types list of the data family instance , substitute the
kind variables with their respective instantiated kinds ( which you took earlier ) ,
and proceed as normal .
3 . On GHC 7.8 , an even uglier bug is present ( GHC Trac # 9692 ) in which Template
Haskell might not even list all of the Types of a data family instance , since
they are eta - reduced away ! And yes , kinds can be eta - reduced too .
The simplest workaround is to count how many instantiated types are missing from
the list and generate extra type variables to use in their place . Luckily , we
need n't worry much if its kind was eta - reduced away , since using stealKindForType
will get it back .
Note [ Kind signatures in derived instances ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We generally include explicit type signatures in derived instances . One reason for
doing so is that in the case of certain data family instances , not including kind
signatures can result in ambiguity . For example , consider the following two data
family instances that are distinguished by their kinds :
data family Fam ( a : : k )
data instance Fam ( a : : * - > * )
data instance Fam ( a : : * )
If we dropped the kind signature for a in a derived instance for Fam a , then GHC
would have no way of knowing which instance we are talking about .
Another motivation for explicit kind signatures is the -XTypeInType extension .
With -XTypeInType , dropping kind signatures can completely change the meaning
of some data types . For example , there is a substantial difference between these
two data types :
data T k ( a : : k ) = T k
data T k a = T k
In addition to using explicit kind signatures on type variables , we also put
explicit return kinds in the instance head , so generated instances will look
something like this :
data S ( a : : k ) = S k
instance Generic1 ( S : : k - > * ) where
type Rep1 ( S : : k - > * ) = ... ( Rec0 k )
Why do we do this ? Imagine what the instance would be without the explicit return kind :
instance Generic1 S where
type Rep1 S = ... ( Rec0 k )
This is an error , since the variable k is now out - of - scope !
Although explicit kind signatures are the right thing to do in most cases , there
are sadly some degenerate cases where this is n't true . Consider this example :
newtype Compose ( f : : k2 - > * ) ( g : : k1 - > k2 ) ( a : : k1 ) = Compose ( f ( g a ) )
The Rep1 type instance in a Generic1 instance for Compose would involve the type
( f : . : ) , which forces ( f : : * - > * ) . But this library does n't have very
sophisticated kind inference machinery ( other than what is mentioned in
Note [ Substituting types in constructor type signatures ] ) , so at the moment we
have no way of actually unifying k1 with * . So the naïve generated Generic1
instance would be :
instance Generic1 ( Compose ( f : : k2 - > * ) ( g : : k1 - > k2 ) ) where
type Rep1 ( Compose f g ) = ... ( f : . : )
This is wrong , since f 's kind is overly generalized . To get around this issue ,
there are variants of the TH functions that allow you to configure the KindSigOptions .
If KindSigOptions is set to False , then generated instances will not include
explicit kind signatures , leaving it up to GHC 's kind inference machinery to
figure out the correct kinds .
Note [ Generic1 is polykinded on GHC 8.2 ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Prior to GHC 8.2 , Generic1 : : ( * - > * ) - > Constraint . This means that if a Generic1
instance is defined for a polykinded data type like so :
data Proxy k ( a : : k ) = Proxy
Then k is unified with * , and this has an effect on the generated Generic1 instance :
instance Generic1 ( Proxy * ) where ...
We must take great care to ensure that all occurrences of k are substituted with * ,
or else the generated instance will be ill kinded .
On GHC 8.2 and later , Generic1 : : ( k - > * ) - > Constraint . This means we do n't have
to do this kind unification anymore ! !
Note [Forcing buildTypeInstance]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes, we don't explicitly need to generate a Generic(1) type instance, but
we force buildTypeInstance nevertheless. This is because it performs some checks
for whether or not the provided datatype can actually have Generic(1) implemented for
it, and produces errors if it can't. Otherwise, laziness would cause these checks
to be skipped entirely, which could result in some indecipherable type errors
down the road.
Note [Substituting types in constructor type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
While reifyConTys gives you the type variables of a constructor, they may not be
the same of the data declaration's type variables. The classic example of this is
GADTs:
data GADT a b where
GADTCon :: e -> f -> GADT e f
The type variables of GADTCon are completely different from the declaration's, which
can cause a problem when generating a Rep instance:
type Rep (GADT a b) = Rec0 e :*: Rec0 f
Naïvely, we would generate something like this, since traversing the constructor
would give us precisely those arguments. Not good. We need to perform a type
substitution to ensure that e maps to a, and f maps to b.
This turns out to be surprisingly simple. Whenever you have a constructor type
signature like (e -> f -> GADT e f), take the result type, collect all of its
distinct type variables in order from left-to-right, and then map them to their
corresponding type variables from the data declaration.
There is another obscure case where we need to do a type subtitution. With
-XTypeInType enabled on GHC 8.0, you might have something like this:
data Proxy (a :: k) (b :: k) = Proxy k deriving Generic1
Then k gets specialized to *, which means that k should NOT show up in the RHS of
a Rep1 type instance! To avoid this, make sure to substitute k with *.
See also Note [Generic1 is polykinded on GHC 8.2].
Note [Arguments to generated type synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A surprisingly difficult component of generating the type synonyms for Rep/Rep1 is
coming up with the type synonym variable arguments, since they have to be just the
right name and kind to work. The type signature of a constructor does a remarkably
good job of coming up with these type variables for us, so if at least one constructor
exists, we simply steal the type variables from that constructor's type signature
for use in the generated type synonym. We also count the number of type variables
that the first constructor's type signature has in order to determine how many
type variables we should give it as arguments in the generated
(type Rep (Foo ...) = <makeRep> ...) code.
This leads one to ask: what if there are no constructors? If that's the case, then
we're OK, since that means no type variables can possibly appear on the RHS of the
type synonym! In such a special case, we're perfectly justified in making the type
synonym not have any type variable arguments, and similarly, we don't apply any
arguments to it in the generated (type Rep Foo = <makeRep>) code.
Note [Polykinded data families in Template Haskell]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to come up with the correct instance context and head for an instance, e.g.,
instance C a => C (Data a) where ...
We need to know the exact types and kinds used to instantiate the instance. For
plain old datatypes, this is simple: every type must be a type variable, and
Template Haskell reliably tells us the type variables and their kinds.
Doing the same for data families proves to be much harder for three reasons:
1. On any version of Template Haskell, it may not tell you what an instantiated
type's kind is. For instance, in the following data family instance:
data family Fam (f :: * -> *) (a :: *)
data instance Fam f a
Then if we use TH's reify function, it would tell us the TyVarBndrs of the
data family declaration are:
[KindedTV f (AppT (AppT ArrowT StarT) StarT),KindedTV a StarT]
and the instantiated types of the data family instance are:
[VarT f1,VarT a1]
We can't just pass [VarT f1,VarT a1] to buildTypeInstanceFromTys, since we
have no way of knowing their kinds. Luckily, the TyVarBndrs tell us what the
kind is in case an instantiated type isn't a SigT, so we use the stealKindForType
function to ensure all of the instantiated types are SigTs before passing them
to buildTypeInstanceFromTys.
2. On GHC 7.6 and 7.8, a bug is present in which Template Haskell lists all of
the specified kinds of a data family instance efore any of the instantiated
types. Fortunately, this is easy to deal with: you simply count the number of
distinct kind variables in the data family declaration, take that many elements
from the front of the Types list of the data family instance, substitute the
kind variables with their respective instantiated kinds (which you took earlier),
and proceed as normal.
3. On GHC 7.8, an even uglier bug is present (GHC Trac #9692) in which Template
Haskell might not even list all of the Types of a data family instance, since
they are eta-reduced away! And yes, kinds can be eta-reduced too.
The simplest workaround is to count how many instantiated types are missing from
the list and generate extra type variables to use in their place. Luckily, we
needn't worry much if its kind was eta-reduced away, since using stealKindForType
will get it back.
Note [Kind signatures in derived instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We generally include explicit type signatures in derived instances. One reason for
doing so is that in the case of certain data family instances, not including kind
signatures can result in ambiguity. For example, consider the following two data
family instances that are distinguished by their kinds:
data family Fam (a :: k)
data instance Fam (a :: * -> *)
data instance Fam (a :: *)
If we dropped the kind signature for a in a derived instance for Fam a, then GHC
would have no way of knowing which instance we are talking about.
Another motivation for explicit kind signatures is the -XTypeInType extension.
With -XTypeInType, dropping kind signatures can completely change the meaning
of some data types. For example, there is a substantial difference between these
two data types:
data T k (a :: k) = T k
data T k a = T k
In addition to using explicit kind signatures on type variables, we also put
explicit return kinds in the instance head, so generated instances will look
something like this:
data S (a :: k) = S k
instance Generic1 (S :: k -> *) where
type Rep1 (S :: k -> *) = ... (Rec0 k)
Why do we do this? Imagine what the instance would be without the explicit return kind:
instance Generic1 S where
type Rep1 S = ... (Rec0 k)
This is an error, since the variable k is now out-of-scope!
Although explicit kind signatures are the right thing to do in most cases, there
are sadly some degenerate cases where this isn't true. Consider this example:
newtype Compose (f :: k2 -> *) (g :: k1 -> k2) (a :: k1) = Compose (f (g a))
The Rep1 type instance in a Generic1 instance for Compose would involve the type
(f :.: Rec1 g), which forces (f :: * -> *). But this library doesn't have very
sophisticated kind inference machinery (other than what is mentioned in
Note [Substituting types in constructor type signatures]), so at the moment we
have no way of actually unifying k1 with *. So the naïve generated Generic1
instance would be:
instance Generic1 (Compose (f :: k2 -> *) (g :: k1 -> k2)) where
type Rep1 (Compose f g) = ... (f :.: Rec1 g)
This is wrong, since f's kind is overly generalized. To get around this issue,
there are variants of the TH functions that allow you to configure the KindSigOptions.
If KindSigOptions is set to False, then generated instances will not include
explicit kind signatures, leaving it up to GHC's kind inference machinery to
figure out the correct kinds.
Note [Generic1 is polykinded on GHC 8.2]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Prior to GHC 8.2, Generic1 :: (* -> *) -> Constraint. This means that if a Generic1
instance is defined for a polykinded data type like so:
data Proxy k (a :: k) = Proxy
Then k is unified with *, and this has an effect on the generated Generic1 instance:
instance Generic1 (Proxy *) where ...
We must take great care to ensure that all occurrences of k are substituted with *,
or else the generated instance will be ill kinded.
On GHC 8.2 and later, Generic1 :: (k -> *) -> Constraint. This means we don't have
to do this kind unification anymore! Hooray!
-}
| null | https://raw.githubusercontent.com/iu-parfunc/verified-instances/cebfdf1e3357a693360be74c90211be18ce3c045/generic-proofs/generic-deriving-newtypeless/src/Generics/Deriving/Newtypeless/TH.hs | haskell | # LANGUAGE BangPatterns #
Derives Generic instance
Derives Generic1 instance
Derives Generic and Generic1 instances
instance Generic ( Family Char b ) where ...
instance Generic1 ( ) where ...
Alternatively , one could type $ ( deriveAll1 ' FamilyFalse )
2009 Universiteit Utrecht
Derives Generic instance
Derives Generic1 instance
Derives Generic and Generic1 instances
instance Generic (Family Char b) where ...
instance Generic1 (Family Bool) where ...
Alternatively, one could type $(deriveAll1 'FamilyFalse)
Adapted from Generics.Regular.TH
* @derive@- functions
* @make@- functions
$make
* Options
$options
** Option types
** Functions with optional arguments
| Given the names of a generic class, a type to instantiate, a function in
the class and the default implementation, generates the code for a basic
generic instance.
| Additional options for configuring derived 'Generic'/'Generic1' instances
| Sensible default 'Options' ('defaultRepOptions' and 'defaultKindSigOptions').
| Configures whether 'Rep'/'Rep1' type instances should be defined inline in a
derived 'Generic'/'Generic1' instance ('InlineRep') or defined in terms of a
type synonym ('TypeSynonymRep').
| 'True' if explicit kind signatures should be used in derived
'Generic'/'Generic1' instances, 'False' otherwise.
| 'True', a sensible default 'KindSigOptions'.
| A backwards-compatible synonym for 'deriveAll0'.
| Given the type and the name (as string) for the type to derive,
generate the 'Data' instance, the 'Constructor' instances, the 'Selector'
instances, and the 'Representable0' instance.
| Like 'deriveAll0', but takes an 'Options' argument.
| Given the type and the name (as string) for the type to derive,
generate the 'Data' instance, the 'Constructor' instances, the 'Selector'
instances, and the 'Representable1' instance.
| Like 'deriveAll1', but takes an 'Options' argument.
| Given the type and the name (as string) for the type to derive,
generate the 'Data' instance, the 'Constructor' instances, the 'Selector'
instances, the 'Representable0' instance, and the 'Representable1' instance.
| Like 'deriveAll0And1', but takes an 'Options' argument.
| Given the type and the name (as string) for the Representable0 type
synonym to derive, generate the 'Representable0' instance.
| Like 'deriveRepresentable0', but takes an 'Options' argument.
| Given the type and the name (as string) for the Representable1 type
synonym to derive, generate the 'Representable1' instance.
| Like 'deriveRepresentable1', but takes an 'Options' argument.
| Derive only the 'Rep0' type synonym. Not needed if 'deriveRepresentable0'
is used.
| Like 'deriveRep0', but takes an 'KindSigOptions' argument.
| Derive only the 'Rep1' type synonym. Not needed if 'deriveRepresentable1'
is used.
| Like 'deriveRep1', but takes an 'KindSigOptions' argument.
See Note [Forcing buildTypeInstance]
See Note [Kind signatures in derived instances]
See Note [Forcing buildTypeInstance]
| Generates the full 'Rep' type inline. Since this type can be quite
large, it is recommended you only use this to define 'Rep', e.g.,
@
type Rep (Foo (a :: k) b) = $('makeRep0Inline' ''Foo [t| Foo (a :: k) b |])
@
You can then simply refer to @Rep (Foo a b)@ elsewhere.
Note that the type passed as an argument to 'makeRep0Inline' must match the
type argument of 'Rep' exactly, even up to including the explicit kind
the kind signature, 'makeRep0Inline' has no way of figuring out the kind of
@a@, and the generated type might be completely wrong as a result!
| Generates the full 'Rep1' type inline. Since this type can be quite
large, it is recommended you only use this to define 'Rep1', e.g.,
@
@
You can then simply refer to @Rep1 (Foo a)@ elsewhere.
Note that the type passed as an argument to 'makeRep1Inline' must match the
type argument of 'Rep1' exactly, even up to including the explicit kind
the kind signature, 'makeRep1Inline' has no way of figuring out the kind of
@a@, and the generated type might be completely wrong as a result!
| Generates the 'Rep' type synonym constructor (as opposed to 'deriveRep0',
which generates the type synonym declaration). After splicing it into
@
@
The use of 'makeRep0' is generally discouraged, as it can sometimes be
difficult to predict the order in which you are expected to pass type
variables. As a result, 'makeRep0Inline' is recommended instead. However,
| Generates the 'Rep1' type synonym constructor (as opposed to 'deriveRep1',
which generates the type synonym declaration). After splicing it into
@
@
The use of 'makeRep1' is generally discouraged, as it can sometimes be
difficult to predict the order in which you are expected to pass type
variables. As a result, 'makeRep1Inline' is recommended instead. However,
| Generates the 'Rep' type synonym constructor (as opposed to 'deriveRep0',
which generates the type synonym declaration) applied to its type arguments.
Unlike 'makeRep0', this also takes a quoted 'Type' as an argument, e.g.,
@
@
Note that the type passed as an argument to 'makeRep0FromType' must match the
type argument of 'Rep' exactly, even up to including the explicit kind
@a@, and the generated type might be completely wrong as a result!
The use of 'makeRep0FromType' is generally discouraged, since 'makeRep0Inline'
does exactly the same thing but without having to go through an intermediate
type synonym, and as a result, 'makeRep0Inline' tends to be less buggy.
| Generates the 'Rep1' type synonym constructor (as opposed to 'deriveRep1',
which generates the type synonym declaration) applied to its type arguments.
Unlike 'makeRep1', this also takes a quoted 'Type' as an argument, e.g.,
@
@
type argument of 'Rep' exactly, even up to including the explicit kind
@a@, and the generated type might be completely wrong as a result!
does exactly the same thing but without having to go through an intermediate
type synonym, and as a result, 'makeRep1Inline' tends to be less buggy.
See Note [Forcing buildTypeInstance]
Here, we figure out the distinct type variables (in order from left-to-right)
inferencer can figure out the kinds perfectly well, so we don't need to
give anything here explicit kind signatures.
Or, if there are no constructors, we grab no type variables. The latter
is okay because we use zipWith to ensure that we never pass more type
variables than the generated type synonym can accept.
See Note [Arguments to generated type synonyms]
| A backwards-compatible synonym for 'makeFrom0'.
| Generates a lambda expression which behaves like 'from'.
| A backwards-compatible synonym for 'makeTo0'.
| Generates a lambda expression which behaves like 'to'.
| Generates a lambda expression which behaves like 'from1'.
See Note [Forcing buildTypeInstance]
See Note [Substituting types in a constructor type signature]
See Note [Substituting types in constructor type signatures]
| Deduces the instance type (and kind) to use for a Generic(1) instance.
^ Whether or not to use explicit kind signatures in the instance type
^ The type constructor or data family name
^ The type variables from the data type/data family declaration
^ If using a data family instance, provides the types used
to instantiate the instance
Data family instance case
Luckily, (ConT GHC.Prim.*) only seems to occur in this one spot.
eta-reduced away.
Because these type variables were eta-reduced away, we can only
determine their kind by using stealKindForType. Therefore, we mark
them as VarT to ensure they will be given an explicit kind annotation
(and so the kind inference machinery has the right information).
The types from the data family instance might not have explicit kind
annotations, which the kind machinery needs to work correctly. To
compensate, we use stealKindForType to explicitly annotate any
types without kind annotations.
there may be more kind variable names than there are kinds
to substitute. But this is OK! If a kind is eta-reduced, it
means that is was not instantiated to something more specific,
so we need not substitute it. Using stealKindForType will
grab the correct kind.
For the given Types, deduces the instance type (and kind) to use for a
Generic(1) instance. Coming up with the instance type isn't as simple as
dropping the last types, as you need to be wary of kinds being instantiated
with *.
See Note [Type inference in derived instances]
^ Whether or not to use explicit kind signatures in the instance type
^ The type constructor or data family name
^ The types to instantiate the instance with
Make sure to expand through type/kind synonyms! Otherwise, the
eta-reduction check might get tripped up over type variables in a
synonym that are actually dropped.
Check there are enough types to drop and that all of them are either of
kind * or kind k (for some kind variable k). If not, throw an error.
Substitute kind * for any dropped kind variables
If any of the dropped types were polykinded, ensure that there are of
kind * after substituting * for the dropped kind variables. If not,
throw an error.
We now substitute all of the specialized-to-* kind variable names
with *, but in the original types, not the synonym-expanded types. The reason
we do this is a superficial one: we want the derived instance to resemble
the datatype written in source code as closely as possible. For example,
for the following data family instance:
data family Fam a
newtype instance Fam String = Fam String
We'd want to generate the instance:
instance C (Fam String)
Not:
instance C (Fam [Char])
See Note [Kind signatures in derived instances] for an explanation
of the useKindSigs check.
See Note [Kind signatures in derived instances]
Ensure the dropped types can be safely eta-reduced. Otherwise,
throw an error.
See Note [Arguments to generated type synonyms] | # LANGUAGE CPP #
|
Module : Generics . Deriving . Newtypeless . TH
Copyright : ( c ) 2008 - -2009 Universiteit Utrecht
License : BSD3
Maintainer :
Stability : experimental
Portability : non - portable
This module contains Template Haskell code that can be used to
automatically generate the boilerplate code for the generic deriving
library .
To use these functions , pass the name of a data type as an argument :
@
& # 123;-# ; LANGUAGE TemplateHaskell & # 35;-} ;
data Example a = Example Int Char a
@
On GHC 7.4 or later , this code can also be used with data families . To derive
for a data family instance , pass the name of one of the instance 's constructors :
@
& # 123;-# ; LANGUAGE FlexibleInstances , TemplateHaskell , TypeFamilies & # 35;-} ;
data family Family a b
newtype instance = FamilyChar
data instance = FamilyTrue | FamilyFalse
@
Module : Generics.Deriving.Newtypeless.TH
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
This module contains Template Haskell code that can be used to
automatically generate the boilerplate code for the generic deriving
library.
To use these functions, pass the name of a data type as an argument:
@
{-# LANGUAGE TemplateHaskell #-}
data Example a = Example Int Char a
@
On GHC 7.4 or later, this code can also be used with data families. To derive
for a data family instance, pass the name of one of the instance's constructors:
@
{-# LANGUAGE FlexibleInstances, TemplateHaskell, TypeFamilies #-}
data family Family a b
newtype instance Family Char x = FamilyChar Char
data instance Family Bool x = FamilyTrue | FamilyFalse
@
-}
module Generics.Deriving.Newtypeless.TH (
deriveMeta
, deriveData
, deriveConstructors
, deriveSelectors
, deriveAll
, deriveAll0
, deriveAll1
, deriveAll0And1
, deriveRepresentable0
, deriveRepresentable1
, deriveRep0
, deriveRep1
, simplInstance
, makeRep0Inline
, makeRep0
, makeRep0FromType
, makeFrom
, makeFrom0
, makeTo
, makeTo0
, makeRep1Inline
, makeRep1
, makeRep1FromType
, makeFrom1
, makeTo1
, Options(..)
, defaultOptions
, RepOptions(..)
, defaultRepOptions
, KindSigOptions
, defaultKindSigOptions
, deriveAll0Options
, deriveAll1Options
, deriveAll0And1Options
, deriveRepresentable0Options
, deriveRepresentable1Options
, deriveRep0Options
, deriveRep1Options
) where
import Control.Monad ((>=>), unless, when)
import Data.List (nub)
import qualified Data.Map as Map (fromList)
import Data.Maybe (catMaybes)
import Generics.Deriving.Newtypeless.TH.Internal
import Generics.Deriving.Newtypeless.TH.NonDataKinded
import Language.Haskell.TH.Lib
import Language.Haskell.TH
$ options
' Options ' gives you a way to further tweak derived ' Generic ' and ' Generic1 ' instances :
* ' RepOptions ' : By default , all derived ' Rep ' and ' Rep1 ' type instances emit the code
directly ( the ' InlineRep ' option ) . One can also choose to emit a separate type
synonym for the ' Rep ' type ( this is the functionality of ' deriveRep0 ' and
' deriveRep1 ' ) and define a ' Rep ' instance in terms of that type synonym ( the
' TypeSynonymRep ' option ) .
* ' KindSigOptions ' : By default , all derived instances will use explicit kind
signatures ( when the ' KindSigOptions ' is ' True ' ) . You might wish to set the
' KindSigOptions ' to ' False ' if you want a ' Generic'/'Generic1 ' instance at
a particular kind that GHC will infer correctly , but the functions in this
module wo n't guess correctly . For example , the following example will only
compile with ' KindSigOptions ' set to ' False ' :
@
newtype Compose ( f : : k2 - > * ) ( g : : k1 - > k2 ) ( a : : k1 ) = Compose ( f ( g a ) )
$ ( ' deriveAll1Options ' False '' Compose )
@
'Options' gives you a way to further tweak derived 'Generic' and 'Generic1' instances:
* 'RepOptions': By default, all derived 'Rep' and 'Rep1' type instances emit the code
directly (the 'InlineRep' option). One can also choose to emit a separate type
synonym for the 'Rep' type (this is the functionality of 'deriveRep0' and
'deriveRep1') and define a 'Rep' instance in terms of that type synonym (the
'TypeSynonymRep' option).
* 'KindSigOptions': By default, all derived instances will use explicit kind
signatures (when the 'KindSigOptions' is 'True'). You might wish to set the
'KindSigOptions' to 'False' if you want a 'Generic'/'Generic1' instance at
a particular kind that GHC will infer correctly, but the functions in this
module won't guess correctly. For example, the following example will only
compile with 'KindSigOptions' set to 'False':
@
newtype Compose (f :: k2 -> *) (g :: k1 -> k2) (a :: k1) = Compose (f (g a))
$('deriveAll1Options' False ''Compose)
@
-}
simplInstance :: Name -> Name -> Name -> Name -> Q [Dec]
simplInstance cl ty fn df = do
x <- newName "x"
let typ = ForallT [PlainTV x] []
((foldl (\a -> AppT a . VarT . tyVarBndrName) (ConT (genRepName Generic DataPlain ty)) []) `AppT` (VarT x))
fmap (: []) $ instanceD (cxt []) (conT cl `appT` conT ty)
[funD fn [clause [] (normalB (varE df `appE`
(sigE (varE undefinedValName) (return typ)))) []]]
using Template Haskell .
data Options = Options
{ repOptions :: RepOptions
, kindSigOptions :: KindSigOptions
} deriving (Eq, Ord, Read, Show)
defaultOptions :: Options
defaultOptions = Options
{ repOptions = defaultRepOptions
, kindSigOptions = defaultKindSigOptions
}
data RepOptions = InlineRep
| TypeSynonymRep
deriving (Eq, Ord, Read, Show)
| ' InlineRep ' , a sensible default ' RepOptions ' .
defaultRepOptions :: RepOptions
defaultRepOptions = InlineRep
type KindSigOptions = Bool
defaultKindSigOptions :: KindSigOptions
defaultKindSigOptions = True
deriveAll :: Name -> Q [Dec]
deriveAll = deriveAll0
deriveAll0 :: Name -> Q [Dec]
deriveAll0 = deriveAll0Options defaultOptions
deriveAll0Options :: Options -> Name -> Q [Dec]
deriveAll0Options = deriveAllCommon True False
deriveAll1 :: Name -> Q [Dec]
deriveAll1 = deriveAll1Options defaultOptions
deriveAll1Options :: Options -> Name -> Q [Dec]
deriveAll1Options = deriveAllCommon False True
deriveAll0And1 :: Name -> Q [Dec]
deriveAll0And1 = deriveAll0And1Options defaultOptions
deriveAll0And1Options :: Options -> Name -> Q [Dec]
deriveAll0And1Options = deriveAllCommon True True
deriveAllCommon :: Bool -> Bool -> Options -> Name -> Q [Dec]
deriveAllCommon generic generic1 opts n = do
a <- deriveMeta n
b <- if generic
then deriveRepresentableCommon Generic opts n
else return []
c <- if generic1
then deriveRepresentableCommon Generic1 opts n
else return []
return (a ++ b ++ c)
deriveRepresentable0 :: Name -> Q [Dec]
deriveRepresentable0 = deriveRepresentable0Options defaultOptions
deriveRepresentable0Options :: Options -> Name -> Q [Dec]
deriveRepresentable0Options = deriveRepresentableCommon Generic
deriveRepresentable1 :: Name -> Q [Dec]
deriveRepresentable1 = deriveRepresentable1Options defaultOptions
deriveRepresentable1Options :: Options -> Name -> Q [Dec]
deriveRepresentable1Options = deriveRepresentableCommon Generic1
deriveRepresentableCommon :: GenericClass -> Options -> Name -> Q [Dec]
deriveRepresentableCommon gClass opts n = do
rep <- if repOptions opts == InlineRep
then return []
else deriveRepCommon gClass (kindSigOptions opts) n
inst <- deriveInst gClass opts n
return (rep ++ inst)
deriveRep0 :: Name -> Q [Dec]
deriveRep0 = deriveRep0Options defaultKindSigOptions
deriveRep0Options :: KindSigOptions -> Name -> Q [Dec]
deriveRep0Options = deriveRepCommon Generic
deriveRep1 :: Name -> Q [Dec]
deriveRep1 = deriveRep1Options defaultKindSigOptions
deriveRep1Options :: KindSigOptions -> Name -> Q [Dec]
deriveRep1Options = deriveRepCommon Generic1
deriveRepCommon :: GenericClass -> KindSigOptions -> Name -> Q [Dec]
deriveRepCommon gClass useKindSigs n = do
i <- reifyDataInfo n
let (name, isNT, declTvbs, cons, dv) = either error id i
!_ <- buildTypeInstance gClass useKindSigs name declTvbs dv
tySynVars <- grabTyVarsFromCons gClass cons
let tySynVars' = if useKindSigs
then tySynVars
else map unSigT tySynVars
fmap (:[]) $ tySynD (genRepName gClass dv name)
(catMaybes $ map typeToTyVarBndr tySynVars')
(repType gClass dv name isNT cons tySynVars)
deriveInst :: GenericClass -> Options -> Name -> Q [Dec]
deriveInst Generic = deriveInstCommon genericTypeName repTypeName Generic fromValName toValName
deriveInst Generic1 = deriveInstCommon generic1TypeName rep1TypeName Generic1 from1ValName to1ValName
deriveInstCommon :: Name
-> Name
-> GenericClass
-> Name
-> Name
-> Options
-> Name
-> Q [Dec]
deriveInstCommon genericName repName gClass fromName toName opts n = do
i <- reifyDataInfo n
let (name, isNT, allTvbs, cons, dv) = either error id i
useKindSigs = kindSigOptions opts
!(origTy, origKind) <- buildTypeInstance gClass useKindSigs name allTvbs dv
tyInsRHS <- if repOptions opts == InlineRep
then makeRepInline gClass dv name isNT cons origTy
else makeRepTySynApp gClass dv name cons origTy
let origSigTy = if useKindSigs
then SigT origTy origKind
else origTy
tyIns = TySynInstD repName
#if MIN_VERSION_template_haskell(2,9,0)
(TySynEqn [origSigTy] tyInsRHS)
#else
[origSigTy] tyInsRHS
#endif
mkBody maker = [clause [] (normalB $ mkCaseExp gClass name cons maker) []]
fcs = mkBody mkFrom
tcs = mkBody mkTo
fmap (:[]) $
instanceD (cxt []) (conT genericName `appT` return origSigTy)
[return tyIns, funD fromName fcs, funD toName tcs]
$ make
There are some data types for which the Template Haskell deriver functions in
this module are not sophisticated enough to infer the correct ' Generic ' or
' Generic1 ' instances . As an example , consider this data type :
@
newtype Fix f a = Fix ( f ( Fix f a ) )
@
A proper ' Generic1 ' instance would look like this :
@
instance Functor f = > Generic1 ( Fix f ) where ...
@
Unfortunately , ' deriveRepresentable1 ' can not infer the @Functor f@ constraint .
One can still define a ' Generic1 ' instance for , however , by using the
functions in this module that are prefixed with @make@- . For example :
@
$ ( ' deriveMeta ' ' ' Fix )
$ ( ' deriveRep1 ' ' ' Fix )
instance Functor f = > Generic1 ( Fix f ) where
type Rep1 ( Fix f ) = $ ( ' makeRep1Inline ' ' ' Fix [ t| Fix f | ] )
from1 = $ ( ' makeFrom1 ' ' ' Fix )
to1 = $ ( ' makeTo1 ' '' Fix )
@
Note that due to the lack of type - level lambdas in Haskell , one must manually
apply @'makeRep1Inline ' ' ' Fix@ to the type @Fix f@.
Be aware that there is a bug on GHC 7.0 , 7.2 , and 7.4 which might prevent you from
using ' makeRep0Inline ' and ' makeRep1Inline ' . In the example above , you
would experience the following error :
@
Kinded thing ` f ' used as a type
In the Template Haskell quotation [ t| Fix f | ]
@
Then a workaround is to use ' makeRep1 ' instead , which requires you to :
1 . Invoke ' deriveRep1 ' beforehand
2 . Pass as arguments the type variables that occur in the instance , in order
from left to right , topologically sorted , excluding duplicates . ( Normally ,
' makeRep1Inline ' would figure this out for you . )
Using the above example :
@
$ ( ' deriveMeta ' ' ' Fix )
$ ( ' deriveRep1 ' ' ' Fix )
instance Functor f = > Generic1 ( Fix f ) where
type Rep1 ( Fix f ) = $ ( ' makeRep1 ' ' ' Fix ) f
from1 = $ ( ' makeFrom1 ' ' ' Fix )
to1 = $ ( ' makeTo1 ' '' Fix )
@
On GHC 7.4 , you might encounter more complicated examples involving data
families . For instance :
@
data family Fix a b c d
newtype instance Fix b ( f c ) ( g b ) a = Fix ( f ( Fix b ( f c ) ( g b ) a ) )
$ ( ' deriveMeta ' ' ' Fix )
$ ( ' deriveRep1 ' ' ' Fix )
instance Functor f = > Generic1 ( Fix b ( f c ) ( g b ) ) where
type Rep1 ( Fix b ( f c ) ( g b ) ) = $ ( ' makeRep1 ' ' Fix ) b f c g
from1 = $ ( ' makeFrom1 ' ' Fix )
to1 = $ ( ' makeTo1 ' ' Fix )
@
Note that you do n't pass @b@ twice , only once .
There are some data types for which the Template Haskell deriver functions in
this module are not sophisticated enough to infer the correct 'Generic' or
'Generic1' instances. As an example, consider this data type:
@
newtype Fix f a = Fix (f (Fix f a))
@
A proper 'Generic1' instance would look like this:
@
instance Functor f => Generic1 (Fix f) where ...
@
Unfortunately, 'deriveRepresentable1' cannot infer the @Functor f@ constraint.
One can still define a 'Generic1' instance for @Fix@, however, by using the
functions in this module that are prefixed with @make@-. For example:
@
$('deriveMeta' ''Fix)
$('deriveRep1' ''Fix)
instance Functor f => Generic1 (Fix f) where
type Rep1 (Fix f) = $('makeRep1Inline' ''Fix [t| Fix f |])
from1 = $('makeFrom1' ''Fix)
to1 = $('makeTo1' ''Fix)
@
Note that due to the lack of type-level lambdas in Haskell, one must manually
apply @'makeRep1Inline' ''Fix@ to the type @Fix f@.
Be aware that there is a bug on GHC 7.0, 7.2, and 7.4 which might prevent you from
using 'makeRep0Inline' and 'makeRep1Inline'. In the @Fix@ example above, you
would experience the following error:
@
Kinded thing `f' used as a type
In the Template Haskell quotation [t| Fix f |]
@
Then a workaround is to use 'makeRep1' instead, which requires you to:
1. Invoke 'deriveRep1' beforehand
2. Pass as arguments the type variables that occur in the instance, in order
from left to right, topologically sorted, excluding duplicates. (Normally,
'makeRep1Inline' would figure this out for you.)
Using the above example:
@
$('deriveMeta' ''Fix)
$('deriveRep1' ''Fix)
instance Functor f => Generic1 (Fix f) where
type Rep1 (Fix f) = $('makeRep1' ''Fix) f
from1 = $('makeFrom1' ''Fix)
to1 = $('makeTo1' ''Fix)
@
On GHC 7.4, you might encounter more complicated examples involving data
families. For instance:
@
data family Fix a b c d
newtype instance Fix b (f c) (g b) a = Fix (f (Fix b (f c) (g b) a))
$('deriveMeta' ''Fix)
$('deriveRep1' ''Fix)
instance Functor f => Generic1 (Fix b (f c) (g b)) where
type Rep1 (Fix b (f c) (g b)) = $('makeRep1' 'Fix) b f c g
from1 = $('makeFrom1' 'Fix)
to1 = $('makeTo1' 'Fix)
@
Note that you don't pass @b@ twice, only once.
-}
signature on This is due to a limitation of Template Haskell — without
makeRep0Inline :: Name -> Q Type -> Q Type
makeRep0Inline n = makeRepCommon Generic InlineRep n . Just
type Rep1 ( ( a : : k ) ) = $ ( ' makeRep0Inline ' ' ' Foo [ t| Foo ( a : : k ) | ] )
signature on This is due to a limitation of Template Haskell — without
makeRep1Inline :: Name -> Q Type -> Q Type
makeRep1Inline n = makeRepCommon Generic1 InlineRep n . Just
Haskell source , it expects types as arguments . For example :
type Rep ( Foo a b ) = $ ( ' makeRep0 ' ' ' ) a b
' makeRep0Inline ' is not usable on GHC 7.0 , 7.2 , or 7.4 due to a GHC bug ,
so ' makeRep0 ' still exists for GHC 7.0 , 7.2 , and 7.4 users .
makeRep0 :: Name -> Q Type
makeRep0 n = makeRepCommon Generic TypeSynonymRep n Nothing
Haskell source , it expects types as arguments . For example :
type Rep1 ( a ) = $ ( ' makeRep1 ' ' ' ) a
' makeRep1Inline ' is not usable on GHC 7.0 , 7.2 , or 7.4 due to a GHC bug ,
so ' makeRep1 ' still exists for GHC 7.0 , 7.2 , and 7.4 users .
makeRep1 :: Name -> Q Type
makeRep1 n = makeRepCommon Generic1 TypeSynonymRep n Nothing
type Rep ( Foo ( a : : k ) b ) = $ ( ' makeRep0FromType ' ' ' Foo [ t| Foo ( a : : k ) b | ] )
signature on This is due to a limitation of Template Haskell — without
the kind signature , ' makeRep0FromType ' has no way of figuring out the kind of
makeRep0FromType :: Name -> Q Type -> Q Type
makeRep0FromType n = makeRepCommon Generic TypeSynonymRep n . Just
type Rep1 ( ( a : : k ) ) = $ ( ' makeRep1FromType ' ' ' Foo [ t| Foo ( a : : k ) | ] )
Note that the type passed as an argument to ' makeRep1FromType ' must match the
signature on This is due to a limitation of Template Haskell — without
the kind signature , ' makeRep1FromType ' has no way of figuring out the kind of
The use of ' makeRep1FromType ' is generally discouraged , since ' makeRep1Inline '
makeRep1FromType :: Name -> Q Type -> Q Type
makeRep1FromType n = makeRepCommon Generic1 TypeSynonymRep n . Just
makeRepCommon :: GenericClass
-> RepOptions
-> Name
-> Maybe (Q Type)
-> Q Type
makeRepCommon gClass repOpts n mbQTy = do
i <- reifyDataInfo n
let (name, isNT, declTvbs, cons, dv) = either error id i
!_ <- buildTypeInstance gClass False name declTvbs dv
case (mbQTy, repOpts) of
(Just qTy, TypeSynonymRep) -> qTy >>= makeRepTySynApp gClass dv name cons
(Just qTy, InlineRep) -> qTy >>= makeRepInline gClass dv name isNT cons
(Nothing, TypeSynonymRep) -> conT $ genRepName gClass dv name
(Nothing, InlineRep) -> fail "makeRepCommon"
makeRepInline :: GenericClass
-> DataVariety
-> Name
-> Bool
-> [Con]
-> Type
-> Q Type
makeRepInline gClass dv name isNT cons ty = do
let instVars = map tyVarBndrToType $ requiredTyVarsOfType ty
repType gClass dv name isNT cons instVars
makeRepTySynApp :: GenericClass
-> DataVariety
-> Name
-> [Con]
-> Type
-> Q Type
makeRepTySynApp gClass dv name cons ty = do
of the LHS of the Rep(1 ) instance . We call unKindedTV because the kind
let instTvbs = map unKindedTV $ requiredTyVarsOfType ty
We grab the type variables from the first constructor 's type signature .
tySynVars <- grabTyVarsFromCons gClass cons
return . applyTyToTvbs (genRepName gClass dv name)
$ zipWith const instTvbs tySynVars
makeFrom :: Name -> Q Exp
makeFrom = makeFrom0
makeFrom0 :: Name -> Q Exp
makeFrom0 = makeFunCommon mkFrom Generic
makeTo :: Name -> Q Exp
makeTo = makeTo0
makeTo0 :: Name -> Q Exp
makeTo0 = makeFunCommon mkTo Generic
makeFrom1 :: Name -> Q Exp
makeFrom1 = makeFunCommon mkFrom Generic1
| Generates a lambda expression which behaves like ' ' .
makeTo1 :: Name -> Q Exp
makeTo1 = makeFunCommon mkTo Generic1
makeFunCommon :: (GenericClass -> Int -> Int -> Name -> [Con] -> Q Match)
-> GenericClass -> Name -> Q Exp
makeFunCommon maker gClass n = do
i <- reifyDataInfo n
let (name, _, allTvbs, cons, dv) = either error id i
buildTypeInstance gClass False name allTvbs dv
`seq` mkCaseExp gClass name cons maker
genRepName :: GenericClass -> DataVariety -> Name -> Name
genRepName gClass dv n = mkName
. showsDataVariety dv
. (("Rep" ++ show (fromEnum gClass)) ++)
. ((showNameQual n ++ "_") ++)
. sanitizeName
$ nameBase n
repType :: GenericClass
-> DataVariety
-> Name
-> Bool
-> [Con]
-> [Type]
-> Q Type
repType gClass dv dt isNT cs tySynVars =
conT d1TypeName `appT` mkMetaDataType dv dt isNT `appT`
foldr1' sum' (conT v1TypeName)
(map (repCon gClass dv dt tySynVars) cs)
where
sum' :: Q Type -> Q Type -> Q Type
sum' a b = conT sumTypeName `appT` a `appT` b
repCon :: GenericClass
-> DataVariety
-> Name
-> [Type]
-> Con
-> Q Type
repCon gClass dv dt tySynVars (NormalC n bts) = do
let bangs = map fst bts
ssis <- reifySelStrictInfo n bangs
repConWith gClass dv dt n tySynVars Nothing ssis False False
repCon gClass dv dt tySynVars (RecC n vbts) = do
let (selNames, bangs, _) = unzip3 vbts
ssis <- reifySelStrictInfo n bangs
repConWith gClass dv dt n tySynVars (Just selNames) ssis True False
repCon gClass dv dt tySynVars (InfixC t1 n t2) = do
let bangs = map fst [t1, t2]
ssis <- reifySelStrictInfo n bangs
repConWith gClass dv dt n tySynVars Nothing ssis False True
repCon _ _ _ _ con = gadtError con
repConWith :: GenericClass
-> DataVariety
-> Name
-> Name
-> [Type]
-> Maybe [Name]
-> [SelStrictInfo]
-> Bool
-> Bool
-> Q Type
repConWith gClass dv dt n tySynVars mbSelNames ssis isRecord isInfix = do
(conVars, ts, gk) <- reifyConTys gClass n
let structureType :: Q Type
structureType = case ssis of
[] -> conT u1TypeName
_ -> foldr1 prodT f
typeSubst :: TypeSubst
typeSubst = Map.fromList $
zip (nub $ concatMap tyVarNamesOfType conVars)
(nub $ concatMap (map VarT . tyVarNamesOfType) tySynVars)
f :: [Q Type]
f = case mbSelNames of
Just selNames -> zipWith3 (repField gk dv dt n typeSubst . Just)
selNames ssis ts
Nothing -> zipWith (repField gk dv dt n typeSubst Nothing)
ssis ts
conT c1TypeName
`appT` mkMetaConsType dv dt n isRecord isInfix
`appT` structureType
prodT :: Q Type -> Q Type -> Q Type
prodT a b = conT productTypeName `appT` a `appT` b
repField :: GenericKind
-> DataVariety
-> Name
-> Name
-> TypeSubst
-> Maybe Name
-> SelStrictInfo
-> Type
-> Q Type
repField gk dv dt ns typeSubst mbF ssi t =
conT s1TypeName
`appT` mkMetaSelType dv dt ns mbF ssi
`appT` (repFieldArg gk =<< expandSyn t'')
where
t', t'' :: Type
t' = case gk of
Gen1 _ (Just _kvName) ->
See Note [ Generic1 is polykinded on GHC 8.2 ]
#if __GLASGOW_HASKELL__ >= 801
t
#else
substNameWithKind _kvName starK t
#endif
_ -> t
t'' = substType typeSubst t'
repFieldArg :: GenericKind -> Type -> Q Type
repFieldArg _ ForallT{} = rankNError
repFieldArg gk (SigT t _) = repFieldArg gk t
repFieldArg Gen0 t = boxT t
repFieldArg (Gen1 name _) (VarT t) | t == name = conT par1TypeName
repFieldArg gk@(Gen1 name _) t = do
let tyHead:tyArgs = unapplyTy t
numLastArgs = min 1 $ length tyArgs
(lhsArgs, rhsArgs) = splitAt (length tyArgs - numLastArgs) tyArgs
rec0Type = boxT t
phiType = return $ applyTyToTys tyHead lhsArgs
inspectTy :: Type -> Q Type
inspectTy (VarT a)
| a == name
= conT rec1TypeName `appT` phiType
inspectTy (SigT ty _) = inspectTy ty
inspectTy beta
| not (ground beta name)
= conT composeTypeName `appT` phiType
`appT` repFieldArg gk beta
inspectTy _ = rec0Type
itf <- isTyFamily tyHead
if any (not . (`ground` name)) lhsArgs
|| any (not . (`ground` name)) tyArgs && itf
then outOfPlaceTyVarError
else case rhsArgs of
[] -> rec0Type
ty:_ -> inspectTy ty
boxT :: Type -> Q Type
boxT ty = case unboxedRepNames ty of
Just (boxTyName, _, _) -> conT boxTyName
Nothing -> conT rec0TypeName `appT` return ty
mkCaseExp :: GenericClass -> Name -> [Con]
-> (GenericClass -> Int -> Int -> Name -> [Con] -> Q Match)
-> Q Exp
mkCaseExp gClass dt cs matchmaker = do
val <- newName "val"
lam1E (varP val) $ caseE (varE val) [matchmaker gClass 1 0 dt cs]
mkFrom :: GenericClass -> Int -> Int -> Name -> [Con] -> Q Match
mkFrom gClass m i dt cs = do
y <- newName "y"
match (varP y)
(normalB $ conE m1DataName `appE` caseE (varE y) cases)
[]
where
cases = case cs of
[] -> [errorFrom dt]
_ -> zipWith (fromCon gClass wrapE (length cs)) [0..] cs
wrapE e = lrE m i e
errorFrom :: Name -> Q Match
errorFrom dt =
match
wildP
(normalB $ varE errorValName `appE` stringE
("No generic representation for empty datatype " ++ nameBase dt))
[]
errorTo :: Name -> Q Match
errorTo dt =
match
wildP
(normalB $ varE errorValName `appE` stringE
("No values for empty datatype " ++ nameBase dt))
[]
mkTo :: GenericClass -> Int -> Int -> Name -> [Con] -> Q Match
mkTo gClass m i dt cs = do
y <- newName "y"
match (conP m1DataName [varP y])
(normalB $ caseE (varE y) cases)
[]
where
cases = case cs of
[] -> [errorTo dt]
_ -> zipWith (toCon gClass wrapP (length cs)) [0..] cs
wrapP p = lrP m i p
fromCon :: GenericClass -> (Q Exp -> Q Exp) -> Int -> Int -> Con -> Q Match
fromCon _ wrap m i (NormalC cn []) =
match
(conP cn [])
(normalB $ wrap $ lrE m i $ conE m1DataName `appE` (conE u1DataName)) []
fromCon gClass wrap m i (NormalC cn _) = do
(ts, gk) <- fmap shrink $ reifyConTys gClass cn
fNames <- newNameList "f" $ length ts
match
(conP cn (map varP fNames))
(normalB $ wrap $ lrE m i $ conE m1DataName `appE`
foldr1 prodE (zipWith (fromField gk) fNames ts)) []
fromCon _ wrap m i (RecC cn []) =
match
(conP cn [])
(normalB $ wrap $ lrE m i $ conE m1DataName `appE` (conE u1DataName)) []
fromCon gClass wrap m i (RecC cn _) = do
(ts, gk) <- fmap shrink $ reifyConTys gClass cn
fNames <- newNameList "f" $ length ts
match
(conP cn (map varP fNames))
(normalB $ wrap $ lrE m i $ conE m1DataName `appE`
foldr1 prodE (zipWith (fromField gk) fNames ts)) []
fromCon gClass wrap m i (InfixC t1 cn t2) =
fromCon gClass wrap m i (NormalC cn [t1,t2])
fromCon _ _ _ _ con = gadtError con
prodE :: Q Exp -> Q Exp -> Q Exp
prodE x y = conE productDataName `appE` x `appE` y
fromField :: GenericKind -> Name -> Type -> Q Exp
fromField gk nr t = conE m1DataName `appE` (fromFieldWrap gk nr =<< expandSyn t)
fromFieldWrap :: GenericKind -> Name -> Type -> Q Exp
fromFieldWrap _ _ ForallT{} = rankNError
fromFieldWrap gk nr (SigT t _) = fromFieldWrap gk nr t
fromFieldWrap Gen0 nr t = conE (boxRepName t) `appE` varE nr
fromFieldWrap (Gen1 name _) nr t = wC t name `appE` varE nr
wC :: Type -> Name -> Q Exp
wC (VarT t) name | t == name = conE par1DataName
wC t name
| ground t name = conE $ boxRepName t
| otherwise = do
let tyHead:tyArgs = unapplyTy t
numLastArgs = min 1 $ length tyArgs
(lhsArgs, rhsArgs) = splitAt (length tyArgs - numLastArgs) tyArgs
inspectTy :: Type -> Q Exp
inspectTy ForallT{} = rankNError
inspectTy (SigT ty _) = inspectTy ty
inspectTy (VarT a)
| a == name
= conE rec1DataName
inspectTy beta = infixApp (conE comp1DataName)
(varE composeValName)
(varE fmapValName `appE` wC beta name)
itf <- isTyFamily tyHead
if any (not . (`ground` name)) lhsArgs
|| any (not . (`ground` name)) tyArgs && itf
then outOfPlaceTyVarError
else case rhsArgs of
[] -> conE $ boxRepName t
ty:_ -> inspectTy ty
boxRepName :: Type -> Name
boxRepName = maybe k1DataName snd3 . unboxedRepNames
toCon :: GenericClass -> (Q Pat -> Q Pat) -> Int -> Int -> Con -> Q Match
toCon _ wrap m i (NormalC cn []) =
match
(wrap $ lrP m i $ conP m1DataName [conP u1DataName []])
(normalB $ conE cn) []
toCon gClass wrap m i (NormalC cn _) = do
(ts, gk) <- fmap shrink $ reifyConTys gClass cn
fNames <- newNameList "f" $ length ts
match
(wrap $ lrP m i $ conP m1DataName
[foldr1 prod (zipWith (toField gk) fNames ts)])
(normalB $ foldl appE (conE cn) (zipWith (\nr -> expandSyn >=> toConUnwC gk nr)
fNames ts)) []
where prod x y = conP productDataName [x,y]
toCon _ wrap m i (RecC cn []) =
match
(wrap $ lrP m i $ conP m1DataName [conP u1DataName []])
(normalB $ conE cn) []
toCon gClass wrap m i (RecC cn _) = do
(ts, gk) <- fmap shrink $ reifyConTys gClass cn
fNames <- newNameList "f" $ length ts
match
(wrap $ lrP m i $ conP m1DataName
[foldr1 prod (zipWith (toField gk) fNames ts)])
(normalB $ foldl appE (conE cn) (zipWith (\nr -> expandSyn >=> toConUnwC gk nr)
fNames ts)) []
where prod x y = conP productDataName [x,y]
toCon gk wrap m i (InfixC t1 cn t2) =
toCon gk wrap m i (NormalC cn [t1,t2])
toCon _ _ _ _ con = gadtError con
toConUnwC :: GenericKind -> Name -> Type -> Q Exp
toConUnwC Gen0 nr _ = varE nr
toConUnwC (Gen1 name _) nr t = unwC t name `appE` varE nr
toField :: GenericKind -> Name -> Type -> Q Pat
toField gk nr t = conP m1DataName [toFieldWrap gk nr t]
toFieldWrap :: GenericKind -> Name -> Type -> Q Pat
toFieldWrap Gen0 nr t = conP (boxRepName t) [varP nr]
toFieldWrap Gen1{} nr _ = varP nr
unwC :: Type -> Name -> Q Exp
unwC (SigT t _) name = unwC t name
unwC (VarT t) name | t == name = varE unPar1ValName
unwC t name
| ground t name = varE $ unboxRepName t
| otherwise = do
let tyHead:tyArgs = unapplyTy t
numLastArgs = min 1 $ length tyArgs
(lhsArgs, rhsArgs) = splitAt (length tyArgs - numLastArgs) tyArgs
inspectTy :: Type -> Q Exp
inspectTy ForallT{} = rankNError
inspectTy (SigT ty _) = inspectTy ty
inspectTy (VarT a)
| a == name
= varE unRec1ValName
inspectTy beta = infixApp (varE fmapValName `appE` unwC beta name)
(varE composeValName)
(varE unComp1ValName)
itf <- isTyFamily tyHead
if any (not . (`ground` name)) lhsArgs
|| any (not . (`ground` name)) tyArgs && itf
then outOfPlaceTyVarError
else case rhsArgs of
[] -> varE $ unboxRepName t
ty:_ -> inspectTy ty
unboxRepName :: Type -> Name
unboxRepName = maybe unK1ValName trd3 . unboxedRepNames
lrP :: Int -> Int -> (Q Pat -> Q Pat)
lrP 1 0 p = p
lrP _ 0 p = conP l1DataName [p]
lrP m i p = conP r1DataName [lrP (m-1) (i-1) p]
lrE :: Int -> Int -> (Q Exp -> Q Exp)
lrE 1 0 e = e
lrE _ 0 e = conE l1DataName `appE` e
lrE m i e = conE r1DataName `appE` lrE (m-1) (i-1) e
unboxedRepNames :: Type -> Maybe (Name, Name, Name)
unboxedRepNames ty
| ty == ConT addrHashTypeName = Just (uAddrTypeName, uAddrDataName, uAddrHashValName)
| ty == ConT charHashTypeName = Just (uCharTypeName, uCharDataName, uCharHashValName)
| ty == ConT doubleHashTypeName = Just (uDoubleTypeName, uDoubleDataName, uDoubleHashValName)
| ty == ConT floatHashTypeName = Just (uFloatTypeName, uFloatDataName, uFloatHashValName)
| ty == ConT intHashTypeName = Just (uIntTypeName, uIntDataName, uIntHashValName)
| ty == ConT wordHashTypeName = Just (uWordTypeName, uWordDataName, uWordHashValName)
| otherwise = Nothing
buildTypeInstance :: GenericClass
^ Generic or Generic1
-> KindSigOptions
-> Name
-> [TyVarBndr]
-> DataVariety
-> Q (Type, Kind)
Plain data type / newtype case
buildTypeInstance gClass useKindSigs tyConName tvbs DataPlain =
let varTys :: [Type]
varTys = map tyVarBndrToType tvbs
in buildTypeInstanceFromTys gClass useKindSigs tyConName varTys
The CPP is present to work around a couple of annoying old GHC bugs .
See Note [ Polykinded data families in Template Haskell ]
buildTypeInstance gClass useKindSigs parentName tvbs (DataFamily _ instTysAndKinds) = do
#if !(MIN_VERSION_template_haskell(2,8,0)) || MIN_VERSION_template_haskell(2,10,0)
let instTys :: [Type]
instTys = zipWith stealKindForType tvbs instTysAndKinds
#else
let kindVarNames :: [Name]
kindVarNames = nub $ concatMap (tyVarNamesOfType . tyVarBndrKind) tvbs
numKindVars :: Int
numKindVars = length kindVarNames
givenKinds, givenKinds' :: [Kind]
givenTys :: [Type]
(givenKinds, givenTys) = splitAt numKindVars instTysAndKinds
givenKinds' = map sanitizeStars givenKinds
A GHC 7.6 - specific bug requires us to replace all occurrences of
( ConT GHC.Prim . * ) with StarT , or else will reject it .
sanitizeStars :: Kind -> Kind
sanitizeStars = go
where
go :: Kind -> Kind
go (AppT t1 t2) = AppT (go t1) (go t2)
go (SigT t k) = SigT (go t) (go k)
go (ConT n) | n == starKindName = StarT
go t = t
If we run this code with GHC 7.8 , we might have to generate extra type
variables to compensate for any type variables that
See Note [ Polykinded data families in Template Haskell ]
xTypeNames <- newNameList "tExtra" (length tvbs - length givenTys)
let xTys :: [Type]
xTys = map VarT xTypeNames
substNamesWithKinds :: [(Name, Kind)] -> Type -> Type
substNamesWithKinds nks t = foldr' (uncurry substNameWithKind) t nks
instTys :: [Type]
instTys = map (substNamesWithKinds (zip kindVarNames givenKinds'))
Note that due to a GHC 7.8 - specific bug
( see Note [ Polykinded data families in Template Haskell ] ) ,
$ zipWith stealKindForType tvbs (givenTys ++ xTys)
#endif
buildTypeInstanceFromTys gClass useKindSigs parentName instTys
buildTypeInstanceFromTys :: GenericClass
^ Generic or Generic1
-> KindSigOptions
-> Name
-> [Type]
-> Q (Type, Kind)
buildTypeInstanceFromTys gClass useKindSigs tyConName varTysOrig = do
( See GHC Trac # 11416 for a scenario where this actually happened . )
varTysExp <- mapM expandSyn varTysOrig
let remainingLength :: Int
remainingLength = length varTysOrig - fromEnum gClass
droppedTysExp :: [Type]
droppedTysExp = drop remainingLength varTysExp
droppedStarKindStati :: [StarKindStatus]
droppedStarKindStati = map canRealizeKindStar droppedTysExp
when (remainingLength < 0 || any (== NotKindStar) droppedStarKindStati) $
derivingKindError tyConName
let varTysExpSubst :: [Type]
See Note [ Generic1 is polykinded on GHC 8.2 ]
#if __GLASGOW_HASKELL__ >= 801
varTysExpSubst = varTysExp
#else
varTysExpSubst = map (substNamesWithKindStar droppedKindVarNames) varTysExp
droppedKindVarNames :: [Name]
droppedKindVarNames = catKindVarNames droppedStarKindStati
#endif
let remainingTysExpSubst, droppedTysExpSubst :: [Type]
(remainingTysExpSubst, droppedTysExpSubst) =
splitAt remainingLength varTysExpSubst
See Note [ Generic1 is polykinded on GHC 8.2 ]
#if __GLASGOW_HASKELL__ < 801
unless (all hasKindStar droppedTysExpSubst) $
derivingKindError tyConName
#endif
let varTysOrigSubst :: [Type]
varTysOrigSubst =
See Note [ Generic1 is polykinded on GHC 8.2 ]
#if __GLASGOW_HASKELL__ >= 801
id
#else
map (substNamesWithKindStar droppedKindVarNames)
#endif
$ varTysOrig
remainingTysOrigSubst, droppedTysOrigSubst :: [Type]
(remainingTysOrigSubst, droppedTysOrigSubst) =
splitAt remainingLength varTysOrigSubst
remainingTysOrigSubst' :: [Type]
remainingTysOrigSubst' =
if useKindSigs
then remainingTysOrigSubst
else map unSigT remainingTysOrigSubst
instanceType :: Type
instanceType = applyTyToTys (ConT tyConName) remainingTysOrigSubst'
instanceKind :: Kind
instanceKind = makeFunKind (map typeKind droppedTysOrigSubst) starK
unless (canEtaReduce remainingTysExpSubst droppedTysExpSubst) $
etaReductionError instanceType
return (instanceType, instanceKind)
grabTyVarsFromCons :: GenericClass -> [Con] -> Q [Type]
grabTyVarsFromCons _ [] = return []
grabTyVarsFromCons gClass (con:_) =
fmap fst3 $ reifyConTys gClass (constructorName con)
Note [ Forcing buildTypeInstance ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes , we do n't explicitly need to generate a Generic(1 ) type instance , but
we force buildTypeInstance nevertheless . This is because it performs some checks
for whether or not the provided datatype can actually have ) implemented for
it , and produces errors if it ca n't . Otherwise , laziness would cause these checks
to be skipped entirely , which could result in some indecipherable type errors
down the road .
Note [ Substituting types in constructor type signatures ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
While reifyConTys gives you the type variables of a constructor , they may not be
the same of the data declaration 's type variables . The classic example of this is
GADTs :
data GADT a b where
GADTCon : : e - > f - > GADT e f
The type variables of GADTCon are completely different from the declaration 's , which
can cause a problem when generating a Rep instance :
type Rep ( GADT a b ) = Rec0 e :* : , we would generate something like this , since traversing the constructor
would give us precisely those arguments . Not good . We need to perform a type
substitution to ensure that e maps to a , and f maps to b.
This turns out to be surprisingly simple . Whenever you have a constructor type
signature like ( e - > f - > GADT e f ) , take the result type , collect all of its
distinct type variables in order from left - to - right , and then map them to their
corresponding type variables from the data declaration .
There is another obscure case where we need to do a type subtitution . With
-XTypeInType enabled on GHC 8.0 , you might have something like this :
data Proxy ( a : : k ) ( b : : k ) = Proxy k deriving Generic1
Then k gets specialized to * , which means that k should NOT show up in the RHS of
a Rep1 type instance ! To avoid this , make sure to substitute k with * .
See also Note [ Generic1 is polykinded on GHC 8.2 ] .
Note [ Arguments to generated type synonyms ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A surprisingly difficult component of generating the type synonyms for Rep / Rep1 is
coming up with the type synonym variable arguments , since they have to be just the
right name and kind to work . The type signature of a constructor does a remarkably
good job of coming up with these type variables for us , so if at least one constructor
exists , we simply steal the type variables from that constructor 's type signature
for use in the generated type synonym . We also count the number of type variables
that the first constructor 's type signature has in order to determine how many
type variables we should give it as arguments in the generated
( type Rep ( Foo ... ) = < makeRep > ... ) code .
This leads one to ask : what if there are no constructors ? If that 's the case , then
we 're OK , since that means no type variables can possibly appear on the RHS of the
type synonym ! In such a special case , we 're perfectly justified in making the type
synonym not have any type variable arguments , and similarly , we do n't apply any
arguments to it in the generated ( type = < makeRep > ) code .
Note [ Polykinded data families in Template Haskell ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to come up with the correct instance context and head for an instance , e.g. ,
instance C a = > C ( Data a ) where ...
We need to know the exact types and kinds used to instantiate the instance . For
plain old datatypes , this is simple : every type must be a type variable , and
reliably tells us the type variables and their kinds .
Doing the same for data families proves to be much harder for three reasons :
1 . On any version of Template Haskell , it may not tell you what an instantiated
type 's kind is . For instance , in the following data family instance :
data family Fam ( f : : * - > * ) ( a : : * )
data instance Fam f a
Then if we use TH 's reify function , it would tell us the TyVarBndrs of the
data family declaration are :
[ KindedTV f ( AppT ( AppT ArrowT StarT ) StarT),KindedTV a StarT ]
and the instantiated types of the data family instance are :
[ VarT f1,VarT a1 ]
We ca n't just pass [ VarT f1,VarT a1 ] to buildTypeInstanceFromTys , since we
have no way of knowing their kinds . Luckily , the TyVarBndrs tell us what the
kind is in case an instantiated type is n't a SigT , so we use the stealKindForType
function to ensure all of the instantiated types are SigTs before passing them
to buildTypeInstanceFromTys .
2 . On GHC 7.6 and 7.8 , a bug is present in which Template Haskell lists all of
the specified kinds of a data family instance efore any of the instantiated
types . Fortunately , this is easy to deal with : you simply count the number of
distinct kind variables in the data family declaration , take that many elements
from the front of the Types list of the data family instance , substitute the
kind variables with their respective instantiated kinds ( which you took earlier ) ,
and proceed as normal .
3 . On GHC 7.8 , an even uglier bug is present ( GHC Trac # 9692 ) in which Template
Haskell might not even list all of the Types of a data family instance , since
they are eta - reduced away ! And yes , kinds can be eta - reduced too .
The simplest workaround is to count how many instantiated types are missing from
the list and generate extra type variables to use in their place . Luckily , we
need n't worry much if its kind was eta - reduced away , since using stealKindForType
will get it back .
Note [ Kind signatures in derived instances ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We generally include explicit type signatures in derived instances . One reason for
doing so is that in the case of certain data family instances , not including kind
signatures can result in ambiguity . For example , consider the following two data
family instances that are distinguished by their kinds :
data family Fam ( a : : k )
data instance Fam ( a : : * - > * )
data instance Fam ( a : : * )
If we dropped the kind signature for a in a derived instance for Fam a , then GHC
would have no way of knowing which instance we are talking about .
Another motivation for explicit kind signatures is the -XTypeInType extension .
With -XTypeInType , dropping kind signatures can completely change the meaning
of some data types . For example , there is a substantial difference between these
two data types :
data T k ( a : : k ) = T k
data T k a = T k
In addition to using explicit kind signatures on type variables , we also put
explicit return kinds in the instance head , so generated instances will look
something like this :
data S ( a : : k ) = S k
instance Generic1 ( S : : k - > * ) where
type Rep1 ( S : : k - > * ) = ... ( Rec0 k )
Why do we do this ? Imagine what the instance would be without the explicit return kind :
instance Generic1 S where
type Rep1 S = ... ( Rec0 k )
This is an error , since the variable k is now out - of - scope !
Although explicit kind signatures are the right thing to do in most cases , there
are sadly some degenerate cases where this is n't true . Consider this example :
newtype Compose ( f : : k2 - > * ) ( g : : k1 - > k2 ) ( a : : k1 ) = Compose ( f ( g a ) )
The Rep1 type instance in a Generic1 instance for Compose would involve the type
( f : . : ) , which forces ( f : : * - > * ) . But this library does n't have very
sophisticated kind inference machinery ( other than what is mentioned in
Note [ Substituting types in constructor type signatures ] ) , so at the moment we
have no way of actually unifying k1 with * . So the naïve generated Generic1
instance would be :
instance Generic1 ( Compose ( f : : k2 - > * ) ( g : : k1 - > k2 ) ) where
type Rep1 ( Compose f g ) = ... ( f : . : )
This is wrong , since f 's kind is overly generalized . To get around this issue ,
there are variants of the TH functions that allow you to configure the KindSigOptions .
If KindSigOptions is set to False , then generated instances will not include
explicit kind signatures , leaving it up to GHC 's kind inference machinery to
figure out the correct kinds .
Note [ Generic1 is polykinded on GHC 8.2 ]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Prior to GHC 8.2 , Generic1 : : ( * - > * ) - > Constraint . This means that if a Generic1
instance is defined for a polykinded data type like so :
data Proxy k ( a : : k ) = Proxy
Then k is unified with * , and this has an effect on the generated Generic1 instance :
instance Generic1 ( Proxy * ) where ...
We must take great care to ensure that all occurrences of k are substituted with * ,
or else the generated instance will be ill kinded .
On GHC 8.2 and later , Generic1 : : ( k - > * ) - > Constraint . This means we do n't have
to do this kind unification anymore ! !
Note [Forcing buildTypeInstance]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes, we don't explicitly need to generate a Generic(1) type instance, but
we force buildTypeInstance nevertheless. This is because it performs some checks
for whether or not the provided datatype can actually have Generic(1) implemented for
it, and produces errors if it can't. Otherwise, laziness would cause these checks
to be skipped entirely, which could result in some indecipherable type errors
down the road.
Note [Substituting types in constructor type signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
While reifyConTys gives you the type variables of a constructor, they may not be
the same of the data declaration's type variables. The classic example of this is
GADTs:
data GADT a b where
GADTCon :: e -> f -> GADT e f
The type variables of GADTCon are completely different from the declaration's, which
can cause a problem when generating a Rep instance:
type Rep (GADT a b) = Rec0 e :*: Rec0 f
Naïvely, we would generate something like this, since traversing the constructor
would give us precisely those arguments. Not good. We need to perform a type
substitution to ensure that e maps to a, and f maps to b.
This turns out to be surprisingly simple. Whenever you have a constructor type
signature like (e -> f -> GADT e f), take the result type, collect all of its
distinct type variables in order from left-to-right, and then map them to their
corresponding type variables from the data declaration.
There is another obscure case where we need to do a type subtitution. With
-XTypeInType enabled on GHC 8.0, you might have something like this:
data Proxy (a :: k) (b :: k) = Proxy k deriving Generic1
Then k gets specialized to *, which means that k should NOT show up in the RHS of
a Rep1 type instance! To avoid this, make sure to substitute k with *.
See also Note [Generic1 is polykinded on GHC 8.2].
Note [Arguments to generated type synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A surprisingly difficult component of generating the type synonyms for Rep/Rep1 is
coming up with the type synonym variable arguments, since they have to be just the
right name and kind to work. The type signature of a constructor does a remarkably
good job of coming up with these type variables for us, so if at least one constructor
exists, we simply steal the type variables from that constructor's type signature
for use in the generated type synonym. We also count the number of type variables
that the first constructor's type signature has in order to determine how many
type variables we should give it as arguments in the generated
(type Rep (Foo ...) = <makeRep> ...) code.
This leads one to ask: what if there are no constructors? If that's the case, then
we're OK, since that means no type variables can possibly appear on the RHS of the
type synonym! In such a special case, we're perfectly justified in making the type
synonym not have any type variable arguments, and similarly, we don't apply any
arguments to it in the generated (type Rep Foo = <makeRep>) code.
Note [Polykinded data families in Template Haskell]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In order to come up with the correct instance context and head for an instance, e.g.,
instance C a => C (Data a) where ...
We need to know the exact types and kinds used to instantiate the instance. For
plain old datatypes, this is simple: every type must be a type variable, and
Template Haskell reliably tells us the type variables and their kinds.
Doing the same for data families proves to be much harder for three reasons:
1. On any version of Template Haskell, it may not tell you what an instantiated
type's kind is. For instance, in the following data family instance:
data family Fam (f :: * -> *) (a :: *)
data instance Fam f a
Then if we use TH's reify function, it would tell us the TyVarBndrs of the
data family declaration are:
[KindedTV f (AppT (AppT ArrowT StarT) StarT),KindedTV a StarT]
and the instantiated types of the data family instance are:
[VarT f1,VarT a1]
We can't just pass [VarT f1,VarT a1] to buildTypeInstanceFromTys, since we
have no way of knowing their kinds. Luckily, the TyVarBndrs tell us what the
kind is in case an instantiated type isn't a SigT, so we use the stealKindForType
function to ensure all of the instantiated types are SigTs before passing them
to buildTypeInstanceFromTys.
2. On GHC 7.6 and 7.8, a bug is present in which Template Haskell lists all of
the specified kinds of a data family instance efore any of the instantiated
types. Fortunately, this is easy to deal with: you simply count the number of
distinct kind variables in the data family declaration, take that many elements
from the front of the Types list of the data family instance, substitute the
kind variables with their respective instantiated kinds (which you took earlier),
and proceed as normal.
3. On GHC 7.8, an even uglier bug is present (GHC Trac #9692) in which Template
Haskell might not even list all of the Types of a data family instance, since
they are eta-reduced away! And yes, kinds can be eta-reduced too.
The simplest workaround is to count how many instantiated types are missing from
the list and generate extra type variables to use in their place. Luckily, we
needn't worry much if its kind was eta-reduced away, since using stealKindForType
will get it back.
Note [Kind signatures in derived instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We generally include explicit type signatures in derived instances. One reason for
doing so is that in the case of certain data family instances, not including kind
signatures can result in ambiguity. For example, consider the following two data
family instances that are distinguished by their kinds:
data family Fam (a :: k)
data instance Fam (a :: * -> *)
data instance Fam (a :: *)
If we dropped the kind signature for a in a derived instance for Fam a, then GHC
would have no way of knowing which instance we are talking about.
Another motivation for explicit kind signatures is the -XTypeInType extension.
With -XTypeInType, dropping kind signatures can completely change the meaning
of some data types. For example, there is a substantial difference between these
two data types:
data T k (a :: k) = T k
data T k a = T k
In addition to using explicit kind signatures on type variables, we also put
explicit return kinds in the instance head, so generated instances will look
something like this:
data S (a :: k) = S k
instance Generic1 (S :: k -> *) where
type Rep1 (S :: k -> *) = ... (Rec0 k)
Why do we do this? Imagine what the instance would be without the explicit return kind:
instance Generic1 S where
type Rep1 S = ... (Rec0 k)
This is an error, since the variable k is now out-of-scope!
Although explicit kind signatures are the right thing to do in most cases, there
are sadly some degenerate cases where this isn't true. Consider this example:
newtype Compose (f :: k2 -> *) (g :: k1 -> k2) (a :: k1) = Compose (f (g a))
The Rep1 type instance in a Generic1 instance for Compose would involve the type
(f :.: Rec1 g), which forces (f :: * -> *). But this library doesn't have very
sophisticated kind inference machinery (other than what is mentioned in
Note [Substituting types in constructor type signatures]), so at the moment we
have no way of actually unifying k1 with *. So the naïve generated Generic1
instance would be:
instance Generic1 (Compose (f :: k2 -> *) (g :: k1 -> k2)) where
type Rep1 (Compose f g) = ... (f :.: Rec1 g)
This is wrong, since f's kind is overly generalized. To get around this issue,
there are variants of the TH functions that allow you to configure the KindSigOptions.
If KindSigOptions is set to False, then generated instances will not include
explicit kind signatures, leaving it up to GHC's kind inference machinery to
figure out the correct kinds.
Note [Generic1 is polykinded on GHC 8.2]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Prior to GHC 8.2, Generic1 :: (* -> *) -> Constraint. This means that if a Generic1
instance is defined for a polykinded data type like so:
data Proxy k (a :: k) = Proxy
Then k is unified with *, and this has an effect on the generated Generic1 instance:
instance Generic1 (Proxy *) where ...
We must take great care to ensure that all occurrences of k are substituted with *,
or else the generated instance will be ill kinded.
On GHC 8.2 and later, Generic1 :: (k -> *) -> Constraint. This means we don't have
to do this kind unification anymore! Hooray!
-}
|
83ca7681f65e972596c37d00410a578bb7cf844307133bef4f2f6024ef560e63 | mfikes/fifth-postulate | ns348.cljs | (ns fifth-postulate.ns348)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| null | https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns348.cljs | clojure | (ns fifth-postulate.ns348)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| |
c16c0609eed2ea4df879556a03433041a6daf6ab8bbad771464d7628a05bd75d | ariesteam/aries | recreation_san_pedro.clj | Copyright 2011 The ARIES Consortium ( )
;;;
;;; This file is part of ARIES.
;;;
;;; ARIES 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.
;;;
;;; ARIES 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 ARIES. If not, see </>.
;;;
;;;-------------------------------------------------------------------
;;;
Recreation model for San Pedro
;;;
Valid Contexts : core.contexts.san - pedro / - us *
;;;
;;;-------------------------------------------------------------------
(ns core.models.recreation-san-pedro
(:refer-clojure :rename {count length})
(:refer tl :only [is? conc])
(:refer modelling :only [defscenario defmodel model measurement
classification categorization
namespace-ontology ranking numeric-coding
binary-coding probabilistic-measurement
probabilistic-classification
probabilistic-ranking identification
bayesian no-data? count])
(:refer aries :only [span]))
(namespace-ontology recreationService)
;;;-------------------------------------------------------------------
;;; Birding source models
;;;-------------------------------------------------------------------
(defmodel bird-richness sanPedro:BirdSpeciesRichness
(classification (ranking habitat:AvianRichness)
[8 10 :inclusive] sanPedro:VeryHighBirdSpeciesRichness
[6 8] sanPedro:HighBirdSpeciesRichness
[4 6] sanPedro:ModerateBirdSpeciesRichness
[0 4] sanPedro:LowBirdSpeciesRichness))
(defmodel bird-rarity sanPedro:RareCharismaticBirdHabitat
(classification (ranking habitat:RareBirdHabitat)
#{4 5} sanPedro:HighRareCharismaticBirdHabitat
#{1 2 3} sanPedro:ModerateRareCharismaticBirdHabitat
0 sanPedro:LowRareCharismaticBirdHabitat))
;; Riparian zones as important to birding and hunting because of their
;; importance to valued animal species and for human preferences to
;; recreate in riparian areas in the desert.
(defmodel streams geofeatures:River
(binary-coding geofeatures:River))
(defmodel springs waterSupplyService:Springs
(binary-coding waterSupplyService:Springs))
(defmodel water-presence sanPedro:WaterPresence
(binary-coding sanPedro:WaterPresence
:context [streams springs]
:state #(or (:river %)
(:springs %))))
;; This model assumes that all riparian areas that are not mapped
within the SPRNCA are low quality . This is an iffy assumption -
;; moderate quality might also be appropriate and it might be better
to run these as a simple BN for presence and quality like the
housing presence and value , incoprorating priors for quality
;; when we lack data.
(defmodel condition-class sanPedro:RiparianConditionClass
(ranking sanPedro:RiparianConditionClass))
(defmodel riparian-wetland sanPedro:RiparianSpringWetlandQuality
(classification sanPedro:RiparianSpringWetlandQuality
:context [water-presence condition-class]
:state #(if (nil? (:water-presence %))
(tl/conc 'sanPedro:RiparianSpringWetlandAbsent)
(cond (= (:riparian-condition-class %) 3) (tl/conc 'sanPedro:HighQualityRiparianSpringWetland)
(= (:riparian-condition-class %) 2) (tl/conc 'sanPedro:ModerateQualityRiparianSpringWetland)
(= (:riparian-condition-class %) 1) (tl/conc 'sanPedro:LowQualityRiparianSpringWetland)
:otherwise (tl/conc 'sanPedro:LowQualityRiparianSpringWetland)))))
No public access includes private land , Native American
;; reservations, military land. Accessible public land includes state
trust land , BLM , Forest Service , NPS , FWS , etc . Ft .
;; currently is accessible to the public and birdwatching and hunting
;; occur on-base
(defmodel public-lands sanPedro:PublicAccessClass
(classification (numeric-coding habitat:LandOwnership)
#{2 3 4 8 12 13 14 15 16 36 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 60 61 62 63 64 65 66 67
68 69 70 71 73 75 76 82 83 86 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127} sanPedro:PublicLand
#{1 5 6 11 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 37 38 39 40 41 42 72 74 77
78 79 84 87 88 89 90} sanPedro:NoPublicAccess))
;; This statement (not yet implemented) accounts for public recognition
of a site , e.g. , SPRNCA & Ramsy Canyon 's high values for birding ,
or Mt. Mansfield & Camels Hump 's high values for hiking in the VT
;; model. Need to develop a data layer that has these features, link
nodes in the BN and finish the CPT , and include the correct
concepts in the defmodel statement below , then test results .
( defmodel site - recognition SiteRecognitionClass
( classification ( ranking SiteRecognition )
1 HighSiteRecognition
;; 2 ModerateSiteRecognition
;; 3 LowSiteRecognition))
Undiscretization statements to be use in BNs
(defmodel birding-quality sanPedro:SiteBirdingQuality
(probabilistic-ranking sanPedro:SiteBirdingQuality
[67 100] sanPedro:HighBirdingQuality
[33 67] sanPedro:ModerateBirdingQuality
[10 33] sanPedro:LowBirdingQuality
[ 0 10] sanPedro:VeryLowBirdingQuality))
Bayesian source models
(defmodel source-birding sanPedro:BirdingSourceValue
(bayesian sanPedro:BirdingSourceValue
:import "aries.core::RecreationSourceSanPedroBirding.xdsl"
:context [bird-richness bird-rarity riparian-wetland public-lands]
:keep [sanPedro:SiteBirdingQuality]
:result birding-quality))
;;;-------------------------------------------------------------------
;;; Wildlife viewing source models
;;;-------------------------------------------------------------------
(defmodel wildlife-species-richness sanPedro:WildlifeSpeciesRichness
(ranking sanPedro:WildlifeSpeciesRichness
:context [(ranking habitat:AvianRichness) (ranking habitat:MammalRichness)
(ranking habitat:ReptileRichness) (ranking habitat:AmphibianRichness)]
:state #(Math/round (* (+ (or (:avian-richness %) 0)
(or (:mammal-richness %) 0)
(or (:reptile-richness %) 0)
(or (:amphibian-richness %) 0))
0.25))))
;;#(let [b (:bird-species-richness %) alternative code for the above state statement
;; m (:mammal-species-richness %)
;; r (:reptile-species-richness %)
;; a (:amphibian-species-richness %)]
( Math / round ( * 0.25 ( reduce + 0 ( remove nil ? [ b m r a ] ) ) ) ) ) ) )
(defmodel wildlife-species-richness-class sanPedro:WildlifeSpeciesRichnessClass
(classification wildlife-species-richness
[8 10] sanPedro:VeryHighWildlifeSpeciesRichness
[6 8] sanPedro:HighWildlifeSpeciesRichness
[4 6] sanPedro:ModerateWildlifeSpeciesRichness
[0 4] sanPedro:LowWildlifeSpeciesRichness))
(defmodel wildlife-quality sanPedro:SiteWildlifeQuality
(probabilistic-ranking sanPedro:SiteWildlifeQuality
[67 100] sanPedro:HighWildlifeQuality
[33 67] sanPedro:ModerateWildlifeQuality
[10 33] sanPedro:LowWildlifeQuality
[ 0 10] sanPedro:VeryLowWildlifeQuality))
(defmodel source-wildlife sanPedro:WildlifeViewingSourceValue
(bayesian sanPedro:WildlifeViewingSourceValue
:import "aries.core::RecreationSourceSanPedroWildlife.xdsl"
:context [riparian-wetland public-lands wildlife-species-richness-class]
:keep [sanPedro:SiteWildlifeQuality]
:result wildlife-quality))
;;;-------------------------------------------------------------------
;;; Hunting source models
;;;-------------------------------------------------------------------
(defmodel dove-habitat sanPedro:DoveHabitat
(classification sanPedro:DoveHabitat
:context [(numeric-coding sanPedro:MourningDoveHabitat)
(numeric-coding sanPedro:WhiteWingedDoveHabitat)]
:state #(let [num-dove (+ (if (no-data? (:mourning-dove-habitat %)) 0 1)
(if (no-data? (:white-winged-dove-habitat %)) 0 1))]
(cond (= num-dove 2) (tl/conc 'sanPedro:MultipleDoveSpeciesPresent)
(= num-dove 1) (tl/conc 'sanPedro:SingleDoveSpeciesPresent)
:otherwise (tl/conc 'sanPedro:DoveSpeciesAbsent)))))
(defmodel deer-habitat sanPedro:DeerHabitat
(classification sanPedro:DeerHabitat
:context [(numeric-coding sanPedro:MuleDeerHabitat)
(numeric-coding sanPedro:WhiteTailDeerHabitat)]
:state #(let [num-deer (+ (if (no-data? (:mule-deer-habitat %)) 0 1)
(if (no-data? (:white-tail-deer-habitat %)) 0 1))]
(cond (= num-deer 2) (tl/conc 'sanPedro:MultipleDeerSpeciesPresent)
(= num-deer 1) (tl/conc 'sanPedro:SingleDeerSpeciesPresent)
:otherwise (tl/conc 'sanPedro:DeerSpeciesAbsent)))))
(defmodel quail-habitat sanPedro:QuailHabitat
(classification sanPedro:QuailHabitat
:context [(numeric-coding sanPedro:ScaledQuailHabitat)
(numeric-coding sanPedro:MearnsQuailHabitat)
(numeric-coding sanPedro:GambelsQuailHabitat)]
:state #(let [num-quail (+ (if (no-data? (:scaled-quail-habitat %)) 0 1)
(if (no-data? (:mearns-quail-habitat %)) 0 1)
(if (no-data? (:gambels-quail-habitat %)) 0 1))]
(cond (> num-quail 1) (tl/conc 'sanPedro:MultipleQuailSpeciesPresent)
(= num-quail 1) (tl/conc 'sanPedro:SingleQuailSpeciesPresent)
:otherwise (tl/conc 'sanPedro:QuailSpeciesAbsent)))))
(defmodel javelina-habitat sanPedro:JavelinaHabitat
(classification (numeric-coding sanPedro:JavelinaHabitat)
29 sanPedro:JavelinaHabitatPresent
nil sanPedro:JavelinaHabitatAbsent
:otherwise sanPedro:JavelinaHabitatAbsent))
TRANSITION ZONES ? LULC TO VECTOR & BUFFER . WHAT
;; TRANSITION ZONES MATTER TO WHAT SPECIES IS IMPORTANT. COULD ASK BILL K &
KEN BOYKIN ABOUT IMPORTANT HABITAT TYPES / TRANSITION ZONES FOR OUR 8
SPP . OF INTEREST .
;; ELEVATION & COOLNESS MAY MATTER LESS FOR HUNTING IF THE SEASON IS IN
;; LATE FALL/WINTER. CHECK THE REST OF THE HUNTING SEASONS INFO.
( defmodel elevation ( high elevation areas may be more attractive for
recreation , especially as an escape from summer heat ) . People do
;; recreate in the mountains but this might already be accounted for
;; by presense & biodiversity?
( defmodel mountain aestheticService : Mountain
;; (classification (measurement geophysics:Altitude "m")
[ 1800 8850 ] aestheticService : LargeMountain
[ 1400 1800 ] aestheticService : SmallMountain
: otherwise aestheticService : ) )
;; VIEW QUALITY AS IMPORTANT, AT LEAST FOR SOME RECREATIONAL TYPES. IF
YOU HAD SOURCE MODELS FOR HUNTING , BIRDING , VIEW QUALITY YOU COULD
COMBINE THE 3 BASED ON PREFERENCES FOR MULTI - ACTIVITY / MULTI - GOAL
RECREATION ( SUMMED , WEIGHTED UTILITY FUNCTION )
Undiscretization statements to be use in BNs
(defmodel deer-hunting-quality sanPedro:SiteDeerHuntingQuality
(probabilistic-ranking sanPedro:SiteDeerHuntingQuality
[67 100] sanPedro:HighDeerHuntingQuality
[33 67] sanPedro:ModerateDeerHuntingQuality
[ 5 33] sanPedro:LowDeerHuntingQuality
[ 0 5] sanPedro:VeryLowDeerHuntingQuality))
(defmodel javelina-hunting-quality sanPedro:SiteJavelinaHuntingQuality
(probabilistic-ranking sanPedro:SiteJavelinaHuntingQuality
[67 100] sanPedro:HighJavelinaHuntingQuality
[33 67] sanPedro:ModerateJavelinaHuntingQuality
[ 5 33] sanPedro:LowJavelinaHuntingQuality
[ 0 5] sanPedro:VeryLowJavelinaHuntingQuality))
(defmodel dove-hunting-quality sanPedro:SiteDoveHuntingQuality
(probabilistic-ranking sanPedro:SiteDoveHuntingQuality
[67 100] sanPedro:HighDoveHuntingQuality
[33 67] sanPedro:ModerateDoveHuntingQuality
[ 5 33] sanPedro:LowDoveHuntingQuality
[ 0 5] sanPedro:VeryLowDoveHuntingQuality))
(defmodel quail-hunting-quality sanPedro:SiteQuailHuntingQuality
(probabilistic-ranking sanPedro:SiteQuailHuntingQuality
[67 100] sanPedro:HighQuailHuntingQuality
[33 67] sanPedro:ModerateQuailHuntingQuality
[ 5 33] sanPedro:LowQuailHuntingQuality
[ 0 5] sanPedro:VeryLowQuailHuntingQuality))
Bayesian source models
(defmodel source-deer-hunting sanPedro:DeerHuntingSourceValue
(bayesian sanPedro:DeerHuntingSourceValue
:import "aries.core::RecreationSourceSanPedroDeerHunting.xdsl"
:context [riparian-wetland public-lands deer-habitat]
:keep [sanPedro:SiteDeerHuntingQuality]
:result deer-hunting-quality))
(defmodel source-javelina-hunting sanPedro:JavelinaHuntingSourceValue
(bayesian sanPedro:JavelinaHuntingSourceValue
:import "aries.core::RecreationSourceSanPedroJavelinaHunting.xdsl"
:context [riparian-wetland public-lands javelina-habitat]
:keep [sanPedro:SiteJavelinaHuntingQuality]
:result javelina-hunting-quality))
(defmodel source-dove-hunting sanPedro:DoveHuntingSourceValue
(bayesian sanPedro:DoveHuntingSourceValue
:import "aries.core::RecreationSourceSanPedroDoveHunting.xdsl"
:context [riparian-wetland public-lands dove-habitat]
:keep [sanPedro:SiteDoveHuntingQuality]
:result dove-hunting-quality))
(defmodel source-quail-hunting sanPedro:QuailHuntingSourceValue
(bayesian sanPedro:QuailHuntingSourceValue
:import "aries.core::RecreationSourceSanPedroQuailHunting.xdsl"
:context [riparian-wetland public-lands quail-habitat]
:keep [sanPedro:SiteQuailHuntingQuality]
:result quail-hunting-quality))
;;;-------------------------------------------------------------------
;;; Use models
;;;-------------------------------------------------------------------
(defmodel population-density policytarget:PopulationDensity
(count policytarget:PopulationDensity "/km^2"))
;;;-------------------------------------------------------------------
;;; Identification models
;;;-------------------------------------------------------------------
( defmodel travel - capacity RoadTravelCapacity
;; This is a categorization; values are "interstates", "highways", "arterials", "streets",
;; "primitive roads", "trails & alleys", "access ramps".
;; This is a massive layer - it may be really tough for ARIES to rasterize every time, while also time
;; consuming for me to do so...
(defmodel roads Roads
(classification (binary-coding infrastructure:Road)
1 RoadsPresent
:otherwise RoadsAbsent))
SPRNCA trails : need to expand bounding box so it does n't throw errors .
( defmodel trails Trails
;; (classification (binary-coding infrastructure:Path)
1 TrailPresent
;; :otherwise TrailAbsent))
How to account for congestion and visitor response to it ? See
et al . 2005 , 2008 on modeling visitor choice between
;; alternative recreational sites, RUMs, etc.
Identifications for recreation : flow models are not yet ready but concepts will be exported to .
(defmodel recreation-data OutdoorRecreation
(identification OutdoorRecreation
:context [source-birding source-wildlife source-deer-hunting
source-quail-hunting source-dove-hunting
source-javelina-hunting population-density
roads])) ; Add trails data once its bounding box has been adjusted
;;;-------------------------------------------------------------------
;;; Flow models
;;;-------------------------------------------------------------------
SPAN statements written but recreational flow models are not yet developed .
( defmodel recreation - flow - birding BirdingUse
( span BirdingAccessAndUse
;; BirdingSourceValue
BirdingDemand ; Need to create this model
;; nil
;; nil
nil ; May need concepts here
: source - threshold 10.0
: sink - threshold 10.0
;; :use-threshold 1.0
;; :trans-threshold nil
;; :source-type :infinite
;; :sink-type :infinite
;; :use-type :infinite
;; :benefit-type :non-rival
: downscaling - factor 8
: 10
;; :animation? true
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
;; :context [source-birding population-density roads]
: keep [ TheoreticalSource
ActualFlow
ActualSource
;; ActualUse
InaccessibleSource
] ) )
( defmodel recreation - flow - wildlife WildlifeViewingUse
( span
;; WildlifeViewingSourceValue
;; WildlifeViewingDemand ; Need to create this model
;; nil
;; nil
nil ; May need concepts here
: source - threshold 10.0
: sink - threshold 10.0
;; :use-threshold 1.0
;; :trans-threshold nil
;; :source-type :infinite
;; :sink-type :infinite
;; :use-type :infinite
;; :benefit-type :non-rival
: downscaling - factor 8
: 10
;; :animation? true
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
;; :context [source-wildlife population-density roads] ; Replace with final use concept
: keep [ TheoreticalSource
ActualFlow
ActualSource
;; ActualUse
InaccessibleSource
] ) )
( defmodel recreation - flow - javelina - hunting JavelinaHuntingUse
;; (span JavelinaHuntingAccessAndUse
JavelinaHuntingSourceValue
;; JavelinaHuntingDemand ; Need to create this model
;; nil
;; nil
nil ; May need concepts here
: source - threshold 10.0
: sink - threshold 10.0
;; :use-threshold 1.0
;; :trans-threshold nil
;; :source-type :infinite
;; :sink-type :infinite
;; :use-type :infinite
;; :benefit-type :non-rival
: downscaling - factor 8
: 10
;; :animation? true
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
;; :context [source-javelina-hunting population-density roads]
: keep [ TheoreticalSource
ActualFlow
ActualSource
;; ActualUse
InaccessibleSource
] ) )
( defmodel recreation - flow - dove - hunting
;; (span DoveHuntingAccessAndUse
DoveHuntingSourceValue
DoveHuntingDemand ; Need to create this model
;; nil
;; nil
nil ; May need concepts here
: source - threshold 10.0
: sink - threshold 10.0
;; :use-threshold 1.0
;; :trans-threshold nil
;; :source-type :infinite
;; :sink-type :infinite
;; :use-type :infinite
;; :benefit-type :non-rival
: downscaling - factor 8
: 10
;; :animation? true
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
;; :context [source-dove-hunting population-density roads]
: keep [ TheoreticalSource
ActualFlow
ActualSource
;; ActualUse
InaccessibleSource
] ) )
( defmodel recreation - flow - quail - hunting QuailHuntingUse
;; (span QuailHuntingAccessAndUse
;; QuailHuntingSourceValue
;; QuailHuntingDemand ; Need to create this model
;; nil
;; nil
nil ; May need concepts here
: source - threshold 10.0
: sink - threshold 10.0
;; :use-threshold 1.0
;; :trans-threshold nil
;; :source-type :infinite
;; :sink-type :infinite
;; :use-type :infinite
;; :benefit-type :non-rival
: downscaling - factor 8
: 10
;; :animation? true
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
;; :context [source-quail-hunting population-density roads]
: keep [ TheoreticalSource
ActualFlow
ActualSource
;; ActualUse
InaccessibleSource
] ) )
( defmodel recreation - flow - deer - hunting DeerHuntingUse
( span
;; DeerHuntingSourceValue
;; DeerHuntingDemand ; Need to create this model
;; nil
;; nil
nil ; May need concepts here
: source - threshold 10.0
: sink - threshold 10.0
;; :use-threshold 1.0
;; :trans-threshold nil
;; :source-type :infinite
;; :sink-type :infinite
;; :use-type :infinite
;; :benefit-type :non-rival
: downscaling - factor 8
: 10
;; :animation? true
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
;; :context [source-deer-hunting population-density roads]
: keep [ TheoreticalSource
ActualFlow
ActualSource
;; ActualUse
InaccessibleSource
] ) )
;;;-------------------------------------------------------------------
;;; Scenarios
;;;-------------------------------------------------------------------
(defscenario cap-water-augmentation-half-meter-rise
"Water augmentation leading to a 0.5 meter rise across the San Pedro Riparian National Conservation Area"
(model sanPedro:RiparianConditionClass
(ranking sanPedro:RiparianConditionClassHalfMeterRise)))
(defscenario cap-water-augmentation-all-perennial
"Water augmentation leading to perennial flow conditions across the San Pedro Riparian National Conservation Area"
(model sanPedro:RiparianConditionClass
(ranking sanPedro:RiparianConditionClassAllWet)))
(defmodel constrained-development-scenario sanPedro:ConstrainedDevelopment
(classification (numeric-coding sanPedro:Steinitz30ClassUrbanGrowthLULCConstrained)
#{10 11 12 13 19 22 25} sanPedro:DevelopedConstrained
#{0 1 2 4 5 6 7 8 9 14 16 23 26 27 28} sanPedro:NotDevelopedConstrained))
(defmodel open-development-scenario sanPedro:OpenDevelopment
(classification (numeric-coding sanPedro:Steinitz30ClassUrbanGrowthLULCOpen)
#{10 11 12 13 19 22 25} sanPedro:DevelopedOpen
#{0 1 2 4 5 6 7 8 9 14 16 23 26 27 28 29} sanPedro:NotDevelopedOpen))
(defscenario constrained-development-recreation
"Changes values in developed areas to very private land and locally appropriate low values for habitat and species richness."
(model BirdSpeciesRichness
(classification BirdSpeciesRichness
:context [bird-richness :as br constrained-development-scenario :as cd]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'recreationService:LowBirdSpeciesRichness)
(:br %))))
(model RareCharismaticBirdHabitat
(classification RareCharismaticBirdHabitat
:context [bird-rarity :as br constrained-development-scenario :as cd]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'recreationService:LowRareCharismaticBirdHabitat)
(:br %))))
(model sanPedro:PublicAccessClass
(classification sanPedro:PublicAccessClass
:context [public-lands :as pl constrained-development-scenario :as cd]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'sanPedro:NoPublicAccess)
(:pl %))))
(model WildlifeSpeciesRichnessClass
(classification WildlifeSpeciesRichnessClass
:context [constrained-development-scenario :as cd wildlife-species-richness-class :as wl]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'recreationService:LowWildlifeSpeciesRichness)
(:wl %))))
(model sanPedro:DoveHabitat
(classification sanPedro:DoveHabitat
:context [constrained-development-scenario :as cd dove-habitat :as dh]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'sanPedro:SingleDoveSpeciesPresent)
(:dh %))))
(model sanPedro:DeerHabitat
(classification sanPedro:DeerHabitat
:context [constrained-development-scenario :as cd deer-habitat :as dh]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'sanPedro:DeerSpeciesAbsent)
(:dh %))))
(model sanPedro:QuailHabitat
(classification sanPedro:QuailHabitat
:context [constrained-development-scenario :as cd quail-habitat :as qh]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'sanPedro:QuailSpeciesAbsent)
(:qh %))))
(model sanPedro:JavelinaHabitat
(classification sanPedro:JavelinaHabitat
:context [constrained-development-scenario :as cd javelina-habitat :as jh]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'sanPedro:JavelinaHabitatAbsent)
(:jh %)))))
(defscenario open-development-recreation
"Changes values in developed areas to very private land and locally appropriate low values for habitat and species richness."
(model BirdSpeciesRichness
(classification BirdSpeciesRichness
:context [open-development-scenario :as od bird-richness :as br]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'recreationService:LowBirdSpeciesRichness)
(:br %))))
(model RareCharismaticBirdHabitat
(classification RareCharismaticBirdHabitat
:context [open-development-scenario :as od bird-rarity :as br]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'recreationService:LowRareCharismaticBirdHabitat)
(:br %))))
(model PublicAccessClass
(classification PublicAccessClass
:context [open-development-scenario :as od public-lands :as pl]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'recreationService:NoPublicAccess)
(:pl %))))
(model WildlifeSpeciesRichnessClass
(classification WildlifeSpeciesRichnessClass
:context [open-development-scenario :as od wildlife-species-richness-class :as wl]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'recreationService:LowWildlifeSpeciesRichness)
(:wl %))))
(model sanPedro:DoveHabitat
(classification sanPedro:DoveHabitat
:context [open-development-scenario :as od dove-habitat :as dh]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'sanPedro:SingleDoveSpeciesPresent)
(:dh %))))
(model sanPedro:DeerHabitat
(classification sanPedro:DeerHabitat
:context [open-development-scenario :as od deer-habitat :as dh]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'sanPedro:DeerSpeciesAbsent)
(:dh %))))
(model sanPedro:QuailHabitat
(classification sanPedro:QuailHabitat
:context [open-development-scenario :as od quail-habitat :as qh]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'sanPedro:QuailSpeciesAbsent)
(:qh %))))
(model sanPedro:JavelinaHabitat
(classification sanPedro:JavelinaHabitat
:context [open-development-scenario :as od javelina-habitat :as jh]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'sanPedro:JavelinaHabitatAbsent)
(:jh %)))))
( defscenario urban - growth sanPedro : UrbanGrowth ( add new users , up 10.4 % in constrained , 56.8 % in open )
sanPedro : UrbanGrowth2020Open
sanPedro : UrbanGrowth2020Constrained
sanPedro : Steinitz30ClassUrbanGrowthLULCOpen
sanPedro : Steinitz30ClassUrbanGrowthLULCConstrained | null | https://raw.githubusercontent.com/ariesteam/aries/b3fafd4640f4e7950fff3791bc4ea4c06ee4dcdf/plugins/org.integratedmodelling.aries.core/models/recreation_san_pedro.clj | clojure |
This file is part of ARIES.
ARIES is free software: you can redistribute it and/or modify it
(at your option) any later version.
ARIES 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 ARIES. If not, see </>.
-------------------------------------------------------------------
-------------------------------------------------------------------
-------------------------------------------------------------------
Birding source models
-------------------------------------------------------------------
Riparian zones as important to birding and hunting because of their
importance to valued animal species and for human preferences to
recreate in riparian areas in the desert.
This model assumes that all riparian areas that are not mapped
moderate quality might also be appropriate and it might be better
when we lack data.
reservations, military land. Accessible public land includes state
currently is accessible to the public and birdwatching and hunting
occur on-base
This statement (not yet implemented) accounts for public recognition
model. Need to develop a data layer that has these features, link
2 ModerateSiteRecognition
3 LowSiteRecognition))
-------------------------------------------------------------------
Wildlife viewing source models
-------------------------------------------------------------------
#(let [b (:bird-species-richness %) alternative code for the above state statement
m (:mammal-species-richness %)
r (:reptile-species-richness %)
a (:amphibian-species-richness %)]
-------------------------------------------------------------------
Hunting source models
-------------------------------------------------------------------
TRANSITION ZONES MATTER TO WHAT SPECIES IS IMPORTANT. COULD ASK BILL K &
ELEVATION & COOLNESS MAY MATTER LESS FOR HUNTING IF THE SEASON IS IN
LATE FALL/WINTER. CHECK THE REST OF THE HUNTING SEASONS INFO.
recreate in the mountains but this might already be accounted for
by presense & biodiversity?
(classification (measurement geophysics:Altitude "m")
VIEW QUALITY AS IMPORTANT, AT LEAST FOR SOME RECREATIONAL TYPES. IF
-------------------------------------------------------------------
Use models
-------------------------------------------------------------------
-------------------------------------------------------------------
Identification models
-------------------------------------------------------------------
This is a categorization; values are "interstates", "highways", "arterials", "streets",
"primitive roads", "trails & alleys", "access ramps".
This is a massive layer - it may be really tough for ARIES to rasterize every time, while also time
consuming for me to do so...
(classification (binary-coding infrastructure:Path)
:otherwise TrailAbsent))
alternative recreational sites, RUMs, etc.
Add trails data once its bounding box has been adjusted
-------------------------------------------------------------------
Flow models
-------------------------------------------------------------------
BirdingSourceValue
Need to create this model
nil
nil
May need concepts here
:use-threshold 1.0
:trans-threshold nil
:source-type :infinite
:sink-type :infinite
:use-type :infinite
:benefit-type :non-rival
:animation? true
:context [source-birding population-density roads]
ActualUse
WildlifeViewingSourceValue
WildlifeViewingDemand ; Need to create this model
nil
nil
May need concepts here
:use-threshold 1.0
:trans-threshold nil
:source-type :infinite
:sink-type :infinite
:use-type :infinite
:benefit-type :non-rival
:animation? true
:context [source-wildlife population-density roads] ; Replace with final use concept
ActualUse
(span JavelinaHuntingAccessAndUse
JavelinaHuntingDemand ; Need to create this model
nil
nil
May need concepts here
:use-threshold 1.0
:trans-threshold nil
:source-type :infinite
:sink-type :infinite
:use-type :infinite
:benefit-type :non-rival
:animation? true
:context [source-javelina-hunting population-density roads]
ActualUse
(span DoveHuntingAccessAndUse
Need to create this model
nil
nil
May need concepts here
:use-threshold 1.0
:trans-threshold nil
:source-type :infinite
:sink-type :infinite
:use-type :infinite
:benefit-type :non-rival
:animation? true
:context [source-dove-hunting population-density roads]
ActualUse
(span QuailHuntingAccessAndUse
QuailHuntingSourceValue
QuailHuntingDemand ; Need to create this model
nil
nil
May need concepts here
:use-threshold 1.0
:trans-threshold nil
:source-type :infinite
:sink-type :infinite
:use-type :infinite
:benefit-type :non-rival
:animation? true
:context [source-quail-hunting population-density roads]
ActualUse
DeerHuntingSourceValue
DeerHuntingDemand ; Need to create this model
nil
nil
May need concepts here
:use-threshold 1.0
:trans-threshold nil
:source-type :infinite
:sink-type :infinite
:use-type :infinite
:benefit-type :non-rival
:animation? true
:context [source-deer-hunting population-density roads]
ActualUse
-------------------------------------------------------------------
Scenarios
-------------------------------------------------------------------
| Copyright 2011 The ARIES Consortium ( )
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
Recreation model for San Pedro
Valid Contexts : core.contexts.san - pedro / - us *
(ns core.models.recreation-san-pedro
(:refer-clojure :rename {count length})
(:refer tl :only [is? conc])
(:refer modelling :only [defscenario defmodel model measurement
classification categorization
namespace-ontology ranking numeric-coding
binary-coding probabilistic-measurement
probabilistic-classification
probabilistic-ranking identification
bayesian no-data? count])
(:refer aries :only [span]))
(namespace-ontology recreationService)
(defmodel bird-richness sanPedro:BirdSpeciesRichness
(classification (ranking habitat:AvianRichness)
[8 10 :inclusive] sanPedro:VeryHighBirdSpeciesRichness
[6 8] sanPedro:HighBirdSpeciesRichness
[4 6] sanPedro:ModerateBirdSpeciesRichness
[0 4] sanPedro:LowBirdSpeciesRichness))
(defmodel bird-rarity sanPedro:RareCharismaticBirdHabitat
(classification (ranking habitat:RareBirdHabitat)
#{4 5} sanPedro:HighRareCharismaticBirdHabitat
#{1 2 3} sanPedro:ModerateRareCharismaticBirdHabitat
0 sanPedro:LowRareCharismaticBirdHabitat))
(defmodel streams geofeatures:River
(binary-coding geofeatures:River))
(defmodel springs waterSupplyService:Springs
(binary-coding waterSupplyService:Springs))
(defmodel water-presence sanPedro:WaterPresence
(binary-coding sanPedro:WaterPresence
:context [streams springs]
:state #(or (:river %)
(:springs %))))
within the SPRNCA are low quality . This is an iffy assumption -
to run these as a simple BN for presence and quality like the
housing presence and value , incoprorating priors for quality
(defmodel condition-class sanPedro:RiparianConditionClass
(ranking sanPedro:RiparianConditionClass))
(defmodel riparian-wetland sanPedro:RiparianSpringWetlandQuality
(classification sanPedro:RiparianSpringWetlandQuality
:context [water-presence condition-class]
:state #(if (nil? (:water-presence %))
(tl/conc 'sanPedro:RiparianSpringWetlandAbsent)
(cond (= (:riparian-condition-class %) 3) (tl/conc 'sanPedro:HighQualityRiparianSpringWetland)
(= (:riparian-condition-class %) 2) (tl/conc 'sanPedro:ModerateQualityRiparianSpringWetland)
(= (:riparian-condition-class %) 1) (tl/conc 'sanPedro:LowQualityRiparianSpringWetland)
:otherwise (tl/conc 'sanPedro:LowQualityRiparianSpringWetland)))))
No public access includes private land , Native American
trust land , BLM , Forest Service , NPS , FWS , etc . Ft .
(defmodel public-lands sanPedro:PublicAccessClass
(classification (numeric-coding habitat:LandOwnership)
#{2 3 4 8 12 13 14 15 16 36 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 60 61 62 63 64 65 66 67
68 69 70 71 73 75 76 82 83 86 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
117 118 119 120 121 122 123 124 125 126 127} sanPedro:PublicLand
#{1 5 6 11 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 37 38 39 40 41 42 72 74 77
78 79 84 87 88 89 90} sanPedro:NoPublicAccess))
of a site , e.g. , SPRNCA & Ramsy Canyon 's high values for birding ,
or Mt. Mansfield & Camels Hump 's high values for hiking in the VT
nodes in the BN and finish the CPT , and include the correct
concepts in the defmodel statement below , then test results .
( defmodel site - recognition SiteRecognitionClass
( classification ( ranking SiteRecognition )
1 HighSiteRecognition
Undiscretization statements to be use in BNs
(defmodel birding-quality sanPedro:SiteBirdingQuality
(probabilistic-ranking sanPedro:SiteBirdingQuality
[67 100] sanPedro:HighBirdingQuality
[33 67] sanPedro:ModerateBirdingQuality
[10 33] sanPedro:LowBirdingQuality
[ 0 10] sanPedro:VeryLowBirdingQuality))
Bayesian source models
(defmodel source-birding sanPedro:BirdingSourceValue
(bayesian sanPedro:BirdingSourceValue
:import "aries.core::RecreationSourceSanPedroBirding.xdsl"
:context [bird-richness bird-rarity riparian-wetland public-lands]
:keep [sanPedro:SiteBirdingQuality]
:result birding-quality))
(defmodel wildlife-species-richness sanPedro:WildlifeSpeciesRichness
(ranking sanPedro:WildlifeSpeciesRichness
:context [(ranking habitat:AvianRichness) (ranking habitat:MammalRichness)
(ranking habitat:ReptileRichness) (ranking habitat:AmphibianRichness)]
:state #(Math/round (* (+ (or (:avian-richness %) 0)
(or (:mammal-richness %) 0)
(or (:reptile-richness %) 0)
(or (:amphibian-richness %) 0))
0.25))))
( Math / round ( * 0.25 ( reduce + 0 ( remove nil ? [ b m r a ] ) ) ) ) ) ) )
(defmodel wildlife-species-richness-class sanPedro:WildlifeSpeciesRichnessClass
(classification wildlife-species-richness
[8 10] sanPedro:VeryHighWildlifeSpeciesRichness
[6 8] sanPedro:HighWildlifeSpeciesRichness
[4 6] sanPedro:ModerateWildlifeSpeciesRichness
[0 4] sanPedro:LowWildlifeSpeciesRichness))
(defmodel wildlife-quality sanPedro:SiteWildlifeQuality
(probabilistic-ranking sanPedro:SiteWildlifeQuality
[67 100] sanPedro:HighWildlifeQuality
[33 67] sanPedro:ModerateWildlifeQuality
[10 33] sanPedro:LowWildlifeQuality
[ 0 10] sanPedro:VeryLowWildlifeQuality))
(defmodel source-wildlife sanPedro:WildlifeViewingSourceValue
(bayesian sanPedro:WildlifeViewingSourceValue
:import "aries.core::RecreationSourceSanPedroWildlife.xdsl"
:context [riparian-wetland public-lands wildlife-species-richness-class]
:keep [sanPedro:SiteWildlifeQuality]
:result wildlife-quality))
(defmodel dove-habitat sanPedro:DoveHabitat
(classification sanPedro:DoveHabitat
:context [(numeric-coding sanPedro:MourningDoveHabitat)
(numeric-coding sanPedro:WhiteWingedDoveHabitat)]
:state #(let [num-dove (+ (if (no-data? (:mourning-dove-habitat %)) 0 1)
(if (no-data? (:white-winged-dove-habitat %)) 0 1))]
(cond (= num-dove 2) (tl/conc 'sanPedro:MultipleDoveSpeciesPresent)
(= num-dove 1) (tl/conc 'sanPedro:SingleDoveSpeciesPresent)
:otherwise (tl/conc 'sanPedro:DoveSpeciesAbsent)))))
(defmodel deer-habitat sanPedro:DeerHabitat
(classification sanPedro:DeerHabitat
:context [(numeric-coding sanPedro:MuleDeerHabitat)
(numeric-coding sanPedro:WhiteTailDeerHabitat)]
:state #(let [num-deer (+ (if (no-data? (:mule-deer-habitat %)) 0 1)
(if (no-data? (:white-tail-deer-habitat %)) 0 1))]
(cond (= num-deer 2) (tl/conc 'sanPedro:MultipleDeerSpeciesPresent)
(= num-deer 1) (tl/conc 'sanPedro:SingleDeerSpeciesPresent)
:otherwise (tl/conc 'sanPedro:DeerSpeciesAbsent)))))
(defmodel quail-habitat sanPedro:QuailHabitat
(classification sanPedro:QuailHabitat
:context [(numeric-coding sanPedro:ScaledQuailHabitat)
(numeric-coding sanPedro:MearnsQuailHabitat)
(numeric-coding sanPedro:GambelsQuailHabitat)]
:state #(let [num-quail (+ (if (no-data? (:scaled-quail-habitat %)) 0 1)
(if (no-data? (:mearns-quail-habitat %)) 0 1)
(if (no-data? (:gambels-quail-habitat %)) 0 1))]
(cond (> num-quail 1) (tl/conc 'sanPedro:MultipleQuailSpeciesPresent)
(= num-quail 1) (tl/conc 'sanPedro:SingleQuailSpeciesPresent)
:otherwise (tl/conc 'sanPedro:QuailSpeciesAbsent)))))
(defmodel javelina-habitat sanPedro:JavelinaHabitat
(classification (numeric-coding sanPedro:JavelinaHabitat)
29 sanPedro:JavelinaHabitatPresent
nil sanPedro:JavelinaHabitatAbsent
:otherwise sanPedro:JavelinaHabitatAbsent))
TRANSITION ZONES ? LULC TO VECTOR & BUFFER . WHAT
KEN BOYKIN ABOUT IMPORTANT HABITAT TYPES / TRANSITION ZONES FOR OUR 8
SPP . OF INTEREST .
( defmodel elevation ( high elevation areas may be more attractive for
recreation , especially as an escape from summer heat ) . People do
( defmodel mountain aestheticService : Mountain
[ 1800 8850 ] aestheticService : LargeMountain
[ 1400 1800 ] aestheticService : SmallMountain
: otherwise aestheticService : ) )
YOU HAD SOURCE MODELS FOR HUNTING , BIRDING , VIEW QUALITY YOU COULD
COMBINE THE 3 BASED ON PREFERENCES FOR MULTI - ACTIVITY / MULTI - GOAL
RECREATION ( SUMMED , WEIGHTED UTILITY FUNCTION )
Undiscretization statements to be use in BNs
(defmodel deer-hunting-quality sanPedro:SiteDeerHuntingQuality
(probabilistic-ranking sanPedro:SiteDeerHuntingQuality
[67 100] sanPedro:HighDeerHuntingQuality
[33 67] sanPedro:ModerateDeerHuntingQuality
[ 5 33] sanPedro:LowDeerHuntingQuality
[ 0 5] sanPedro:VeryLowDeerHuntingQuality))
(defmodel javelina-hunting-quality sanPedro:SiteJavelinaHuntingQuality
(probabilistic-ranking sanPedro:SiteJavelinaHuntingQuality
[67 100] sanPedro:HighJavelinaHuntingQuality
[33 67] sanPedro:ModerateJavelinaHuntingQuality
[ 5 33] sanPedro:LowJavelinaHuntingQuality
[ 0 5] sanPedro:VeryLowJavelinaHuntingQuality))
(defmodel dove-hunting-quality sanPedro:SiteDoveHuntingQuality
(probabilistic-ranking sanPedro:SiteDoveHuntingQuality
[67 100] sanPedro:HighDoveHuntingQuality
[33 67] sanPedro:ModerateDoveHuntingQuality
[ 5 33] sanPedro:LowDoveHuntingQuality
[ 0 5] sanPedro:VeryLowDoveHuntingQuality))
(defmodel quail-hunting-quality sanPedro:SiteQuailHuntingQuality
(probabilistic-ranking sanPedro:SiteQuailHuntingQuality
[67 100] sanPedro:HighQuailHuntingQuality
[33 67] sanPedro:ModerateQuailHuntingQuality
[ 5 33] sanPedro:LowQuailHuntingQuality
[ 0 5] sanPedro:VeryLowQuailHuntingQuality))
Bayesian source models
(defmodel source-deer-hunting sanPedro:DeerHuntingSourceValue
(bayesian sanPedro:DeerHuntingSourceValue
:import "aries.core::RecreationSourceSanPedroDeerHunting.xdsl"
:context [riparian-wetland public-lands deer-habitat]
:keep [sanPedro:SiteDeerHuntingQuality]
:result deer-hunting-quality))
(defmodel source-javelina-hunting sanPedro:JavelinaHuntingSourceValue
(bayesian sanPedro:JavelinaHuntingSourceValue
:import "aries.core::RecreationSourceSanPedroJavelinaHunting.xdsl"
:context [riparian-wetland public-lands javelina-habitat]
:keep [sanPedro:SiteJavelinaHuntingQuality]
:result javelina-hunting-quality))
(defmodel source-dove-hunting sanPedro:DoveHuntingSourceValue
(bayesian sanPedro:DoveHuntingSourceValue
:import "aries.core::RecreationSourceSanPedroDoveHunting.xdsl"
:context [riparian-wetland public-lands dove-habitat]
:keep [sanPedro:SiteDoveHuntingQuality]
:result dove-hunting-quality))
(defmodel source-quail-hunting sanPedro:QuailHuntingSourceValue
(bayesian sanPedro:QuailHuntingSourceValue
:import "aries.core::RecreationSourceSanPedroQuailHunting.xdsl"
:context [riparian-wetland public-lands quail-habitat]
:keep [sanPedro:SiteQuailHuntingQuality]
:result quail-hunting-quality))
(defmodel population-density policytarget:PopulationDensity
(count policytarget:PopulationDensity "/km^2"))
( defmodel travel - capacity RoadTravelCapacity
(defmodel roads Roads
(classification (binary-coding infrastructure:Road)
1 RoadsPresent
:otherwise RoadsAbsent))
SPRNCA trails : need to expand bounding box so it does n't throw errors .
( defmodel trails Trails
1 TrailPresent
How to account for congestion and visitor response to it ? See
et al . 2005 , 2008 on modeling visitor choice between
Identifications for recreation : flow models are not yet ready but concepts will be exported to .
(defmodel recreation-data OutdoorRecreation
(identification OutdoorRecreation
:context [source-birding source-wildlife source-deer-hunting
source-quail-hunting source-dove-hunting
source-javelina-hunting population-density
SPAN statements written but recreational flow models are not yet developed .
( defmodel recreation - flow - birding BirdingUse
( span BirdingAccessAndUse
: source - threshold 10.0
: sink - threshold 10.0
: downscaling - factor 8
: 10
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
: keep [ TheoreticalSource
ActualFlow
ActualSource
InaccessibleSource
] ) )
( defmodel recreation - flow - wildlife WildlifeViewingUse
( span
: source - threshold 10.0
: sink - threshold 10.0
: downscaling - factor 8
: 10
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
: keep [ TheoreticalSource
ActualFlow
ActualSource
InaccessibleSource
] ) )
( defmodel recreation - flow - javelina - hunting JavelinaHuntingUse
JavelinaHuntingSourceValue
: source - threshold 10.0
: sink - threshold 10.0
: downscaling - factor 8
: 10
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
: keep [ TheoreticalSource
ActualFlow
ActualSource
InaccessibleSource
] ) )
( defmodel recreation - flow - dove - hunting
DoveHuntingSourceValue
: source - threshold 10.0
: sink - threshold 10.0
: downscaling - factor 8
: 10
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
: keep [ TheoreticalSource
ActualFlow
ActualSource
InaccessibleSource
] ) )
( defmodel recreation - flow - quail - hunting QuailHuntingUse
: source - threshold 10.0
: sink - threshold 10.0
: downscaling - factor 8
: 10
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
: keep [ TheoreticalSource
ActualFlow
ActualSource
InaccessibleSource
] ) )
( defmodel recreation - flow - deer - hunting DeerHuntingUse
( span
: source - threshold 10.0
: sink - threshold 10.0
: downscaling - factor 8
: 10
: save - file ( str ( System / getProperty " user.home " ) " /recreation_san_pedro_data.clj " )
: keep [ TheoreticalSource
ActualFlow
ActualSource
InaccessibleSource
] ) )
(defscenario cap-water-augmentation-half-meter-rise
"Water augmentation leading to a 0.5 meter rise across the San Pedro Riparian National Conservation Area"
(model sanPedro:RiparianConditionClass
(ranking sanPedro:RiparianConditionClassHalfMeterRise)))
(defscenario cap-water-augmentation-all-perennial
"Water augmentation leading to perennial flow conditions across the San Pedro Riparian National Conservation Area"
(model sanPedro:RiparianConditionClass
(ranking sanPedro:RiparianConditionClassAllWet)))
(defmodel constrained-development-scenario sanPedro:ConstrainedDevelopment
(classification (numeric-coding sanPedro:Steinitz30ClassUrbanGrowthLULCConstrained)
#{10 11 12 13 19 22 25} sanPedro:DevelopedConstrained
#{0 1 2 4 5 6 7 8 9 14 16 23 26 27 28} sanPedro:NotDevelopedConstrained))
(defmodel open-development-scenario sanPedro:OpenDevelopment
(classification (numeric-coding sanPedro:Steinitz30ClassUrbanGrowthLULCOpen)
#{10 11 12 13 19 22 25} sanPedro:DevelopedOpen
#{0 1 2 4 5 6 7 8 9 14 16 23 26 27 28 29} sanPedro:NotDevelopedOpen))
(defscenario constrained-development-recreation
"Changes values in developed areas to very private land and locally appropriate low values for habitat and species richness."
(model BirdSpeciesRichness
(classification BirdSpeciesRichness
:context [bird-richness :as br constrained-development-scenario :as cd]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'recreationService:LowBirdSpeciesRichness)
(:br %))))
(model RareCharismaticBirdHabitat
(classification RareCharismaticBirdHabitat
:context [bird-rarity :as br constrained-development-scenario :as cd]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'recreationService:LowRareCharismaticBirdHabitat)
(:br %))))
(model sanPedro:PublicAccessClass
(classification sanPedro:PublicAccessClass
:context [public-lands :as pl constrained-development-scenario :as cd]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'sanPedro:NoPublicAccess)
(:pl %))))
(model WildlifeSpeciesRichnessClass
(classification WildlifeSpeciesRichnessClass
:context [constrained-development-scenario :as cd wildlife-species-richness-class :as wl]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'recreationService:LowWildlifeSpeciesRichness)
(:wl %))))
(model sanPedro:DoveHabitat
(classification sanPedro:DoveHabitat
:context [constrained-development-scenario :as cd dove-habitat :as dh]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'sanPedro:SingleDoveSpeciesPresent)
(:dh %))))
(model sanPedro:DeerHabitat
(classification sanPedro:DeerHabitat
:context [constrained-development-scenario :as cd deer-habitat :as dh]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'sanPedro:DeerSpeciesAbsent)
(:dh %))))
(model sanPedro:QuailHabitat
(classification sanPedro:QuailHabitat
:context [constrained-development-scenario :as cd quail-habitat :as qh]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'sanPedro:QuailSpeciesAbsent)
(:qh %))))
(model sanPedro:JavelinaHabitat
(classification sanPedro:JavelinaHabitat
:context [constrained-development-scenario :as cd javelina-habitat :as jh]
:state #(if (is? (:cd %) (conc 'sanPedro:DevelopedConstrained))
(conc 'sanPedro:JavelinaHabitatAbsent)
(:jh %)))))
(defscenario open-development-recreation
"Changes values in developed areas to very private land and locally appropriate low values for habitat and species richness."
(model BirdSpeciesRichness
(classification BirdSpeciesRichness
:context [open-development-scenario :as od bird-richness :as br]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'recreationService:LowBirdSpeciesRichness)
(:br %))))
(model RareCharismaticBirdHabitat
(classification RareCharismaticBirdHabitat
:context [open-development-scenario :as od bird-rarity :as br]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'recreationService:LowRareCharismaticBirdHabitat)
(:br %))))
(model PublicAccessClass
(classification PublicAccessClass
:context [open-development-scenario :as od public-lands :as pl]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'recreationService:NoPublicAccess)
(:pl %))))
(model WildlifeSpeciesRichnessClass
(classification WildlifeSpeciesRichnessClass
:context [open-development-scenario :as od wildlife-species-richness-class :as wl]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'recreationService:LowWildlifeSpeciesRichness)
(:wl %))))
(model sanPedro:DoveHabitat
(classification sanPedro:DoveHabitat
:context [open-development-scenario :as od dove-habitat :as dh]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'sanPedro:SingleDoveSpeciesPresent)
(:dh %))))
(model sanPedro:DeerHabitat
(classification sanPedro:DeerHabitat
:context [open-development-scenario :as od deer-habitat :as dh]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'sanPedro:DeerSpeciesAbsent)
(:dh %))))
(model sanPedro:QuailHabitat
(classification sanPedro:QuailHabitat
:context [open-development-scenario :as od quail-habitat :as qh]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'sanPedro:QuailSpeciesAbsent)
(:qh %))))
(model sanPedro:JavelinaHabitat
(classification sanPedro:JavelinaHabitat
:context [open-development-scenario :as od javelina-habitat :as jh]
:state #(if (is? (:od %) (conc 'sanPedro:DevelopedOpen))
(conc 'sanPedro:JavelinaHabitatAbsent)
(:jh %)))))
( defscenario urban - growth sanPedro : UrbanGrowth ( add new users , up 10.4 % in constrained , 56.8 % in open )
sanPedro : UrbanGrowth2020Open
sanPedro : UrbanGrowth2020Constrained
sanPedro : Steinitz30ClassUrbanGrowthLULCOpen
sanPedro : Steinitz30ClassUrbanGrowthLULCConstrained |
a3b594f3ad62376c48a9ebaf2825d36c20b878948ef9daa79cde87ec89d23268 | tsloughter/kuberl | kuberl_v1beta1_daemon_set_update_strategy.erl | -module(kuberl_v1beta1_daemon_set_update_strategy).
-export([encode/1]).
-export_type([kuberl_v1beta1_daemon_set_update_strategy/0]).
-type kuberl_v1beta1_daemon_set_update_strategy() ::
#{ 'rollingUpdate' => kuberl_v1beta1_rolling_update_daemon_set:kuberl_v1beta1_rolling_update_daemon_set(),
'type' => binary()
}.
encode(#{ 'rollingUpdate' := RollingUpdate,
'type' := Type
}) ->
#{ 'rollingUpdate' => RollingUpdate,
'type' => Type
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1beta1_daemon_set_update_strategy.erl | erlang | -module(kuberl_v1beta1_daemon_set_update_strategy).
-export([encode/1]).
-export_type([kuberl_v1beta1_daemon_set_update_strategy/0]).
-type kuberl_v1beta1_daemon_set_update_strategy() ::
#{ 'rollingUpdate' => kuberl_v1beta1_rolling_update_daemon_set:kuberl_v1beta1_rolling_update_daemon_set(),
'type' => binary()
}.
encode(#{ 'rollingUpdate' := RollingUpdate,
'type' := Type
}) ->
#{ 'rollingUpdate' => RollingUpdate,
'type' => Type
}.
| |
34552623859b317c19f9ad36ba2e05139c54e2615973121cde4baabcb5a4d64a | ocaml/ocaml | ast_helper.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, LexiFi
(* *)
Copyright 2012 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
* Helpers to produce Parsetree fragments
open Asttypes
open Parsetree
open Docstrings
type 'a with_loc = 'a Location.loc
type loc = Location.t
type lid = Longident.t with_loc
type str = string with_loc
type str_opt = string option with_loc
type attrs = attribute list
let default_loc = ref Location.none
let with_default_loc l f =
Misc.protect_refs [Misc.R (default_loc, l)] f
module Const = struct
let integer ?suffix i = Pconst_integer (i, suffix)
let int ?suffix i = integer ?suffix (Int.to_string i)
let int32 ?(suffix='l') i = integer ~suffix (Int32.to_string i)
let int64 ?(suffix='L') i = integer ~suffix (Int64.to_string i)
let nativeint ?(suffix='n') i = integer ~suffix (Nativeint.to_string i)
let float ?suffix f = Pconst_float (f, suffix)
let char c = Pconst_char c
let string ?quotation_delimiter ?(loc= !default_loc) s =
Pconst_string (s, loc, quotation_delimiter)
end
module Attr = struct
let mk ?(loc= !default_loc) name payload =
{ attr_name = name;
attr_payload = payload;
attr_loc = loc }
end
module Typ = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{ptyp_desc = d;
ptyp_loc = loc;
ptyp_loc_stack = [];
ptyp_attributes = attrs}
let attr d a = {d with ptyp_attributes = d.ptyp_attributes @ [a]}
let any ?loc ?attrs () = mk ?loc ?attrs Ptyp_any
let var ?loc ?attrs a = mk ?loc ?attrs (Ptyp_var a)
let arrow ?loc ?attrs a b c = mk ?loc ?attrs (Ptyp_arrow (a, b, c))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Ptyp_tuple a)
let constr ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_constr (a, b))
let object_ ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_object (a, b))
let class_ ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_class (a, b))
let alias ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_alias (a, b))
let variant ?loc ?attrs a b c = mk ?loc ?attrs (Ptyp_variant (a, b, c))
let poly ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_poly (a, b))
let package ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_package (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Ptyp_extension a)
let force_poly t =
match t.ptyp_desc with
| Ptyp_poly _ -> t
| _ -> poly ~loc:t.ptyp_loc [] t (* -> ghost? *)
let varify_constructors var_names t =
let check_variable vl loc v =
if List.mem v vl then
raise Syntaxerr.(Error(Variable_in_scope(loc,v))) in
let var_names = List.map (fun v -> v.txt) var_names in
let rec loop t =
let desc =
match t.ptyp_desc with
| Ptyp_any -> Ptyp_any
| Ptyp_var x ->
check_variable var_names t.ptyp_loc x;
Ptyp_var x
| Ptyp_arrow (label,core_type,core_type') ->
Ptyp_arrow(label, loop core_type, loop core_type')
| Ptyp_tuple lst -> Ptyp_tuple (List.map loop lst)
| Ptyp_constr( { txt = Longident.Lident s }, [])
when List.mem s var_names ->
Ptyp_var s
| Ptyp_constr(longident, lst) ->
Ptyp_constr(longident, List.map loop lst)
| Ptyp_object (lst, o) ->
Ptyp_object (List.map loop_object_field lst, o)
| Ptyp_class (longident, lst) ->
Ptyp_class (longident, List.map loop lst)
| Ptyp_alias(core_type, string) ->
check_variable var_names t.ptyp_loc string;
Ptyp_alias(loop core_type, string)
| Ptyp_variant(row_field_list, flag, lbl_lst_option) ->
Ptyp_variant(List.map loop_row_field row_field_list,
flag, lbl_lst_option)
| Ptyp_poly(string_lst, core_type) ->
List.iter (fun v ->
check_variable var_names t.ptyp_loc v.txt) string_lst;
Ptyp_poly(string_lst, loop core_type)
| Ptyp_package(longident,lst) ->
Ptyp_package(longident,List.map (fun (n,typ) -> (n,loop typ) ) lst)
| Ptyp_extension (s, arg) ->
Ptyp_extension (s, arg)
in
{t with ptyp_desc = desc}
and loop_row_field field =
let prf_desc = match field.prf_desc with
| Rtag(label,flag,lst) ->
Rtag(label,flag,List.map loop lst)
| Rinherit t ->
Rinherit (loop t)
in
{ field with prf_desc; }
and loop_object_field field =
let pof_desc = match field.pof_desc with
| Otag(label, t) ->
Otag(label, loop t)
| Oinherit t ->
Oinherit (loop t)
in
{ field with pof_desc; }
in
loop t
end
module Pat = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{ppat_desc = d;
ppat_loc = loc;
ppat_loc_stack = [];
ppat_attributes = attrs}
let attr d a = {d with ppat_attributes = d.ppat_attributes @ [a]}
let any ?loc ?attrs () = mk ?loc ?attrs Ppat_any
let var ?loc ?attrs a = mk ?loc ?attrs (Ppat_var a)
let alias ?loc ?attrs a b = mk ?loc ?attrs (Ppat_alias (a, b))
let constant ?loc ?attrs a = mk ?loc ?attrs (Ppat_constant a)
let interval ?loc ?attrs a b = mk ?loc ?attrs (Ppat_interval (a, b))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Ppat_tuple a)
let construct ?loc ?attrs a b = mk ?loc ?attrs (Ppat_construct (a, b))
let variant ?loc ?attrs a b = mk ?loc ?attrs (Ppat_variant (a, b))
let record ?loc ?attrs a b = mk ?loc ?attrs (Ppat_record (a, b))
let array ?loc ?attrs a = mk ?loc ?attrs (Ppat_array a)
let or_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_or (a, b))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_constraint (a, b))
let type_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_type a)
let lazy_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_lazy a)
let unpack ?loc ?attrs a = mk ?loc ?attrs (Ppat_unpack a)
let open_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_open (a, b))
let exception_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_exception a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Ppat_extension a)
end
module Exp = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pexp_desc = d;
pexp_loc = loc;
pexp_loc_stack = [];
pexp_attributes = attrs}
let attr d a = {d with pexp_attributes = d.pexp_attributes @ [a]}
let ident ?loc ?attrs a = mk ?loc ?attrs (Pexp_ident a)
let constant ?loc ?attrs a = mk ?loc ?attrs (Pexp_constant a)
let let_ ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_let (a, b, c))
let fun_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pexp_fun (a, b, c, d))
let function_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_function a)
let apply ?loc ?attrs a b = mk ?loc ?attrs (Pexp_apply (a, b))
let match_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_match (a, b))
let try_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_try (a, b))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Pexp_tuple a)
let construct ?loc ?attrs a b = mk ?loc ?attrs (Pexp_construct (a, b))
let variant ?loc ?attrs a b = mk ?loc ?attrs (Pexp_variant (a, b))
let record ?loc ?attrs a b = mk ?loc ?attrs (Pexp_record (a, b))
let field ?loc ?attrs a b = mk ?loc ?attrs (Pexp_field (a, b))
let setfield ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_setfield (a, b, c))
let array ?loc ?attrs a = mk ?loc ?attrs (Pexp_array a)
let ifthenelse ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_ifthenelse (a, b, c))
let sequence ?loc ?attrs a b = mk ?loc ?attrs (Pexp_sequence (a, b))
let while_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_while (a, b))
let for_ ?loc ?attrs a b c d e = mk ?loc ?attrs (Pexp_for (a, b, c, d, e))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_constraint (a, b))
let coerce ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_coerce (a, b, c))
let send ?loc ?attrs a b = mk ?loc ?attrs (Pexp_send (a, b))
let new_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_new a)
let setinstvar ?loc ?attrs a b = mk ?loc ?attrs (Pexp_setinstvar (a, b))
let override ?loc ?attrs a = mk ?loc ?attrs (Pexp_override a)
let letmodule ?loc ?attrs a b c= mk ?loc ?attrs (Pexp_letmodule (a, b, c))
let letexception ?loc ?attrs a b = mk ?loc ?attrs (Pexp_letexception (a, b))
let assert_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_assert a)
let lazy_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_lazy a)
let poly ?loc ?attrs a b = mk ?loc ?attrs (Pexp_poly (a, b))
let object_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_object a)
let newtype ?loc ?attrs a b = mk ?loc ?attrs (Pexp_newtype (a, b))
let pack ?loc ?attrs a = mk ?loc ?attrs (Pexp_pack a)
let open_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_open (a, b))
let letop ?loc ?attrs let_ ands body =
mk ?loc ?attrs (Pexp_letop {let_; ands; body})
let extension ?loc ?attrs a = mk ?loc ?attrs (Pexp_extension a)
let unreachable ?loc ?attrs () = mk ?loc ?attrs Pexp_unreachable
let case lhs ?guard rhs =
{
pc_lhs = lhs;
pc_guard = guard;
pc_rhs = rhs;
}
let binding_op op pat exp loc =
{
pbop_op = op;
pbop_pat = pat;
pbop_exp = exp;
pbop_loc = loc;
}
end
module Mty = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pmty_desc = d; pmty_loc = loc; pmty_attributes = attrs}
let attr d a = {d with pmty_attributes = d.pmty_attributes @ [a]}
let ident ?loc ?attrs a = mk ?loc ?attrs (Pmty_ident a)
let alias ?loc ?attrs a = mk ?loc ?attrs (Pmty_alias a)
let signature ?loc ?attrs a = mk ?loc ?attrs (Pmty_signature a)
let functor_ ?loc ?attrs a b = mk ?loc ?attrs (Pmty_functor (a, b))
let with_ ?loc ?attrs a b = mk ?loc ?attrs (Pmty_with (a, b))
let typeof_ ?loc ?attrs a = mk ?loc ?attrs (Pmty_typeof a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pmty_extension a)
end
module Mod = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pmod_desc = d; pmod_loc = loc; pmod_attributes = attrs}
let attr d a = {d with pmod_attributes = d.pmod_attributes @ [a]}
let ident ?loc ?attrs x = mk ?loc ?attrs (Pmod_ident x)
let structure ?loc ?attrs x = mk ?loc ?attrs (Pmod_structure x)
let functor_ ?loc ?attrs arg body =
mk ?loc ?attrs (Pmod_functor (arg, body))
let apply ?loc ?attrs m1 m2 = mk ?loc ?attrs (Pmod_apply (m1, m2))
let apply_unit ?loc ?attrs m1 = mk ?loc ?attrs (Pmod_apply_unit m1)
let constraint_ ?loc ?attrs m mty = mk ?loc ?attrs (Pmod_constraint (m, mty))
let unpack ?loc ?attrs e = mk ?loc ?attrs (Pmod_unpack e)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pmod_extension a)
end
module Sig = struct
let mk ?(loc = !default_loc) d = {psig_desc = d; psig_loc = loc}
let value ?loc a = mk ?loc (Psig_value a)
let type_ ?loc rec_flag a = mk ?loc (Psig_type (rec_flag, a))
let type_subst ?loc a = mk ?loc (Psig_typesubst a)
let type_extension ?loc a = mk ?loc (Psig_typext a)
let exception_ ?loc a = mk ?loc (Psig_exception a)
let module_ ?loc a = mk ?loc (Psig_module a)
let mod_subst ?loc a = mk ?loc (Psig_modsubst a)
let rec_module ?loc a = mk ?loc (Psig_recmodule a)
let modtype ?loc a = mk ?loc (Psig_modtype a)
let modtype_subst ?loc a = mk ?loc (Psig_modtypesubst a)
let open_ ?loc a = mk ?loc (Psig_open a)
let include_ ?loc a = mk ?loc (Psig_include a)
let class_ ?loc a = mk ?loc (Psig_class a)
let class_type ?loc a = mk ?loc (Psig_class_type a)
let extension ?loc ?(attrs = []) a = mk ?loc (Psig_extension (a, attrs))
let attribute ?loc a = mk ?loc (Psig_attribute a)
let text txt =
let f_txt = List.filter (fun ds -> docstring_body ds <> "") txt in
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
f_txt
end
module Str = struct
let mk ?(loc = !default_loc) d = {pstr_desc = d; pstr_loc = loc}
let eval ?loc ?(attrs = []) a = mk ?loc (Pstr_eval (a, attrs))
let value ?loc a b = mk ?loc (Pstr_value (a, b))
let primitive ?loc a = mk ?loc (Pstr_primitive a)
let type_ ?loc rec_flag a = mk ?loc (Pstr_type (rec_flag, a))
let type_extension ?loc a = mk ?loc (Pstr_typext a)
let exception_ ?loc a = mk ?loc (Pstr_exception a)
let module_ ?loc a = mk ?loc (Pstr_module a)
let rec_module ?loc a = mk ?loc (Pstr_recmodule a)
let modtype ?loc a = mk ?loc (Pstr_modtype a)
let open_ ?loc a = mk ?loc (Pstr_open a)
let class_ ?loc a = mk ?loc (Pstr_class a)
let class_type ?loc a = mk ?loc (Pstr_class_type a)
let include_ ?loc a = mk ?loc (Pstr_include a)
let extension ?loc ?(attrs = []) a = mk ?loc (Pstr_extension (a, attrs))
let attribute ?loc a = mk ?loc (Pstr_attribute a)
let text txt =
let f_txt = List.filter (fun ds -> docstring_body ds <> "") txt in
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
f_txt
end
module Cl = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{
pcl_desc = d;
pcl_loc = loc;
pcl_attributes = attrs;
}
let attr d a = {d with pcl_attributes = d.pcl_attributes @ [a]}
let constr ?loc ?attrs a b = mk ?loc ?attrs (Pcl_constr (a, b))
let structure ?loc ?attrs a = mk ?loc ?attrs (Pcl_structure a)
let fun_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pcl_fun (a, b, c, d))
let apply ?loc ?attrs a b = mk ?loc ?attrs (Pcl_apply (a, b))
let let_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcl_let (a, b, c))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pcl_constraint (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcl_extension a)
let open_ ?loc ?attrs a b = mk ?loc ?attrs (Pcl_open (a, b))
end
module Cty = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{
pcty_desc = d;
pcty_loc = loc;
pcty_attributes = attrs;
}
let attr d a = {d with pcty_attributes = d.pcty_attributes @ [a]}
let constr ?loc ?attrs a b = mk ?loc ?attrs (Pcty_constr (a, b))
let signature ?loc ?attrs a = mk ?loc ?attrs (Pcty_signature a)
let arrow ?loc ?attrs a b c = mk ?loc ?attrs (Pcty_arrow (a, b, c))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcty_extension a)
let open_ ?loc ?attrs a b = mk ?loc ?attrs (Pcty_open (a, b))
end
module Ctf = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) d =
{
pctf_desc = d;
pctf_loc = loc;
pctf_attributes = add_docs_attrs docs attrs;
}
let inherit_ ?loc ?attrs a = mk ?loc ?attrs (Pctf_inherit a)
let val_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pctf_val (a, b, c, d))
let method_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pctf_method (a, b, c, d))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pctf_constraint (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pctf_extension a)
let attribute ?loc a = mk ?loc (Pctf_attribute a)
let text txt =
let f_txt = List.filter (fun ds -> docstring_body ds <> "") txt in
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
f_txt
let attr d a = {d with pctf_attributes = d.pctf_attributes @ [a]}
end
module Cf = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) d =
{
pcf_desc = d;
pcf_loc = loc;
pcf_attributes = add_docs_attrs docs attrs;
}
let inherit_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_inherit (a, b, c))
let val_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_val (a, b, c))
let method_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_method (a, b, c))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pcf_constraint (a, b))
let initializer_ ?loc ?attrs a = mk ?loc ?attrs (Pcf_initializer a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcf_extension a)
let attribute ?loc a = mk ?loc (Pcf_attribute a)
let text txt =
let f_txt = List.filter (fun ds -> docstring_body ds <> "") txt in
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
f_txt
let virtual_ ct = Cfk_virtual ct
let concrete o e = Cfk_concrete (o, e)
let attr d a = {d with pcf_attributes = d.pcf_attributes @ [a]}
end
module Val = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(prim = []) name typ =
{
pval_name = name;
pval_type = typ;
pval_attributes = add_docs_attrs docs attrs;
pval_loc = loc;
pval_prim = prim;
}
end
module Md = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) name typ =
{
pmd_name = name;
pmd_type = typ;
pmd_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmd_loc = loc;
}
end
module Ms = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) name syn =
{
pms_name = name;
pms_manifest = syn;
pms_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pms_loc = loc;
}
end
module Mtd = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) ?typ name =
{
pmtd_name = name;
pmtd_type = typ;
pmtd_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmtd_loc = loc;
}
end
module Mb = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) name expr =
{
pmb_name = name;
pmb_expr = expr;
pmb_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmb_loc = loc;
}
end
module Opn = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(override = Fresh) expr =
{
popen_expr = expr;
popen_override = override;
popen_loc = loc;
popen_attributes = add_docs_attrs docs attrs;
}
end
module Incl = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs) mexpr =
{
pincl_mod = mexpr;
pincl_loc = loc;
pincl_attributes = add_docs_attrs docs attrs;
}
end
module Vb = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(text = []) pat expr =
{
pvb_pat = pat;
pvb_expr = expr;
pvb_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pvb_loc = loc;
}
end
module Ci = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = [])
?(virt = Concrete) ?(params = []) name expr =
{
pci_virt = virt;
pci_params = params;
pci_name = name;
pci_expr = expr;
pci_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pci_loc = loc;
}
end
module Type = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = [])
?(params = [])
?(cstrs = [])
?(kind = Ptype_abstract)
?(priv = Public)
?manifest
name =
{
ptype_name = name;
ptype_params = params;
ptype_cstrs = cstrs;
ptype_kind = kind;
ptype_private = priv;
ptype_manifest = manifest;
ptype_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
ptype_loc = loc;
}
let constructor ?(loc = !default_loc) ?(attrs = []) ?(info = empty_info)
?(vars = []) ?(args = Pcstr_tuple []) ?res name =
{
pcd_name = name;
pcd_vars = vars;
pcd_args = args;
pcd_res = res;
pcd_loc = loc;
pcd_attributes = add_info_attrs info attrs;
}
let field ?(loc = !default_loc) ?(attrs = []) ?(info = empty_info)
?(mut = Immutable) name typ =
{
pld_name = name;
pld_mutable = mut;
pld_type = typ;
pld_loc = loc;
pld_attributes = add_info_attrs info attrs;
}
end
(** Type extensions *)
module Te = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(params = []) ?(priv = Public) path constructors =
{
ptyext_path = path;
ptyext_params = params;
ptyext_constructors = constructors;
ptyext_private = priv;
ptyext_loc = loc;
ptyext_attributes = add_docs_attrs docs attrs;
}
let mk_exception ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
constructor =
{
ptyexn_constructor = constructor;
ptyexn_loc = loc;
ptyexn_attributes = add_docs_attrs docs attrs;
}
let constructor ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(info = empty_info) name kind =
{
pext_name = name;
pext_kind = kind;
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
let decl ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(info = empty_info) ?(vars = []) ?(args = Pcstr_tuple []) ?res name =
{
pext_name = name;
pext_kind = Pext_decl(vars, args, res);
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
let rebind ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(info = empty_info) name lid =
{
pext_name = name;
pext_kind = Pext_rebind lid;
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
end
module Csig = struct
let mk self fields =
{
pcsig_self = self;
pcsig_fields = fields;
}
end
module Cstr = struct
let mk self fields =
{
pcstr_self = self;
pcstr_fields = fields;
}
end
(** Row fields *)
module Rf = struct
let mk ?(loc = !default_loc) ?(attrs = []) desc = {
prf_desc = desc;
prf_loc = loc;
prf_attributes = attrs;
}
let tag ?loc ?attrs label const tys =
mk ?loc ?attrs (Rtag (label, const, tys))
let inherit_?loc ty =
mk ?loc (Rinherit ty)
end
(** Object fields *)
module Of = struct
let mk ?(loc = !default_loc) ?(attrs=[]) desc = {
pof_desc = desc;
pof_loc = loc;
pof_attributes = attrs;
}
let tag ?loc ?attrs label ty =
mk ?loc ?attrs (Otag (label, ty))
let inherit_ ?loc ty =
mk ?loc (Oinherit ty)
end
| null | https://raw.githubusercontent.com/ocaml/ocaml/8a61778d2716304203974d20ead1b2736c1694a8/parsing/ast_helper.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
-> ghost?
* Type extensions
* Row fields
* Object fields | , LexiFi
Copyright 2012 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
* Helpers to produce Parsetree fragments
open Asttypes
open Parsetree
open Docstrings
type 'a with_loc = 'a Location.loc
type loc = Location.t
type lid = Longident.t with_loc
type str = string with_loc
type str_opt = string option with_loc
type attrs = attribute list
let default_loc = ref Location.none
let with_default_loc l f =
Misc.protect_refs [Misc.R (default_loc, l)] f
module Const = struct
let integer ?suffix i = Pconst_integer (i, suffix)
let int ?suffix i = integer ?suffix (Int.to_string i)
let int32 ?(suffix='l') i = integer ~suffix (Int32.to_string i)
let int64 ?(suffix='L') i = integer ~suffix (Int64.to_string i)
let nativeint ?(suffix='n') i = integer ~suffix (Nativeint.to_string i)
let float ?suffix f = Pconst_float (f, suffix)
let char c = Pconst_char c
let string ?quotation_delimiter ?(loc= !default_loc) s =
Pconst_string (s, loc, quotation_delimiter)
end
module Attr = struct
let mk ?(loc= !default_loc) name payload =
{ attr_name = name;
attr_payload = payload;
attr_loc = loc }
end
module Typ = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{ptyp_desc = d;
ptyp_loc = loc;
ptyp_loc_stack = [];
ptyp_attributes = attrs}
let attr d a = {d with ptyp_attributes = d.ptyp_attributes @ [a]}
let any ?loc ?attrs () = mk ?loc ?attrs Ptyp_any
let var ?loc ?attrs a = mk ?loc ?attrs (Ptyp_var a)
let arrow ?loc ?attrs a b c = mk ?loc ?attrs (Ptyp_arrow (a, b, c))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Ptyp_tuple a)
let constr ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_constr (a, b))
let object_ ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_object (a, b))
let class_ ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_class (a, b))
let alias ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_alias (a, b))
let variant ?loc ?attrs a b c = mk ?loc ?attrs (Ptyp_variant (a, b, c))
let poly ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_poly (a, b))
let package ?loc ?attrs a b = mk ?loc ?attrs (Ptyp_package (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Ptyp_extension a)
let force_poly t =
match t.ptyp_desc with
| Ptyp_poly _ -> t
let varify_constructors var_names t =
let check_variable vl loc v =
if List.mem v vl then
raise Syntaxerr.(Error(Variable_in_scope(loc,v))) in
let var_names = List.map (fun v -> v.txt) var_names in
let rec loop t =
let desc =
match t.ptyp_desc with
| Ptyp_any -> Ptyp_any
| Ptyp_var x ->
check_variable var_names t.ptyp_loc x;
Ptyp_var x
| Ptyp_arrow (label,core_type,core_type') ->
Ptyp_arrow(label, loop core_type, loop core_type')
| Ptyp_tuple lst -> Ptyp_tuple (List.map loop lst)
| Ptyp_constr( { txt = Longident.Lident s }, [])
when List.mem s var_names ->
Ptyp_var s
| Ptyp_constr(longident, lst) ->
Ptyp_constr(longident, List.map loop lst)
| Ptyp_object (lst, o) ->
Ptyp_object (List.map loop_object_field lst, o)
| Ptyp_class (longident, lst) ->
Ptyp_class (longident, List.map loop lst)
| Ptyp_alias(core_type, string) ->
check_variable var_names t.ptyp_loc string;
Ptyp_alias(loop core_type, string)
| Ptyp_variant(row_field_list, flag, lbl_lst_option) ->
Ptyp_variant(List.map loop_row_field row_field_list,
flag, lbl_lst_option)
| Ptyp_poly(string_lst, core_type) ->
List.iter (fun v ->
check_variable var_names t.ptyp_loc v.txt) string_lst;
Ptyp_poly(string_lst, loop core_type)
| Ptyp_package(longident,lst) ->
Ptyp_package(longident,List.map (fun (n,typ) -> (n,loop typ) ) lst)
| Ptyp_extension (s, arg) ->
Ptyp_extension (s, arg)
in
{t with ptyp_desc = desc}
and loop_row_field field =
let prf_desc = match field.prf_desc with
| Rtag(label,flag,lst) ->
Rtag(label,flag,List.map loop lst)
| Rinherit t ->
Rinherit (loop t)
in
{ field with prf_desc; }
and loop_object_field field =
let pof_desc = match field.pof_desc with
| Otag(label, t) ->
Otag(label, loop t)
| Oinherit t ->
Oinherit (loop t)
in
{ field with pof_desc; }
in
loop t
end
module Pat = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{ppat_desc = d;
ppat_loc = loc;
ppat_loc_stack = [];
ppat_attributes = attrs}
let attr d a = {d with ppat_attributes = d.ppat_attributes @ [a]}
let any ?loc ?attrs () = mk ?loc ?attrs Ppat_any
let var ?loc ?attrs a = mk ?loc ?attrs (Ppat_var a)
let alias ?loc ?attrs a b = mk ?loc ?attrs (Ppat_alias (a, b))
let constant ?loc ?attrs a = mk ?loc ?attrs (Ppat_constant a)
let interval ?loc ?attrs a b = mk ?loc ?attrs (Ppat_interval (a, b))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Ppat_tuple a)
let construct ?loc ?attrs a b = mk ?loc ?attrs (Ppat_construct (a, b))
let variant ?loc ?attrs a b = mk ?loc ?attrs (Ppat_variant (a, b))
let record ?loc ?attrs a b = mk ?loc ?attrs (Ppat_record (a, b))
let array ?loc ?attrs a = mk ?loc ?attrs (Ppat_array a)
let or_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_or (a, b))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_constraint (a, b))
let type_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_type a)
let lazy_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_lazy a)
let unpack ?loc ?attrs a = mk ?loc ?attrs (Ppat_unpack a)
let open_ ?loc ?attrs a b = mk ?loc ?attrs (Ppat_open (a, b))
let exception_ ?loc ?attrs a = mk ?loc ?attrs (Ppat_exception a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Ppat_extension a)
end
module Exp = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pexp_desc = d;
pexp_loc = loc;
pexp_loc_stack = [];
pexp_attributes = attrs}
let attr d a = {d with pexp_attributes = d.pexp_attributes @ [a]}
let ident ?loc ?attrs a = mk ?loc ?attrs (Pexp_ident a)
let constant ?loc ?attrs a = mk ?loc ?attrs (Pexp_constant a)
let let_ ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_let (a, b, c))
let fun_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pexp_fun (a, b, c, d))
let function_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_function a)
let apply ?loc ?attrs a b = mk ?loc ?attrs (Pexp_apply (a, b))
let match_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_match (a, b))
let try_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_try (a, b))
let tuple ?loc ?attrs a = mk ?loc ?attrs (Pexp_tuple a)
let construct ?loc ?attrs a b = mk ?loc ?attrs (Pexp_construct (a, b))
let variant ?loc ?attrs a b = mk ?loc ?attrs (Pexp_variant (a, b))
let record ?loc ?attrs a b = mk ?loc ?attrs (Pexp_record (a, b))
let field ?loc ?attrs a b = mk ?loc ?attrs (Pexp_field (a, b))
let setfield ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_setfield (a, b, c))
let array ?loc ?attrs a = mk ?loc ?attrs (Pexp_array a)
let ifthenelse ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_ifthenelse (a, b, c))
let sequence ?loc ?attrs a b = mk ?loc ?attrs (Pexp_sequence (a, b))
let while_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_while (a, b))
let for_ ?loc ?attrs a b c d e = mk ?loc ?attrs (Pexp_for (a, b, c, d, e))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_constraint (a, b))
let coerce ?loc ?attrs a b c = mk ?loc ?attrs (Pexp_coerce (a, b, c))
let send ?loc ?attrs a b = mk ?loc ?attrs (Pexp_send (a, b))
let new_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_new a)
let setinstvar ?loc ?attrs a b = mk ?loc ?attrs (Pexp_setinstvar (a, b))
let override ?loc ?attrs a = mk ?loc ?attrs (Pexp_override a)
let letmodule ?loc ?attrs a b c= mk ?loc ?attrs (Pexp_letmodule (a, b, c))
let letexception ?loc ?attrs a b = mk ?loc ?attrs (Pexp_letexception (a, b))
let assert_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_assert a)
let lazy_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_lazy a)
let poly ?loc ?attrs a b = mk ?loc ?attrs (Pexp_poly (a, b))
let object_ ?loc ?attrs a = mk ?loc ?attrs (Pexp_object a)
let newtype ?loc ?attrs a b = mk ?loc ?attrs (Pexp_newtype (a, b))
let pack ?loc ?attrs a = mk ?loc ?attrs (Pexp_pack a)
let open_ ?loc ?attrs a b = mk ?loc ?attrs (Pexp_open (a, b))
let letop ?loc ?attrs let_ ands body =
mk ?loc ?attrs (Pexp_letop {let_; ands; body})
let extension ?loc ?attrs a = mk ?loc ?attrs (Pexp_extension a)
let unreachable ?loc ?attrs () = mk ?loc ?attrs Pexp_unreachable
let case lhs ?guard rhs =
{
pc_lhs = lhs;
pc_guard = guard;
pc_rhs = rhs;
}
let binding_op op pat exp loc =
{
pbop_op = op;
pbop_pat = pat;
pbop_exp = exp;
pbop_loc = loc;
}
end
module Mty = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pmty_desc = d; pmty_loc = loc; pmty_attributes = attrs}
let attr d a = {d with pmty_attributes = d.pmty_attributes @ [a]}
let ident ?loc ?attrs a = mk ?loc ?attrs (Pmty_ident a)
let alias ?loc ?attrs a = mk ?loc ?attrs (Pmty_alias a)
let signature ?loc ?attrs a = mk ?loc ?attrs (Pmty_signature a)
let functor_ ?loc ?attrs a b = mk ?loc ?attrs (Pmty_functor (a, b))
let with_ ?loc ?attrs a b = mk ?loc ?attrs (Pmty_with (a, b))
let typeof_ ?loc ?attrs a = mk ?loc ?attrs (Pmty_typeof a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pmty_extension a)
end
module Mod = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{pmod_desc = d; pmod_loc = loc; pmod_attributes = attrs}
let attr d a = {d with pmod_attributes = d.pmod_attributes @ [a]}
let ident ?loc ?attrs x = mk ?loc ?attrs (Pmod_ident x)
let structure ?loc ?attrs x = mk ?loc ?attrs (Pmod_structure x)
let functor_ ?loc ?attrs arg body =
mk ?loc ?attrs (Pmod_functor (arg, body))
let apply ?loc ?attrs m1 m2 = mk ?loc ?attrs (Pmod_apply (m1, m2))
let apply_unit ?loc ?attrs m1 = mk ?loc ?attrs (Pmod_apply_unit m1)
let constraint_ ?loc ?attrs m mty = mk ?loc ?attrs (Pmod_constraint (m, mty))
let unpack ?loc ?attrs e = mk ?loc ?attrs (Pmod_unpack e)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pmod_extension a)
end
module Sig = struct
let mk ?(loc = !default_loc) d = {psig_desc = d; psig_loc = loc}
let value ?loc a = mk ?loc (Psig_value a)
let type_ ?loc rec_flag a = mk ?loc (Psig_type (rec_flag, a))
let type_subst ?loc a = mk ?loc (Psig_typesubst a)
let type_extension ?loc a = mk ?loc (Psig_typext a)
let exception_ ?loc a = mk ?loc (Psig_exception a)
let module_ ?loc a = mk ?loc (Psig_module a)
let mod_subst ?loc a = mk ?loc (Psig_modsubst a)
let rec_module ?loc a = mk ?loc (Psig_recmodule a)
let modtype ?loc a = mk ?loc (Psig_modtype a)
let modtype_subst ?loc a = mk ?loc (Psig_modtypesubst a)
let open_ ?loc a = mk ?loc (Psig_open a)
let include_ ?loc a = mk ?loc (Psig_include a)
let class_ ?loc a = mk ?loc (Psig_class a)
let class_type ?loc a = mk ?loc (Psig_class_type a)
let extension ?loc ?(attrs = []) a = mk ?loc (Psig_extension (a, attrs))
let attribute ?loc a = mk ?loc (Psig_attribute a)
let text txt =
let f_txt = List.filter (fun ds -> docstring_body ds <> "") txt in
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
f_txt
end
module Str = struct
let mk ?(loc = !default_loc) d = {pstr_desc = d; pstr_loc = loc}
let eval ?loc ?(attrs = []) a = mk ?loc (Pstr_eval (a, attrs))
let value ?loc a b = mk ?loc (Pstr_value (a, b))
let primitive ?loc a = mk ?loc (Pstr_primitive a)
let type_ ?loc rec_flag a = mk ?loc (Pstr_type (rec_flag, a))
let type_extension ?loc a = mk ?loc (Pstr_typext a)
let exception_ ?loc a = mk ?loc (Pstr_exception a)
let module_ ?loc a = mk ?loc (Pstr_module a)
let rec_module ?loc a = mk ?loc (Pstr_recmodule a)
let modtype ?loc a = mk ?loc (Pstr_modtype a)
let open_ ?loc a = mk ?loc (Pstr_open a)
let class_ ?loc a = mk ?loc (Pstr_class a)
let class_type ?loc a = mk ?loc (Pstr_class_type a)
let include_ ?loc a = mk ?loc (Pstr_include a)
let extension ?loc ?(attrs = []) a = mk ?loc (Pstr_extension (a, attrs))
let attribute ?loc a = mk ?loc (Pstr_attribute a)
let text txt =
let f_txt = List.filter (fun ds -> docstring_body ds <> "") txt in
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
f_txt
end
module Cl = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{
pcl_desc = d;
pcl_loc = loc;
pcl_attributes = attrs;
}
let attr d a = {d with pcl_attributes = d.pcl_attributes @ [a]}
let constr ?loc ?attrs a b = mk ?loc ?attrs (Pcl_constr (a, b))
let structure ?loc ?attrs a = mk ?loc ?attrs (Pcl_structure a)
let fun_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pcl_fun (a, b, c, d))
let apply ?loc ?attrs a b = mk ?loc ?attrs (Pcl_apply (a, b))
let let_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcl_let (a, b, c))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pcl_constraint (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcl_extension a)
let open_ ?loc ?attrs a b = mk ?loc ?attrs (Pcl_open (a, b))
end
module Cty = struct
let mk ?(loc = !default_loc) ?(attrs = []) d =
{
pcty_desc = d;
pcty_loc = loc;
pcty_attributes = attrs;
}
let attr d a = {d with pcty_attributes = d.pcty_attributes @ [a]}
let constr ?loc ?attrs a b = mk ?loc ?attrs (Pcty_constr (a, b))
let signature ?loc ?attrs a = mk ?loc ?attrs (Pcty_signature a)
let arrow ?loc ?attrs a b c = mk ?loc ?attrs (Pcty_arrow (a, b, c))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcty_extension a)
let open_ ?loc ?attrs a b = mk ?loc ?attrs (Pcty_open (a, b))
end
module Ctf = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) d =
{
pctf_desc = d;
pctf_loc = loc;
pctf_attributes = add_docs_attrs docs attrs;
}
let inherit_ ?loc ?attrs a = mk ?loc ?attrs (Pctf_inherit a)
let val_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pctf_val (a, b, c, d))
let method_ ?loc ?attrs a b c d = mk ?loc ?attrs (Pctf_method (a, b, c, d))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pctf_constraint (a, b))
let extension ?loc ?attrs a = mk ?loc ?attrs (Pctf_extension a)
let attribute ?loc a = mk ?loc (Pctf_attribute a)
let text txt =
let f_txt = List.filter (fun ds -> docstring_body ds <> "") txt in
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
f_txt
let attr d a = {d with pctf_attributes = d.pctf_attributes @ [a]}
end
module Cf = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) d =
{
pcf_desc = d;
pcf_loc = loc;
pcf_attributes = add_docs_attrs docs attrs;
}
let inherit_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_inherit (a, b, c))
let val_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_val (a, b, c))
let method_ ?loc ?attrs a b c = mk ?loc ?attrs (Pcf_method (a, b, c))
let constraint_ ?loc ?attrs a b = mk ?loc ?attrs (Pcf_constraint (a, b))
let initializer_ ?loc ?attrs a = mk ?loc ?attrs (Pcf_initializer a)
let extension ?loc ?attrs a = mk ?loc ?attrs (Pcf_extension a)
let attribute ?loc a = mk ?loc (Pcf_attribute a)
let text txt =
let f_txt = List.filter (fun ds -> docstring_body ds <> "") txt in
List.map
(fun ds -> attribute ~loc:(docstring_loc ds) (text_attr ds))
f_txt
let virtual_ ct = Cfk_virtual ct
let concrete o e = Cfk_concrete (o, e)
let attr d a = {d with pcf_attributes = d.pcf_attributes @ [a]}
end
module Val = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(prim = []) name typ =
{
pval_name = name;
pval_type = typ;
pval_attributes = add_docs_attrs docs attrs;
pval_loc = loc;
pval_prim = prim;
}
end
module Md = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) name typ =
{
pmd_name = name;
pmd_type = typ;
pmd_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmd_loc = loc;
}
end
module Ms = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) name syn =
{
pms_name = name;
pms_manifest = syn;
pms_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pms_loc = loc;
}
end
module Mtd = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) ?typ name =
{
pmtd_name = name;
pmtd_type = typ;
pmtd_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmtd_loc = loc;
}
end
module Mb = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = []) name expr =
{
pmb_name = name;
pmb_expr = expr;
pmb_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pmb_loc = loc;
}
end
module Opn = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(override = Fresh) expr =
{
popen_expr = expr;
popen_override = override;
popen_loc = loc;
popen_attributes = add_docs_attrs docs attrs;
}
end
module Incl = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs) mexpr =
{
pincl_mod = mexpr;
pincl_loc = loc;
pincl_attributes = add_docs_attrs docs attrs;
}
end
module Vb = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(text = []) pat expr =
{
pvb_pat = pat;
pvb_expr = expr;
pvb_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pvb_loc = loc;
}
end
module Ci = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = [])
?(virt = Concrete) ?(params = []) name expr =
{
pci_virt = virt;
pci_params = params;
pci_name = name;
pci_expr = expr;
pci_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
pci_loc = loc;
}
end
module Type = struct
let mk ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(text = [])
?(params = [])
?(cstrs = [])
?(kind = Ptype_abstract)
?(priv = Public)
?manifest
name =
{
ptype_name = name;
ptype_params = params;
ptype_cstrs = cstrs;
ptype_kind = kind;
ptype_private = priv;
ptype_manifest = manifest;
ptype_attributes =
add_text_attrs text (add_docs_attrs docs attrs);
ptype_loc = loc;
}
let constructor ?(loc = !default_loc) ?(attrs = []) ?(info = empty_info)
?(vars = []) ?(args = Pcstr_tuple []) ?res name =
{
pcd_name = name;
pcd_vars = vars;
pcd_args = args;
pcd_res = res;
pcd_loc = loc;
pcd_attributes = add_info_attrs info attrs;
}
let field ?(loc = !default_loc) ?(attrs = []) ?(info = empty_info)
?(mut = Immutable) name typ =
{
pld_name = name;
pld_mutable = mut;
pld_type = typ;
pld_loc = loc;
pld_attributes = add_info_attrs info attrs;
}
end
module Te = struct
let mk ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(params = []) ?(priv = Public) path constructors =
{
ptyext_path = path;
ptyext_params = params;
ptyext_constructors = constructors;
ptyext_private = priv;
ptyext_loc = loc;
ptyext_attributes = add_docs_attrs docs attrs;
}
let mk_exception ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
constructor =
{
ptyexn_constructor = constructor;
ptyexn_loc = loc;
ptyexn_attributes = add_docs_attrs docs attrs;
}
let constructor ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(info = empty_info) name kind =
{
pext_name = name;
pext_kind = kind;
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
let decl ?(loc = !default_loc) ?(attrs = []) ?(docs = empty_docs)
?(info = empty_info) ?(vars = []) ?(args = Pcstr_tuple []) ?res name =
{
pext_name = name;
pext_kind = Pext_decl(vars, args, res);
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
let rebind ?(loc = !default_loc) ?(attrs = [])
?(docs = empty_docs) ?(info = empty_info) name lid =
{
pext_name = name;
pext_kind = Pext_rebind lid;
pext_loc = loc;
pext_attributes = add_docs_attrs docs (add_info_attrs info attrs);
}
end
module Csig = struct
let mk self fields =
{
pcsig_self = self;
pcsig_fields = fields;
}
end
module Cstr = struct
let mk self fields =
{
pcstr_self = self;
pcstr_fields = fields;
}
end
module Rf = struct
let mk ?(loc = !default_loc) ?(attrs = []) desc = {
prf_desc = desc;
prf_loc = loc;
prf_attributes = attrs;
}
let tag ?loc ?attrs label const tys =
mk ?loc ?attrs (Rtag (label, const, tys))
let inherit_?loc ty =
mk ?loc (Rinherit ty)
end
module Of = struct
let mk ?(loc = !default_loc) ?(attrs=[]) desc = {
pof_desc = desc;
pof_loc = loc;
pof_attributes = attrs;
}
let tag ?loc ?attrs label ty =
mk ?loc ?attrs (Otag (label, ty))
let inherit_ ?loc ty =
mk ?loc (Oinherit ty)
end
|
7f8f432fe27fcf1e41c481a8d22a3b08dc35b8d9a634b05f8f51419edcca816a | Ericson2314/lighthouse | Random.hs | -----------------------------------------------------------------------------
-- |
-- Module : System.Random
Copyright : ( c ) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer :
-- Stability : stable
-- Portability : portable
--
-- This library deals with the common task of pseudo-random number
-- generation. The library makes it possible to generate repeatable
-- results, by starting with a specified initial random number generator,
-- or to get different results on each run by using the system-initialised
-- generator or by supplying a seed from some other source.
--
The library is split into two layers :
--
-- * A core /random number generator/ provides a supply of bits.
The class ' RandomGen ' provides a common interface to such generators .
The library provides one instance of ' RandomGen ' , the abstract
data type ' StdGen ' . Programmers may , of course , supply their own
instances of ' RandomGen ' .
--
-- * The class 'Random' provides a way to extract values of a particular
-- type from a random number generator. For example, the 'Float'
-- instance of 'Random' allows one to generate random values of type
-- 'Float'.
--
This implementation uses the Portable Combined Generator of L'Ecuyer
[ " System . Random\#LEcuyer " ] for 32 - bit computers , transliterated by
. It has a period of roughly 2.30584e18 .
--
-----------------------------------------------------------------------------
module System.Random
(
-- $intro
-- * Random number generators
RandomGen(next, split, genRange)
-- ** Standard random number generators
, StdGen
, mkStdGen
-- ** The global random number generator
-- $globalrng
, getStdRandom
, getStdGen
, setStdGen
, newStdGen
-- * Random values of various types
, Random ( random, randomR,
randoms, randomRs,
randomIO, randomRIO )
-- * References
-- $references
) where
import Prelude
import Data.Int
#ifdef __NHC__
import CPUTime ( getCPUTime )
import Foreign.Ptr ( Ptr, nullPtr )
import Foreign.C ( CTime, CUInt )
#else
import System.CPUTime ( getCPUTime )
import System.Time ( getClockTime, ClockTime(..) )
#endif
import Data.Char ( isSpace, chr, ord )
import System.IO.Unsafe ( unsafePerformIO )
import Data.IORef
import Numeric ( readDec )
The standard nhc98 implementation of Time . ClockTime does not match
-- the extended one expected in this module, so we lash-up a quick
-- replacement here.
#ifdef __NHC__
data ClockTime = TOD Integer ()
foreign import ccall "time.h time" readtime :: Ptr CTime -> IO CTime
getClockTime :: IO ClockTime
getClockTime = do CTime t <- readtime nullPtr; return (TOD (toInteger t) ())
#endif
| The class ' RandomGen ' provides a common interface to random number
-- generators.
--
-- Minimal complete definition: 'next' and 'split'.
class RandomGen g where
-- |The 'next' operation returns an 'Int' that is uniformly distributed
-- in the range returned by 'genRange' (including both end points),
-- and a new generator.
next :: g -> (Int, g)
|The ' split ' operation allows one to obtain two distinct random number
-- generators. This is very useful in functional programs (for example, when
-- passing a random number generator down to recursive calls), but very
-- little work has been done on statistically robust implementations of
' split ' ( [ " System . " , " System . Random\#Hellekalek " ]
-- are the only examples we know of).
split :: g -> (g, g)
-- |The 'genRange' operation yields the range of values returned by
-- the generator.
--
-- It is required that:
--
* If @(a , b ) = ' genRange ' g@ , then @a < b@.
--
-- * 'genRange' always returns a pair of defined 'Int's.
--
The second condition ensures that ' genRange ' can not examine its
-- argument, and hence the value it returns can be determined only by the
instance of ' RandomGen ' . That in turn allows an implementation to make
-- a single call to 'genRange' to establish a generator's range, without
-- being concerned that the generator returned by (say) 'next' might have
-- a different range to the generator passed to 'next'.
--
-- The default definition spans the full range of 'Int'.
genRange :: g -> (Int,Int)
-- default method
genRange g = (minBound,maxBound)
|
The ' StdGen ' instance of ' RandomGen ' has a ' genRange ' of at least 30 bits .
The result of repeatedly using ' next ' should be at least as statistically
robust as the /Minimal Standard Random Number Generator/ described by
[ " System . Random\#Park " , " System . Random\#Carta " ] .
Until more is known about implementations of ' split ' , all we require is
that ' split ' deliver generators that are ( a ) not identical and
( b ) independently robust in the sense just given .
The ' Show ' and ' Read ' instances of ' StdGen ' provide a primitive way to save the
state of a random number generator .
It is required that ' ( ' show ' g ) = = g@.
In addition , ' read ' may be used to map an arbitrary string ( not necessarily one
produced by ' show ' ) onto a value of type ' StdGen ' . In general , the ' read '
instance of ' StdGen ' has the following properties :
* It guarantees to succeed on any string .
* It guarantees to consume only a finite portion of the string .
* Different argument strings are likely to result in different results .
The 'StdGen' instance of 'RandomGen' has a 'genRange' of at least 30 bits.
The result of repeatedly using 'next' should be at least as statistically
robust as the /Minimal Standard Random Number Generator/ described by
["System.Random\#Park", "System.Random\#Carta"].
Until more is known about implementations of 'split', all we require is
that 'split' deliver generators that are (a) not identical and
(b) independently robust in the sense just given.
The 'Show' and 'Read' instances of 'StdGen' provide a primitive way to save the
state of a random number generator.
It is required that @'read' ('show' g) == g@.
In addition, 'read' may be used to map an arbitrary string (not necessarily one
produced by 'show') onto a value of type 'StdGen'. In general, the 'read'
instance of 'StdGen' has the following properties:
* It guarantees to succeed on any string.
* It guarantees to consume only a finite portion of the string.
* Different argument strings are likely to result in different results.
-}
data StdGen
= StdGen Int32 Int32
instance RandomGen StdGen where
next = stdNext
split = stdSplit
genRange _ = stdRange
instance Show StdGen where
showsPrec p (StdGen s1 s2) =
showsPrec p s1 .
showChar ' ' .
showsPrec p s2
instance Read StdGen where
readsPrec _p = \ r ->
case try_read r of
r@[_] -> r
_ -> [stdFromString r] -- because it shouldn't ever fail.
where
try_read r = do
(s1, r1) <- readDec (dropWhile isSpace r)
(s2, r2) <- readDec (dropWhile isSpace r1)
return (StdGen s1 s2, r2)
If we can not unravel the StdGen from a string , create
one based on the string given .
If we cannot unravel the StdGen from a string, create
one based on the string given.
-}
stdFromString :: String -> (StdGen, String)
stdFromString s = (mkStdGen num, rest)
where (cs, rest) = splitAt 6 s
num = foldl (\a x -> x + 3 * a) 1 (map ord cs)
{- |
The function 'mkStdGen' provides an alternative way of producing an initial
generator, by mapping an 'Int' into a generator. Again, distinct arguments
should be likely to produce distinct generators.
-}
why not Integer ?
mkStdGen s = mkStdGen32 $ fromIntegral s
mkStdGen32 :: Int32 -> StdGen
mkStdGen32 s
| s < 0 = mkStdGen32 (-s)
| otherwise = StdGen (s1+1) (s2+1)
where
(q, s1) = s `divMod` 2147483562
s2 = q `mod` 2147483398
createStdGen :: Integer -> StdGen
createStdGen s = mkStdGen32 $ fromIntegral s
FIXME : 1/2/3 below should be * * ( ) XXX
{- |
With a source of random number supply in hand, the 'Random' class allows the
programmer to extract random values of a variety of types.
Minimal complete definition: 'randomR' and 'random'.
-}
class Random a where
| Takes a range /(lo , and a random number generator
/g/ , and returns a random value uniformly distributed in the closed
interval /[lo , hi]/ , together with a new generator . It is unspecified
-- what happens if /lo>hi/. For continuous types there is no requirement
-- that the values /lo/ and /hi/ are ever produced, but they may be,
-- depending on the implementation and the interval.
randomR :: RandomGen g => (a,a) -> g -> (a,g)
-- | The same as 'randomR', but using a default range determined by the type:
--
* For bounded types ( instances of ' Bounded ' , such as ' ' ) ,
-- the range is normally the whole type.
--
-- * For fractional types, the range is normally the semi-closed interval
@[0,1)@.
--
-- * For 'Integer', the range is (arbitrarily) the range of 'Int'.
random :: RandomGen g => g -> (a, g)
-- | Plural variant of 'randomR', producing an infinite list of
-- random values instead of returning a new generator.
randomRs :: RandomGen g => (a,a) -> g -> [a]
randomRs ival g = x : randomRs ival g' where (x,g') = randomR ival g
-- | Plural variant of 'random', producing an infinite list of
-- random values instead of returning a new generator.
randoms :: RandomGen g => g -> [a]
randoms g = (\(x,g') -> x : randoms g') (random g)
-- | A variant of 'randomR' that uses the global random number generator
-- (see "System.Random#globalrng").
randomRIO :: (a,a) -> IO a
randomRIO range = getStdRandom (randomR range)
-- | A variant of 'random' that uses the global random number generator
-- (see "System.Random#globalrng").
randomIO :: IO a
randomIO = getStdRandom random
instance Random Int where
randomR (a,b) g = randomIvalInteger (toInteger a, toInteger b) g
random g = randomR (minBound,maxBound) g
instance Random Char where
randomR (a,b) g =
case (randomIvalInteger (toInteger (ord a), toInteger (ord b)) g) of
(x,g) -> (chr x, g)
random g = randomR (minBound,maxBound) g
instance Random Bool where
randomR (a,b) g =
case (randomIvalInteger (toInteger (bool2Int a), toInteger (bool2Int b)) g) of
(x, g) -> (int2Bool x, g)
where
bool2Int False = 0
bool2Int True = 1
int2Bool 0 = False
int2Bool _ = True
random g = randomR (minBound,maxBound) g
instance Random Integer where
randomR ival g = randomIvalInteger ival g
random g = randomR (toInteger (minBound::Int), toInteger (maxBound::Int)) g
instance Random Double where
randomR ival g = randomIvalDouble ival id g
random g = randomR (0::Double,1) g
-- hah, so you thought you were saving cycles by using Float?
instance Random Float where
random g = randomIvalDouble (0::Double,1) realToFrac g
randomR (a,b) g = randomIvalDouble (realToFrac a, realToFrac b) realToFrac g
mkStdRNG :: Integer -> IO StdGen
mkStdRNG o = do
ct <- getCPUTime
(TOD sec psec) <- getClockTime
return (createStdGen (sec * 12345 + psec + ct + o))
randomIvalInteger :: (RandomGen g, Num a) => (Integer, Integer) -> g -> (a, g)
randomIvalInteger (l,h) rng
| l > h = randomIvalInteger (h,l) rng
| otherwise = case (f n 1 rng) of (v, rng') -> (fromInteger (l + v `mod` k), rng')
where
k = h - l + 1
b = 2147483561
n = iLogBase b k
f 0 acc g = (acc, g)
f n acc g =
let
(x,g') = next g
in
f (n-1) (fromIntegral x + acc * b) g'
randomIvalDouble :: (RandomGen g, Fractional a) => (Double, Double) -> (Double -> a) -> g -> (a, g)
randomIvalDouble (l,h) fromDouble rng
| l > h = randomIvalDouble (h,l) fromDouble rng
| otherwise =
case (randomIvalInteger (toInteger (minBound::Int32), toInteger (maxBound::Int32)) rng) of
(x, rng') ->
let
scaled_x =
fromDouble ((l+h)/2) +
fromDouble ((h-l) / realToFrac int32Range) *
fromIntegral (x::Int32)
in
(scaled_x, rng')
int32Range :: Integer
int32Range = toInteger (maxBound::Int32) - toInteger (minBound::Int32)
iLogBase :: Integer -> Integer -> Integer
iLogBase b i = if i < b then 1 else 1 + iLogBase b (i `div` b)
stdRange :: (Int,Int)
stdRange = (0, 2147483562)
stdNext :: StdGen -> (Int, StdGen)
Returns values in the range stdRange
stdNext (StdGen s1 s2) = (fromIntegral z', StdGen s1'' s2'')
where z' = if z < 1 then z + 2147483562 else z
z = s1'' - s2''
k = s1 `quot` 53668
s1' = 40014 * (s1 - k * 53668) - k * 12211
s1'' = if s1' < 0 then s1' + 2147483563 else s1'
k' = s2 `quot` 52774
s2' = 40692 * (s2 - k' * 52774) - k' * 3791
s2'' = if s2' < 0 then s2' + 2147483399 else s2'
stdSplit :: StdGen -> (StdGen, StdGen)
stdSplit std@(StdGen s1 s2)
= (left, right)
where
-- no statistical foundation for this!
left = StdGen new_s1 t2
right = StdGen t1 new_s2
new_s1 | s1 == 2147483562 = 1
| otherwise = s1 + 1
new_s2 | s2 == 1 = 2147483398
| otherwise = s2 - 1
StdGen t1 t2 = snd (next std)
-- The global random number generator
$ globalrng # globalrng #
There is a single , implicit , global random number generator of type
' StdGen ' , held in some global variable maintained by the ' IO ' monad . It is
initialised automatically in some system - dependent fashion , for example , by
using the time of day , or Linux 's kernel random number generator . To get
deterministic behaviour , use ' setStdGen ' .
There is a single, implicit, global random number generator of type
'StdGen', held in some global variable maintained by the 'IO' monad. It is
initialised automatically in some system-dependent fashion, for example, by
using the time of day, or Linux's kernel random number generator. To get
deterministic behaviour, use 'setStdGen'.
-}
-- |Sets the global random number generator.
setStdGen :: StdGen -> IO ()
setStdGen sgen = writeIORef theStdGen sgen
-- |Gets the global random number generator.
getStdGen :: IO StdGen
getStdGen = readIORef theStdGen
theStdGen :: IORef StdGen
theStdGen = unsafePerformIO $ do
rng <- mkStdRNG 0
newIORef rng
-- |Applies 'split' to the current global random generator,
updates it with one of the results , and returns the other .
newStdGen :: IO StdGen
newStdGen = atomicModifyIORef theStdGen split
|Uses the supplied function to get a value from the current global
random generator , and updates the global generator with the new generator
returned by the function . For example , @rollDice@ gets a random integer
between 1 and 6 :
> rollDice : : IO Int
> rollDice = getStdRandom ( randomR ( 1,6 ) )
random generator, and updates the global generator with the new generator
returned by the function. For example, @rollDice@ gets a random integer
between 1 and 6:
> rollDice :: IO Int
> rollDice = getStdRandom (randomR (1,6))
-}
getStdRandom :: (StdGen -> (a,StdGen)) -> IO a
getStdRandom f = atomicModifyIORef theStdGen (swap . f)
where swap (v,g) = (g,v)
$ references
1 . FW # Burton # Burton and RL Page , /Distributed random number generation/ ,
Journal of Functional Programming , 2(2):203 - 212 , April 1992 .
2 . SK # Park # Park , and KW Miller , /Random number generators -
good ones are hard to find/ , Comm ACM 31(10 ) , Oct 1988 , pp1192 - 1201 .
3 . DG # Carta # Carta , /Two fast implementations of the minimal standard
random number generator/ , Comm ACM , 33(1 ) , Jan 1990 , pp87 - 88 .
4 . P # Hellekalek # Hellekalek , /Don\'t trust parallel Monte Carlo/ ,
Department of Mathematics , University of Salzburg ,
< /~peter/pads98.ps > , 1998 .
5 . # L'Ecuyer , /Efficient and portable combined random
number generators/ , Comm ACM , 31(6 ) , Jun 1988 , pp742 - 749 .
The Web site < > is a great source of information .
1. FW #Burton# Burton and RL Page, /Distributed random number generation/,
Journal of Functional Programming, 2(2):203-212, April 1992.
2. SK #Park# Park, and KW Miller, /Random number generators -
good ones are hard to find/, Comm ACM 31(10), Oct 1988, pp1192-1201.
3. DG #Carta# Carta, /Two fast implementations of the minimal standard
random number generator/, Comm ACM, 33(1), Jan 1990, pp87-88.
4. P #Hellekalek# Hellekalek, /Don\'t trust parallel Monte Carlo/,
Department of Mathematics, University of Salzburg,
</~peter/pads98.ps>, 1998.
5. Pierre #LEcuyer# L'Ecuyer, /Efficient and portable combined random
number generators/, Comm ACM, 31(6), Jun 1988, pp742-749.
The Web site </> is a great source of information.
-}
| null | https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/random/System/Random.hs | haskell | ---------------------------------------------------------------------------
|
Module : System.Random
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : stable
Portability : portable
This library deals with the common task of pseudo-random number
generation. The library makes it possible to generate repeatable
results, by starting with a specified initial random number generator,
or to get different results on each run by using the system-initialised
generator or by supplying a seed from some other source.
* A core /random number generator/ provides a supply of bits.
* The class 'Random' provides a way to extract values of a particular
type from a random number generator. For example, the 'Float'
instance of 'Random' allows one to generate random values of type
'Float'.
---------------------------------------------------------------------------
$intro
* Random number generators
** Standard random number generators
** The global random number generator
$globalrng
* Random values of various types
* References
$references
the extended one expected in this module, so we lash-up a quick
replacement here.
generators.
Minimal complete definition: 'next' and 'split'.
|The 'next' operation returns an 'Int' that is uniformly distributed
in the range returned by 'genRange' (including both end points),
and a new generator.
generators. This is very useful in functional programs (for example, when
passing a random number generator down to recursive calls), but very
little work has been done on statistically robust implementations of
are the only examples we know of).
|The 'genRange' operation yields the range of values returned by
the generator.
It is required that:
* 'genRange' always returns a pair of defined 'Int's.
argument, and hence the value it returns can be determined only by the
a single call to 'genRange' to establish a generator's range, without
being concerned that the generator returned by (say) 'next' might have
a different range to the generator passed to 'next'.
The default definition spans the full range of 'Int'.
default method
because it shouldn't ever fail.
|
The function 'mkStdGen' provides an alternative way of producing an initial
generator, by mapping an 'Int' into a generator. Again, distinct arguments
should be likely to produce distinct generators.
|
With a source of random number supply in hand, the 'Random' class allows the
programmer to extract random values of a variety of types.
Minimal complete definition: 'randomR' and 'random'.
what happens if /lo>hi/. For continuous types there is no requirement
that the values /lo/ and /hi/ are ever produced, but they may be,
depending on the implementation and the interval.
| The same as 'randomR', but using a default range determined by the type:
the range is normally the whole type.
* For fractional types, the range is normally the semi-closed interval
* For 'Integer', the range is (arbitrarily) the range of 'Int'.
| Plural variant of 'randomR', producing an infinite list of
random values instead of returning a new generator.
| Plural variant of 'random', producing an infinite list of
random values instead of returning a new generator.
| A variant of 'randomR' that uses the global random number generator
(see "System.Random#globalrng").
| A variant of 'random' that uses the global random number generator
(see "System.Random#globalrng").
hah, so you thought you were saving cycles by using Float?
no statistical foundation for this!
The global random number generator
|Sets the global random number generator.
|Gets the global random number generator.
|Applies 'split' to the current global random generator, | Copyright : ( c ) The University of Glasgow 2001
The library is split into two layers :
The class ' RandomGen ' provides a common interface to such generators .
The library provides one instance of ' RandomGen ' , the abstract
data type ' StdGen ' . Programmers may , of course , supply their own
instances of ' RandomGen ' .
This implementation uses the Portable Combined Generator of L'Ecuyer
[ " System . Random\#LEcuyer " ] for 32 - bit computers , transliterated by
. It has a period of roughly 2.30584e18 .
module System.Random
(
RandomGen(next, split, genRange)
, StdGen
, mkStdGen
, getStdRandom
, getStdGen
, setStdGen
, newStdGen
, Random ( random, randomR,
randoms, randomRs,
randomIO, randomRIO )
) where
import Prelude
import Data.Int
#ifdef __NHC__
import CPUTime ( getCPUTime )
import Foreign.Ptr ( Ptr, nullPtr )
import Foreign.C ( CTime, CUInt )
#else
import System.CPUTime ( getCPUTime )
import System.Time ( getClockTime, ClockTime(..) )
#endif
import Data.Char ( isSpace, chr, ord )
import System.IO.Unsafe ( unsafePerformIO )
import Data.IORef
import Numeric ( readDec )
The standard nhc98 implementation of Time . ClockTime does not match
#ifdef __NHC__
data ClockTime = TOD Integer ()
foreign import ccall "time.h time" readtime :: Ptr CTime -> IO CTime
getClockTime :: IO ClockTime
getClockTime = do CTime t <- readtime nullPtr; return (TOD (toInteger t) ())
#endif
| The class ' RandomGen ' provides a common interface to random number
class RandomGen g where
next :: g -> (Int, g)
|The ' split ' operation allows one to obtain two distinct random number
' split ' ( [ " System . " , " System . Random\#Hellekalek " ]
split :: g -> (g, g)
* If @(a , b ) = ' genRange ' g@ , then @a < b@.
The second condition ensures that ' genRange ' can not examine its
instance of ' RandomGen ' . That in turn allows an implementation to make
genRange :: g -> (Int,Int)
genRange g = (minBound,maxBound)
|
The ' StdGen ' instance of ' RandomGen ' has a ' genRange ' of at least 30 bits .
The result of repeatedly using ' next ' should be at least as statistically
robust as the /Minimal Standard Random Number Generator/ described by
[ " System . Random\#Park " , " System . Random\#Carta " ] .
Until more is known about implementations of ' split ' , all we require is
that ' split ' deliver generators that are ( a ) not identical and
( b ) independently robust in the sense just given .
The ' Show ' and ' Read ' instances of ' StdGen ' provide a primitive way to save the
state of a random number generator .
It is required that ' ( ' show ' g ) = = g@.
In addition , ' read ' may be used to map an arbitrary string ( not necessarily one
produced by ' show ' ) onto a value of type ' StdGen ' . In general , the ' read '
instance of ' StdGen ' has the following properties :
* It guarantees to succeed on any string .
* It guarantees to consume only a finite portion of the string .
* Different argument strings are likely to result in different results .
The 'StdGen' instance of 'RandomGen' has a 'genRange' of at least 30 bits.
The result of repeatedly using 'next' should be at least as statistically
robust as the /Minimal Standard Random Number Generator/ described by
["System.Random\#Park", "System.Random\#Carta"].
Until more is known about implementations of 'split', all we require is
that 'split' deliver generators that are (a) not identical and
(b) independently robust in the sense just given.
The 'Show' and 'Read' instances of 'StdGen' provide a primitive way to save the
state of a random number generator.
It is required that @'read' ('show' g) == g@.
In addition, 'read' may be used to map an arbitrary string (not necessarily one
produced by 'show') onto a value of type 'StdGen'. In general, the 'read'
instance of 'StdGen' has the following properties:
* It guarantees to succeed on any string.
* It guarantees to consume only a finite portion of the string.
* Different argument strings are likely to result in different results.
-}
data StdGen
= StdGen Int32 Int32
instance RandomGen StdGen where
next = stdNext
split = stdSplit
genRange _ = stdRange
instance Show StdGen where
showsPrec p (StdGen s1 s2) =
showsPrec p s1 .
showChar ' ' .
showsPrec p s2
instance Read StdGen where
readsPrec _p = \ r ->
case try_read r of
r@[_] -> r
where
try_read r = do
(s1, r1) <- readDec (dropWhile isSpace r)
(s2, r2) <- readDec (dropWhile isSpace r1)
return (StdGen s1 s2, r2)
If we can not unravel the StdGen from a string , create
one based on the string given .
If we cannot unravel the StdGen from a string, create
one based on the string given.
-}
stdFromString :: String -> (StdGen, String)
stdFromString s = (mkStdGen num, rest)
where (cs, rest) = splitAt 6 s
num = foldl (\a x -> x + 3 * a) 1 (map ord cs)
why not Integer ?
mkStdGen s = mkStdGen32 $ fromIntegral s
mkStdGen32 :: Int32 -> StdGen
mkStdGen32 s
| s < 0 = mkStdGen32 (-s)
| otherwise = StdGen (s1+1) (s2+1)
where
(q, s1) = s `divMod` 2147483562
s2 = q `mod` 2147483398
createStdGen :: Integer -> StdGen
createStdGen s = mkStdGen32 $ fromIntegral s
FIXME : 1/2/3 below should be * * ( ) XXX
class Random a where
| Takes a range /(lo , and a random number generator
/g/ , and returns a random value uniformly distributed in the closed
interval /[lo , hi]/ , together with a new generator . It is unspecified
randomR :: RandomGen g => (a,a) -> g -> (a,g)
* For bounded types ( instances of ' Bounded ' , such as ' ' ) ,
@[0,1)@.
random :: RandomGen g => g -> (a, g)
randomRs :: RandomGen g => (a,a) -> g -> [a]
randomRs ival g = x : randomRs ival g' where (x,g') = randomR ival g
randoms :: RandomGen g => g -> [a]
randoms g = (\(x,g') -> x : randoms g') (random g)
randomRIO :: (a,a) -> IO a
randomRIO range = getStdRandom (randomR range)
randomIO :: IO a
randomIO = getStdRandom random
instance Random Int where
randomR (a,b) g = randomIvalInteger (toInteger a, toInteger b) g
random g = randomR (minBound,maxBound) g
instance Random Char where
randomR (a,b) g =
case (randomIvalInteger (toInteger (ord a), toInteger (ord b)) g) of
(x,g) -> (chr x, g)
random g = randomR (minBound,maxBound) g
instance Random Bool where
randomR (a,b) g =
case (randomIvalInteger (toInteger (bool2Int a), toInteger (bool2Int b)) g) of
(x, g) -> (int2Bool x, g)
where
bool2Int False = 0
bool2Int True = 1
int2Bool 0 = False
int2Bool _ = True
random g = randomR (minBound,maxBound) g
instance Random Integer where
randomR ival g = randomIvalInteger ival g
random g = randomR (toInteger (minBound::Int), toInteger (maxBound::Int)) g
instance Random Double where
randomR ival g = randomIvalDouble ival id g
random g = randomR (0::Double,1) g
instance Random Float where
random g = randomIvalDouble (0::Double,1) realToFrac g
randomR (a,b) g = randomIvalDouble (realToFrac a, realToFrac b) realToFrac g
mkStdRNG :: Integer -> IO StdGen
mkStdRNG o = do
ct <- getCPUTime
(TOD sec psec) <- getClockTime
return (createStdGen (sec * 12345 + psec + ct + o))
randomIvalInteger :: (RandomGen g, Num a) => (Integer, Integer) -> g -> (a, g)
randomIvalInteger (l,h) rng
| l > h = randomIvalInteger (h,l) rng
| otherwise = case (f n 1 rng) of (v, rng') -> (fromInteger (l + v `mod` k), rng')
where
k = h - l + 1
b = 2147483561
n = iLogBase b k
f 0 acc g = (acc, g)
f n acc g =
let
(x,g') = next g
in
f (n-1) (fromIntegral x + acc * b) g'
randomIvalDouble :: (RandomGen g, Fractional a) => (Double, Double) -> (Double -> a) -> g -> (a, g)
randomIvalDouble (l,h) fromDouble rng
| l > h = randomIvalDouble (h,l) fromDouble rng
| otherwise =
case (randomIvalInteger (toInteger (minBound::Int32), toInteger (maxBound::Int32)) rng) of
(x, rng') ->
let
scaled_x =
fromDouble ((l+h)/2) +
fromDouble ((h-l) / realToFrac int32Range) *
fromIntegral (x::Int32)
in
(scaled_x, rng')
int32Range :: Integer
int32Range = toInteger (maxBound::Int32) - toInteger (minBound::Int32)
iLogBase :: Integer -> Integer -> Integer
iLogBase b i = if i < b then 1 else 1 + iLogBase b (i `div` b)
stdRange :: (Int,Int)
stdRange = (0, 2147483562)
stdNext :: StdGen -> (Int, StdGen)
Returns values in the range stdRange
stdNext (StdGen s1 s2) = (fromIntegral z', StdGen s1'' s2'')
where z' = if z < 1 then z + 2147483562 else z
z = s1'' - s2''
k = s1 `quot` 53668
s1' = 40014 * (s1 - k * 53668) - k * 12211
s1'' = if s1' < 0 then s1' + 2147483563 else s1'
k' = s2 `quot` 52774
s2' = 40692 * (s2 - k' * 52774) - k' * 3791
s2'' = if s2' < 0 then s2' + 2147483399 else s2'
stdSplit :: StdGen -> (StdGen, StdGen)
stdSplit std@(StdGen s1 s2)
= (left, right)
where
left = StdGen new_s1 t2
right = StdGen t1 new_s2
new_s1 | s1 == 2147483562 = 1
| otherwise = s1 + 1
new_s2 | s2 == 1 = 2147483398
| otherwise = s2 - 1
StdGen t1 t2 = snd (next std)
$ globalrng # globalrng #
There is a single , implicit , global random number generator of type
' StdGen ' , held in some global variable maintained by the ' IO ' monad . It is
initialised automatically in some system - dependent fashion , for example , by
using the time of day , or Linux 's kernel random number generator . To get
deterministic behaviour , use ' setStdGen ' .
There is a single, implicit, global random number generator of type
'StdGen', held in some global variable maintained by the 'IO' monad. It is
initialised automatically in some system-dependent fashion, for example, by
using the time of day, or Linux's kernel random number generator. To get
deterministic behaviour, use 'setStdGen'.
-}
setStdGen :: StdGen -> IO ()
setStdGen sgen = writeIORef theStdGen sgen
getStdGen :: IO StdGen
getStdGen = readIORef theStdGen
theStdGen :: IORef StdGen
theStdGen = unsafePerformIO $ do
rng <- mkStdRNG 0
newIORef rng
updates it with one of the results , and returns the other .
newStdGen :: IO StdGen
newStdGen = atomicModifyIORef theStdGen split
|Uses the supplied function to get a value from the current global
random generator , and updates the global generator with the new generator
returned by the function . For example , @rollDice@ gets a random integer
between 1 and 6 :
> rollDice : : IO Int
> rollDice = getStdRandom ( randomR ( 1,6 ) )
random generator, and updates the global generator with the new generator
returned by the function. For example, @rollDice@ gets a random integer
between 1 and 6:
> rollDice :: IO Int
> rollDice = getStdRandom (randomR (1,6))
-}
getStdRandom :: (StdGen -> (a,StdGen)) -> IO a
getStdRandom f = atomicModifyIORef theStdGen (swap . f)
where swap (v,g) = (g,v)
$ references
1 . FW # Burton # Burton and RL Page , /Distributed random number generation/ ,
Journal of Functional Programming , 2(2):203 - 212 , April 1992 .
2 . SK # Park # Park , and KW Miller , /Random number generators -
good ones are hard to find/ , Comm ACM 31(10 ) , Oct 1988 , pp1192 - 1201 .
3 . DG # Carta # Carta , /Two fast implementations of the minimal standard
random number generator/ , Comm ACM , 33(1 ) , Jan 1990 , pp87 - 88 .
4 . P # Hellekalek # Hellekalek , /Don\'t trust parallel Monte Carlo/ ,
Department of Mathematics , University of Salzburg ,
< /~peter/pads98.ps > , 1998 .
5 . # L'Ecuyer , /Efficient and portable combined random
number generators/ , Comm ACM , 31(6 ) , Jun 1988 , pp742 - 749 .
The Web site < > is a great source of information .
1. FW #Burton# Burton and RL Page, /Distributed random number generation/,
Journal of Functional Programming, 2(2):203-212, April 1992.
2. SK #Park# Park, and KW Miller, /Random number generators -
good ones are hard to find/, Comm ACM 31(10), Oct 1988, pp1192-1201.
3. DG #Carta# Carta, /Two fast implementations of the minimal standard
random number generator/, Comm ACM, 33(1), Jan 1990, pp87-88.
4. P #Hellekalek# Hellekalek, /Don\'t trust parallel Monte Carlo/,
Department of Mathematics, University of Salzburg,
</~peter/pads98.ps>, 1998.
5. Pierre #LEcuyer# L'Ecuyer, /Efficient and portable combined random
number generators/, Comm ACM, 31(6), Jun 1988, pp742-749.
The Web site </> is a great source of information.
-}
|
32952137a9004bd9e0c295648333c053d2b05ad96cef2b0f8d1461ca4db00346 | exercism/scheme | test.scm | (load "test-util.ss")
(define test-cases
`((test-success "stating something" equal? response-for
'("Tom-ay-to, tom-aaaah-to.") "Whatever.")
(test-success "shouting" equal? response-for '("WATCH OUT!")
"Whoa, chill out!")
(test-success "shouting gibberish" equal? response-for
'("FCECDFCAAB") "Whoa, chill out!")
(test-success "asking a question" equal? response-for
'("Does this cryogenic chamber make me look fat?") "Sure.")
(test-success "asking a numeric question" equal?
response-for '("You are, what, like 15?") "Sure.")
(test-success "asking gibberish" equal? response-for
'("fffbbcbeab?") "Sure.")
(test-success "talking forcefully" equal? response-for
'("Hi there!") "Whatever.")
(test-success "using acronyms in regular speech" equal? response-for
'("It's OK if you don't want to go work for NASA.")
"Whatever.")
(test-success "forceful question" equal? response-for
'("WHAT'S GOING ON?") "Calm down, I know what I'm doing!")
(test-success "shouting numbers" equal? response-for
'("1, 2, 3 GO!") "Whoa, chill out!")
(test-success "no letters" equal? response-for '("1, 2, 3")
"Whatever.")
(test-success "question with no letters" equal? response-for
'("4?") "Sure.")
(test-success "shouting with special characters" equal? response-for
'("ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!")
"Whoa, chill out!")
(test-success "shouting with no exclamation mark" equal?
response-for '("I HATE THE DENTIST") "Whoa, chill out!")
(test-success "statement containing question mark" equal? response-for
'("Ending with ? means a question.") "Whatever.")
(test-success "non-letters with question" equal?
response-for '(":) ?") "Sure.")
(test-success "prattling on" equal? response-for
'("Wait! Hang on. Are you going to be OK?") "Sure.")
(test-success "silence" equal? response-for '("")
"Fine. Be that way!")
(test-success "prolonged silence" equal? response-for
'(" ") "Fine. Be that way!")
(test-success "alternate silence" equal? response-for
'("\t\t\t\t\t\t\t\t\t\t") "Fine. Be that way!")
(test-success "multiple line question" equal? response-for
'("\nDoes this cryogenic chamber make me look fat?\nNo.")
"Whatever.")
(test-success "starting with whitespace" equal? response-for
'(" hmmmmmmm...") "Whatever.")
(test-success "ending with whitespace" equal? response-for
'("Okay if like my spacebar quite a bit? ") "Sure.")
(test-success "other whitespace" equal? response-for
'("\n\r \t") "Fine. Be that way!")
(test-success "non-question ending with whitespace" equal? response-for
'("This is a statement ending with whitespace ")
"Whatever.")))
(run-with-cli "bob.scm" (list test-cases))
| null | https://raw.githubusercontent.com/exercism/scheme/2064dd5e5d5a03a06417d28c33c5349bec97dad7/exercises/practice/bob/test.scm | scheme | (load "test-util.ss")
(define test-cases
`((test-success "stating something" equal? response-for
'("Tom-ay-to, tom-aaaah-to.") "Whatever.")
(test-success "shouting" equal? response-for '("WATCH OUT!")
"Whoa, chill out!")
(test-success "shouting gibberish" equal? response-for
'("FCECDFCAAB") "Whoa, chill out!")
(test-success "asking a question" equal? response-for
'("Does this cryogenic chamber make me look fat?") "Sure.")
(test-success "asking a numeric question" equal?
response-for '("You are, what, like 15?") "Sure.")
(test-success "asking gibberish" equal? response-for
'("fffbbcbeab?") "Sure.")
(test-success "talking forcefully" equal? response-for
'("Hi there!") "Whatever.")
(test-success "using acronyms in regular speech" equal? response-for
'("It's OK if you don't want to go work for NASA.")
"Whatever.")
(test-success "forceful question" equal? response-for
'("WHAT'S GOING ON?") "Calm down, I know what I'm doing!")
(test-success "shouting numbers" equal? response-for
'("1, 2, 3 GO!") "Whoa, chill out!")
(test-success "no letters" equal? response-for '("1, 2, 3")
"Whatever.")
(test-success "question with no letters" equal? response-for
'("4?") "Sure.")
(test-success "shouting with special characters" equal? response-for
'("ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!")
"Whoa, chill out!")
(test-success "shouting with no exclamation mark" equal?
response-for '("I HATE THE DENTIST") "Whoa, chill out!")
(test-success "statement containing question mark" equal? response-for
'("Ending with ? means a question.") "Whatever.")
(test-success "non-letters with question" equal?
response-for '(":) ?") "Sure.")
(test-success "prattling on" equal? response-for
'("Wait! Hang on. Are you going to be OK?") "Sure.")
(test-success "silence" equal? response-for '("")
"Fine. Be that way!")
(test-success "prolonged silence" equal? response-for
'(" ") "Fine. Be that way!")
(test-success "alternate silence" equal? response-for
'("\t\t\t\t\t\t\t\t\t\t") "Fine. Be that way!")
(test-success "multiple line question" equal? response-for
'("\nDoes this cryogenic chamber make me look fat?\nNo.")
"Whatever.")
(test-success "starting with whitespace" equal? response-for
'(" hmmmmmmm...") "Whatever.")
(test-success "ending with whitespace" equal? response-for
'("Okay if like my spacebar quite a bit? ") "Sure.")
(test-success "other whitespace" equal? response-for
'("\n\r \t") "Fine. Be that way!")
(test-success "non-question ending with whitespace" equal? response-for
'("This is a statement ending with whitespace ")
"Whatever.")))
(run-with-cli "bob.scm" (list test-cases))
| |
e734e1946663ad5f1395a67f9e58fa39afa85519e45e76cb282275b05b3b91d4 | sgimenez/laby | sound.mli |
* Copyright ( C ) 2007 - 2014 The laby team
* You have permission to copy , modify , and redistribute under the
* terms of the GPL-3.0 . For full license terms , see gpl-3.0.txt .
* Copyright (C) 2007-2014 The laby team
* You have permission to copy, modify, and redistribute under the
* terms of the GPL-3.0. For full license terms, see gpl-3.0.txt.
*)
val conf : Conf.ut
val conf_enabled : bool Conf.t
val action : State.action -> unit
| null | https://raw.githubusercontent.com/sgimenez/laby/47f9560eb827790d26900bb553719afb4b0554ea/src/sound.mli | ocaml |
* Copyright ( C ) 2007 - 2014 The laby team
* You have permission to copy , modify , and redistribute under the
* terms of the GPL-3.0 . For full license terms , see gpl-3.0.txt .
* Copyright (C) 2007-2014 The laby team
* You have permission to copy, modify, and redistribute under the
* terms of the GPL-3.0. For full license terms, see gpl-3.0.txt.
*)
val conf : Conf.ut
val conf_enabled : bool Conf.t
val action : State.action -> unit
| |
63cb5e4f66d8888fc4d155bc07009de80e26f3da89857df3f1cb49f2a3f50d8a | mbenke/zpf2013 | examples3.hs | import Control.Monad(ap)
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
f <$> x = pure f <*> x
instance = > Applicative m where
pure = return
( < * > ) = ap
instance Monad m => Applicative m where
pure = return
(<*>) = ap
-}
instance Applicative Maybe where
pure = return
(<*>) = ap
instance Applicative IO where
pure = return
(<*>) = ap
instance Applicative [] where
pure = (:[])
fs <*> xs = concat $ for fs (for xs)
for = flip map
mif c t e = do { b <- c; if b then t else e }
aif fc ft fe = cond <$> fc <*> ft <*> fe where
cond c t e =if c then t else e
main = do
putStrLn "Monad:"
mif (return True) (putStrLn "True") (putStrLn "False")
putStrLn "Idiom:"
aif (pure True) (putStrLn "True") (putStrLn "False")
| null | https://raw.githubusercontent.com/mbenke/zpf2013/85f32747e17f07a74e1c3cb064b1d6acaca3f2f0/Slides/09Idiom/examples3.hs | haskell | import Control.Monad(ap)
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
f <$> x = pure f <*> x
instance = > Applicative m where
pure = return
( < * > ) = ap
instance Monad m => Applicative m where
pure = return
(<*>) = ap
-}
instance Applicative Maybe where
pure = return
(<*>) = ap
instance Applicative IO where
pure = return
(<*>) = ap
instance Applicative [] where
pure = (:[])
fs <*> xs = concat $ for fs (for xs)
for = flip map
mif c t e = do { b <- c; if b then t else e }
aif fc ft fe = cond <$> fc <*> ft <*> fe where
cond c t e =if c then t else e
main = do
putStrLn "Monad:"
mif (return True) (putStrLn "True") (putStrLn "False")
putStrLn "Idiom:"
aif (pure True) (putStrLn "True") (putStrLn "False")
| |
aebca269c7656c655fd693f7c42f269f9a2a1a0198011725b5419f23a482a463 | faylang/fay | Recursive.hs | {-# OPTIONS -fno-warn-name-shadowing #-}
# LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module Language.Haskell.Names.Recursive
( computeInterfaces
, getInterfaces
, annotateModule
) where
import Fay.Compiler.Prelude
import Fay.Compiler.ModuleT
import Language.Haskell.Names.Annotated
import Language.Haskell.Names.Exports
import Language.Haskell.Names.Imports
import Language.Haskell.Names.ModuleSymbols
import Language.Haskell.Names.Open.Base
import Language.Haskell.Names.ScopeUtils
import Language.Haskell.Names.SyntaxUtils
import Language.Haskell.Names.Types
import Data.Data (Data)
import Data.Foldable
import Data.Graph (flattenSCC, stronglyConnComp)
import qualified Data.Set as Set
import Language.Haskell.Exts
-- | Take a set of modules and return a list of sets, where each sets for
-- a strongly connected component in the import graph.
-- The boolean determines if imports using @SOURCE@ are taken into account.
groupModules :: forall l . [Module l] -> [[Module l]]
groupModules modules =
map flattenSCC $ stronglyConnComp $ map mkNode modules
where
mkNode :: Module l -> (Module l, ModuleName (), [ModuleName ()])
mkNode m =
( m
, dropAnn $ getModuleName m
, map (dropAnn . importModule) $ getImports m
)
-- | Annotate a module with scoping information. This assumes that all
-- module dependencies have been resolved and cached — usually you need
to run ' computeInterfaces ' first , unless you have one module in
-- isolation.
annotateModule
:: (MonadModule m, ModuleInfo m ~ Symbols, Data l, SrcInfo l, Eq l)
=> Language -- ^ base language
-> [Extension] -- ^ global extensions (e.g. specified on the command line)
-> Module l -- ^ input module
-> m (Module (Scoped l)) -- ^ output (annotated) module
annotateModule lang exts mod@(Module lm mh os is ds) = do
let extSet = moduleExtensions lang exts mod
(imp, impTbl) <- processImports extSet is
let tbl = moduleTable impTbl mod
(exp, _syms) <- processExports tbl mod
let
lm' = none lm
os' = fmap noScope os
is' = imp
ds' = annotate (initialScope tbl) `map` ds
mh' = flip fmap mh $ \(ModuleHead lh n mw _me) ->
let
lh' = none lh
n' = noScope n
mw' = fmap noScope mw
me' = exp
in ModuleHead lh' n' mw' me'
return $ Module lm' mh' os' is' ds'
annotateModule _ _ _ = error "annotateModule: non-standard modules are not supported"
-- | Compute interfaces for a set of mutually recursive modules and write
-- the results to the cache. Return the set of import/export errors.
findFixPoint
:: (Ord l, Data l, MonadModule m, ModuleInfo m ~ Symbols)
=> [(Module l, ExtensionSet)]
-- ^ module and all extensions with which it is to be compiled.
-- Use 'moduleExtensions' to build this list.
-> m (Set.Set (Error l))
findFixPoint mods = go mods (map (const mempty) mods) where
go mods syms = do
forM_ (zip syms mods) $ \(s,(m, _)) -> insertInCache (getModuleName m) s
(syms', errors) <- liftM unzip $ forM mods $ \(m, extSet) -> do
(imp, impTbl) <- processImports extSet $ getImports m
let tbl = moduleTable impTbl m
(exp, syms) <- processExports tbl m
return (syms, foldMap getErrors imp <> foldMap getErrors exp)
if syms' == syms
then return $ mconcat errors
else go mods syms'
-- | 'computeInterfaces' takes a list of possibly recursive modules and
-- computes the interface of each module. The computed interfaces are
-- written into the @m@'s cache and are available to further computations
-- in this monad.
--
-- Returns the set of import/export errors. Note that the interfaces are
-- registered in the cache regardless of whether there are any errors, but
-- if there are errors, the interfaces may be incomplete.
computeInterfaces
:: (MonadModule m, ModuleInfo m ~ Symbols, Data l, SrcInfo l, Ord l)
=> Language -- ^ base language
-> [Extension] -- ^ global extensions (e.g. specified on the command line)
-> [Module l] -- ^ input modules
-> m (Set.Set (Error l)) -- ^ errors in export or import lists
computeInterfaces lang exts =
liftM fold . mapM findFixPoint . map supplyExtensions . groupModules
where
supplyExtensions = map $ \m -> (m, moduleExtensions lang exts m)
| Like ' computeInterfaces ' , but also returns a list of interfaces , one
-- per module and in the same order
getInterfaces
:: (MonadModule m, ModuleInfo m ~ Symbols, Data l, SrcInfo l, Ord l)
=> Language -- ^ base language
-> [Extension] -- ^ global extensions (e.g. specified on the command line)
-> [Module l] -- ^ input modules
-> m ([Symbols], Set.Set (Error l)) -- ^ output modules, and errors in export or import lists
getInterfaces lang exts mods = do
errs <- computeInterfaces lang exts mods
ifaces <- forM mods $ \mod ->
let modName = getModuleName mod in
fromMaybe (error $ msg modName) `liftM` lookupInCache modName
return (ifaces, errs)
where
msg modName = "getInterfaces: module " ++ modToString modName ++ " is not in the cache"
| null | https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/src/haskell-names/Language/Haskell/Names/Recursive.hs | haskell | # OPTIONS -fno-warn-name-shadowing #
| Take a set of modules and return a list of sets, where each sets for
a strongly connected component in the import graph.
The boolean determines if imports using @SOURCE@ are taken into account.
| Annotate a module with scoping information. This assumes that all
module dependencies have been resolved and cached — usually you need
isolation.
^ base language
^ global extensions (e.g. specified on the command line)
^ input module
^ output (annotated) module
| Compute interfaces for a set of mutually recursive modules and write
the results to the cache. Return the set of import/export errors.
^ module and all extensions with which it is to be compiled.
Use 'moduleExtensions' to build this list.
| 'computeInterfaces' takes a list of possibly recursive modules and
computes the interface of each module. The computed interfaces are
written into the @m@'s cache and are available to further computations
in this monad.
Returns the set of import/export errors. Note that the interfaces are
registered in the cache regardless of whether there are any errors, but
if there are errors, the interfaces may be incomplete.
^ base language
^ global extensions (e.g. specified on the command line)
^ input modules
^ errors in export or import lists
per module and in the same order
^ base language
^ global extensions (e.g. specified on the command line)
^ input modules
^ output modules, and errors in export or import lists | # LANGUAGE NoImplicitPrelude #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
module Language.Haskell.Names.Recursive
( computeInterfaces
, getInterfaces
, annotateModule
) where
import Fay.Compiler.Prelude
import Fay.Compiler.ModuleT
import Language.Haskell.Names.Annotated
import Language.Haskell.Names.Exports
import Language.Haskell.Names.Imports
import Language.Haskell.Names.ModuleSymbols
import Language.Haskell.Names.Open.Base
import Language.Haskell.Names.ScopeUtils
import Language.Haskell.Names.SyntaxUtils
import Language.Haskell.Names.Types
import Data.Data (Data)
import Data.Foldable
import Data.Graph (flattenSCC, stronglyConnComp)
import qualified Data.Set as Set
import Language.Haskell.Exts
groupModules :: forall l . [Module l] -> [[Module l]]
groupModules modules =
map flattenSCC $ stronglyConnComp $ map mkNode modules
where
mkNode :: Module l -> (Module l, ModuleName (), [ModuleName ()])
mkNode m =
( m
, dropAnn $ getModuleName m
, map (dropAnn . importModule) $ getImports m
)
to run ' computeInterfaces ' first , unless you have one module in
annotateModule
:: (MonadModule m, ModuleInfo m ~ Symbols, Data l, SrcInfo l, Eq l)
annotateModule lang exts mod@(Module lm mh os is ds) = do
let extSet = moduleExtensions lang exts mod
(imp, impTbl) <- processImports extSet is
let tbl = moduleTable impTbl mod
(exp, _syms) <- processExports tbl mod
let
lm' = none lm
os' = fmap noScope os
is' = imp
ds' = annotate (initialScope tbl) `map` ds
mh' = flip fmap mh $ \(ModuleHead lh n mw _me) ->
let
lh' = none lh
n' = noScope n
mw' = fmap noScope mw
me' = exp
in ModuleHead lh' n' mw' me'
return $ Module lm' mh' os' is' ds'
annotateModule _ _ _ = error "annotateModule: non-standard modules are not supported"
findFixPoint
:: (Ord l, Data l, MonadModule m, ModuleInfo m ~ Symbols)
=> [(Module l, ExtensionSet)]
-> m (Set.Set (Error l))
findFixPoint mods = go mods (map (const mempty) mods) where
go mods syms = do
forM_ (zip syms mods) $ \(s,(m, _)) -> insertInCache (getModuleName m) s
(syms', errors) <- liftM unzip $ forM mods $ \(m, extSet) -> do
(imp, impTbl) <- processImports extSet $ getImports m
let tbl = moduleTable impTbl m
(exp, syms) <- processExports tbl m
return (syms, foldMap getErrors imp <> foldMap getErrors exp)
if syms' == syms
then return $ mconcat errors
else go mods syms'
computeInterfaces
:: (MonadModule m, ModuleInfo m ~ Symbols, Data l, SrcInfo l, Ord l)
computeInterfaces lang exts =
liftM fold . mapM findFixPoint . map supplyExtensions . groupModules
where
supplyExtensions = map $ \m -> (m, moduleExtensions lang exts m)
| Like ' computeInterfaces ' , but also returns a list of interfaces , one
getInterfaces
:: (MonadModule m, ModuleInfo m ~ Symbols, Data l, SrcInfo l, Ord l)
getInterfaces lang exts mods = do
errs <- computeInterfaces lang exts mods
ifaces <- forM mods $ \mod ->
let modName = getModuleName mod in
fromMaybe (error $ msg modName) `liftM` lookupInCache modName
return (ifaces, errs)
where
msg modName = "getInterfaces: module " ++ modToString modName ++ " is not in the cache"
|
e860cf36e090513ab463c5de883e48b87958a47ae8c1f52fda02089b57527810 | astrada/ocaml-extjs | ext_chart_Highlight.ml | class type t =
object('self)
inherit Ext_Base.t
method highlightCfg : _ Js.t Js.prop
method highlightItem : _ Js.t -> unit Js.meth
method unHighlightItem : unit Js.meth
end
class type configs =
object('self)
inherit Ext_Base.configs
method highlight : _ Js.t Js.prop
end
class type events =
object
inherit Ext_Base.events
end
class type statics =
object
inherit Ext_Base.statics
end
let get_static () = Js.Unsafe.variable "Ext.chart.Highlight"
let static = get_static ()
let of_configs c = Js.Unsafe.coerce c
let to_configs o = Js.Unsafe.coerce o
| null | https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/lib/ext_chart_Highlight.ml | ocaml | class type t =
object('self)
inherit Ext_Base.t
method highlightCfg : _ Js.t Js.prop
method highlightItem : _ Js.t -> unit Js.meth
method unHighlightItem : unit Js.meth
end
class type configs =
object('self)
inherit Ext_Base.configs
method highlight : _ Js.t Js.prop
end
class type events =
object
inherit Ext_Base.events
end
class type statics =
object
inherit Ext_Base.statics
end
let get_static () = Js.Unsafe.variable "Ext.chart.Highlight"
let static = get_static ()
let of_configs c = Js.Unsafe.coerce c
let to_configs o = Js.Unsafe.coerce o
| |
5c0feb25ee133236994ab788e341ee4a402c7d4a9f5a90538417501e94783d92 | lynaghk/reflex | project.clj | (defproject com.keminglabs/reflex "0.1.2-SNAPSHOT"
:description "ClojureScript state propagation."
:license {:name "BSD" :url "-3-Clause"}
:dependencies [[org.clojure/clojure "1.4.0"]]
:min-lein-version "2.0.0"
:plugins [[lein-cljsbuild "0.2.5"]]
:source-paths ["src/clj" "src/cljs"]
:cljsbuild {:builds {:test {:source-path "test/integration"
:compiler {:output-to "out/test/integration.js"
:optimizations :whitespace
:pretty-print true}}}
:test-commands {"integration" ["phantomjs"
"test/integration/runner.coffee"]}})
| null | https://raw.githubusercontent.com/lynaghk/reflex/a891d9c4857af3c47de92af865fad324ab9f23e3/project.clj | clojure | (defproject com.keminglabs/reflex "0.1.2-SNAPSHOT"
:description "ClojureScript state propagation."
:license {:name "BSD" :url "-3-Clause"}
:dependencies [[org.clojure/clojure "1.4.0"]]
:min-lein-version "2.0.0"
:plugins [[lein-cljsbuild "0.2.5"]]
:source-paths ["src/clj" "src/cljs"]
:cljsbuild {:builds {:test {:source-path "test/integration"
:compiler {:output-to "out/test/integration.js"
:optimizations :whitespace
:pretty-print true}}}
:test-commands {"integration" ["phantomjs"
"test/integration/runner.coffee"]}})
| |
fc054af6fe7ada59be7181f1c1b9e8d974297d8e41cc0ca68ec2527ba6830458 | abdulapopoola/SICPBook | eceval-machine-non-tail-recursive.scm | (define eceval-operations
(list
; install inbuilt scheme operators
(list 'read read)
; install operators from scheme-operators.scm
(list 'self-evaluating? self-evaluating?)
(list 'variable? variable?)
(list 'quoted? quoted?)
(list 'text-of-quotation text-of-quotation)
(list 'assignment? assignment?)
(list 'assignment-variable assignment-variable)
(list 'assignment-value assignment-value)
(list 'definition? definition?)
(list 'definition-variable definition-variable)
(list 'definition-value definition-value)
(list 'lambda? lambda?)
(list 'lambda-parameters lambda-parameters)
(list 'lambda-body lambda-body)
(list 'if? if?)
(list 'if-predicate if-predicate)
(list 'if-alternative if-alternative)
(list 'if-consequent if-consequent)
(list 'begin? begin?)
(list 'begin-actions begin-actions)
(list 'first-exp first-exp)
(list 'last-exp? last-exp?)
(list 'rest-exps rest-exps)
(list 'application? application?)
(list 'operator operator)
(list 'operands operands)
(list 'no-operands? no-operands?)
(list 'first-operand first-operand)
(list 'rest-operands rest-operands)
; install operators from machine-operations.scm
(list 'true? true?)
(list 'make-procedure make-procedure)
(list 'compound-procedure? compound-procedure?)
(list 'procedure-parameters procedure-parameters)
(list 'procedure-body procedure-body)
(list 'procedure-environment procedure-environment)
(list 'extend-environment extend-environment)
(list 'lookup-variable-value lookup-variable-value)
(list 'set-variable-value! set-variable-value!)
(list 'define-variable! define-variable!)
(list 'primitive-procedure? primitive-procedure?)
(list 'apply-primitive-procedure apply-primitive-procedure)
(list 'prompt-for-input prompt-for-input)
(list 'announce-output announce-output)
(list 'user-print user-print)
(list 'empty-arglist empty-arglist)
(list 'adjoin-arg adjoin-arg)
(list 'last-operand? last-operand?)
(list 'no-more-exps? no-more-exps?)
(list 'get-global-environment get-global-environment)))
(define eceval
(make-machine
'(exp env val proc argl continue unev)
eceval-operations
'(
read-eval-print-loop
(perform (op initialize-stack))
(perform (op prompt-for-input)
(const ";;; EC-Eval input:"))
(assign exp (op read))
(assign env (op get-global-environment))
(assign continue (label print-result))
(goto (label eval-dispatch))
print-result
;; Add stack tracing
(perform (op print-stack-statistics))
(perform (op announce-output)
(const ";;; EC-Eval value:"))
(perform (op user-print) (reg val))
(goto (label read-eval-print-loop))
unknown-expression-type
(assign
val
(const unknown-expression-type-error))
(goto (label signal-error))
unknown-procedure-type
; clean up stack (from apply-dispatch):
(restore continue)
(assign
val
(const unknown-procedure-type-error))
(goto (label signal-error))
signal-error
(perform (op user-print) (reg val))
(goto (label read-eval-print-loop))
eval-dispatch
(test (op self-evaluating?) (reg exp))
(branch (label ev-self-eval))
(test (op variable?) (reg exp))
(branch (label ev-variable))
(test (op quoted?) (reg exp))
(branch (label ev-quoted))
(test (op assignment?) (reg exp))
(branch (label ev-assignment))
(test (op definition?) (reg exp))
(branch (label ev-definition))
(test (op if?) (reg exp))
(branch (label ev-if))
(test (op lambda?) (reg exp))
(branch (label ev-lambda))
(test (op begin?) (reg exp))
(branch (label ev-begin))
(test (op application?) (reg exp))
(branch (label ev-application))
(goto (label unknown-expression-type))
ev-self-eval
(assign val (reg exp))
(goto (reg continue))
ev-variable
(assign val
(op lookup-variable-value)
(reg exp)
(reg env))
(goto (reg continue))
ev-quoted
(assign val
(op text-of-quotation)
(reg exp))
(goto (reg continue))
ev-lambda
(assign unev
(op lambda-parameters)
(reg exp))
(assign exp
(op lambda-body)
(reg exp))
(assign val
(op make-procedure)
(reg unev)
(reg exp)
(reg env))
(goto (reg continue))
ev-application
(save continue)
(save env)
(assign unev (op operands) (reg exp))
(save unev)
(assign exp (op operator) (reg exp))
(assign
continue (label ev-appl-did-operator))
(goto (label eval-dispatch))
ev-appl-did-operator
(restore unev) ; the operands
(restore env)
(assign argl (op empty-arglist))
(assign proc (reg val)) ; the operator
(test (op no-operands?) (reg unev))
(branch (label apply-dispatch))
(save proc)
ev-appl-operand-loop
(save argl)
(assign exp
(op first-operand)
(reg unev))
(test (op last-operand?) (reg unev))
(branch (label ev-appl-last-arg))
(save env)
(save unev)
(assign continue
(label ev-appl-accumulate-arg))
(goto (label eval-dispatch))
ev-appl-accumulate-arg
(restore unev)
(restore env)
(restore argl)
(assign argl
(op adjoin-arg)
(reg val)
(reg argl))
(assign unev
(op rest-operands)
(reg unev))
(goto (label ev-appl-operand-loop))
ev-appl-last-arg
(assign continue
(label ev-appl-accum-last-arg))
(goto (label eval-dispatch))
ev-appl-accum-last-arg
(restore argl)
(assign argl
(op adjoin-arg)
(reg val)
(reg argl))
(restore proc)
(goto (label apply-dispatch))
apply-dispatch
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-apply))
(test (op compound-procedure?) (reg proc))
(branch (label compound-apply))
(goto (label unknown-procedure-type))
primitive-apply
(assign val (op apply-primitive-procedure)
(reg proc)
(reg argl))
(restore continue)
(goto (reg continue))
compound-apply
(assign unev
(op procedure-parameters)
(reg proc))
(assign env
(op procedure-environment)
(reg proc))
(assign env
(op extend-environment)
(reg unev)
(reg argl)
(reg env))
(assign unev
(op procedure-body)
(reg proc))
(goto (label ev-sequence))
ev-begin
(assign unev
(op begin-actions)
(reg exp))
(save continue)
(goto (label ev-sequence))
ev-sequence
(test (op no-more-exps?) (reg unev))
(branch (label ev-sequence-end))
(assign exp (op first-exp) (reg unev))
(save unev)
(save env)
(assign continue
(label ev-sequence-continue))
(goto (label eval-dispatch))
ev-sequence-continue
(restore env)
(restore unev)
(assign unev (op rest-exps) (reg unev))
(goto (label ev-sequence))
ev-sequence-end
(restore continue)
(goto (reg continue))
ev-if
(save exp) ; save expression for later
(save env)
(save continue)
(assign continue (label ev-if-decide))
(assign exp (op if-predicate) (reg exp))
; evaluate the predicate:
(goto (label eval-dispatch))
ev-if-decide
(restore continue)
(restore env)
(restore exp)
(test (op true?) (reg val))
(branch (label ev-if-consequent))
ev-if-alternative
(assign exp (op if-alternative) (reg exp))
(goto (label eval-dispatch))
ev-if-consequent
(assign exp (op if-consequent) (reg exp))
(goto (label eval-dispatch))
ev-assignment
(assign unev
(op assignment-variable)
(reg exp))
(save unev) ; save variable for later
(assign exp
(op assignment-value)
(reg exp))
(save env)
(save continue)
(assign continue
(label ev-assignment-1))
; evaluate the assignment value:
(goto (label eval-dispatch))
ev-assignment-1
(restore continue)
(restore env)
(restore unev)
(perform (op set-variable-value!)
(reg unev)
(reg val)
(reg env))
(assign val
(const ok))
(goto (reg continue))
ev-definition
(assign unev
(op definition-variable)
(reg exp))
(save unev) ; save variable for later
(assign exp
(op definition-value)
(reg exp))
(save env)
(save continue)
(assign continue (label ev-definition-1))
; evaluate the definition value:
(goto (label eval-dispatch))
ev-definition-1
(restore continue)
(restore env)
(restore unev)
(perform (op define-variable!)
(reg unev)
(reg val)
(reg env))
(assign val (const ok))
(goto (reg continue)))))
'(EC-EVAL LOADED) | null | https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%205/5.4/eceval-machine-non-tail-recursive.scm | scheme | install inbuilt scheme operators
install operators from scheme-operators.scm
install operators from machine-operations.scm
Add stack tracing
clean up stack (from apply-dispatch):
the operands
the operator
save expression for later
evaluate the predicate:
save variable for later
evaluate the assignment value:
save variable for later
evaluate the definition value: | (define eceval-operations
(list
(list 'read read)
(list 'self-evaluating? self-evaluating?)
(list 'variable? variable?)
(list 'quoted? quoted?)
(list 'text-of-quotation text-of-quotation)
(list 'assignment? assignment?)
(list 'assignment-variable assignment-variable)
(list 'assignment-value assignment-value)
(list 'definition? definition?)
(list 'definition-variable definition-variable)
(list 'definition-value definition-value)
(list 'lambda? lambda?)
(list 'lambda-parameters lambda-parameters)
(list 'lambda-body lambda-body)
(list 'if? if?)
(list 'if-predicate if-predicate)
(list 'if-alternative if-alternative)
(list 'if-consequent if-consequent)
(list 'begin? begin?)
(list 'begin-actions begin-actions)
(list 'first-exp first-exp)
(list 'last-exp? last-exp?)
(list 'rest-exps rest-exps)
(list 'application? application?)
(list 'operator operator)
(list 'operands operands)
(list 'no-operands? no-operands?)
(list 'first-operand first-operand)
(list 'rest-operands rest-operands)
(list 'true? true?)
(list 'make-procedure make-procedure)
(list 'compound-procedure? compound-procedure?)
(list 'procedure-parameters procedure-parameters)
(list 'procedure-body procedure-body)
(list 'procedure-environment procedure-environment)
(list 'extend-environment extend-environment)
(list 'lookup-variable-value lookup-variable-value)
(list 'set-variable-value! set-variable-value!)
(list 'define-variable! define-variable!)
(list 'primitive-procedure? primitive-procedure?)
(list 'apply-primitive-procedure apply-primitive-procedure)
(list 'prompt-for-input prompt-for-input)
(list 'announce-output announce-output)
(list 'user-print user-print)
(list 'empty-arglist empty-arglist)
(list 'adjoin-arg adjoin-arg)
(list 'last-operand? last-operand?)
(list 'no-more-exps? no-more-exps?)
(list 'get-global-environment get-global-environment)))
(define eceval
(make-machine
'(exp env val proc argl continue unev)
eceval-operations
'(
read-eval-print-loop
(perform (op initialize-stack))
(perform (op prompt-for-input)
(const ";;; EC-Eval input:"))
(assign exp (op read))
(assign env (op get-global-environment))
(assign continue (label print-result))
(goto (label eval-dispatch))
print-result
(perform (op print-stack-statistics))
(perform (op announce-output)
(const ";;; EC-Eval value:"))
(perform (op user-print) (reg val))
(goto (label read-eval-print-loop))
unknown-expression-type
(assign
val
(const unknown-expression-type-error))
(goto (label signal-error))
unknown-procedure-type
(restore continue)
(assign
val
(const unknown-procedure-type-error))
(goto (label signal-error))
signal-error
(perform (op user-print) (reg val))
(goto (label read-eval-print-loop))
eval-dispatch
(test (op self-evaluating?) (reg exp))
(branch (label ev-self-eval))
(test (op variable?) (reg exp))
(branch (label ev-variable))
(test (op quoted?) (reg exp))
(branch (label ev-quoted))
(test (op assignment?) (reg exp))
(branch (label ev-assignment))
(test (op definition?) (reg exp))
(branch (label ev-definition))
(test (op if?) (reg exp))
(branch (label ev-if))
(test (op lambda?) (reg exp))
(branch (label ev-lambda))
(test (op begin?) (reg exp))
(branch (label ev-begin))
(test (op application?) (reg exp))
(branch (label ev-application))
(goto (label unknown-expression-type))
ev-self-eval
(assign val (reg exp))
(goto (reg continue))
ev-variable
(assign val
(op lookup-variable-value)
(reg exp)
(reg env))
(goto (reg continue))
ev-quoted
(assign val
(op text-of-quotation)
(reg exp))
(goto (reg continue))
ev-lambda
(assign unev
(op lambda-parameters)
(reg exp))
(assign exp
(op lambda-body)
(reg exp))
(assign val
(op make-procedure)
(reg unev)
(reg exp)
(reg env))
(goto (reg continue))
ev-application
(save continue)
(save env)
(assign unev (op operands) (reg exp))
(save unev)
(assign exp (op operator) (reg exp))
(assign
continue (label ev-appl-did-operator))
(goto (label eval-dispatch))
ev-appl-did-operator
(restore env)
(assign argl (op empty-arglist))
(test (op no-operands?) (reg unev))
(branch (label apply-dispatch))
(save proc)
ev-appl-operand-loop
(save argl)
(assign exp
(op first-operand)
(reg unev))
(test (op last-operand?) (reg unev))
(branch (label ev-appl-last-arg))
(save env)
(save unev)
(assign continue
(label ev-appl-accumulate-arg))
(goto (label eval-dispatch))
ev-appl-accumulate-arg
(restore unev)
(restore env)
(restore argl)
(assign argl
(op adjoin-arg)
(reg val)
(reg argl))
(assign unev
(op rest-operands)
(reg unev))
(goto (label ev-appl-operand-loop))
ev-appl-last-arg
(assign continue
(label ev-appl-accum-last-arg))
(goto (label eval-dispatch))
ev-appl-accum-last-arg
(restore argl)
(assign argl
(op adjoin-arg)
(reg val)
(reg argl))
(restore proc)
(goto (label apply-dispatch))
apply-dispatch
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-apply))
(test (op compound-procedure?) (reg proc))
(branch (label compound-apply))
(goto (label unknown-procedure-type))
primitive-apply
(assign val (op apply-primitive-procedure)
(reg proc)
(reg argl))
(restore continue)
(goto (reg continue))
compound-apply
(assign unev
(op procedure-parameters)
(reg proc))
(assign env
(op procedure-environment)
(reg proc))
(assign env
(op extend-environment)
(reg unev)
(reg argl)
(reg env))
(assign unev
(op procedure-body)
(reg proc))
(goto (label ev-sequence))
ev-begin
(assign unev
(op begin-actions)
(reg exp))
(save continue)
(goto (label ev-sequence))
ev-sequence
(test (op no-more-exps?) (reg unev))
(branch (label ev-sequence-end))
(assign exp (op first-exp) (reg unev))
(save unev)
(save env)
(assign continue
(label ev-sequence-continue))
(goto (label eval-dispatch))
ev-sequence-continue
(restore env)
(restore unev)
(assign unev (op rest-exps) (reg unev))
(goto (label ev-sequence))
ev-sequence-end
(restore continue)
(goto (reg continue))
ev-if
(save env)
(save continue)
(assign continue (label ev-if-decide))
(assign exp (op if-predicate) (reg exp))
(goto (label eval-dispatch))
ev-if-decide
(restore continue)
(restore env)
(restore exp)
(test (op true?) (reg val))
(branch (label ev-if-consequent))
ev-if-alternative
(assign exp (op if-alternative) (reg exp))
(goto (label eval-dispatch))
ev-if-consequent
(assign exp (op if-consequent) (reg exp))
(goto (label eval-dispatch))
ev-assignment
(assign unev
(op assignment-variable)
(reg exp))
(assign exp
(op assignment-value)
(reg exp))
(save env)
(save continue)
(assign continue
(label ev-assignment-1))
(goto (label eval-dispatch))
ev-assignment-1
(restore continue)
(restore env)
(restore unev)
(perform (op set-variable-value!)
(reg unev)
(reg val)
(reg env))
(assign val
(const ok))
(goto (reg continue))
ev-definition
(assign unev
(op definition-variable)
(reg exp))
(assign exp
(op definition-value)
(reg exp))
(save env)
(save continue)
(assign continue (label ev-definition-1))
(goto (label eval-dispatch))
ev-definition-1
(restore continue)
(restore env)
(restore unev)
(perform (op define-variable!)
(reg unev)
(reg val)
(reg env))
(assign val (const ok))
(goto (reg continue)))))
'(EC-EVAL LOADED) |
a4a8c0c142072f808f71f8887a0a96b6736b0b8872aac82956a8344f6dda2b27 | jrm-code-project/LISP-Machine | peek.lisp | -*- Mode : LISP ; Package : TV ; Base:8 ; : ZL -*-
* * ( c ) Copyright 1980 Massachusetts Institute of Technology * *
PEEK -- displays status information about the Lisp Machine
Define the display modes , and how to select them .
(DEFVAR *PEEK-DEFAULT-MODE-ALIST* NIL
"This variable has one element for each Peek display mode.
Elements are added by calls to DEFINE-PEEK-MODE which appear in this file
and the other source files of PEEK, and are executed at load time.
Each element looks like:
/(character display-function menu-item-string no-updating-flag long-documentation).
That is also what the five arguments to DEFINE-PEEK-MODE look like.
The menu-item-string is a short phrase of documentation which is also
what appears in the menu proper.
The display function is what is called to update the display.
NO-UPDATING-FLAG is either T or NIL. If T, it means simply call the
function once and leave what it prints on the screen. Normally it is NIL,
which means that the updating function returns a set of scroll items.")
(DEFVAR *PEEK-MENU-ITEM-ALIST* NIL
"This is the item alist for the command menu.
The first element of each element is the menu item string.
The third element is the corresponding element of *PEEK-DEFAULT-MODE-ALIST*.")
(DEFMACRO DEFINE-PEEK-MODE (FUNCTION CHARACTER DOCUMENTATION &OPTIONAL FUNCTION-P
&BODY LONG-DOCUMENTATION) ;this is to get the indentation right
(DECLARE (ARGLIST FUNCTION CHARACTER DOCUMENTATION &OPTIONAL FUNCTION-P LONG-DOCUMENTATION))
`(DEFINE-PEEK-MODE-1 ',FUNCTION ,CHARACTER ,DOCUMENTATION ,FUNCTION-P ,(CAR LONG-DOCUMENTATION)))
(DEFUN DEFINE-PEEK-MODE-1 (FUNCTION CHARACTER DOCUMENTATION FUNCTION-P LONG-DOCUMENTATION)
;character lossage
(IF (NUMBERP CHARACTER) (SETQ CHARACTER (INT-CHAR CHARACTER)))
(WITHOUT-INTERRUPTS
(SETQ *PEEK-DEFAULT-MODE-ALIST*
(NCONC (DELQ (ASSQ CHARACTER *PEEK-DEFAULT-MODE-ALIST*) *PEEK-DEFAULT-MODE-ALIST*)
(NCONS (LIST CHARACTER FUNCTION DOCUMENTATION
FUNCTION-P LONG-DOCUMENTATION))))
(SETQ *PEEK-MENU-ITEM-ALIST*
(MAPCAR (LAMBDA (ELT)
`(,(THIRD ELT) :VALUE ,ELT
:DOCUMENTATION ,(OR (FIFTH ELT) "This PEEK mode is undocumented.")))
*PEEK-DEFAULT-MODE-ALIST*))))
;;; This is meant to be called inside the PEEK-TOP-LEVEL,
and MODE should be a character and the first arg can be a numeric argument .
(DEFUN PEEK-SET-MODE (WINDOW MODE &REST ARGS &AUX OLD-MODE)
;character lossage
(IF (NUMBERP MODE) (SETQ MODE (INT-CHAR MODE)))
(WHEN (SETQ MODE (ASSQ MODE *PEEK-DEFAULT-MODE-ALIST*))
(SETQ OLD-MODE (LABEL-STRING (SEND WINDOW :LABEL)))
(SEND (SEND (SEND WINDOW :SUPERIOR) :GET-PANE 'MENU)
:SET-HIGHLIGHTED-ITEMS
(LIST (SYS:ASSOC-EQUALP (THIRD MODE) *PEEK-MENU-ITEM-ALIST*)))
(SEND WINDOW :SET-LABEL (THIRD MODE))
(IF (FOURTH MODE)
;; If you want to execute only once,
(UNWIND-PROTECT
(APPLY (SECOND MODE) WINDOW ARGS)
;; Then on exit restore the old mode in the menu and label.
;; Since probably the typeout window is going away now
;; and that old mode's data is reappearing.
(PEEK-ASSURE-NO-TYPEOUT WINDOW)
(DOLIST (ELT *PEEK-DEFAULT-MODE-ALIST*)
(IF (EQUALP OLD-MODE (THIRD ELT))
(RETURN (SETQ MODE ELT))))
(SEND (SEND (SEND WINDOW :SUPERIOR) :GET-PANE 'MENU)
:SET-HIGHLIGHTED-ITEMS
(LIST (SYS:ASSOC-EQUALP (THIRD MODE) *PEEK-MENU-ITEM-ALIST*)))
(SEND WINDOW :SET-LABEL (THIRD MODE)))
;; Here if we are entering a mode that really does update.
;; We stay in it semipermanently.
(PEEK-ASSURE-NO-TYPEOUT WINDOW)
(SEND WINDOW :SET-DISPLAY-ITEM (APPLY (SECOND MODE) ARGS)))
T))
Windows for PEEK .
(DEFFLAVOR BASIC-PEEK ((NEEDS-REDISPLAY NIL))
(SCROLL-MOUSE-MIXIN SCROLL-WINDOW-WITH-TYPEOUT FULL-SCREEN-HACK-MIXIN)
:SETTABLE-INSTANCE-VARIABLES
:GETTABLE-INSTANCE-VARIABLES
(:DEFAULT-INIT-PLIST :SAVE-BITS T
:LABEL "Peek"
:TRUNCATION T)
(:DOCUMENTATION :SPECIAL-PURPOSE "The actual peek window. This has the capability
to display in a PEEK display mode."))
(DEFMETHOD (BASIC-PEEK :NAME-FOR-SELECTION) ()
(STRING-APPEND "Peek: " (LABEL-STRING LABEL)))
(DEFFLAVOR PEEK-WINDOW () (PROCESS-MIXIN TV:INITIALLY-INVISIBLE-MIXIN BASIC-PEEK)
(:DEFAULT-INIT-PLIST :PROCESS
'(PEEK-STANDALONE-TOP-LEVEL :SPECIAL-PDL-SIZE #o4000
:REGULAR-PDL-SIZE #o10000))
(:DOCUMENTATION :COMBINATION "Peek window with a process.
Usable as a stand-alone window that does PEEK display,
but with no menu -- only keyboard commands will be available."))
(DEFUN PEEK-MOUSE-CLICK (ITEM LEADER-TO-COMPLEMENT)
(DECLARE (:SELF-FLAVOR BASIC-PEEK))
(SETQ NEEDS-REDISPLAY T)
(SETF (ARRAY-LEADER ITEM (+ SCROLL-ITEM-LEADER-OFFSET LEADER-TO-COMPLEMENT))
(NOT (ARRAY-LEADER ITEM (+ SCROLL-ITEM-LEADER-OFFSET LEADER-TO-COMPLEMENT)))))
;This is the top level function that runs in the process of a window of flavor PEEK.
(DEFUN PEEK-STANDALONE-TOP-LEVEL (WINDOW)
(PEEK-TOP-LEVEL WINDOW #/HELP)
(DO-FOREVER
(DESELECT-AND-MAYBE-BURY-WINDOW (SEND WINDOW :ALIAS-FOR-SELECTED-WINDOWS) :FIRST)
(PEEK-TOP-LEVEL WINDOW NIL)))
Peek frames that have command menus of modes , as well as a peek - window
;;; to do the actual displaying in.
(DEFFLAVOR PEEK-FRAME ()
(PROCESS-MIXIN
FRAME-DONT-SELECT-INFERIORS-WITH-MOUSE-MIXIN
BORDERED-CONSTRAINT-FRAME-WITH-SHARED-IO-BUFFER)
(:DEFAULT-INIT-PLIST :SAVE-BITS :DELAYED :PROCESS ))
(DEFMETHOD (PEEK-FRAME :BEFORE :INIT) (INIT-PLIST)
(SETQ PANES (LIST
(IF (GETL INIT-PLIST '(:PROCESS))
`(PEEK PEEK-WINDOW :SAVE-BITS NIL :PROCESS ,(GET INIT-PLIST :PROCESS))
'(PEEK PEEK-WINDOW :SAVE-BITS NIL))
`(MENU DYNAMIC-HIGHLIGHTING-COMMAND-MENU-PANE
:FONT-MAP ,(LIST FONTS:CPTFONT) ;not the usual large menu font
:LABEL "Peek Modes"
:ITEM-LIST-POINTER *PEEK-MENU-ITEM-ALIST*)))
(SETQ CONSTRAINTS `((MAIN . ((MENU PEEK)
((MENU :ASK :PANE-SIZE))
((PEEK :EVEN)))))))
(DEFMETHOD (PEEK-FRAME :AFTER :INIT) (IGNORE)
(LET ((PANE (SEND SELF :GET-PANE 'PEEK)))
(SEND SELF :SELECT-PANE PANE)
(SETQ PROCESS (SEND PANE :PROCESS))))
(DEFMETHOD (PEEK-FRAME :BEFORE :EXPOSE) (&REST IGNORE)
(OR EXPOSED-P
(EQUAL *PEEK-MENU-ITEM-ALIST*
(SEND (SEND SELF :GET-PANE 'MENU) :ITEM-LIST))
(SEND SELF :SET-CONFIGURATION 'MAIN)))
(DEFFLAVOR DYNAMIC-HIGHLIGHTING-COMMAND-MENU-PANE ()
(DYNAMIC-ITEM-LIST-MIXIN MENU-HIGHLIGHTING-MIXIN COMMAND-MENU))
(COMPILE-FLAVOR-METHODS PEEK-FRAME PEEK-WINDOW DYNAMIC-HIGHLIGHTING-COMMAND-MENU-PANE)
(DEFUN PEEK (&OPTIONAL INITIAL-MODE)
"Select a new or old Peek window. An argument sets the Peek display mode."
(SELECT-OR-CREATE-WINDOW-OF-FLAVOR 'PEEK-FRAME)
(IF INITIAL-MODE
(SEND SELECTED-WINDOW :FORCE-KBD-INPUT
(TYPECASE INITIAL-MODE
(STRING (CHAR INITIAL-MODE 0))
(SYMBOL (CHAR (SYMBOL-NAME INITIAL-MODE) 0))
(T INITIAL-MODE))))
(AWAIT-WINDOW-EXPOSURE))
(DEFVAR PEEK-SLEEP-TIME 120.
"This is how long, in 60'ths of a second, to wait between updates of the screen in PEEK.")
;;; This is the command reading loop.
(DEFUN PEEK-TOP-LEVEL (WINDOW MODE)
(COND-EVERY
((AND MODE (SYMBOLP MODE)) (SETQ MODE (SYMBOL-NAME MODE)))
((STRINGP MODE) (SETQ MODE (CHAR MODE 0)))
((CHARACTERP MODE) (SETQ MODE (CHAR-INT MODE)))
;character lossage
((NUMBERP MODE) (SEND WINDOW :FORCE-KBD-INPUT MODE)))
(BLOCK PEEK
(DO-FOREVER
(CATCH-ERROR-RESTART ((SYS:ABORT ERROR) "Return to PEEK command level.")
(DO ((SLEEP-TIME PEEK-SLEEP-TIME)
(WAKEUP-TIME (TIME-DIFFERENCE (TIME) (- PEEK-SLEEP-TIME)))
(wakeup-time-passed nil)
(*TERMINAL-IO* (SEND WINDOW :TYPEOUT-WINDOW))
(ARG)
(CHAR))
(())
(when (or (TIME-LESSP WAKEUP-TIME (TIME)) wakeup-time-passed)
(SETQ WAKEUP-TIME (TIME-DIFFERENCE (TIME) (- SLEEP-TIME)))
(setq wakeup-time-passed nil))
(OR (= SLEEP-TIME 0)
(PROCESS-WAIT "Peek Timeout or TYI"
(LAMBDA (TIME FLAG-LOC STREAM PEEK-WINDOW)
(if (SHEET-EXPOSED-P PEEK-WINDOW)
(OR wakeup-time-passed
(TIME-LESSP TIME (TIME))
(CONTENTS FLAG-LOC)
(SEND STREAM :LISTEN))
;;If sheet not exposed, notice when wakeup-time is passed
;;If we don't do this and sheet is deexposed for a long time, peek
;;stops redisplaying
(when (time-lessp time (time))
(setq wakeup-time-passed t)
nil)))
WAKEUP-TIME
(LOCATE-IN-INSTANCE WINDOW 'NEEDS-REDISPLAY)
*TERMINAL-IO*
(SEND WINDOW :ALIAS-FOR-SELECTED-WINDOWS)))
(DO ()
((PROGN (PEEK-ASSURE-NO-TYPEOUT WINDOW)
(NULL (SETQ CHAR (SEND *TERMINAL-IO* :ANY-TYI-NO-HANG)))))
(COND-EVERY
((CONSP CHAR)
;; A special command (forced input, no doubt)
(CASE (CAR CHAR)
(SUPDUP (SUPDUP (CADR CHAR)))
(SUPDUP:TELNET (TELNET (CADR CHAR)))
(QSEND (QSEND (CADR CHAR))
(SEND WINDOW :SET-NEEDS-REDISPLAY T)
(SEND *TERMINAL-IO* :MAKE-COMPLETE))
(EH (EH (CADR CHAR)))
(INSPECT (INSPECT (CADR CHAR)))
(DESCRIBE (DESCRIBE (CADR CHAR)))
(:eval (eval (cadr char)))
(:MENU (SETQ CHAR (FIRST (THIRD (SECOND CHAR)))))
(:mouse-button
(mouse-call-system-menu))
(OTHERWISE (BEEP)))
(SETQ ARG NIL))
((NUMBERP CHAR)
(SETQ CHAR (INT-CHAR CHAR)))
((CHARACTERP CHAR)
;; Standard character, either accumulate arg or select new mode
(SETQ CHAR (CHAR-UPCASE CHAR))
(IF (DIGIT-CHAR-P CHAR)
(SETQ ARG (+ (* 10. (OR ARG 0)) (DIGIT-CHAR-P CHAR)))
(IF (PEEK-SET-MODE WINDOW CHAR ARG)
(SETQ ARG NIL)
;; Check for standard character assignments
(CASE CHAR
(#/HELP
(SEND *STANDARD-OUTPUT* :CLEAR-WINDOW)
(LET (INPUT)
(SETQ INPUT (SEND *STANDARD-INPUT* :LISTEN))
(UNLESS INPUT
(FORMAT T "The Peek program shows a continuously updating status display.
There are several modes that display different status.
Here is a list of modes. Select a mode by typing the character
or by clicking on the corresponding menu item.~2%"))
(DOLIST (E *PEEK-DEFAULT-MODE-ALIST*)
(WHEN (OR INPUT (SETQ INPUT (SEND *STANDARD-INPUT* :LISTEN)))
(RETURN))
(FORMAT T "~:@C~5T~A~%~@[~6T~A~%~]"
(FIRST E) (THIRD E) (FIFTH E)))
(UNLESS INPUT
(FORMAT T "~%Q~5TQuit.~%")
(FORMAT T "nZ~5TSets sleep time between updates to n seconds.~2%")
(FORMAT T "[Help] Prints this message.~2%")))
(SETQ ARG NIL))
(#/Q
(RETURN-FROM PEEK NIL))
(#/Z
(AND ARG (SETQ SLEEP-TIME (* 60. ARG)))
(SEND WINDOW :SET-NEEDS-REDISPLAY T)
(SETQ ARG NIL))
(#/SPACE (SEND WINDOW :SET-NEEDS-REDISPLAY T))
(OTHERWISE (BEEP))))))))
(WHEN (OR (SEND WINDOW :NEEDS-REDISPLAY) (TIME-LESSP WAKEUP-TIME (TIME)))
;; We want to redisplay. If have typeout, hang until user confirms.
(SEND WINDOW :SET-NEEDS-REDISPLAY NIL)
(SEND WINDOW :REDISPLAY)))))))
(DEFUN PEEK-ASSURE-NO-TYPEOUT (WINDOW)
(WHEN (SEND (SETQ WINDOW (SEND WINDOW :TYPEOUT-WINDOW)) :INCOMPLETE-P)
(FORMAT T "~&Type any character to flush:")
(LET ((CHAR (SEND *TERMINAL-IO* :ANY-TYI)))
(SEND WINDOW :MAKE-COMPLETE)
(UNLESS (EQ CHAR #/SPACE)
(SEND *TERMINAL-IO* :UNTYI CHAR)))))
;;;; Processes, meters
(DEFINE-PEEK-MODE PEEK-PROCESSES #/P "Active Processes" NIL
"List status of every process -- why waiting, how much run recently.")
(DEFUN PEEK-PROCESSES (IGNORE)
"Shows state of all active processes."
(LIST ()
30 of process name , 25 of state , 5 of priority , 10 of quantum left / quantum ,
8 of percentage , followed by idle time ( 11 columns )
(SCROLL-PARSE-ITEM (FORMAT NIL "~30A~21A~10A~10A~8A~8A"
"Process Name" "State" "Priority" "Quantum"
" %" "Idle"))
(SCROLL-PARSE-ITEM "")
(SCROLL-MAINTAIN-LIST #'(LAMBDA () ALL-PROCESSES)
#'(LAMBDA (PROCESS)
(SCROLL-PARSE-ITEM
`(:MOUSE-ITEM
(NIL :EVAL (PEEK-PROCESS-MENU ',PROCESS 'ITEM 0)
:DOCUMENTATION
"Menu of useful things to do to this process.")
:STRING ,(PROCESS-NAME PROCESS) 30.)
`(:FUNCTION ,#'PEEK-WHOSTATE ,(NCONS PROCESS) 25.)
`(:FUNCTION ,PROCESS (:PRIORITY) 5. ("~D."))
`(:FUNCTION ,PROCESS (:QUANTUM-REMAINING) 5. ("~4D//"))
`(:FUNCTION ,PROCESS (:QUANTUM) 5. ("~D."))
`(:FUNCTION ,PROCESS (:PERCENT-UTILIZATION) 8.
("~1,1,4$%"))
`(:FUNCTION ,PROCESS (:IDLE-TIME) NIL
("~\TV::PEEK-PROCESS-IDLE-TIME\"))))
NIL
NIL)
(SCROLL-PARSE-ITEM "")
(SCROLL-PARSE-ITEM "Clock Function List")
(SCROLL-MAINTAIN-LIST #'(LAMBDA () SI::CLOCK-FUNCTION-LIST)
#'(LAMBDA (FUNC)
(SCROLL-PARSE-ITEM
`(:STRING ,(WITH-OUTPUT-TO-STRING (STR)
(PRINC FUNC STR))))))))
(FORMAT:DEFFORMAT PEEK-PROCESS-IDLE-TIME (:ONE-ARG) (ARG IGNORE)
(COND ((NULL ARG) (SEND *STANDARD-OUTPUT* :STRING-OUT "forever")) ; character too small
((ZEROP ARG)) ;Not idle
((< ARG 60.) (FORMAT T "~D sec" ARG))
((< ARG 3600.) (FORMAT T "~D min" (TRUNCATE ARG 60.)))
(T (FORMAT T "~D hr" (TRUNCATE ARG 3600.)))))
(DEFUN PEEK-WHOSTATE (PROCESS)
(COND ((SI::PROCESS-ARREST-REASONS PROCESS) "Arrest")
((SI::PROCESS-RUN-REASONS PROCESS)
(or (si::process-wait-whostate process)
(string-append "Running: " (si::process-run-whostate process))))
(T "Stop")))
(DEFINE-PEEK-MODE PEEK-RATES #/R "Counter Rates" NIL
"Display the rate of change of the counters.")
(defstruct (peek-rate (:type :list))
peek-rate-counter-name
peek-rate-counter-type
peek-rate-last-value
peek-rate-average
)
(defconst peek-rate-list nil)
(defun put-meters-on-peek-rate-list (meter-list function-list)
(dolist (m meter-list)
(cond ((null (memq m si:a-memory-counter-block-names)))
((null (assq m peek-rate-list))
(let ((pr (make-peek-rate)))
(setf (peek-rate-counter-type pr) :meter)
(setf (peek-rate-counter-name pr) m)
(setf (peek-rate-last-value pr) (read-meter m))
(setf (peek-rate-average pr) 0)
(without-interrupts
(setq peek-rate-list (nconc peek-rate-list (list pr))))))))
(dolist (f function-list)
(cond ((null (assq f peek-rate-list))
(let ((pr (make-peek-rate)))
(setf (peek-rate-counter-type pr) :function)
(setf (peek-rate-counter-name pr) f)
(setf (peek-rate-last-value pr) (funcall f))
(setf (peek-rate-average pr) 0)
(without-interrupts
(setq peek-rate-list (nconc peek-rate-list (list pr)))))))))
(put-meters-on-peek-rate-list '(si:%count-first-level-map-reloads
si:%count-second-level-map-reloads
%COUNT-PDL-BUFFER-READ-FAULTS
%COUNT-PDL-BUFFER-WRITE-FAULTS
%COUNT-PDL-BUFFER-MEMORY-FAULTS
%COUNT-DISK-PAGE-READS
%COUNT-DISK-PAGE-WRITES
%COUNT-FRESH-PAGES
%COUNT-AGED-PAGES
%COUNT-AGE-FLUSHED-PAGES
%COUNT-META-BITS-MAP-RELOADS
%COUNT-CONS-WORK
%COUNT-SCAVENGER-WORK
%AGING-DEPTH
%COUNT-FINDCORE-STEPS
%COUNT-FINDCORE-EMERGENCIES
%COUNT-DISK-PAGE-READ-OPERATIONS
%COUNT-DISK-PAGE-WRITE-OPERATIONS
%COUNT-DISK-PAGE-WRITE-WAITS
%COUNT-DISK-PAGE-WRITE-BUSYS
%COUNT-DISK-PREPAGES-USED
%COUNT-DISK-PREPAGES-NOT-USED
%DISK-WAIT-TIME
%COUNT-DISK-PAGE-WRITE-APPENDS
%COUNT-DISK-PAGE-READ-APPENDS
%COUNT-ILLOP-DEBUG
%COUNT-MICRO-FAULTS
)
'(
; si:read-main-stat-counter
; si:read-aux-stat-counter
time:microsecond-time
))
(defconst peek-maintain-rates-time-constant 16.)
(defconst peek-maintain-rates-number-of-sixtieths 30.)
(defvar peek-maintain-rates-ticks-to-go 0)
(defun peek-maintain-rates (time-delta)
(condition-case ()
(progn
(decf peek-maintain-rates-ticks-to-go time-delta)
(cond ((<= peek-maintain-rates-ticks-to-go 0)
(setq peek-maintain-rates-ticks-to-go peek-maintain-rates-number-of-sixtieths)
(dolist (pr peek-rate-list)
(let* ((new-value (selectq (peek-rate-counter-type pr)
(:meter (read-meter (peek-rate-counter-name pr)))
(:function (funcall (peek-rate-counter-name pr)))))
(delta (- new-value (peek-rate-last-value pr))))
(decf (peek-rate-average pr)
(// (peek-rate-average pr) peek-maintain-rates-time-constant))
(incf (peek-rate-average pr) delta)
(setf (peek-rate-last-value pr) new-value)))
)))
(error (without-interrupts
(setq clock-function-list (delq 'peek-maintain-rates si:clock-function-list))))))
(defun activate-peek-rate-maintainer (on-p)
(peek-maintain-rates 1)
(without-interrupts
(cond ((null on-p)
(setq si:clock-function-list (delq 'peek-maintain-rates si:clock-function-list)))
((memq 'peek-maintain-rates si:clock-function-list))
(t
(setq peek-maintain-rates-ticks-to-go 0)
(push 'peek-maintain-rates si:clock-function-list)))))
(defmethod (peek-frame :after :deexpose) (&rest ignore)
(activate-peek-rate-maintainer nil))
(DEFUN PEEK-RATES (IGNORE)
"Statistics counter rates"
(activate-peek-rate-maintainer t)
(SCROLL-MAINTAIN-LIST
#'(LAMBDA () peek-rate-list)
#'(LAMBDA (pr)
(SCROLL-PARSE-ITEM
`(:STRING ,(STRING (peek-rate-counter-name pr)) 35.)
`(:function ,#'(lambda (pr)
(case (peek-rate-counter-type pr)
(:meter (read-meter (peek-rate-counter-name pr)))
(:function (funcall (peek-rate-counter-name pr)))))
(,pr) nil ("~15:d" 10. T))
`(:function ,#'(lambda (pr)
( // ( * ( // 60 . peek - maintain - rates - number - of - sixtieths )
; (peek-rate-average pr))
; peek-maintain-rates-time-constant)
(fix (* 0.12 (peek-rate-average pr)))
)
(,pr)
nil ("~15:d" 10. T))))))
(DEFINE-PEEK-MODE PEEK-COUNTERS #/% "Statistics Counters" NIL
"Display the values of all the microcode meters.")
(DEFUN PEEK-COUNTERS (IGNORE)
"Statistics counters"
( not ( fboundp ' - main - stat - counter ) )
(LIST ()
(SCROLL-MAINTAIN-LIST #'(LAMBDA () SYS:A-MEMORY-COUNTER-BLOCK-NAMES)
#'(LAMBDA (COUNTER)
(SCROLL-PARSE-ITEM
`(:STRING ,(STRING COUNTER) 35.)
`(:FUNCTION READ-METER (,COUNTER) NIL
("~@15A" 10. T)))))))
; (t
; (LIST ()
( SCROLL - MAINTAIN - LIST # ' ( LAMBDA ( ) SYS : A - MEMORY - COUNTER - BLOCK - NAMES )
; #'(LAMBDA (COUNTER)
; (SCROLL-PARSE-ITEM
` (: STRING , ( STRING COUNTER ) 35 . )
; `(:FUNCTION READ-METER (,COUNTER) NIL
( " ~@15A " 10 . T ) ) ) ) )
; (SCROLL-PARSE-ITEM "")
; (scroll-parse-item
; `(:mouse-item
; (nil :eval (peek-stat-counter-controls-menu)
; :documentation
; "Change stat counter controls.")
: string " Statistics Counters " 20 . ) )
; (scroll-parse-item "Main: "
; `(:function ,#'(lambda ()
; (nth (ldb si::%%main-stat-clock-control
; (si::read-rg-mode))
; stat-clock-values))
; () nil ("~a"))
; "; "
; `(:function ,#'(lambda ()
; (nth (ldb si::%%main-stat-count-control
; (si::read-rg-mode))
; stat-count-values))
; () nil ("~a")))
; (scroll-parse-item "Aux : "
; `(:function ,#'(lambda ()
; (nth (ldb si::%%aux-stat-clock-control
; (si::read-rg-mode))
; stat-clock-values))
; () nil ("~a"))
; "; "
; `(:function ,#'(lambda ()
; (nth (ldb si::%%aux-stat-count-control
; (si::read-rg-mode))
; stat-count-values))
; () nil ("~a")))
; (scroll-parse-item "Main counter: "
` (: function - main - stat - counter ( ) nil ( " ~20 : d " ) ) )
; (scroll-parse-item "Aux counter: "
` (: function - stat - counter ( ) nil ( " ~20 : d " ) ) )
; (scroll-parse-item "Main - Aux: "
; `(:function ,#'(lambda ()
; (- (si::read-main-stat-counter)
; (si::read-aux-stat-counter)))
; () nil ("~20:d")))
( scroll - parse - item " Main // Aux : "
; `(:function ,#'(lambda ()
; (let ((main (si::read-main-stat-counter))
; (aux (si::read-aux-stat-counter)))
( cond ( ( zerop aux )
; "***")
; (t
; (// (float main) aux)))))
; () nil ("~20f")))
; (scroll-parse-item "Aux // Main: "
; `(:function ,#'(lambda ()
; (let ((main (si::read-main-stat-counter))
; (aux (si::read-aux-stat-counter)))
; (cond ((zerop main)
; "***")
; (t
; (// (float aux) main)))))
; () nil ("~20f")))
; ))
;
))
;(defun peek-stat-counter-controls-menu ()
( process - run - function " Change Stat Counters " ' peek - stat - counter - controls - function ) )
( defvar peek - main - stat - clock : )
;(defvar peek-main-stat-count :hi)
( defvar peek - aux - stat - clock : )
;(defvar peek-aux-stat-count :hi)
( defconst stat - clock - values ' (: : UINST.CLOCK ) )
;(defconst stat-count-values '(:VALID.STATISTICS.BIT
: MEMORY.START.NEXT.CYCLE
; :CSM.STATISTICS.BIT
; :INCREMENT.LC
:
; :T.STATISTICS.BIT
: 1.MHZ.CLOCK
; :HI))
;(defun make-atom-list-into-menu-alist (atom-list)
; (loop for a in atom-list
; collect (list (string a) a)))
;(defun peek-stat-counter-controls-function ()
; (tv:choose-variable-values `((peek-main-stat-clock
; "Main stat clock"
; :menu-alist ,(make-atom-list-into-menu-alist stat-clock-values))
; (peek-main-stat-count
; "Main stat count control"
; :menu-alist ,(make-atom-list-into-menu-alist stat-count-values))
; (peek-aux-stat-clock
; "Aux stat clock"
; :menu-alist ,(make-atom-list-into-menu-alist stat-clock-values))
; (peek-aux-stat-count
; "Aux stat count control"
; :menu-alist ,(make-atom-list-into-menu-alist stat-count-values))
; "foo"
; "bar"
; )
; )
; (si::write-main-stat-control (find-position-in-list peek-main-stat-clock stat-clock-values)
; (find-position-in-list peek-main-stat-count stat-count-values))
; (si::write-aux-stat-control (find-position-in-list peek-aux-stat-clock stat-clock-values)
; (find-position-in-list peek-aux-stat-count stat-count-values))
;; (si::reset-stat-counters)
; )
;;;; Memory
(defun peek-memory-header ()
(scroll-parse-item
"Physical memory: "
`(:function ,(lambda (&aux (val (aref (symbol-function 'system-communication-area)
%sys-com-memory-size)))
(setf (value 0) (truncate val #o2000))
val)
nil nil (nil 8.))
`(:value 0 nil (" (~DK), "))
"Free space: "
`(:function ,(lambda (&aux (val (si::free-space)))
(setf (value 0) (truncate val #o2000))
val)
nil nil (nil 8.))
`(:value 0 nil (" (~DK)"))
", Wired pages "
`(:function ,(lambda ()
(multiple-value-bind (n-wired-pages n-fixed-wired-pages)
(si::count-wired-pages)
(setf (value 0) (- n-wired-pages n-fixed-wired-pages))
(setf (value 1) (truncate n-wired-pages (truncate 2000 page-size)))
(setf (value 2) (\ n-wired-pages (truncate 2000 page-size)))
n-fixed-wired-pages))
nil nil ("~D"))
`(:value 0 nil ("+~D "))
`(:value 1 nil ("(~D"))
`(:value 2 nil ("~[~;.25~;.5~;.75~]K)"))))
(define-peek-mode peek-areas #/A "Areas" nil
"Display status of areas, including how much memory allocated and used.")
(defconst *first-interesting-area* working-storage-area
"All areas this are uninteresting crufty system frobs and kludges.")
(defun peek-areas (ignore)
"Areas"
(list ()
(peek-memory-header)
(scroll-parse-item "")
(scroll-maintain-list
(lambda () 'boring)
(lambda (area)
(if (eq area 'boring)
(list
'(:pre-process-function peek-areas-boring-display)
(scroll-parse-item
:mouse-self '(nil :eval (peek-mouse-click 'self 0)
:documentation
"Insert//remove display of boring areas.")
:leader `(nil)
`(:function ,(lambda () (1- *first-interesting-area*))
()
nil (" 0-~D /"Uninteresting/" system-internal areas"))))
(list
'(:pre-process-function peek-areas-region-display)
(scroll-parse-item
:mouse-self '(nil :eval (peek-mouse-click 'self 0)
:documentation
"Insert//remove display of all regions in this area.")
:leader `(nil ,area)
`(:function identity (,area) 4 ("~3D"))
`(:string ,(string (area-name area)) 40.)
`(:function ,(lambda (area)
(multiple-value-bind (length used n-regions)
(si::room-get-area-length-used area)
(setf (value 0) used)
(setf (value 1) length)
(setf (value 2)
(cond ((zerop length) 0)
((< length #o40000)
(truncate (* 100. (- length used)) length))
(t
(truncate (- length used) (truncate length 100.)))))
n-regions))
(,area) 15. ("(~D region~0@*~P)"))
`(:value 2 nil ("~@3A% free, " 10. t))
`(:value 0 nil ("~8O"))
`(:value 1 nil ("//~8O used"))))))
nil
(lambda (state &aux next-one this-one (len (array-length (symbol-function 'area-name))))
(if (eq state 'boring)
(values 'boring *first-interesting-area* nil)
(do ((i state (1+ i)))
(( i len) nil)
(cond ((and (null this-one) (aref (symbol-function 'area-name) i))
(setq this-one i))
((and this-one (aref (symbol-function 'area-name) i))
(setq next-one i)
(return t))))
(values this-one next-one (null next-one)))))))
(defun peek-areas-boring-display (item)
"Handles adding/deleting of the boring areas when a mouse button is clicked."
(cond ((null (array-leader (cadr item) scroll-item-leader-offset)))
;; Clicked on this item, need to complement state
((= (length item) 2)
;; If aren't displaying boredom now, display it
(setf (cddr item)
(ncons
(scroll-maintain-list
(lambda () 0)
(lambda (area)
(list
'(:pre-process-function peek-areas-region-display)
(scroll-parse-item
:mouse-self '(nil :eval (peek-mouse-click 'self 0)
:documentation
"Insert//remove display of all regions in this boring area.")
:leader `(nil ,area)
`(:function identity (,area) 5 (" ~3D"))
`(:string ,(string (area-name area)) 39.)
`(:function ,(lambda (area)
(multiple-value-bind (length used n-regions)
(si::room-get-area-length-used area)
(setf (value 0) used)
(setf (value 1) length)
(setf (value 2)
(cond ((zerop length) 0)
((< length #o40000)
(truncate (* 100. (- length used))
length))
(t
(truncate (- length used)
(truncate length 100.)))))
n-regions))
(,area) 15. ("(~D region~0@*~P)"))
`(:value 2 nil ("~@3A% free, " 10. t))
`(:value 0 nil ("~O"))
`(:value 1 nil ("//~O used")))))
nil
(lambda (state &aux next-one this-one)
(do ((i state (1+ i)))
(( i *first-interesting-area*) nil)
(cond ((and (null this-one) (aref (symbol-function 'area-name) i))
(setq this-one i))
((and this-one (aref (symbol-function 'area-name) i))
(setq next-one i)
(return t))))
(values this-one next-one (null next-one)))))))
(t (setf (cddr item) nil)))
(setf (array-leader (cadr item) scroll-item-leader-offset) nil))
(defun peek-areas-region-display (item)
"Handles adding/deleting of the region display when a mouse button is clicked."
(cond ((null (array-leader (cadr item) scroll-item-leader-offset)))
;; Clicked on this item, need to complement state
((= (length item) 2)
;; If aren't displaying regions now, display them
(setf (cddr item)
(ncons
(scroll-maintain-list
(lambda ()
(si:%area-region-list (array-leader (first (scroll-items item))
(1+ scroll-item-leader-offset))))
(lambda (region)
(if (minusp region)
(scroll-parse-item `(:string " No regions in this area"))
(scroll-parse-item
`(:string
,(format nil " ~3O: Origin ~8O, Length ~8O, "
region
(si:%pointer-unsigned (si::%region-origin region))
(si::%region-length region)))
`(:function ,#'si::%region-free-pointer (,region) nil ("Used ~8O, "))
`(:function
,(lambda (region)
(let ((used (si::%region-free-pointer region))
(scavenged (si::%region-gc-pointer region)))
(cond ((not (si::%region-scavenge-enable region))
"Scavenger off, ")
((= used scavenged)
"Scavenge done, ")
((= used 0)
"Scavenged 0%, ")
(t
(format nil "Scavenged ~D%, "
(round
(* 100. (// (float scavenged)
(float used)))))))))
(,region))
`(:string
,(format nil "~A space, Vol=~D."
(nth (si::%region-type region)
'(free old new new1 new2 new3 new4 new5 new6
static fixed extra-pdl copy))
(si::%region-volatility region))))))
nil
(lambda (state)
(if (minusp state)
;; no regions at all in this area
(values -1 -1 t)
(values state
(si:%region-list-thread state)
(minusp (si:%region-list-thread state)))))))))
(t (setf (cddr item) nil)))
(setf (array-leader (cadr item) scroll-item-leader-offset) nil))
(DEFINE-PEEK-MODE PEEK-page-status #/M "Memory Usage" NIL
"Percent of each area paged in.")
(DEFUN PEEK-page-status (IGNORE)
"Page Status"
(LIST ()
(scroll-maintain-list
#'(lambda ()
(loop for i from si:VIRTUAL-PAGE-DATA below (array-length #'area-name)
when (aref #'area-name i)
collect (aref #'area-name i)))
#'(lambda (area)
(scroll-parse-item
`(:string ,(string area) 40.)
`(:function page-status-function (,area) nil
("~@15A" 10. t)))))))
(defun page-status-function (area &aux (total-pages 0) (paged-in-pages 0))
(gc:without-flipping
(si:for-every-region-in-area (region (symbol-value area))
(select (ldb %%region-space-type (si:%region-bits region))
((%REGION-SPACE-FREE
%REGION-SPACE-OLD
%REGION-SPACE-EXTRA-PDL
%REGION-SPACE-MOBY-FIXED
%REGION-SPACE-MOBY-NEW))
((%REGION-SPACE-NEW
%REGION-SPACE-STATIC
%REGION-SPACE-FIXED
%REGION-SPACE-COPY)
(let ((pages-in-this-region (ceiling (si:%region-free-pointer region) page-size)))
(incf total-pages pages-in-this-region)
(dotimes (page-number pages-in-this-region)
(if (%page-status (ash page-number 8))
(incf paged-in-pages)))))
(t
(ferror nil "unknown region space type")))))
(when (not (zerop total-pages))
(format nil "~2d% of ~5d pages"
(round (* 100. (// (float paged-in-pages) total-pages)))
total-pages)))
;;;; File system status
(DEFINE-PEEK-MODE PEEK-FILE-SYSTEM #/F "File System Status" NIL
"Display status of FILE protocol connections to remote file systems.")
(DEFUN NEXT-INTERESTING-FILE-HOST-STEPPER (LIST)
(LET ((GOOD (SOME LIST (LAMBDA (X) (SEND-IF-HANDLES X :ACCESS)))))
(VALUES (CAR GOOD) (CDR GOOD) (NULL GOOD))))
(defun file-host-item-function (host)
(when host
(list (list :pre-process-function 'peek-file-host-pre-process
:host host
:access nil
:host-units nil)
'(nil)
'(nil))))
(defun peek-file-host-pre-process (item)
(let* ((host (getf (tv:scroll-item-plist item) :host))
(access (getf (tv:scroll-item-plist item) :access))
(host-units (getf (tv:scroll-item-plist item) :host-units))
(new-access (send host :access))
(new-host-units (send-if-handles new-access :host-units)))
(unless (and (eq access new-access) (equal host-units new-host-units))
(setf (getf (tv:scroll-item-plist item) :access) new-access)
(setf (getf (tv:scroll-item-plist item) :host-units) new-host-units)
(setf (cdr (tv:scroll-item-component-items item))
(append (send host :peek-file-system-header)
(send host :peek-file-system))))))
(defun peek-file-system (ignore)
"Display status of file system"
(scroll-maintain-list
#'(lambda () fs:*pathname-host-list*)
'file-host-item-function
nil
'next-interesting-file-host-stepper))
(DEFMETHOD (SI::FILE-DATA-STREAM-MIXIN :PEEK-FILE-SYSTEM) (&OPTIONAL (INDENT 0) &AUX DIRECTION)
"Returns a scroll item describing a stream"
(TV:SCROLL-PARSE-ITEM
:MOUSE `(NIL :EVAL (PEEK-FILE-SYSTEM-STREAM-MENU ',SELF)
:DOCUMENTATION "Menu of useful things to do to this open file.")
(AND ( INDENT 0) (FORMAT NIL "~V@T" INDENT))
(CASE (SETQ DIRECTION (SEND SELF :DIRECTION))
(:INPUT "Input ")
(:OUTPUT "Output ")
(OTHERWISE "?Direction? "))
(SEND (SEND SELF :PATHNAME) :STRING-FOR-PRINTING)
(IF (SEND SELF :CHARACTERS)
", Character, " ", Binary, ")
`(:FUNCTION ,#'(LAMBDA (STREAM)
(SETF (TV:VALUE 0) (SEND STREAM :READ-POINTER))
(TV:VALUE 0))
(,SELF) NIL ("~D"))
(AND (EQ DIRECTION :INPUT)
`(:FUNCTION ,#'(LAMBDA (STREAM)
(LET ((LENGTH (SEND STREAM :LENGTH)))
(AND LENGTH (NOT (ZEROP LENGTH))
(TRUNCATE (* 100. (TV:VALUE 0)) LENGTH))))
(,SELF) NIL ("~@[ (~D%)~]")))
" bytes"))
(DEFUN PEEK-FILE-SYSTEM-STREAM-MENU (STREAM)
(APPLY #'PROCESS-RUN-FUNCTION "Peek File System Menu"
SELF :PEEK-FILE-SYSTEM-MENU
(LIST STREAM)))
(DEFMETHOD (BASIC-PEEK :PEEK-FILE-SYSTEM-MENU) (STREAM)
(LET ((*TERMINAL-IO* TYPEOUT-WINDOW))
(MENU-CHOOSE `(("Close" :EVAL (SEND ',STREAM :CLOSE)
:DOCUMENTATION "Close selected file (normally).")
("Abort" :EVAL (SEND ',STREAM :CLOSE :ABORT)
:DOCUMENTATION "Close selected file (aborts writing).")
("Delete" :EVAL (SEND ',STREAM :DELETE)
:DOCUMENTATION "Delete selected file, but don't close it.")
("Describe" :EVAL (DESCRIBE ',STREAM)
:DOCUMENTATION "Describe the file's stream.")
("Inspect" :EVAL (INSPECT ',STREAM)
:DOCUMENTATION "Inspect the file's stream.")
)
(STRING (SEND STREAM :TRUENAME)))))
(DEFUN PEEK-PROCESS-MENU (&REST ARGS)
(APPLY #'PROCESS-RUN-FUNCTION "Peek Process Menu"
SELF :PEEK-PROCESS-MENU ARGS))
(DEFMETHOD (BASIC-PEEK :PEEK-PROCESS-MENU) (PROCESS &REST IGNORE &AUX CHOICE)
"Menu for interesting operations on processes in a peek display"
(LET ((*TERMINAL-IO* TYPEOUT-WINDOW)
(CHOICES '(("Debugger" :VALUE PROCESS-EH
:DOCUMENTATION
"Call the debugger to examine the selected process.")
("Arrest" :VALUE PROCESS-ARREST
:DOCUMENTATION "Arrest the selected process. Undone by Un-Arrest.")
("Un-Arrest" :VALUE PROCESS-UN-ARREST
:DOCUMENTATION "Un-Arrest the selected process. Complement of Arrest.")
("Flush" :VALUE PROCESS-FLUSH
:DOCUMENTATION
"Unwind the selected process' stack and make it unrunnable. Ask for confirmation.")
("Reset" :VALUE PROCESS-RESET
:DOCUMENTATION "Reset the selected process. Ask for confirmation.")
("Kill" :VALUE PROCESS-KILL
:DOCUMENTATION
"Kill the selected process. Ask for confirmation.")
("Describe" :VALUE PROCESS-DESCRIBE
:DOCUMENTATION
"Call DESCRIBE on this process.")
("Inspect" :VALUE PROCESS-INSPECT
:DOCUMENTATION
"Call INSPECT on this process."))))
Do n't offer EH for a simple process .
(OR (TYPEP (PROCESS-STACK-GROUP PROCESS) 'STACK-GROUP)
(POP CHOICES))
(SETQ CHOICE (MENU-CHOOSE CHOICES (PROCESS-NAME PROCESS)))
(CASE CHOICE
(PROCESS-ARREST (SEND PROCESS :ARREST-REASON))
(PROCESS-UN-ARREST (SEND PROCESS :REVOKE-ARREST-REASON))
(PROCESS-FLUSH (IF (MOUSE-Y-OR-N-P (FORMAT NIL "Flush ~A" PROCESS))
(SEND PROCESS :FLUSH)))
(PROCESS-RESET (IF (MOUSE-Y-OR-N-P (FORMAT NIL "Reset ~A" PROCESS))
(SEND PROCESS :RESET)))
(PROCESS-KILL (IF (MOUSE-Y-OR-N-P (FORMAT NIL "Kill ~A" PROCESS))
(SEND PROCESS :KILL)))
(PROCESS-EH (SEND SELF :FORCE-KBD-INPUT `(EH ,PROCESS)))
(PROCESS-DESCRIBE (SEND SELF :FORCE-KBD-INPUT `(DESCRIBE ,PROCESS)))
(PROCESS-INSPECT (SEND SELF :FORCE-KBD-INPUT `(INSPECT ,PROCESS)))
(NIL)
(OTHERWISE (BEEP)))))
;;;; Peeking at windows
Copied from LAD : RELEASE-3.WINDOW ; PEEK.LISP#191 on 2 - Oct-86 04:12:43
(DEFINE-PEEK-MODE PEEK-WINDOW-HIERARCHY #/W "Window Hierarchy" NIL
"Display the hierarchy of window inferiors, saying which are exposed.")
(DEFUN PEEK-WINDOW-HIERARCHY (IGNORE)
(SCROLL-MAINTAIN-LIST #'(LAMBDA () ALL-THE-SCREENS)
#'(LAMBDA (SCREEN)
(LIST ()
(SCROLL-PARSE-ITEM (FORMAT NIL "Screen ~A" SCREEN))
(PEEK-WINDOW-INFERIORS SCREEN 2)
(SCROLL-PARSE-ITEM "")))))
(DEFUN PEEK-WINDOW-INFERIORS (WINDOW INDENT)
(SCROLL-MAINTAIN-LIST #'(LAMBDA () (SHEET-INFERIORS WINDOW))
#'(LAMBDA (SHEET)
(LIST ()
(SCROLL-PARSE-ITEM
(FORMAT NIL "~V@T" INDENT)
`(:MOUSE
(NIL :EVAL (PEEK-WINDOW-MENU ',SHEET)
:DOCUMENTATION
"Menu of useful things to do to this window.")
:STRING
,(SEND SHEET :NAME)))
(PEEK-WINDOW-INFERIORS SHEET (+ INDENT 4))))))
(DEFUN PEEK-WINDOW-MENU (&REST ARGS)
(APPLY #'PROCESS-RUN-FUNCTION "Peek Window Menu"
#'PEEK-WINDOW-MENU-INTERNAL SELF ARGS))
(DEFUN PEEK-WINDOW-MENU-INTERNAL (PEEK-WINDOW SHEET &REST IGNORE &AUX CHOICE)
"Menu for interesting operations on sheets in a peek display"
(SETQ CHOICE
(MENU-CHOOSE
'(("Deexpose" :VALUE :DEEXPOSE :DOCUMENTATION "Deexpose the window.")
("Expose" :VALUE :EXPOSE :DOCUMENTATION "Expose the window.")
("Select" :VALUE :SELECT :DOCUMENTATION "Select the window.")
("Deselect" :VALUE :DESELECT :DOCUMENTATION "Deselect the window.")
("Deactivate" :VALUE :DEACTIVATE :DOCUMENTATION "Deactivate the window.")
("Kill" :VALUE :KILL :DOCUMENTATION "Kill the window.")
("Bury" :VALUE :BURY :DOCUMENTATION "Bury the window.")
("Inspect" :VALUE :INSPECT :DOCUMENTATION "Look at window data structure."))
(SEND SHEET :NAME)))
(AND CHOICE
(OR (NEQ CHOICE :KILL)
(MOUSE-Y-OR-N-P (FORMAT NIL "Kill ~A" (SEND SHEET :NAME))))
(IF (EQ CHOICE :INSPECT)
(SEND PEEK-WINDOW :FORCE-KBD-INPUT `(INSPECT ,SHEET))
(SEND SHEET CHOICE))))
(DEFINE-PEEK-MODE PEEK-SERVERS #/S "Active Servers" NIL
"List all servers, who they are serving, and their status.")
(DEFUN PEEK-SERVERS (IGNORE)
(LIST ()
(SCROLL-PARSE-ITEM "Active Servers")
(SCROLL-PARSE-ITEM "Contact Name Host Process // State")
(SCROLL-PARSE-ITEM " Connection")
(SCROLL-PARSE-ITEM "")
(SCROLL-MAINTAIN-LIST
#'(LAMBDA () (SEND TV:WHO-LINE-FILE-STATE-SHEET :SERVERS))
#'(LAMBDA (SERVER-DESC)
(LET* ((PROCESS (SERVER-DESC-PROCESS SERVER-DESC))
(CONN (SERVER-DESC-CONNECTION SERVER-DESC))
(contact (server-desc-contact-name server-desc))
(HOST (if (typep conn 'chaos:conn)
(SI:GET-HOST-FROM-ADDRESS (CHAOS:FOREIGN-ADDRESS CONN) :CHAOS)
(nth-value 1 (ip:parse-internet-address (send conn :remote-address))))))
(LIST '(:PRE-PROCESS-FUNCTION PEEK-SERVER-PREPROCESS)
(SCROLL-PARSE-ITEM
:LEADER '(NIL NIL NIL)
`(:FUNCTION ,#'values (,contact) 20. ("~A"))
`(:MOUSE-ITEM
(NIL :EVAL (CHAOS:PEEK-CHAOS-HOST-MENU ',HOST 'TV:ITEM 0)
:DOCUMENTATION "Menu of useful things to do to this host.")
:FUNCTION ,#'VALUES (,HOST) 20. ("~A"))
`(:MOUSE
(NIL :EVAL (PEEK-PROCESS-MENU ',PROCESS)
:DOCUMENTATION
"Menu of useful things to do to this process.")
:STRING
,(FORMAT NIL "~S" PROCESS))
" "
`(:FUNCTION ,#'PEEK-WHOSTATE ,(NCONS PROCESS)))
(SCROLL-PARSE-ITEM
6
" "
`(:MOUSE-ITEM
(NIL :EVAL (PEEK-CONNECTION-MENU ',CONN 'ITEM ',host ',contact)
:DOCUMENTATION
"Menu of useful things to do this connection")
:STRING ,(FORMAT NIL "~S" CONN)))
NIL ;Connection stat
hostat
(AND (SERVER-DESC-FUNCTION SERVER-DESC)
(APPLY (SERVER-DESC-FUNCTION SERVER-DESC)
(SERVER-DESC-ARGS SERVER-DESC)))))))))
(DEFUN PEEK-CONNECTION-MENU (CONN ITEM host contact)
(APPLY #'PROCESS-RUN-FUNCTION "Peek Server Connection Menu"
SELF :PEEK-SERVER-CONNECTION-MENU
(LIST CONN ITEM host contact)))
(DEFMETHOD (BASIC-PEEK :PEEK-SERVER-CONNECTION-MENU) (CONN ITEM host contact)
(LET ((*TERMINAL-IO* TYPEOUT-WINDOW))
(LET ((CHOICE
(MENU-CHOOSE (append '(("Close" :VALUE :CLOSE
:DOCUMENTATION "Close connection forcibly."))
(when (typep conn 'chaos:conn)
'(("Insert Detail" :VALUE :DETAIL
:DOCUMENTATION
"Insert detailed info about chaos connection.")))
(when (typep conn 'chaos:conn)
'(("Remove Detail" :VALUE :UNDETAIL
:DOCUMENTATION
"Remove detailed info from Peek display.")))
'(("Inspect" :VALUE :INSPECT
:DOCUMENTATION "Inspect the connection")))
(STRING-APPEND host "//" contact))))
(CASE CHOICE
(:CLOSE (if (typep conn 'chaos:conn)
(CHAOS:CLOSE-CONN CONN "Manual Close from PEEK")
(send conn :close)))
(:INSPECT (INSPECT CONN))
(:DETAIL (SETF (ARRAY-LEADER ITEM (+ 4 TV:SCROLL-ITEM-LEADER-OFFSET)) CONN)
(SETF (ARRAY-LEADER ITEM (+ 5 TV:SCROLL-ITEM-LEADER-OFFSET)) T))
(:UNDETAIL (SETF (ARRAY-LEADER ITEM (+ 4 TV:SCROLL-ITEM-LEADER-OFFSET)) NIL)
(SETF (ARRAY-LEADER ITEM (+ 5 TV:SCROLL-ITEM-LEADER-OFFSET)) NIL))))))
(DEFUN PEEK-SERVER-PREPROCESS (LIST-ITEM &AUX HOST)
(LET* ((LINE-ITEM (THIRD LIST-ITEM))
(HOST-ITEM (SECOND LIST-ITEM))
(WANTED (ARRAY-LEADER LINE-ITEM (+ 4 TV:SCROLL-ITEM-LEADER-OFFSET)))
(GOT (ARRAY-LEADER LINE-ITEM (+ 5 TV:SCROLL-ITEM-LEADER-OFFSET))))
(COND ((NULL WANTED)
(SETF (ARRAY-LEADER LINE-ITEM (+ 5 TV:SCROLL-ITEM-LEADER-OFFSET)) NIL)
(SETF (FOURTH LIST-ITEM) NIL))
((EQ WANTED GOT))
(T
(SETF (FOURTH LIST-ITEM) (CHAOS:PEEK-CHAOS-CONN WANTED))
(SETF (ARRAY-LEADER LINE-ITEM (+ 5 TV:SCROLL-ITEM-LEADER-OFFSET)) WANTED)))
;; Hack hostat
(COND ((ARRAY-LEADER HOST-ITEM TV:SCROLL-ITEM-LEADER-OFFSET)
Want a hostat , make sure it 's there and for the right host
(IF (AND (EQ (SETQ HOST (ARRAY-LEADER HOST-ITEM (1+ TV:SCROLL-ITEM-LEADER-OFFSET)))
(ARRAY-LEADER HOST-ITEM (+ TV:SCROLL-ITEM-LEADER-OFFSET 2)))
(FIFTH LIST-ITEM))
NIL
(SETF (FIFTH LIST-ITEM) (CONS '() (CHAOS:PEEK-CHAOS-HOSTAT HOST 1)))
(SETF (ARRAY-LEADER HOST-ITEM (+ TV:SCROLL-ITEM-LEADER-OFFSET 2)) HOST)))
(T (SETF (FIFTH LIST-ITEM) NIL)
(SETF (ARRAY-LEADER HOST-ITEM (+ TV:SCROLL-ITEM-LEADER-OFFSET 2)) NIL)))))
(define-peek-mode peek-devices #/D "Devices" NIL
"Display information about devices.")
(defun peek-devices (ignore)
"Devices"
(list ()
(scroll-maintain-list
#'(lambda ()
(reverse
(loop for x in fs:*pathname-host-list*
when (typep x 'si:shared-device)
collect x)))
#'(lambda (dev)
(scroll-parse-item
`(:mouse-item
(nil :eval (peek-device-menu ',dev 'item 0)
:documentation
"Menu of useful things to do to this device.")
:string ,(send dev :name) 20.)
`(:function peek-dev-lock (,dev) nil ("~30a"))
`(:function peek-dev-owner (,dev) nil ("~10a"))
)))))
(defun peek-dev-lock (dev)
(let ((lock (car (send dev :lock))))
(cond ((null lock) "not locked")
(t (send lock :name)))))
(defun peek-dev-owner (dev)
(let ((owner (send dev :owner)))
(cond ((null owner) "free")
((eq owner :not-on-bus) "not on bus")
(t (format nil "slot ~d" owner)))))
(defun peek-device-menu (&rest args)
(apply #'process-run-function "Peek Device Menu"
self :peek-device-menu args))
(defmethod (basic-peek :peek-device-menu) (dev &rest ignore &aux choice)
"Menu for interesting operations on devices in a peek display"
(let ((*terminal-io* typeout-window)
(choices '(("Select window with lock" :value select
:documentation "Select the window who holds the lock for this device.")
("Clear lock" :value clear
:documentation "Clear the lock for this device.")
)))
(setq choice (menu-choose choices (send dev :name)))
(case choice
(select
(let ((proc (car (send dev :lock))))
(if (null proc)
(beep)
(dolist (w (send proc :run-reasons)
(beep))
(when (typep w 'tv:minimum-window)
(send w :select)
(return nil))))))
(clear
(rplaca (send dev :lock) nil))
(nil)
(otherwise (beep)))))
(define-peek-mode peek-general-status #/G "General Status" NIL
"Random internal processor state.")
(defstruct (peek-general-status-item
(:type :named-array)
(:conc-name peek-gs-)
(:print (format nil "#<Peek Processor Switch ~a>"
(peek-gs-pretty-name peek-general-status-item)
)))
name
pretty-name
get-function
set-function
)
(defun peek-gs-get-from-processor-switches (bit-name)
(ldb (symeval bit-name) (%processor-switches nil)))
(defun peek-gs-set-processor-switches (bit-name val)
(%processor-switches (dpb val (symeval bit-name) (%processor-switches nil))))
(defvar peek-processor-switch-items ())
(defun peek-processor-switch-items ()
(or peek-processor-switch-items
(setq peek-processor-switch-items
(loop for x in si::lambda-processor-switches-bits by 'cddr
collect (make-peek-general-status-item
:name x
:pretty-name
(string-capitalize-words
(if (string-equal x "%%PROCESSOR-SWITCH-" :end1 #o23)
(substring x #o23)
x))
:get-function 'peek-gs-get-from-processor-switches
:set-function 'peek-gs-set-processor-switches)))))
(defun peek-general-status (ignore)
"General Status"
(list ()
(scroll-maintain-list
#'(lambda () (peek-processor-switch-items))
#'(lambda (item)
(scroll-parse-item
`(:function ,(peek-gs-get-function item) (,(peek-gs-name item)) ()
("~@5A " 10. T))
`(:string ,(peek-gs-pretty-name item) 50.)
)))))
(defun create-first-peek-frame ()
(or (dolist (x (selectable-windows tv:main-screen))
(when (typep (second x) 'peek-frame)
(return t)))
(make-instance 'peek-frame :activate-p t)))
(add-initialization "Create a Peek Frame" '(create-first-peek-frame) '(:once))
(tv:add-system-key #/P 'PEEK-FRAME "Peek" T)
| null | https://raw.githubusercontent.com/jrm-code-project/LISP-Machine/0a448d27f40761fafabe5775ffc550637be537b2/lambda/window/peek.lisp | lisp | Package : TV ; Base:8 ; : ZL -*-
this is to get the indentation right
character lossage
This is meant to be called inside the PEEK-TOP-LEVEL,
character lossage
If you want to execute only once,
Then on exit restore the old mode in the menu and label.
Since probably the typeout window is going away now
and that old mode's data is reappearing.
Here if we are entering a mode that really does update.
We stay in it semipermanently.
This is the top level function that runs in the process of a window of flavor PEEK.
to do the actual displaying in.
not the usual large menu font
This is the command reading loop.
character lossage
If sheet not exposed, notice when wakeup-time is passed
If we don't do this and sheet is deexposed for a long time, peek
stops redisplaying
A special command (forced input, no doubt)
Standard character, either accumulate arg or select new mode
Check for standard character assignments
We want to redisplay. If have typeout, hang until user confirms.
Processes, meters
character too small
Not idle
si:read-main-stat-counter
si:read-aux-stat-counter
(peek-rate-average pr))
peek-maintain-rates-time-constant)
(t
(LIST ()
#'(LAMBDA (COUNTER)
(SCROLL-PARSE-ITEM
`(:FUNCTION READ-METER (,COUNTER) NIL
(SCROLL-PARSE-ITEM "")
(scroll-parse-item
`(:mouse-item
(nil :eval (peek-stat-counter-controls-menu)
:documentation
"Change stat counter controls.")
(scroll-parse-item "Main: "
`(:function ,#'(lambda ()
(nth (ldb si::%%main-stat-clock-control
(si::read-rg-mode))
stat-clock-values))
() nil ("~a"))
"; "
`(:function ,#'(lambda ()
(nth (ldb si::%%main-stat-count-control
(si::read-rg-mode))
stat-count-values))
() nil ("~a")))
(scroll-parse-item "Aux : "
`(:function ,#'(lambda ()
(nth (ldb si::%%aux-stat-clock-control
(si::read-rg-mode))
stat-clock-values))
() nil ("~a"))
"; "
`(:function ,#'(lambda ()
(nth (ldb si::%%aux-stat-count-control
(si::read-rg-mode))
stat-count-values))
() nil ("~a")))
(scroll-parse-item "Main counter: "
(scroll-parse-item "Aux counter: "
(scroll-parse-item "Main - Aux: "
`(:function ,#'(lambda ()
(- (si::read-main-stat-counter)
(si::read-aux-stat-counter)))
() nil ("~20:d")))
`(:function ,#'(lambda ()
(let ((main (si::read-main-stat-counter))
(aux (si::read-aux-stat-counter)))
"***")
(t
(// (float main) aux)))))
() nil ("~20f")))
(scroll-parse-item "Aux // Main: "
`(:function ,#'(lambda ()
(let ((main (si::read-main-stat-counter))
(aux (si::read-aux-stat-counter)))
(cond ((zerop main)
"***")
(t
(// (float aux) main)))))
() nil ("~20f")))
))
(defun peek-stat-counter-controls-menu ()
(defvar peek-main-stat-count :hi)
(defvar peek-aux-stat-count :hi)
(defconst stat-count-values '(:VALID.STATISTICS.BIT
:CSM.STATISTICS.BIT
:INCREMENT.LC
:T.STATISTICS.BIT
:HI))
(defun make-atom-list-into-menu-alist (atom-list)
(loop for a in atom-list
collect (list (string a) a)))
(defun peek-stat-counter-controls-function ()
(tv:choose-variable-values `((peek-main-stat-clock
"Main stat clock"
:menu-alist ,(make-atom-list-into-menu-alist stat-clock-values))
(peek-main-stat-count
"Main stat count control"
:menu-alist ,(make-atom-list-into-menu-alist stat-count-values))
(peek-aux-stat-clock
"Aux stat clock"
:menu-alist ,(make-atom-list-into-menu-alist stat-clock-values))
(peek-aux-stat-count
"Aux stat count control"
:menu-alist ,(make-atom-list-into-menu-alist stat-count-values))
"foo"
"bar"
)
)
(si::write-main-stat-control (find-position-in-list peek-main-stat-clock stat-clock-values)
(find-position-in-list peek-main-stat-count stat-count-values))
(si::write-aux-stat-control (find-position-in-list peek-aux-stat-clock stat-clock-values)
(find-position-in-list peek-aux-stat-count stat-count-values))
(si::reset-stat-counters)
)
Memory
Clicked on this item, need to complement state
If aren't displaying boredom now, display it
Clicked on this item, need to complement state
If aren't displaying regions now, display them
no regions at all in this area
File system status
Peeking at windows
PEEK.LISP#191 on 2 - Oct-86 04:12:43
Connection stat
Hack hostat | * * ( c ) Copyright 1980 Massachusetts Institute of Technology * *
PEEK -- displays status information about the Lisp Machine
Define the display modes , and how to select them .
(DEFVAR *PEEK-DEFAULT-MODE-ALIST* NIL
"This variable has one element for each Peek display mode.
Elements are added by calls to DEFINE-PEEK-MODE which appear in this file
and the other source files of PEEK, and are executed at load time.
Each element looks like:
/(character display-function menu-item-string no-updating-flag long-documentation).
That is also what the five arguments to DEFINE-PEEK-MODE look like.
The menu-item-string is a short phrase of documentation which is also
what appears in the menu proper.
The display function is what is called to update the display.
NO-UPDATING-FLAG is either T or NIL. If T, it means simply call the
function once and leave what it prints on the screen. Normally it is NIL,
which means that the updating function returns a set of scroll items.")
(DEFVAR *PEEK-MENU-ITEM-ALIST* NIL
"This is the item alist for the command menu.
The first element of each element is the menu item string.
The third element is the corresponding element of *PEEK-DEFAULT-MODE-ALIST*.")
(DEFMACRO DEFINE-PEEK-MODE (FUNCTION CHARACTER DOCUMENTATION &OPTIONAL FUNCTION-P
(DECLARE (ARGLIST FUNCTION CHARACTER DOCUMENTATION &OPTIONAL FUNCTION-P LONG-DOCUMENTATION))
`(DEFINE-PEEK-MODE-1 ',FUNCTION ,CHARACTER ,DOCUMENTATION ,FUNCTION-P ,(CAR LONG-DOCUMENTATION)))
(DEFUN DEFINE-PEEK-MODE-1 (FUNCTION CHARACTER DOCUMENTATION FUNCTION-P LONG-DOCUMENTATION)
(IF (NUMBERP CHARACTER) (SETQ CHARACTER (INT-CHAR CHARACTER)))
(WITHOUT-INTERRUPTS
(SETQ *PEEK-DEFAULT-MODE-ALIST*
(NCONC (DELQ (ASSQ CHARACTER *PEEK-DEFAULT-MODE-ALIST*) *PEEK-DEFAULT-MODE-ALIST*)
(NCONS (LIST CHARACTER FUNCTION DOCUMENTATION
FUNCTION-P LONG-DOCUMENTATION))))
(SETQ *PEEK-MENU-ITEM-ALIST*
(MAPCAR (LAMBDA (ELT)
`(,(THIRD ELT) :VALUE ,ELT
:DOCUMENTATION ,(OR (FIFTH ELT) "This PEEK mode is undocumented.")))
*PEEK-DEFAULT-MODE-ALIST*))))
and MODE should be a character and the first arg can be a numeric argument .
(DEFUN PEEK-SET-MODE (WINDOW MODE &REST ARGS &AUX OLD-MODE)
(IF (NUMBERP MODE) (SETQ MODE (INT-CHAR MODE)))
(WHEN (SETQ MODE (ASSQ MODE *PEEK-DEFAULT-MODE-ALIST*))
(SETQ OLD-MODE (LABEL-STRING (SEND WINDOW :LABEL)))
(SEND (SEND (SEND WINDOW :SUPERIOR) :GET-PANE 'MENU)
:SET-HIGHLIGHTED-ITEMS
(LIST (SYS:ASSOC-EQUALP (THIRD MODE) *PEEK-MENU-ITEM-ALIST*)))
(SEND WINDOW :SET-LABEL (THIRD MODE))
(IF (FOURTH MODE)
(UNWIND-PROTECT
(APPLY (SECOND MODE) WINDOW ARGS)
(PEEK-ASSURE-NO-TYPEOUT WINDOW)
(DOLIST (ELT *PEEK-DEFAULT-MODE-ALIST*)
(IF (EQUALP OLD-MODE (THIRD ELT))
(RETURN (SETQ MODE ELT))))
(SEND (SEND (SEND WINDOW :SUPERIOR) :GET-PANE 'MENU)
:SET-HIGHLIGHTED-ITEMS
(LIST (SYS:ASSOC-EQUALP (THIRD MODE) *PEEK-MENU-ITEM-ALIST*)))
(SEND WINDOW :SET-LABEL (THIRD MODE)))
(PEEK-ASSURE-NO-TYPEOUT WINDOW)
(SEND WINDOW :SET-DISPLAY-ITEM (APPLY (SECOND MODE) ARGS)))
T))
Windows for PEEK .
(DEFFLAVOR BASIC-PEEK ((NEEDS-REDISPLAY NIL))
(SCROLL-MOUSE-MIXIN SCROLL-WINDOW-WITH-TYPEOUT FULL-SCREEN-HACK-MIXIN)
:SETTABLE-INSTANCE-VARIABLES
:GETTABLE-INSTANCE-VARIABLES
(:DEFAULT-INIT-PLIST :SAVE-BITS T
:LABEL "Peek"
:TRUNCATION T)
(:DOCUMENTATION :SPECIAL-PURPOSE "The actual peek window. This has the capability
to display in a PEEK display mode."))
(DEFMETHOD (BASIC-PEEK :NAME-FOR-SELECTION) ()
(STRING-APPEND "Peek: " (LABEL-STRING LABEL)))
(DEFFLAVOR PEEK-WINDOW () (PROCESS-MIXIN TV:INITIALLY-INVISIBLE-MIXIN BASIC-PEEK)
(:DEFAULT-INIT-PLIST :PROCESS
'(PEEK-STANDALONE-TOP-LEVEL :SPECIAL-PDL-SIZE #o4000
:REGULAR-PDL-SIZE #o10000))
(:DOCUMENTATION :COMBINATION "Peek window with a process.
Usable as a stand-alone window that does PEEK display,
but with no menu -- only keyboard commands will be available."))
(DEFUN PEEK-MOUSE-CLICK (ITEM LEADER-TO-COMPLEMENT)
(DECLARE (:SELF-FLAVOR BASIC-PEEK))
(SETQ NEEDS-REDISPLAY T)
(SETF (ARRAY-LEADER ITEM (+ SCROLL-ITEM-LEADER-OFFSET LEADER-TO-COMPLEMENT))
(NOT (ARRAY-LEADER ITEM (+ SCROLL-ITEM-LEADER-OFFSET LEADER-TO-COMPLEMENT)))))
(DEFUN PEEK-STANDALONE-TOP-LEVEL (WINDOW)
(PEEK-TOP-LEVEL WINDOW #/HELP)
(DO-FOREVER
(DESELECT-AND-MAYBE-BURY-WINDOW (SEND WINDOW :ALIAS-FOR-SELECTED-WINDOWS) :FIRST)
(PEEK-TOP-LEVEL WINDOW NIL)))
Peek frames that have command menus of modes , as well as a peek - window
(DEFFLAVOR PEEK-FRAME ()
(PROCESS-MIXIN
FRAME-DONT-SELECT-INFERIORS-WITH-MOUSE-MIXIN
BORDERED-CONSTRAINT-FRAME-WITH-SHARED-IO-BUFFER)
(:DEFAULT-INIT-PLIST :SAVE-BITS :DELAYED :PROCESS ))
(DEFMETHOD (PEEK-FRAME :BEFORE :INIT) (INIT-PLIST)
(SETQ PANES (LIST
(IF (GETL INIT-PLIST '(:PROCESS))
`(PEEK PEEK-WINDOW :SAVE-BITS NIL :PROCESS ,(GET INIT-PLIST :PROCESS))
'(PEEK PEEK-WINDOW :SAVE-BITS NIL))
`(MENU DYNAMIC-HIGHLIGHTING-COMMAND-MENU-PANE
:LABEL "Peek Modes"
:ITEM-LIST-POINTER *PEEK-MENU-ITEM-ALIST*)))
(SETQ CONSTRAINTS `((MAIN . ((MENU PEEK)
((MENU :ASK :PANE-SIZE))
((PEEK :EVEN)))))))
(DEFMETHOD (PEEK-FRAME :AFTER :INIT) (IGNORE)
(LET ((PANE (SEND SELF :GET-PANE 'PEEK)))
(SEND SELF :SELECT-PANE PANE)
(SETQ PROCESS (SEND PANE :PROCESS))))
(DEFMETHOD (PEEK-FRAME :BEFORE :EXPOSE) (&REST IGNORE)
(OR EXPOSED-P
(EQUAL *PEEK-MENU-ITEM-ALIST*
(SEND (SEND SELF :GET-PANE 'MENU) :ITEM-LIST))
(SEND SELF :SET-CONFIGURATION 'MAIN)))
(DEFFLAVOR DYNAMIC-HIGHLIGHTING-COMMAND-MENU-PANE ()
(DYNAMIC-ITEM-LIST-MIXIN MENU-HIGHLIGHTING-MIXIN COMMAND-MENU))
(COMPILE-FLAVOR-METHODS PEEK-FRAME PEEK-WINDOW DYNAMIC-HIGHLIGHTING-COMMAND-MENU-PANE)
(DEFUN PEEK (&OPTIONAL INITIAL-MODE)
"Select a new or old Peek window. An argument sets the Peek display mode."
(SELECT-OR-CREATE-WINDOW-OF-FLAVOR 'PEEK-FRAME)
(IF INITIAL-MODE
(SEND SELECTED-WINDOW :FORCE-KBD-INPUT
(TYPECASE INITIAL-MODE
(STRING (CHAR INITIAL-MODE 0))
(SYMBOL (CHAR (SYMBOL-NAME INITIAL-MODE) 0))
(T INITIAL-MODE))))
(AWAIT-WINDOW-EXPOSURE))
(DEFVAR PEEK-SLEEP-TIME 120.
"This is how long, in 60'ths of a second, to wait between updates of the screen in PEEK.")
(DEFUN PEEK-TOP-LEVEL (WINDOW MODE)
(COND-EVERY
((AND MODE (SYMBOLP MODE)) (SETQ MODE (SYMBOL-NAME MODE)))
((STRINGP MODE) (SETQ MODE (CHAR MODE 0)))
((CHARACTERP MODE) (SETQ MODE (CHAR-INT MODE)))
((NUMBERP MODE) (SEND WINDOW :FORCE-KBD-INPUT MODE)))
(BLOCK PEEK
(DO-FOREVER
(CATCH-ERROR-RESTART ((SYS:ABORT ERROR) "Return to PEEK command level.")
(DO ((SLEEP-TIME PEEK-SLEEP-TIME)
(WAKEUP-TIME (TIME-DIFFERENCE (TIME) (- PEEK-SLEEP-TIME)))
(wakeup-time-passed nil)
(*TERMINAL-IO* (SEND WINDOW :TYPEOUT-WINDOW))
(ARG)
(CHAR))
(())
(when (or (TIME-LESSP WAKEUP-TIME (TIME)) wakeup-time-passed)
(SETQ WAKEUP-TIME (TIME-DIFFERENCE (TIME) (- SLEEP-TIME)))
(setq wakeup-time-passed nil))
(OR (= SLEEP-TIME 0)
(PROCESS-WAIT "Peek Timeout or TYI"
(LAMBDA (TIME FLAG-LOC STREAM PEEK-WINDOW)
(if (SHEET-EXPOSED-P PEEK-WINDOW)
(OR wakeup-time-passed
(TIME-LESSP TIME (TIME))
(CONTENTS FLAG-LOC)
(SEND STREAM :LISTEN))
(when (time-lessp time (time))
(setq wakeup-time-passed t)
nil)))
WAKEUP-TIME
(LOCATE-IN-INSTANCE WINDOW 'NEEDS-REDISPLAY)
*TERMINAL-IO*
(SEND WINDOW :ALIAS-FOR-SELECTED-WINDOWS)))
(DO ()
((PROGN (PEEK-ASSURE-NO-TYPEOUT WINDOW)
(NULL (SETQ CHAR (SEND *TERMINAL-IO* :ANY-TYI-NO-HANG)))))
(COND-EVERY
((CONSP CHAR)
(CASE (CAR CHAR)
(SUPDUP (SUPDUP (CADR CHAR)))
(SUPDUP:TELNET (TELNET (CADR CHAR)))
(QSEND (QSEND (CADR CHAR))
(SEND WINDOW :SET-NEEDS-REDISPLAY T)
(SEND *TERMINAL-IO* :MAKE-COMPLETE))
(EH (EH (CADR CHAR)))
(INSPECT (INSPECT (CADR CHAR)))
(DESCRIBE (DESCRIBE (CADR CHAR)))
(:eval (eval (cadr char)))
(:MENU (SETQ CHAR (FIRST (THIRD (SECOND CHAR)))))
(:mouse-button
(mouse-call-system-menu))
(OTHERWISE (BEEP)))
(SETQ ARG NIL))
((NUMBERP CHAR)
(SETQ CHAR (INT-CHAR CHAR)))
((CHARACTERP CHAR)
(SETQ CHAR (CHAR-UPCASE CHAR))
(IF (DIGIT-CHAR-P CHAR)
(SETQ ARG (+ (* 10. (OR ARG 0)) (DIGIT-CHAR-P CHAR)))
(IF (PEEK-SET-MODE WINDOW CHAR ARG)
(SETQ ARG NIL)
(CASE CHAR
(#/HELP
(SEND *STANDARD-OUTPUT* :CLEAR-WINDOW)
(LET (INPUT)
(SETQ INPUT (SEND *STANDARD-INPUT* :LISTEN))
(UNLESS INPUT
(FORMAT T "The Peek program shows a continuously updating status display.
There are several modes that display different status.
Here is a list of modes. Select a mode by typing the character
or by clicking on the corresponding menu item.~2%"))
(DOLIST (E *PEEK-DEFAULT-MODE-ALIST*)
(WHEN (OR INPUT (SETQ INPUT (SEND *STANDARD-INPUT* :LISTEN)))
(RETURN))
(FORMAT T "~:@C~5T~A~%~@[~6T~A~%~]"
(FIRST E) (THIRD E) (FIFTH E)))
(UNLESS INPUT
(FORMAT T "~%Q~5TQuit.~%")
(FORMAT T "nZ~5TSets sleep time between updates to n seconds.~2%")
(FORMAT T "[Help] Prints this message.~2%")))
(SETQ ARG NIL))
(#/Q
(RETURN-FROM PEEK NIL))
(#/Z
(AND ARG (SETQ SLEEP-TIME (* 60. ARG)))
(SEND WINDOW :SET-NEEDS-REDISPLAY T)
(SETQ ARG NIL))
(#/SPACE (SEND WINDOW :SET-NEEDS-REDISPLAY T))
(OTHERWISE (BEEP))))))))
(WHEN (OR (SEND WINDOW :NEEDS-REDISPLAY) (TIME-LESSP WAKEUP-TIME (TIME)))
(SEND WINDOW :SET-NEEDS-REDISPLAY NIL)
(SEND WINDOW :REDISPLAY)))))))
(DEFUN PEEK-ASSURE-NO-TYPEOUT (WINDOW)
(WHEN (SEND (SETQ WINDOW (SEND WINDOW :TYPEOUT-WINDOW)) :INCOMPLETE-P)
(FORMAT T "~&Type any character to flush:")
(LET ((CHAR (SEND *TERMINAL-IO* :ANY-TYI)))
(SEND WINDOW :MAKE-COMPLETE)
(UNLESS (EQ CHAR #/SPACE)
(SEND *TERMINAL-IO* :UNTYI CHAR)))))
(DEFINE-PEEK-MODE PEEK-PROCESSES #/P "Active Processes" NIL
"List status of every process -- why waiting, how much run recently.")
(DEFUN PEEK-PROCESSES (IGNORE)
"Shows state of all active processes."
(LIST ()
30 of process name , 25 of state , 5 of priority , 10 of quantum left / quantum ,
8 of percentage , followed by idle time ( 11 columns )
(SCROLL-PARSE-ITEM (FORMAT NIL "~30A~21A~10A~10A~8A~8A"
"Process Name" "State" "Priority" "Quantum"
" %" "Idle"))
(SCROLL-PARSE-ITEM "")
(SCROLL-MAINTAIN-LIST #'(LAMBDA () ALL-PROCESSES)
#'(LAMBDA (PROCESS)
(SCROLL-PARSE-ITEM
`(:MOUSE-ITEM
(NIL :EVAL (PEEK-PROCESS-MENU ',PROCESS 'ITEM 0)
:DOCUMENTATION
"Menu of useful things to do to this process.")
:STRING ,(PROCESS-NAME PROCESS) 30.)
`(:FUNCTION ,#'PEEK-WHOSTATE ,(NCONS PROCESS) 25.)
`(:FUNCTION ,PROCESS (:PRIORITY) 5. ("~D."))
`(:FUNCTION ,PROCESS (:QUANTUM-REMAINING) 5. ("~4D//"))
`(:FUNCTION ,PROCESS (:QUANTUM) 5. ("~D."))
`(:FUNCTION ,PROCESS (:PERCENT-UTILIZATION) 8.
("~1,1,4$%"))
`(:FUNCTION ,PROCESS (:IDLE-TIME) NIL
("~\TV::PEEK-PROCESS-IDLE-TIME\"))))
NIL
NIL)
(SCROLL-PARSE-ITEM "")
(SCROLL-PARSE-ITEM "Clock Function List")
(SCROLL-MAINTAIN-LIST #'(LAMBDA () SI::CLOCK-FUNCTION-LIST)
#'(LAMBDA (FUNC)
(SCROLL-PARSE-ITEM
`(:STRING ,(WITH-OUTPUT-TO-STRING (STR)
(PRINC FUNC STR))))))))
(FORMAT:DEFFORMAT PEEK-PROCESS-IDLE-TIME (:ONE-ARG) (ARG IGNORE)
((< ARG 60.) (FORMAT T "~D sec" ARG))
((< ARG 3600.) (FORMAT T "~D min" (TRUNCATE ARG 60.)))
(T (FORMAT T "~D hr" (TRUNCATE ARG 3600.)))))
(DEFUN PEEK-WHOSTATE (PROCESS)
(COND ((SI::PROCESS-ARREST-REASONS PROCESS) "Arrest")
((SI::PROCESS-RUN-REASONS PROCESS)
(or (si::process-wait-whostate process)
(string-append "Running: " (si::process-run-whostate process))))
(T "Stop")))
(DEFINE-PEEK-MODE PEEK-RATES #/R "Counter Rates" NIL
"Display the rate of change of the counters.")
(defstruct (peek-rate (:type :list))
peek-rate-counter-name
peek-rate-counter-type
peek-rate-last-value
peek-rate-average
)
(defconst peek-rate-list nil)
(defun put-meters-on-peek-rate-list (meter-list function-list)
(dolist (m meter-list)
(cond ((null (memq m si:a-memory-counter-block-names)))
((null (assq m peek-rate-list))
(let ((pr (make-peek-rate)))
(setf (peek-rate-counter-type pr) :meter)
(setf (peek-rate-counter-name pr) m)
(setf (peek-rate-last-value pr) (read-meter m))
(setf (peek-rate-average pr) 0)
(without-interrupts
(setq peek-rate-list (nconc peek-rate-list (list pr))))))))
(dolist (f function-list)
(cond ((null (assq f peek-rate-list))
(let ((pr (make-peek-rate)))
(setf (peek-rate-counter-type pr) :function)
(setf (peek-rate-counter-name pr) f)
(setf (peek-rate-last-value pr) (funcall f))
(setf (peek-rate-average pr) 0)
(without-interrupts
(setq peek-rate-list (nconc peek-rate-list (list pr)))))))))
(put-meters-on-peek-rate-list '(si:%count-first-level-map-reloads
si:%count-second-level-map-reloads
%COUNT-PDL-BUFFER-READ-FAULTS
%COUNT-PDL-BUFFER-WRITE-FAULTS
%COUNT-PDL-BUFFER-MEMORY-FAULTS
%COUNT-DISK-PAGE-READS
%COUNT-DISK-PAGE-WRITES
%COUNT-FRESH-PAGES
%COUNT-AGED-PAGES
%COUNT-AGE-FLUSHED-PAGES
%COUNT-META-BITS-MAP-RELOADS
%COUNT-CONS-WORK
%COUNT-SCAVENGER-WORK
%AGING-DEPTH
%COUNT-FINDCORE-STEPS
%COUNT-FINDCORE-EMERGENCIES
%COUNT-DISK-PAGE-READ-OPERATIONS
%COUNT-DISK-PAGE-WRITE-OPERATIONS
%COUNT-DISK-PAGE-WRITE-WAITS
%COUNT-DISK-PAGE-WRITE-BUSYS
%COUNT-DISK-PREPAGES-USED
%COUNT-DISK-PREPAGES-NOT-USED
%DISK-WAIT-TIME
%COUNT-DISK-PAGE-WRITE-APPENDS
%COUNT-DISK-PAGE-READ-APPENDS
%COUNT-ILLOP-DEBUG
%COUNT-MICRO-FAULTS
)
'(
time:microsecond-time
))
(defconst peek-maintain-rates-time-constant 16.)
(defconst peek-maintain-rates-number-of-sixtieths 30.)
(defvar peek-maintain-rates-ticks-to-go 0)
(defun peek-maintain-rates (time-delta)
(condition-case ()
(progn
(decf peek-maintain-rates-ticks-to-go time-delta)
(cond ((<= peek-maintain-rates-ticks-to-go 0)
(setq peek-maintain-rates-ticks-to-go peek-maintain-rates-number-of-sixtieths)
(dolist (pr peek-rate-list)
(let* ((new-value (selectq (peek-rate-counter-type pr)
(:meter (read-meter (peek-rate-counter-name pr)))
(:function (funcall (peek-rate-counter-name pr)))))
(delta (- new-value (peek-rate-last-value pr))))
(decf (peek-rate-average pr)
(// (peek-rate-average pr) peek-maintain-rates-time-constant))
(incf (peek-rate-average pr) delta)
(setf (peek-rate-last-value pr) new-value)))
)))
(error (without-interrupts
(setq clock-function-list (delq 'peek-maintain-rates si:clock-function-list))))))
(defun activate-peek-rate-maintainer (on-p)
(peek-maintain-rates 1)
(without-interrupts
(cond ((null on-p)
(setq si:clock-function-list (delq 'peek-maintain-rates si:clock-function-list)))
((memq 'peek-maintain-rates si:clock-function-list))
(t
(setq peek-maintain-rates-ticks-to-go 0)
(push 'peek-maintain-rates si:clock-function-list)))))
(defmethod (peek-frame :after :deexpose) (&rest ignore)
(activate-peek-rate-maintainer nil))
(DEFUN PEEK-RATES (IGNORE)
"Statistics counter rates"
(activate-peek-rate-maintainer t)
(SCROLL-MAINTAIN-LIST
#'(LAMBDA () peek-rate-list)
#'(LAMBDA (pr)
(SCROLL-PARSE-ITEM
`(:STRING ,(STRING (peek-rate-counter-name pr)) 35.)
`(:function ,#'(lambda (pr)
(case (peek-rate-counter-type pr)
(:meter (read-meter (peek-rate-counter-name pr)))
(:function (funcall (peek-rate-counter-name pr)))))
(,pr) nil ("~15:d" 10. T))
`(:function ,#'(lambda (pr)
( // ( * ( // 60 . peek - maintain - rates - number - of - sixtieths )
(fix (* 0.12 (peek-rate-average pr)))
)
(,pr)
nil ("~15:d" 10. T))))))
(DEFINE-PEEK-MODE PEEK-COUNTERS #/% "Statistics Counters" NIL
"Display the values of all the microcode meters.")
(DEFUN PEEK-COUNTERS (IGNORE)
"Statistics counters"
( not ( fboundp ' - main - stat - counter ) )
(LIST ()
(SCROLL-MAINTAIN-LIST #'(LAMBDA () SYS:A-MEMORY-COUNTER-BLOCK-NAMES)
#'(LAMBDA (COUNTER)
(SCROLL-PARSE-ITEM
`(:STRING ,(STRING COUNTER) 35.)
`(:FUNCTION READ-METER (,COUNTER) NIL
("~@15A" 10. T)))))))
( SCROLL - MAINTAIN - LIST # ' ( LAMBDA ( ) SYS : A - MEMORY - COUNTER - BLOCK - NAMES )
` (: STRING , ( STRING COUNTER ) 35 . )
( " ~@15A " 10 . T ) ) ) ) )
: string " Statistics Counters " 20 . ) )
` (: function - main - stat - counter ( ) nil ( " ~20 : d " ) ) )
` (: function - stat - counter ( ) nil ( " ~20 : d " ) ) )
( scroll - parse - item " Main // Aux : "
( cond ( ( zerop aux )
))
( process - run - function " Change Stat Counters " ' peek - stat - counter - controls - function ) )
( defvar peek - main - stat - clock : )
( defvar peek - aux - stat - clock : )
( defconst stat - clock - values ' (: : UINST.CLOCK ) )
: MEMORY.START.NEXT.CYCLE
:
: 1.MHZ.CLOCK
(defun peek-memory-header ()
(scroll-parse-item
"Physical memory: "
`(:function ,(lambda (&aux (val (aref (symbol-function 'system-communication-area)
%sys-com-memory-size)))
(setf (value 0) (truncate val #o2000))
val)
nil nil (nil 8.))
`(:value 0 nil (" (~DK), "))
"Free space: "
`(:function ,(lambda (&aux (val (si::free-space)))
(setf (value 0) (truncate val #o2000))
val)
nil nil (nil 8.))
`(:value 0 nil (" (~DK)"))
", Wired pages "
`(:function ,(lambda ()
(multiple-value-bind (n-wired-pages n-fixed-wired-pages)
(si::count-wired-pages)
(setf (value 0) (- n-wired-pages n-fixed-wired-pages))
(setf (value 1) (truncate n-wired-pages (truncate 2000 page-size)))
(setf (value 2) (\ n-wired-pages (truncate 2000 page-size)))
n-fixed-wired-pages))
nil nil ("~D"))
`(:value 0 nil ("+~D "))
`(:value 1 nil ("(~D"))
`(:value 2 nil ("~[~;.25~;.5~;.75~]K)"))))
(define-peek-mode peek-areas #/A "Areas" nil
"Display status of areas, including how much memory allocated and used.")
(defconst *first-interesting-area* working-storage-area
"All areas this are uninteresting crufty system frobs and kludges.")
(defun peek-areas (ignore)
"Areas"
(list ()
(peek-memory-header)
(scroll-parse-item "")
(scroll-maintain-list
(lambda () 'boring)
(lambda (area)
(if (eq area 'boring)
(list
'(:pre-process-function peek-areas-boring-display)
(scroll-parse-item
:mouse-self '(nil :eval (peek-mouse-click 'self 0)
:documentation
"Insert//remove display of boring areas.")
:leader `(nil)
`(:function ,(lambda () (1- *first-interesting-area*))
()
nil (" 0-~D /"Uninteresting/" system-internal areas"))))
(list
'(:pre-process-function peek-areas-region-display)
(scroll-parse-item
:mouse-self '(nil :eval (peek-mouse-click 'self 0)
:documentation
"Insert//remove display of all regions in this area.")
:leader `(nil ,area)
`(:function identity (,area) 4 ("~3D"))
`(:string ,(string (area-name area)) 40.)
`(:function ,(lambda (area)
(multiple-value-bind (length used n-regions)
(si::room-get-area-length-used area)
(setf (value 0) used)
(setf (value 1) length)
(setf (value 2)
(cond ((zerop length) 0)
((< length #o40000)
(truncate (* 100. (- length used)) length))
(t
(truncate (- length used) (truncate length 100.)))))
n-regions))
(,area) 15. ("(~D region~0@*~P)"))
`(:value 2 nil ("~@3A% free, " 10. t))
`(:value 0 nil ("~8O"))
`(:value 1 nil ("//~8O used"))))))
nil
(lambda (state &aux next-one this-one (len (array-length (symbol-function 'area-name))))
(if (eq state 'boring)
(values 'boring *first-interesting-area* nil)
(do ((i state (1+ i)))
(( i len) nil)
(cond ((and (null this-one) (aref (symbol-function 'area-name) i))
(setq this-one i))
((and this-one (aref (symbol-function 'area-name) i))
(setq next-one i)
(return t))))
(values this-one next-one (null next-one)))))))
(defun peek-areas-boring-display (item)
"Handles adding/deleting of the boring areas when a mouse button is clicked."
(cond ((null (array-leader (cadr item) scroll-item-leader-offset)))
((= (length item) 2)
(setf (cddr item)
(ncons
(scroll-maintain-list
(lambda () 0)
(lambda (area)
(list
'(:pre-process-function peek-areas-region-display)
(scroll-parse-item
:mouse-self '(nil :eval (peek-mouse-click 'self 0)
:documentation
"Insert//remove display of all regions in this boring area.")
:leader `(nil ,area)
`(:function identity (,area) 5 (" ~3D"))
`(:string ,(string (area-name area)) 39.)
`(:function ,(lambda (area)
(multiple-value-bind (length used n-regions)
(si::room-get-area-length-used area)
(setf (value 0) used)
(setf (value 1) length)
(setf (value 2)
(cond ((zerop length) 0)
((< length #o40000)
(truncate (* 100. (- length used))
length))
(t
(truncate (- length used)
(truncate length 100.)))))
n-regions))
(,area) 15. ("(~D region~0@*~P)"))
`(:value 2 nil ("~@3A% free, " 10. t))
`(:value 0 nil ("~O"))
`(:value 1 nil ("//~O used")))))
nil
(lambda (state &aux next-one this-one)
(do ((i state (1+ i)))
(( i *first-interesting-area*) nil)
(cond ((and (null this-one) (aref (symbol-function 'area-name) i))
(setq this-one i))
((and this-one (aref (symbol-function 'area-name) i))
(setq next-one i)
(return t))))
(values this-one next-one (null next-one)))))))
(t (setf (cddr item) nil)))
(setf (array-leader (cadr item) scroll-item-leader-offset) nil))
(defun peek-areas-region-display (item)
"Handles adding/deleting of the region display when a mouse button is clicked."
(cond ((null (array-leader (cadr item) scroll-item-leader-offset)))
((= (length item) 2)
(setf (cddr item)
(ncons
(scroll-maintain-list
(lambda ()
(si:%area-region-list (array-leader (first (scroll-items item))
(1+ scroll-item-leader-offset))))
(lambda (region)
(if (minusp region)
(scroll-parse-item `(:string " No regions in this area"))
(scroll-parse-item
`(:string
,(format nil " ~3O: Origin ~8O, Length ~8O, "
region
(si:%pointer-unsigned (si::%region-origin region))
(si::%region-length region)))
`(:function ,#'si::%region-free-pointer (,region) nil ("Used ~8O, "))
`(:function
,(lambda (region)
(let ((used (si::%region-free-pointer region))
(scavenged (si::%region-gc-pointer region)))
(cond ((not (si::%region-scavenge-enable region))
"Scavenger off, ")
((= used scavenged)
"Scavenge done, ")
((= used 0)
"Scavenged 0%, ")
(t
(format nil "Scavenged ~D%, "
(round
(* 100. (// (float scavenged)
(float used)))))))))
(,region))
`(:string
,(format nil "~A space, Vol=~D."
(nth (si::%region-type region)
'(free old new new1 new2 new3 new4 new5 new6
static fixed extra-pdl copy))
(si::%region-volatility region))))))
nil
(lambda (state)
(if (minusp state)
(values -1 -1 t)
(values state
(si:%region-list-thread state)
(minusp (si:%region-list-thread state)))))))))
(t (setf (cddr item) nil)))
(setf (array-leader (cadr item) scroll-item-leader-offset) nil))
(DEFINE-PEEK-MODE PEEK-page-status #/M "Memory Usage" NIL
"Percent of each area paged in.")
(DEFUN PEEK-page-status (IGNORE)
"Page Status"
(LIST ()
(scroll-maintain-list
#'(lambda ()
(loop for i from si:VIRTUAL-PAGE-DATA below (array-length #'area-name)
when (aref #'area-name i)
collect (aref #'area-name i)))
#'(lambda (area)
(scroll-parse-item
`(:string ,(string area) 40.)
`(:function page-status-function (,area) nil
("~@15A" 10. t)))))))
(defun page-status-function (area &aux (total-pages 0) (paged-in-pages 0))
(gc:without-flipping
(si:for-every-region-in-area (region (symbol-value area))
(select (ldb %%region-space-type (si:%region-bits region))
((%REGION-SPACE-FREE
%REGION-SPACE-OLD
%REGION-SPACE-EXTRA-PDL
%REGION-SPACE-MOBY-FIXED
%REGION-SPACE-MOBY-NEW))
((%REGION-SPACE-NEW
%REGION-SPACE-STATIC
%REGION-SPACE-FIXED
%REGION-SPACE-COPY)
(let ((pages-in-this-region (ceiling (si:%region-free-pointer region) page-size)))
(incf total-pages pages-in-this-region)
(dotimes (page-number pages-in-this-region)
(if (%page-status (ash page-number 8))
(incf paged-in-pages)))))
(t
(ferror nil "unknown region space type")))))
(when (not (zerop total-pages))
(format nil "~2d% of ~5d pages"
(round (* 100. (// (float paged-in-pages) total-pages)))
total-pages)))
(DEFINE-PEEK-MODE PEEK-FILE-SYSTEM #/F "File System Status" NIL
"Display status of FILE protocol connections to remote file systems.")
(DEFUN NEXT-INTERESTING-FILE-HOST-STEPPER (LIST)
(LET ((GOOD (SOME LIST (LAMBDA (X) (SEND-IF-HANDLES X :ACCESS)))))
(VALUES (CAR GOOD) (CDR GOOD) (NULL GOOD))))
(defun file-host-item-function (host)
(when host
(list (list :pre-process-function 'peek-file-host-pre-process
:host host
:access nil
:host-units nil)
'(nil)
'(nil))))
(defun peek-file-host-pre-process (item)
(let* ((host (getf (tv:scroll-item-plist item) :host))
(access (getf (tv:scroll-item-plist item) :access))
(host-units (getf (tv:scroll-item-plist item) :host-units))
(new-access (send host :access))
(new-host-units (send-if-handles new-access :host-units)))
(unless (and (eq access new-access) (equal host-units new-host-units))
(setf (getf (tv:scroll-item-plist item) :access) new-access)
(setf (getf (tv:scroll-item-plist item) :host-units) new-host-units)
(setf (cdr (tv:scroll-item-component-items item))
(append (send host :peek-file-system-header)
(send host :peek-file-system))))))
(defun peek-file-system (ignore)
"Display status of file system"
(scroll-maintain-list
#'(lambda () fs:*pathname-host-list*)
'file-host-item-function
nil
'next-interesting-file-host-stepper))
(DEFMETHOD (SI::FILE-DATA-STREAM-MIXIN :PEEK-FILE-SYSTEM) (&OPTIONAL (INDENT 0) &AUX DIRECTION)
"Returns a scroll item describing a stream"
(TV:SCROLL-PARSE-ITEM
:MOUSE `(NIL :EVAL (PEEK-FILE-SYSTEM-STREAM-MENU ',SELF)
:DOCUMENTATION "Menu of useful things to do to this open file.")
(AND ( INDENT 0) (FORMAT NIL "~V@T" INDENT))
(CASE (SETQ DIRECTION (SEND SELF :DIRECTION))
(:INPUT "Input ")
(:OUTPUT "Output ")
(OTHERWISE "?Direction? "))
(SEND (SEND SELF :PATHNAME) :STRING-FOR-PRINTING)
(IF (SEND SELF :CHARACTERS)
", Character, " ", Binary, ")
`(:FUNCTION ,#'(LAMBDA (STREAM)
(SETF (TV:VALUE 0) (SEND STREAM :READ-POINTER))
(TV:VALUE 0))
(,SELF) NIL ("~D"))
(AND (EQ DIRECTION :INPUT)
`(:FUNCTION ,#'(LAMBDA (STREAM)
(LET ((LENGTH (SEND STREAM :LENGTH)))
(AND LENGTH (NOT (ZEROP LENGTH))
(TRUNCATE (* 100. (TV:VALUE 0)) LENGTH))))
(,SELF) NIL ("~@[ (~D%)~]")))
" bytes"))
(DEFUN PEEK-FILE-SYSTEM-STREAM-MENU (STREAM)
(APPLY #'PROCESS-RUN-FUNCTION "Peek File System Menu"
SELF :PEEK-FILE-SYSTEM-MENU
(LIST STREAM)))
(DEFMETHOD (BASIC-PEEK :PEEK-FILE-SYSTEM-MENU) (STREAM)
(LET ((*TERMINAL-IO* TYPEOUT-WINDOW))
(MENU-CHOOSE `(("Close" :EVAL (SEND ',STREAM :CLOSE)
:DOCUMENTATION "Close selected file (normally).")
("Abort" :EVAL (SEND ',STREAM :CLOSE :ABORT)
:DOCUMENTATION "Close selected file (aborts writing).")
("Delete" :EVAL (SEND ',STREAM :DELETE)
:DOCUMENTATION "Delete selected file, but don't close it.")
("Describe" :EVAL (DESCRIBE ',STREAM)
:DOCUMENTATION "Describe the file's stream.")
("Inspect" :EVAL (INSPECT ',STREAM)
:DOCUMENTATION "Inspect the file's stream.")
)
(STRING (SEND STREAM :TRUENAME)))))
(DEFUN PEEK-PROCESS-MENU (&REST ARGS)
(APPLY #'PROCESS-RUN-FUNCTION "Peek Process Menu"
SELF :PEEK-PROCESS-MENU ARGS))
(DEFMETHOD (BASIC-PEEK :PEEK-PROCESS-MENU) (PROCESS &REST IGNORE &AUX CHOICE)
"Menu for interesting operations on processes in a peek display"
(LET ((*TERMINAL-IO* TYPEOUT-WINDOW)
(CHOICES '(("Debugger" :VALUE PROCESS-EH
:DOCUMENTATION
"Call the debugger to examine the selected process.")
("Arrest" :VALUE PROCESS-ARREST
:DOCUMENTATION "Arrest the selected process. Undone by Un-Arrest.")
("Un-Arrest" :VALUE PROCESS-UN-ARREST
:DOCUMENTATION "Un-Arrest the selected process. Complement of Arrest.")
("Flush" :VALUE PROCESS-FLUSH
:DOCUMENTATION
"Unwind the selected process' stack and make it unrunnable. Ask for confirmation.")
("Reset" :VALUE PROCESS-RESET
:DOCUMENTATION "Reset the selected process. Ask for confirmation.")
("Kill" :VALUE PROCESS-KILL
:DOCUMENTATION
"Kill the selected process. Ask for confirmation.")
("Describe" :VALUE PROCESS-DESCRIBE
:DOCUMENTATION
"Call DESCRIBE on this process.")
("Inspect" :VALUE PROCESS-INSPECT
:DOCUMENTATION
"Call INSPECT on this process."))))
Do n't offer EH for a simple process .
(OR (TYPEP (PROCESS-STACK-GROUP PROCESS) 'STACK-GROUP)
(POP CHOICES))
(SETQ CHOICE (MENU-CHOOSE CHOICES (PROCESS-NAME PROCESS)))
(CASE CHOICE
(PROCESS-ARREST (SEND PROCESS :ARREST-REASON))
(PROCESS-UN-ARREST (SEND PROCESS :REVOKE-ARREST-REASON))
(PROCESS-FLUSH (IF (MOUSE-Y-OR-N-P (FORMAT NIL "Flush ~A" PROCESS))
(SEND PROCESS :FLUSH)))
(PROCESS-RESET (IF (MOUSE-Y-OR-N-P (FORMAT NIL "Reset ~A" PROCESS))
(SEND PROCESS :RESET)))
(PROCESS-KILL (IF (MOUSE-Y-OR-N-P (FORMAT NIL "Kill ~A" PROCESS))
(SEND PROCESS :KILL)))
(PROCESS-EH (SEND SELF :FORCE-KBD-INPUT `(EH ,PROCESS)))
(PROCESS-DESCRIBE (SEND SELF :FORCE-KBD-INPUT `(DESCRIBE ,PROCESS)))
(PROCESS-INSPECT (SEND SELF :FORCE-KBD-INPUT `(INSPECT ,PROCESS)))
(NIL)
(OTHERWISE (BEEP)))))
(DEFINE-PEEK-MODE PEEK-WINDOW-HIERARCHY #/W "Window Hierarchy" NIL
"Display the hierarchy of window inferiors, saying which are exposed.")
(DEFUN PEEK-WINDOW-HIERARCHY (IGNORE)
(SCROLL-MAINTAIN-LIST #'(LAMBDA () ALL-THE-SCREENS)
#'(LAMBDA (SCREEN)
(LIST ()
(SCROLL-PARSE-ITEM (FORMAT NIL "Screen ~A" SCREEN))
(PEEK-WINDOW-INFERIORS SCREEN 2)
(SCROLL-PARSE-ITEM "")))))
(DEFUN PEEK-WINDOW-INFERIORS (WINDOW INDENT)
(SCROLL-MAINTAIN-LIST #'(LAMBDA () (SHEET-INFERIORS WINDOW))
#'(LAMBDA (SHEET)
(LIST ()
(SCROLL-PARSE-ITEM
(FORMAT NIL "~V@T" INDENT)
`(:MOUSE
(NIL :EVAL (PEEK-WINDOW-MENU ',SHEET)
:DOCUMENTATION
"Menu of useful things to do to this window.")
:STRING
,(SEND SHEET :NAME)))
(PEEK-WINDOW-INFERIORS SHEET (+ INDENT 4))))))
(DEFUN PEEK-WINDOW-MENU (&REST ARGS)
(APPLY #'PROCESS-RUN-FUNCTION "Peek Window Menu"
#'PEEK-WINDOW-MENU-INTERNAL SELF ARGS))
(DEFUN PEEK-WINDOW-MENU-INTERNAL (PEEK-WINDOW SHEET &REST IGNORE &AUX CHOICE)
"Menu for interesting operations on sheets in a peek display"
(SETQ CHOICE
(MENU-CHOOSE
'(("Deexpose" :VALUE :DEEXPOSE :DOCUMENTATION "Deexpose the window.")
("Expose" :VALUE :EXPOSE :DOCUMENTATION "Expose the window.")
("Select" :VALUE :SELECT :DOCUMENTATION "Select the window.")
("Deselect" :VALUE :DESELECT :DOCUMENTATION "Deselect the window.")
("Deactivate" :VALUE :DEACTIVATE :DOCUMENTATION "Deactivate the window.")
("Kill" :VALUE :KILL :DOCUMENTATION "Kill the window.")
("Bury" :VALUE :BURY :DOCUMENTATION "Bury the window.")
("Inspect" :VALUE :INSPECT :DOCUMENTATION "Look at window data structure."))
(SEND SHEET :NAME)))
(AND CHOICE
(OR (NEQ CHOICE :KILL)
(MOUSE-Y-OR-N-P (FORMAT NIL "Kill ~A" (SEND SHEET :NAME))))
(IF (EQ CHOICE :INSPECT)
(SEND PEEK-WINDOW :FORCE-KBD-INPUT `(INSPECT ,SHEET))
(SEND SHEET CHOICE))))
(DEFINE-PEEK-MODE PEEK-SERVERS #/S "Active Servers" NIL
"List all servers, who they are serving, and their status.")
(DEFUN PEEK-SERVERS (IGNORE)
(LIST ()
(SCROLL-PARSE-ITEM "Active Servers")
(SCROLL-PARSE-ITEM "Contact Name Host Process // State")
(SCROLL-PARSE-ITEM " Connection")
(SCROLL-PARSE-ITEM "")
(SCROLL-MAINTAIN-LIST
#'(LAMBDA () (SEND TV:WHO-LINE-FILE-STATE-SHEET :SERVERS))
#'(LAMBDA (SERVER-DESC)
(LET* ((PROCESS (SERVER-DESC-PROCESS SERVER-DESC))
(CONN (SERVER-DESC-CONNECTION SERVER-DESC))
(contact (server-desc-contact-name server-desc))
(HOST (if (typep conn 'chaos:conn)
(SI:GET-HOST-FROM-ADDRESS (CHAOS:FOREIGN-ADDRESS CONN) :CHAOS)
(nth-value 1 (ip:parse-internet-address (send conn :remote-address))))))
(LIST '(:PRE-PROCESS-FUNCTION PEEK-SERVER-PREPROCESS)
(SCROLL-PARSE-ITEM
:LEADER '(NIL NIL NIL)
`(:FUNCTION ,#'values (,contact) 20. ("~A"))
`(:MOUSE-ITEM
(NIL :EVAL (CHAOS:PEEK-CHAOS-HOST-MENU ',HOST 'TV:ITEM 0)
:DOCUMENTATION "Menu of useful things to do to this host.")
:FUNCTION ,#'VALUES (,HOST) 20. ("~A"))
`(:MOUSE
(NIL :EVAL (PEEK-PROCESS-MENU ',PROCESS)
:DOCUMENTATION
"Menu of useful things to do to this process.")
:STRING
,(FORMAT NIL "~S" PROCESS))
" "
`(:FUNCTION ,#'PEEK-WHOSTATE ,(NCONS PROCESS)))
(SCROLL-PARSE-ITEM
6
" "
`(:MOUSE-ITEM
(NIL :EVAL (PEEK-CONNECTION-MENU ',CONN 'ITEM ',host ',contact)
:DOCUMENTATION
"Menu of useful things to do this connection")
:STRING ,(FORMAT NIL "~S" CONN)))
hostat
(AND (SERVER-DESC-FUNCTION SERVER-DESC)
(APPLY (SERVER-DESC-FUNCTION SERVER-DESC)
(SERVER-DESC-ARGS SERVER-DESC)))))))))
(DEFUN PEEK-CONNECTION-MENU (CONN ITEM host contact)
(APPLY #'PROCESS-RUN-FUNCTION "Peek Server Connection Menu"
SELF :PEEK-SERVER-CONNECTION-MENU
(LIST CONN ITEM host contact)))
(DEFMETHOD (BASIC-PEEK :PEEK-SERVER-CONNECTION-MENU) (CONN ITEM host contact)
(LET ((*TERMINAL-IO* TYPEOUT-WINDOW))
(LET ((CHOICE
(MENU-CHOOSE (append '(("Close" :VALUE :CLOSE
:DOCUMENTATION "Close connection forcibly."))
(when (typep conn 'chaos:conn)
'(("Insert Detail" :VALUE :DETAIL
:DOCUMENTATION
"Insert detailed info about chaos connection.")))
(when (typep conn 'chaos:conn)
'(("Remove Detail" :VALUE :UNDETAIL
:DOCUMENTATION
"Remove detailed info from Peek display.")))
'(("Inspect" :VALUE :INSPECT
:DOCUMENTATION "Inspect the connection")))
(STRING-APPEND host "//" contact))))
(CASE CHOICE
(:CLOSE (if (typep conn 'chaos:conn)
(CHAOS:CLOSE-CONN CONN "Manual Close from PEEK")
(send conn :close)))
(:INSPECT (INSPECT CONN))
(:DETAIL (SETF (ARRAY-LEADER ITEM (+ 4 TV:SCROLL-ITEM-LEADER-OFFSET)) CONN)
(SETF (ARRAY-LEADER ITEM (+ 5 TV:SCROLL-ITEM-LEADER-OFFSET)) T))
(:UNDETAIL (SETF (ARRAY-LEADER ITEM (+ 4 TV:SCROLL-ITEM-LEADER-OFFSET)) NIL)
(SETF (ARRAY-LEADER ITEM (+ 5 TV:SCROLL-ITEM-LEADER-OFFSET)) NIL))))))
(DEFUN PEEK-SERVER-PREPROCESS (LIST-ITEM &AUX HOST)
(LET* ((LINE-ITEM (THIRD LIST-ITEM))
(HOST-ITEM (SECOND LIST-ITEM))
(WANTED (ARRAY-LEADER LINE-ITEM (+ 4 TV:SCROLL-ITEM-LEADER-OFFSET)))
(GOT (ARRAY-LEADER LINE-ITEM (+ 5 TV:SCROLL-ITEM-LEADER-OFFSET))))
(COND ((NULL WANTED)
(SETF (ARRAY-LEADER LINE-ITEM (+ 5 TV:SCROLL-ITEM-LEADER-OFFSET)) NIL)
(SETF (FOURTH LIST-ITEM) NIL))
((EQ WANTED GOT))
(T
(SETF (FOURTH LIST-ITEM) (CHAOS:PEEK-CHAOS-CONN WANTED))
(SETF (ARRAY-LEADER LINE-ITEM (+ 5 TV:SCROLL-ITEM-LEADER-OFFSET)) WANTED)))
(COND ((ARRAY-LEADER HOST-ITEM TV:SCROLL-ITEM-LEADER-OFFSET)
Want a hostat , make sure it 's there and for the right host
(IF (AND (EQ (SETQ HOST (ARRAY-LEADER HOST-ITEM (1+ TV:SCROLL-ITEM-LEADER-OFFSET)))
(ARRAY-LEADER HOST-ITEM (+ TV:SCROLL-ITEM-LEADER-OFFSET 2)))
(FIFTH LIST-ITEM))
NIL
(SETF (FIFTH LIST-ITEM) (CONS '() (CHAOS:PEEK-CHAOS-HOSTAT HOST 1)))
(SETF (ARRAY-LEADER HOST-ITEM (+ TV:SCROLL-ITEM-LEADER-OFFSET 2)) HOST)))
(T (SETF (FIFTH LIST-ITEM) NIL)
(SETF (ARRAY-LEADER HOST-ITEM (+ TV:SCROLL-ITEM-LEADER-OFFSET 2)) NIL)))))
(define-peek-mode peek-devices #/D "Devices" NIL
"Display information about devices.")
(defun peek-devices (ignore)
"Devices"
(list ()
(scroll-maintain-list
#'(lambda ()
(reverse
(loop for x in fs:*pathname-host-list*
when (typep x 'si:shared-device)
collect x)))
#'(lambda (dev)
(scroll-parse-item
`(:mouse-item
(nil :eval (peek-device-menu ',dev 'item 0)
:documentation
"Menu of useful things to do to this device.")
:string ,(send dev :name) 20.)
`(:function peek-dev-lock (,dev) nil ("~30a"))
`(:function peek-dev-owner (,dev) nil ("~10a"))
)))))
(defun peek-dev-lock (dev)
(let ((lock (car (send dev :lock))))
(cond ((null lock) "not locked")
(t (send lock :name)))))
(defun peek-dev-owner (dev)
(let ((owner (send dev :owner)))
(cond ((null owner) "free")
((eq owner :not-on-bus) "not on bus")
(t (format nil "slot ~d" owner)))))
(defun peek-device-menu (&rest args)
(apply #'process-run-function "Peek Device Menu"
self :peek-device-menu args))
(defmethod (basic-peek :peek-device-menu) (dev &rest ignore &aux choice)
"Menu for interesting operations on devices in a peek display"
(let ((*terminal-io* typeout-window)
(choices '(("Select window with lock" :value select
:documentation "Select the window who holds the lock for this device.")
("Clear lock" :value clear
:documentation "Clear the lock for this device.")
)))
(setq choice (menu-choose choices (send dev :name)))
(case choice
(select
(let ((proc (car (send dev :lock))))
(if (null proc)
(beep)
(dolist (w (send proc :run-reasons)
(beep))
(when (typep w 'tv:minimum-window)
(send w :select)
(return nil))))))
(clear
(rplaca (send dev :lock) nil))
(nil)
(otherwise (beep)))))
(define-peek-mode peek-general-status #/G "General Status" NIL
"Random internal processor state.")
(defstruct (peek-general-status-item
(:type :named-array)
(:conc-name peek-gs-)
(:print (format nil "#<Peek Processor Switch ~a>"
(peek-gs-pretty-name peek-general-status-item)
)))
name
pretty-name
get-function
set-function
)
(defun peek-gs-get-from-processor-switches (bit-name)
(ldb (symeval bit-name) (%processor-switches nil)))
(defun peek-gs-set-processor-switches (bit-name val)
(%processor-switches (dpb val (symeval bit-name) (%processor-switches nil))))
(defvar peek-processor-switch-items ())
(defun peek-processor-switch-items ()
(or peek-processor-switch-items
(setq peek-processor-switch-items
(loop for x in si::lambda-processor-switches-bits by 'cddr
collect (make-peek-general-status-item
:name x
:pretty-name
(string-capitalize-words
(if (string-equal x "%%PROCESSOR-SWITCH-" :end1 #o23)
(substring x #o23)
x))
:get-function 'peek-gs-get-from-processor-switches
:set-function 'peek-gs-set-processor-switches)))))
(defun peek-general-status (ignore)
"General Status"
(list ()
(scroll-maintain-list
#'(lambda () (peek-processor-switch-items))
#'(lambda (item)
(scroll-parse-item
`(:function ,(peek-gs-get-function item) (,(peek-gs-name item)) ()
("~@5A " 10. T))
`(:string ,(peek-gs-pretty-name item) 50.)
)))))
(defun create-first-peek-frame ()
(or (dolist (x (selectable-windows tv:main-screen))
(when (typep (second x) 'peek-frame)
(return t)))
(make-instance 'peek-frame :activate-p t)))
(add-initialization "Create a Peek Frame" '(create-first-peek-frame) '(:once))
(tv:add-system-key #/P 'PEEK-FRAME "Peek" T)
|
d9eed62e64d375a46f0769e75a65e31ae0f91ad1f99bbb8c72e9a3723048b762 | nyampass/conceit | char.clj | (ns conceit.commons.test.char
(use conceit.commons
conceit.commons.test
clojure.test))
(deftest* char-range-test
(= [\a \b \c \d \e] (char-range \a \e))
(= [\G \H \I \J \K \L] (char-range \G \L))
(= [\0 \1 \2 \3] (char-range \0 \3))
(= [\r] (char-range \r \r))
(= [\a \c \e] (char-range \a \e 2))
(= [\8 \7 \6 \5 \4] (char-range \8 \4 -1))
(= [\y] (char-range \y \y 10)))
;; (run-tests)
| null | https://raw.githubusercontent.com/nyampass/conceit/2b8ba8cc3d732fe2f58d320e2aa4ecdd6f3f3be5/conceit-commons/test/conceit/commons/test/char.clj | clojure | (run-tests) | (ns conceit.commons.test.char
(use conceit.commons
conceit.commons.test
clojure.test))
(deftest* char-range-test
(= [\a \b \c \d \e] (char-range \a \e))
(= [\G \H \I \J \K \L] (char-range \G \L))
(= [\0 \1 \2 \3] (char-range \0 \3))
(= [\r] (char-range \r \r))
(= [\a \c \e] (char-range \a \e 2))
(= [\8 \7 \6 \5 \4] (char-range \8 \4 -1))
(= [\y] (char-range \y \y 10)))
|
7a22e606407cf792e0f3d01cb58351b2b681aba3a2ccdf826a40eccce8a51c72 | kamek-pf/ntfd | Github.hs | module Config.Github
( loadGithubConfig
, GithubConfig(..)
)
where
import Data.Bifunctor (first)
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Data.Time.Clock (NominalDiffTime)
import Data.ByteString (ByteString)
import Numeric.Natural (Natural)
import Toml ((.=), decode, TomlCodec)
import qualified Toml
import Config.Env (expandPath, loadSecret)
import Config.Error (ConfigError(..))
import Helpers (normalizeDuration, toDiffTime)
| Load github configuration from raw TOML content
loadGithubConfig :: Text -> IO (Either ConfigError GithubConfig)
loadGithubConfig toml = do
let decoded = decode (Toml.table githubCodec "github") toml
case first ParseError decoded of
Left e -> pure $ Left e
Right parsed -> withEnv parsed
where
withEnv parsed = do
apiKey <- loadSecret $ apiKeySrc parsed
cacheDir <- expandPath "~/.cache/ntfd/github_avatars"
pure $ build apiKey cacheDir parsed
build Nothing _ parsed
| not (enabled parsed) = Left Disabled
| otherwise = Left MissingApiKey
build (Just key) cacheDir parsed
| not (enabled parsed) = Left Disabled
| otherwise = Right GithubConfig
{ githubEnabled = enabled parsed
, githubApiKey = encodeUtf8 key
, githubNotifTime = toDiffTime $ notifTimeout parsed
, githubShowAvatar = showAvatar parsed
, githubSyncFreq = normalizeDuration 10 $ syncFrequency parsed
, githubTemplate = template parsed
, githubAvatarDir = cacheDir
}
-- | Github configuration options required by the application
data GithubConfig = GithubConfig
{ githubEnabled :: Bool
, githubApiKey :: ByteString
, githubNotifTime :: NominalDiffTime
, githubShowAvatar :: Bool
, githubSyncFreq :: NominalDiffTime
, githubTemplate :: Text
, githubAvatarDir :: FilePath
} deriving (Show)
| Github configuration options as they can be read from the TOML configuration file
data TomlGithubConfig = TomlGithubConfig
{ enabled :: Bool
, apiKeySrc :: Text
, notifTimeout :: Natural
, showAvatar :: Bool
, syncFrequency :: Natural
, template :: Text
}
-- brittany-disable-next-binding
githubCodec :: TomlCodec TomlGithubConfig
githubCodec = TomlGithubConfig
<$> Toml.bool "enabled" .= enabled
<*> Toml.text "api_key" .= apiKeySrc
<*> Toml.natural "notification_timeout" .= notifTimeout
<*> Toml.bool "show_avatar" .= showAvatar
<*> Toml.natural "sync_frequency" .= syncFrequency
<*> Toml.text "display" .= template
| null | https://raw.githubusercontent.com/kamek-pf/ntfd/d297a59339b3310a62341ffa9c378180c578dbce/src/Config/Github.hs | haskell | | Github configuration options required by the application
brittany-disable-next-binding | module Config.Github
( loadGithubConfig
, GithubConfig(..)
)
where
import Data.Bifunctor (first)
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Data.Time.Clock (NominalDiffTime)
import Data.ByteString (ByteString)
import Numeric.Natural (Natural)
import Toml ((.=), decode, TomlCodec)
import qualified Toml
import Config.Env (expandPath, loadSecret)
import Config.Error (ConfigError(..))
import Helpers (normalizeDuration, toDiffTime)
| Load github configuration from raw TOML content
loadGithubConfig :: Text -> IO (Either ConfigError GithubConfig)
loadGithubConfig toml = do
let decoded = decode (Toml.table githubCodec "github") toml
case first ParseError decoded of
Left e -> pure $ Left e
Right parsed -> withEnv parsed
where
withEnv parsed = do
apiKey <- loadSecret $ apiKeySrc parsed
cacheDir <- expandPath "~/.cache/ntfd/github_avatars"
pure $ build apiKey cacheDir parsed
build Nothing _ parsed
| not (enabled parsed) = Left Disabled
| otherwise = Left MissingApiKey
build (Just key) cacheDir parsed
| not (enabled parsed) = Left Disabled
| otherwise = Right GithubConfig
{ githubEnabled = enabled parsed
, githubApiKey = encodeUtf8 key
, githubNotifTime = toDiffTime $ notifTimeout parsed
, githubShowAvatar = showAvatar parsed
, githubSyncFreq = normalizeDuration 10 $ syncFrequency parsed
, githubTemplate = template parsed
, githubAvatarDir = cacheDir
}
data GithubConfig = GithubConfig
{ githubEnabled :: Bool
, githubApiKey :: ByteString
, githubNotifTime :: NominalDiffTime
, githubShowAvatar :: Bool
, githubSyncFreq :: NominalDiffTime
, githubTemplate :: Text
, githubAvatarDir :: FilePath
} deriving (Show)
| Github configuration options as they can be read from the TOML configuration file
data TomlGithubConfig = TomlGithubConfig
{ enabled :: Bool
, apiKeySrc :: Text
, notifTimeout :: Natural
, showAvatar :: Bool
, syncFrequency :: Natural
, template :: Text
}
githubCodec :: TomlCodec TomlGithubConfig
githubCodec = TomlGithubConfig
<$> Toml.bool "enabled" .= enabled
<*> Toml.text "api_key" .= apiKeySrc
<*> Toml.natural "notification_timeout" .= notifTimeout
<*> Toml.bool "show_avatar" .= showAvatar
<*> Toml.natural "sync_frequency" .= syncFrequency
<*> Toml.text "display" .= template
|
bde6ddd9b0ced44402f32c48216dcdf632ae25d142adccb5b1ac543c4c4ba4b9 | pveber/bistro | SE_or_PE.ml | type 'a t =
| Single_end of 'a
| Paired_end of 'a * 'a
let map x ~f = match x with
| Single_end x -> Single_end (f x)
| Paired_end (x, y) -> Paired_end (f x, f y)
let fst = function
| Single_end x
| Paired_end (x, _) -> x
| null | https://raw.githubusercontent.com/pveber/bistro/da0ebc969c8c5ca091905366875cbf8366622280/lib/bio/SE_or_PE.ml | ocaml | type 'a t =
| Single_end of 'a
| Paired_end of 'a * 'a
let map x ~f = match x with
| Single_end x -> Single_end (f x)
| Paired_end (x, y) -> Paired_end (f x, f y)
let fst = function
| Single_end x
| Paired_end (x, _) -> x
| |
33b04b9b5307dfba2195dc4e43d286b57ffbb94b4df66f19fe2c6cafaf78600f | alang9/dynamic-graphs | bench-program.hs | import qualified Criterion.Main as Crit
import qualified Data.Graph.Dynamic.Levels as Levels
import qualified Data.Graph.Dynamic.Program as Program
import qualified Data.Text.Lazy.IO as TL
main :: IO ()
main = do
errOrProgram <- Program.decodeProgram Program.decodeInt <$> TL.getContents
Crit.defaultMain
[ Crit.env (either error return errOrProgram) $ \program -> Crit.bench "levels" $ Crit.nfIO $ do
levels <- Levels.empty'
Program.runProgram levels (program :: Program.Program Int)
]
| null | https://raw.githubusercontent.com/alang9/dynamic-graphs/b88f001850c7bee8faa62099e93172a0bb0df613/benchmarks/hs/bench-program.hs | haskell | import qualified Criterion.Main as Crit
import qualified Data.Graph.Dynamic.Levels as Levels
import qualified Data.Graph.Dynamic.Program as Program
import qualified Data.Text.Lazy.IO as TL
main :: IO ()
main = do
errOrProgram <- Program.decodeProgram Program.decodeInt <$> TL.getContents
Crit.defaultMain
[ Crit.env (either error return errOrProgram) $ \program -> Crit.bench "levels" $ Crit.nfIO $ do
levels <- Levels.empty'
Program.runProgram levels (program :: Program.Program Int)
]
| |
689ab9ce40d4435f381de52dc178d4588ef02f4ce0e8688e7323b4d943d812e0 | fakedata-haskell/fakedata | Opera.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Faker.Provider.Opera where
import Config
import Control.Monad.Catch
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseOpera :: FromJSON a => FakerSettings -> Value -> Parser a
parseOpera settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
opera <- faker .: "opera"
pure opera
parseOpera settings val = fail $ "expected Object, but got " <> (show val)
parseOperaField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseOperaField settings txt val = do
opera <- parseOpera settings val
field <- opera .:? txt .!= mempty
pure field
parseOperaFields ::
(FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a
parseOperaFields settings txts val = do
opera <- parseOpera settings val
helper opera txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser a
helper a [] = parseJSON a
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a (x:xs) = fail $ "expect Object, but got " <> (show a)
$(genParsers "opera" ["italian", "by_giuseppe_verdi"])
$(genProviders "opera" ["italian", "by_giuseppe_verdi"])
$(genParsers "opera" ["italian", "by_gioacchino_rossini"])
$(genProviders "opera" ["italian", "by_gioacchino_rossini"])
$(genParsers "opera" ["italian", "by_gaetano_donizetti"])
$(genProviders "opera" ["italian", "by_gaetano_donizetti"])
$(genParsers "opera" ["italian", "by_vincenzo_bellini"])
$(genProviders "opera" ["italian", "by_vincenzo_bellini"])
$(genParsers "opera" ["italian", "by_christoph_willibald_gluck"])
$(genProviders "opera" ["italian", "by_christoph_willibald_gluck"])
$(genParsers "opera" ["italian", "by_wolfgang_amadeus_mozart"])
$(genProviders "opera" ["italian", "by_wolfgang_amadeus_mozart"])
$(genParsers "opera" ["german", "by_wolfgang_amadeus_mozart"])
$(genProviders "opera" ["german", "by_wolfgang_amadeus_mozart"])
$(genParsers "opera" ["german", "by_ludwig_van_beethoven"])
$(genProviders "opera" ["german", "by_ludwig_van_beethoven"])
$(genParsers "opera" ["german", "by_carl_maria_von_weber"])
$(genProviders "opera" ["german", "by_carl_maria_von_weber"])
$(genParsers "opera" ["german", "by_richard_strauss"])
$(genProviders "opera" ["german", "by_richard_strauss"])
$(genParsers "opera" ["german", "by_richard_wagner"])
$(genProviders "opera" ["german", "by_richard_wagner"])
$(genParsers "opera" ["german", "by_robert_schumann"])
$(genProviders "opera" ["german", "by_robert_schumann"])
$(genParsers "opera" ["german", "by_franz_schubert"])
$(genProviders "opera" ["german", "by_franz_schubert"])
$(genParsers "opera" ["german", "by_alban_berg"])
$(genProviders "opera" ["german", "by_alban_berg"])
$(genParsers "opera" ["french", "by_christoph_willibald_gluck"])
$(genProviders "opera" ["french", "by_christoph_willibald_gluck"])
$(genParsers "opera" ["french", "by_maurice_ravel"])
$(genProviders "opera" ["french", "by_maurice_ravel"])
$(genParsers "opera" ["french", "by_hector_berlioz"])
$(genProviders "opera" ["french", "by_hector_berlioz"])
$(genParsers "opera" ["french", "by_georges_bizet"])
$(genProviders "opera" ["french", "by_georges_bizet"])
$(genParsers "opera" ["french", "by_charles_gounod"])
$(genProviders "opera" ["french", "by_charles_gounod"])
$(genParsers "opera" ["french", "by_camille_saint_saëns"])
$(genProviders "opera" ["french", "by_camille_saint_saëns"])
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/7b0875067386e9bb844c8b985c901c91a58842ff/src/Faker/Provider/Opera.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TemplateHaskell #
module Faker.Provider.Opera where
import Config
import Control.Monad.Catch
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Vector (Vector)
import Data.Yaml
import Faker
import Faker.Internal
import Faker.Provider.TH
import Language.Haskell.TH
parseOpera :: FromJSON a => FakerSettings -> Value -> Parser a
parseOpera settings (Object obj) = do
en <- obj .: (getLocaleKey settings)
faker <- en .: "faker"
opera <- faker .: "opera"
pure opera
parseOpera settings val = fail $ "expected Object, but got " <> (show val)
parseOperaField ::
(FromJSON a, Monoid a) => FakerSettings -> AesonKey -> Value -> Parser a
parseOperaField settings txt val = do
opera <- parseOpera settings val
field <- opera .:? txt .!= mempty
pure field
parseOperaFields ::
(FromJSON a, Monoid a) => FakerSettings -> [AesonKey] -> Value -> Parser a
parseOperaFields settings txts val = do
opera <- parseOpera settings val
helper opera txts
where
helper :: (FromJSON a) => Value -> [AesonKey] -> Parser a
helper a [] = parseJSON a
helper (Object a) (x:xs) = do
field <- a .: x
helper field xs
helper a (x:xs) = fail $ "expect Object, but got " <> (show a)
$(genParsers "opera" ["italian", "by_giuseppe_verdi"])
$(genProviders "opera" ["italian", "by_giuseppe_verdi"])
$(genParsers "opera" ["italian", "by_gioacchino_rossini"])
$(genProviders "opera" ["italian", "by_gioacchino_rossini"])
$(genParsers "opera" ["italian", "by_gaetano_donizetti"])
$(genProviders "opera" ["italian", "by_gaetano_donizetti"])
$(genParsers "opera" ["italian", "by_vincenzo_bellini"])
$(genProviders "opera" ["italian", "by_vincenzo_bellini"])
$(genParsers "opera" ["italian", "by_christoph_willibald_gluck"])
$(genProviders "opera" ["italian", "by_christoph_willibald_gluck"])
$(genParsers "opera" ["italian", "by_wolfgang_amadeus_mozart"])
$(genProviders "opera" ["italian", "by_wolfgang_amadeus_mozart"])
$(genParsers "opera" ["german", "by_wolfgang_amadeus_mozart"])
$(genProviders "opera" ["german", "by_wolfgang_amadeus_mozart"])
$(genParsers "opera" ["german", "by_ludwig_van_beethoven"])
$(genProviders "opera" ["german", "by_ludwig_van_beethoven"])
$(genParsers "opera" ["german", "by_carl_maria_von_weber"])
$(genProviders "opera" ["german", "by_carl_maria_von_weber"])
$(genParsers "opera" ["german", "by_richard_strauss"])
$(genProviders "opera" ["german", "by_richard_strauss"])
$(genParsers "opera" ["german", "by_richard_wagner"])
$(genProviders "opera" ["german", "by_richard_wagner"])
$(genParsers "opera" ["german", "by_robert_schumann"])
$(genProviders "opera" ["german", "by_robert_schumann"])
$(genParsers "opera" ["german", "by_franz_schubert"])
$(genProviders "opera" ["german", "by_franz_schubert"])
$(genParsers "opera" ["german", "by_alban_berg"])
$(genProviders "opera" ["german", "by_alban_berg"])
$(genParsers "opera" ["french", "by_christoph_willibald_gluck"])
$(genProviders "opera" ["french", "by_christoph_willibald_gluck"])
$(genParsers "opera" ["french", "by_maurice_ravel"])
$(genProviders "opera" ["french", "by_maurice_ravel"])
$(genParsers "opera" ["french", "by_hector_berlioz"])
$(genProviders "opera" ["french", "by_hector_berlioz"])
$(genParsers "opera" ["french", "by_georges_bizet"])
$(genProviders "opera" ["french", "by_georges_bizet"])
$(genParsers "opera" ["french", "by_charles_gounod"])
$(genProviders "opera" ["french", "by_charles_gounod"])
$(genParsers "opera" ["french", "by_camille_saint_saëns"])
$(genProviders "opera" ["french", "by_camille_saint_saëns"])
|
7ae5560cdd73d62f32fb9b26d33696114af67edabf1fa98944575c7dbedbbfee | FreeProving/free-compiler | Type.hs | | This module contains functions for converting types to Coq .
module FreeC.Backend.Coq.Converter.Type where
import Control.Monad ( (>=>) )
import qualified FreeC.Backend.Coq.Base as Coq.Base
import FreeC.Backend.Coq.Converter.Free
import qualified FreeC.Backend.Coq.Syntax as Coq
import FreeC.Environment.LookupOrFail
import qualified FreeC.IR.Syntax as IR
import FreeC.LiftedIR.Converter.Type
import qualified FreeC.LiftedIR.Syntax as LIR
import FreeC.Monad.Converter
-------------------------------------------------------------------------------
-- IR to Coq Translation --
-------------------------------------------------------------------------------
| Converts a type from IR to Coq , lifting it into the @Free@ monad .
--
-- [\(\tau^\dagger = Free\,Shape\,Pos\,\tau^*\)]
-- A type \(\tau\) is converted by lifting it into the @Free@ monad and
-- recursively converting the argument and return types of functions
-- using 'convertType''.
convertType :: IR.Type -> Converter Coq.Term
convertType = liftType >=> convertLiftedType
| Converts a type from IR to Coq .
--
-- In contrast to 'convertType', the type itself is not lifted into the
-- @Free@ monad. Only the argument and return types of the contained function
-- type constructors are lifted recursively.
--
-- [\(\alpha^* = \alpha'\)]
A type variable \(\alpha\ ) is translated by looking up the corresponding
-- Coq identifier \(\alpha'\).
--
[ \(T^ * = ) ]
-- A type constructor \(T\) is translated by looking up the corresponding
Coq identifier \(T'\ ) and adding the parameters \(Shape\ ) and ) .
--
-- [\((\tau_1\,\tau_2)^* = \tau_1^*\,\tau_2^*\)]
-- Type constructor applications are translated recursively but
-- remain unchanged otherwise.
--
[ \rightarrow \tau_2)^ * = \tau_1^\dagger \rightarrow \tau_2^\dagger\ ) ]
-- Type constructor applications are translated recursively but
-- remain unchanged otherwise.
convertType' :: IR.Type -> Converter Coq.Term
convertType' = liftType' >=> convertLiftedType
-------------------------------------------------------------------------------
-- Lifted IR to Coq Translation --
-------------------------------------------------------------------------------
| Converts a given type in the lifted IR to a Coq term .
convertLiftedType :: LIR.Type -> Converter Coq.Term
convertLiftedType (LIR.TypeVar srcSpan ident) = do
qualid <- lookupIdentOrFail srcSpan IR.TypeScope (IR.UnQual (IR.Ident ident))
return $ Coq.Qualid qualid
convertLiftedType (LIR.TypeCon srcSpan name args _) = do
qualid <- lookupIdentOrFail srcSpan IR.TypeScope name
args' <- mapM convertLiftedType args
return $ genericApply qualid [] [] args'
convertLiftedType (LIR.FuncType _ l r) = do
l' <- convertLiftedType l
r' <- convertLiftedType r
return $ Coq.Arrow l' r'
convertLiftedType (LIR.FreeTypeCon _ t) = do
t' <- convertLiftedType t
return $ genericApply Coq.Base.free [] [] [t']
| null | https://raw.githubusercontent.com/FreeProving/free-compiler/6931b9ca652a185a92dd824373f092823aea4ea9/src/lib/FreeC/Backend/Coq/Converter/Type.hs | haskell | -----------------------------------------------------------------------------
IR to Coq Translation --
-----------------------------------------------------------------------------
[\(\tau^\dagger = Free\,Shape\,Pos\,\tau^*\)]
A type \(\tau\) is converted by lifting it into the @Free@ monad and
recursively converting the argument and return types of functions
using 'convertType''.
In contrast to 'convertType', the type itself is not lifted into the
@Free@ monad. Only the argument and return types of the contained function
type constructors are lifted recursively.
[\(\alpha^* = \alpha'\)]
Coq identifier \(\alpha'\).
A type constructor \(T\) is translated by looking up the corresponding
[\((\tau_1\,\tau_2)^* = \tau_1^*\,\tau_2^*\)]
Type constructor applications are translated recursively but
remain unchanged otherwise.
Type constructor applications are translated recursively but
remain unchanged otherwise.
-----------------------------------------------------------------------------
Lifted IR to Coq Translation --
----------------------------------------------------------------------------- | | This module contains functions for converting types to Coq .
module FreeC.Backend.Coq.Converter.Type where
import Control.Monad ( (>=>) )
import qualified FreeC.Backend.Coq.Base as Coq.Base
import FreeC.Backend.Coq.Converter.Free
import qualified FreeC.Backend.Coq.Syntax as Coq
import FreeC.Environment.LookupOrFail
import qualified FreeC.IR.Syntax as IR
import FreeC.LiftedIR.Converter.Type
import qualified FreeC.LiftedIR.Syntax as LIR
import FreeC.Monad.Converter
| Converts a type from IR to Coq , lifting it into the @Free@ monad .
convertType :: IR.Type -> Converter Coq.Term
convertType = liftType >=> convertLiftedType
| Converts a type from IR to Coq .
A type variable \(\alpha\ ) is translated by looking up the corresponding
[ \(T^ * = ) ]
Coq identifier \(T'\ ) and adding the parameters \(Shape\ ) and ) .
[ \rightarrow \tau_2)^ * = \tau_1^\dagger \rightarrow \tau_2^\dagger\ ) ]
convertType' :: IR.Type -> Converter Coq.Term
convertType' = liftType' >=> convertLiftedType
| Converts a given type in the lifted IR to a Coq term .
convertLiftedType :: LIR.Type -> Converter Coq.Term
convertLiftedType (LIR.TypeVar srcSpan ident) = do
qualid <- lookupIdentOrFail srcSpan IR.TypeScope (IR.UnQual (IR.Ident ident))
return $ Coq.Qualid qualid
convertLiftedType (LIR.TypeCon srcSpan name args _) = do
qualid <- lookupIdentOrFail srcSpan IR.TypeScope name
args' <- mapM convertLiftedType args
return $ genericApply qualid [] [] args'
convertLiftedType (LIR.FuncType _ l r) = do
l' <- convertLiftedType l
r' <- convertLiftedType r
return $ Coq.Arrow l' r'
convertLiftedType (LIR.FreeTypeCon _ t) = do
t' <- convertLiftedType t
return $ genericApply Coq.Base.free [] [] [t']
|
77a32f0c4e3d6db8c079595f334b206283537899c5d6ee7af7f4155145a1af98 | christiankissig/ocaml99 | problem73.ml | (*# P73 (**) Lisp-like tree representation
#
# There is a particular notation for multiway trees in Lisp. Lisp is a prominent
# functional programming language, which is used primarily for artificial
# intelligence problems. As such it is one of the main competitors of Prolog. In
# Lisp almost everything is a list, just as in Prolog everything is a term.
#
# The following pictures show how multiway tree structures are represented in Lisp.
#
# Note that in the "lispy" notation a node with successors (children) in the
# tree is always the first element in a list, followed by its children. The
# "lispy" representation of a multiway tree is a sequence of atoms and
# parentheses '(' and ')', which we shall collectively call "tokens". We can
# represent this sequence of tokens as a Prolog list; e.g. the lispy expression
# (a (b c)) could be represented as the Prolog list ['(', a, '(', b, c, ')',
# ')']. Write a predicate tree-ltl(T,LTL) which constructs the "lispy token
# list" LTL if the tree is given as term T in the usual Prolog notation.
#
# Example:
# * tree-ltl(t(a,[t(b,[]),t(c,[])]),LTL).
# LTL = ['(', a, '(', b, c, ')', ')']
#
# As a second, even more interesting exercise try to rewrite tree-ltl/2 in a way
# that the inverse conversion is also possible: Given the list LTL, construct
# the Prolog tree T. Use difference lists.
*)
type multi_tree =
Leaf of string
| Node of string * multi_tree list
;;
let rec tree_to_ltl t =
match t with
Leaf a -> [a]
| Node (a,l) ->
List.flatten[
[a,'('],
(List.flatten (List.map tree_to_ltl l)),
[')']
]
;;
| null | https://raw.githubusercontent.com/christiankissig/ocaml99/c25f1790f695f9dd68b23abb472dc7c860d840f8/problem73.ml | ocaml | # P73 (* | #
# There is a particular notation for multiway trees in Lisp. Lisp is a prominent
# functional programming language, which is used primarily for artificial
# intelligence problems. As such it is one of the main competitors of Prolog. In
# Lisp almost everything is a list, just as in Prolog everything is a term.
#
# The following pictures show how multiway tree structures are represented in Lisp.
#
# Note that in the "lispy" notation a node with successors (children) in the
# tree is always the first element in a list, followed by its children. The
# "lispy" representation of a multiway tree is a sequence of atoms and
# parentheses '(' and ')', which we shall collectively call "tokens". We can
# represent this sequence of tokens as a Prolog list; e.g. the lispy expression
# (a (b c)) could be represented as the Prolog list ['(', a, '(', b, c, ')',
# ')']. Write a predicate tree-ltl(T,LTL) which constructs the "lispy token
# list" LTL if the tree is given as term T in the usual Prolog notation.
#
# Example:
# * tree-ltl(t(a,[t(b,[]),t(c,[])]),LTL).
# LTL = ['(', a, '(', b, c, ')', ')']
#
# As a second, even more interesting exercise try to rewrite tree-ltl/2 in a way
# that the inverse conversion is also possible: Given the list LTL, construct
# the Prolog tree T. Use difference lists.
*)
type multi_tree =
Leaf of string
| Node of string * multi_tree list
;;
let rec tree_to_ltl t =
match t with
Leaf a -> [a]
| Node (a,l) ->
List.flatten[
[a,'('],
(List.flatten (List.map tree_to_ltl l)),
[')']
]
;;
|
987c4c905b48ff4d27add7031439a486723bf6c6a9b6752561fd0b7150af2951 | manavpatnaik/haskell | 16_join_list.hs | concat1 xs = foldr (++) [] xs
main = do
print(concat1 ["asd", "dfg", "23"]) | null | https://raw.githubusercontent.com/manavpatnaik/haskell/85be0b7130619c6e5e815a69e66cd366c3e6cb21/higher_order_functions/16_join_list.hs | haskell | concat1 xs = foldr (++) [] xs
main = do
print(concat1 ["asd", "dfg", "23"]) | |
b257f903ad5ace445db982a4cfcbed0ae37f782ad0152170649248609d6627de | Soyn/sicp | Ex2.63.rkt | #lang racket
;--------Support Function-------------------
(define ( make-tree entry left right)
( list entry left right))
( define ( entry tree) ( car tree))
( define ( left-branch tree) ( cadr tree))
( define ( right-branch tree) ( caddr tree))
( define ( tree->list-1 tree)
( if ( null? tree)null
(append ( tree->list-1 ( left-branch tree))
( cons ( entry tree)
( tree->list-1 ( right-branch tree))))))
(define ( adjoin-set x set)
( cond ( (null? set) ( make-tree x null null))
( ( = x ( entry set)) set)
( ( < x ( entry set))
( make-tree ( entry set)
( adjoin-set x (left-branch set))
( right-branch set)))
( ( > x ( entry set))
( make-tree ( entry set)
( left-branch set)
( adjoin-set x ( right-branch set))))))
;------------------------------------------------------------------
; !Ex2.63
; @Soyn
( define ( tree->list-2 tree)
( define ( copy-to-list tree result-list)
( if(null? tree)
result-list
( copy-to-list ( left-branch tree)
( cons ( entry tree)
( copy-to-list ( right-branch tree)
result-list)))))
( copy-to-list tree null))
;--------Usage Test--------------
( define t (make-tree 2 null null))
( define t1 ( adjoin-set 5 t))
( define t2 ( adjoin-set 3 t1))
( define t3 ( adjoin-set 1 t2))
t3
(tree->list-1 t3)
( tree->list-2 t3)
;both procedures produce the same result
;!!!for tree->list-1
;!!!! T(n) = 2*T(n/2) + O(n) =====> T(n) = O(n*lg n) (as the append takes linear time)
;;;;; for the tree->list-2
;;;;;;; T(n) = 2*T(n/2) + O(1) =======> T(n) = O(n)
so the second function is more quick .
| null | https://raw.githubusercontent.com/Soyn/sicp/d2aa6e3b053f6d4c8150ab1b033a18f61fca7e1b/CH2/CH2.3/Ex2.63.rkt | racket | --------Support Function-------------------
------------------------------------------------------------------
!Ex2.63
@Soyn
--------Usage Test--------------
both procedures produce the same result
!!!for tree->list-1
!!!! T(n) = 2*T(n/2) + O(n) =====> T(n) = O(n*lg n) (as the append takes linear time)
for the tree->list-2
T(n) = 2*T(n/2) + O(1) =======> T(n) = O(n) | #lang racket
(define ( make-tree entry left right)
( list entry left right))
( define ( entry tree) ( car tree))
( define ( left-branch tree) ( cadr tree))
( define ( right-branch tree) ( caddr tree))
( define ( tree->list-1 tree)
( if ( null? tree)null
(append ( tree->list-1 ( left-branch tree))
( cons ( entry tree)
( tree->list-1 ( right-branch tree))))))
(define ( adjoin-set x set)
( cond ( (null? set) ( make-tree x null null))
( ( = x ( entry set)) set)
( ( < x ( entry set))
( make-tree ( entry set)
( adjoin-set x (left-branch set))
( right-branch set)))
( ( > x ( entry set))
( make-tree ( entry set)
( left-branch set)
( adjoin-set x ( right-branch set))))))
( define ( tree->list-2 tree)
( define ( copy-to-list tree result-list)
( if(null? tree)
result-list
( copy-to-list ( left-branch tree)
( cons ( entry tree)
( copy-to-list ( right-branch tree)
result-list)))))
( copy-to-list tree null))
( define t (make-tree 2 null null))
( define t1 ( adjoin-set 5 t))
( define t2 ( adjoin-set 3 t1))
( define t3 ( adjoin-set 1 t2))
t3
(tree->list-1 t3)
( tree->list-2 t3)
so the second function is more quick .
|
f8fa3faf26cb21fe44e808d11aece3a66336401f5d2fbe5f8c14bf7f317b4468 | OCamlPro/ocp-build | metaConfig.ml | (**************************************************************************)
(* *)
(* Typerex Tools *)
(* *)
Copyright 2011 - 2017 OCamlPro SAS
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU General Public License version 3 described in the file
(* LICENSE. *)
(* *)
(**************************************************************************)
open BuildBase
(* open Stdlib2 *)
peerocaml:~/.opam/4.00.1 / lib / ocaml% ocamlfind printconf
Effective configuration :
Configuration file :
/home / lefessan/.opam/4.00.1 / lib / findlib.conf
Search path :
/home / lefessan/.opam/4.00.1 / lib
Packages will be installed in / removed from :
/home / lefessan/.opam/4.00.1 / lib
META files will be installed in / removed from :
the corresponding package directories
The standard library is assumed to reside in :
/home / lefessan/.opam/4.00.1 / lib / ocaml
The ld.conf file can be found here :
/home / lefessan/.opam/4.00.1 / lib / ocaml / ld.conf
peerocaml:~/.opam/4.00.1/lib/ocaml% ocamlfind printconf
Effective configuration:
Configuration file:
/home/lefessan/.opam/4.00.1/lib/findlib.conf
Search path:
/home/lefessan/.opam/4.00.1/lib
Packages will be installed in/removed from:
/home/lefessan/.opam/4.00.1/lib
META files will be installed in/removed from:
the corresponding package directories
The standard library is assumed to reside in:
/home/lefessan/.opam/4.00.1/lib/ocaml
The ld.conf file can be found here:
/home/lefessan/.opam/4.00.1/lib/ocaml/ld.conf
*)
(* TODO: We could also try to find "findlib/findlib.conf", in case
ocamlfind is not installed. We could even generate it ! *)
let load_config ?(ocamlfind=["ocamlfind"]) () =
try
match
BuildMisc.get_stdout_lines ocamlfind [ "printconf" ]
with `EXN e -> raise e
| `OUTPUT (_status, lines) ->
let search_path = ref [] in
let rec iter lines =
match lines with
"Search path:" :: lines ->
iter_path lines
| [] -> ()
| _ :: lines -> iter lines
and iter_path lines =
match lines with
| path :: lines when OcpString.starts_with path ~prefix:" " ->
search_path := String.sub path 4 (String.length path - 4) :: !search_path;
iter_path lines
| _ -> iter lines
in
iter lines;
List.rev !search_path
with e ->
Printf.eprintf "MetaConfig: exception %S\n%!" (Printexc.to_string e);
[]
| null | https://raw.githubusercontent.com/OCamlPro/ocp-build/56aff560bb438c12b2929feaf8379bc6f31b9840/tools/ocp-build/meta/metaConfig.ml | ocaml | ************************************************************************
Typerex Tools
All rights reserved. This file is distributed under the terms of
LICENSE.
************************************************************************
open Stdlib2
TODO: We could also try to find "findlib/findlib.conf", in case
ocamlfind is not installed. We could even generate it ! | Copyright 2011 - 2017 OCamlPro SAS
the GNU General Public License version 3 described in the file
open BuildBase
peerocaml:~/.opam/4.00.1 / lib / ocaml% ocamlfind printconf
Effective configuration :
Configuration file :
/home / lefessan/.opam/4.00.1 / lib / findlib.conf
Search path :
/home / lefessan/.opam/4.00.1 / lib
Packages will be installed in / removed from :
/home / lefessan/.opam/4.00.1 / lib
META files will be installed in / removed from :
the corresponding package directories
The standard library is assumed to reside in :
/home / lefessan/.opam/4.00.1 / lib / ocaml
The ld.conf file can be found here :
/home / lefessan/.opam/4.00.1 / lib / ocaml / ld.conf
peerocaml:~/.opam/4.00.1/lib/ocaml% ocamlfind printconf
Effective configuration:
Configuration file:
/home/lefessan/.opam/4.00.1/lib/findlib.conf
Search path:
/home/lefessan/.opam/4.00.1/lib
Packages will be installed in/removed from:
/home/lefessan/.opam/4.00.1/lib
META files will be installed in/removed from:
the corresponding package directories
The standard library is assumed to reside in:
/home/lefessan/.opam/4.00.1/lib/ocaml
The ld.conf file can be found here:
/home/lefessan/.opam/4.00.1/lib/ocaml/ld.conf
*)
let load_config ?(ocamlfind=["ocamlfind"]) () =
try
match
BuildMisc.get_stdout_lines ocamlfind [ "printconf" ]
with `EXN e -> raise e
| `OUTPUT (_status, lines) ->
let search_path = ref [] in
let rec iter lines =
match lines with
"Search path:" :: lines ->
iter_path lines
| [] -> ()
| _ :: lines -> iter lines
and iter_path lines =
match lines with
| path :: lines when OcpString.starts_with path ~prefix:" " ->
search_path := String.sub path 4 (String.length path - 4) :: !search_path;
iter_path lines
| _ -> iter lines
in
iter lines;
List.rev !search_path
with e ->
Printf.eprintf "MetaConfig: exception %S\n%!" (Printexc.to_string e);
[]
|
3680275a0bb50c4605c201b7b1bd1b11d4eb78313fdd286cfeeaa67cf6595435 | danieljharvey/mimsa | Typescript.hs | {-# LANGUAGE OverloadedStrings #-}
module Test.Backend.Typescript
( spec,
)
where
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.Text (Text)
import qualified Data.Text as T
import Language.Mimsa.Backend.Typescript.DataType
import Language.Mimsa.Backend.Typescript.FromExpr
import Language.Mimsa.Backend.Typescript.Monad
import Language.Mimsa.Backend.Typescript.Patterns
import Language.Mimsa.Backend.Typescript.Printer
import Language.Mimsa.Backend.Typescript.Types
import Language.Mimsa.Core
import Test.Hspec
import Test.Utils.Helpers
testFromExpr :: Expr Name MonoType -> (TSModule, Text)
testFromExpr expr =
let readerState =
TSReaderState (M.fromList [("Dog", "Pet"), ("Same", "Same")]) mempty
startState = TSCodegenState mempty mempty mempty
in case fromExpr readerState startState expr of
Right (tsModule, _) -> (tsModule, printModule tsModule)
Left e -> error (T.unpack (prettyPrint e))
spec :: Spec
spec = do
describe "Typescript" $ do
describe "pretty print Typescript AST" $ do
it "literals" $ do
printLiteral (TSBool True) `shouldBe` "true"
printLiteral (TSInt 100) `shouldBe` "100"
printLiteral (TSString "egg") `shouldBe` "`egg`"
it "function" $ do
printExpr
( TSFunction
"a"
mempty
(TSType Nothing "boolean" [])
Nothing
(TSFunctionBody (TSBody mempty (TSLit (TSInt 1))))
)
`shouldBe` "(a: boolean) => 1"
printExpr
( TSFunction
"maybeA"
(S.singleton (TSGeneric "A"))
(TSType (Just "Maybe") "Maybe" [TSTypeVar "A"])
Nothing
(TSFunctionBody (TSBody mempty (TSLit (TSInt 1))))
)
`shouldBe` "<A>(maybeA: Maybe.Maybe<A>) => 1"
printExpr
( TSFunction
"maybeA"
(S.singleton (TSGeneric "A"))
(TSType (Just "Maybe") "Maybe" [TSTypeVar "A"])
Nothing
( TSFunctionBody
( TSBody
[ TSAssignment
(TSVar "b")
Nothing
(TSLetBody (TSBody [] (TSLit (TSBool True))))
]
(TSLit (TSInt 1))
)
)
)
`shouldBe` "<A>(maybeA: Maybe.Maybe<A>) => { const b = true; return 1; }"
it "function application" $ do
printExpr (TSApp (TSVar "id") (TSLit (TSBool True)))
`shouldBe` "id(true)"
printExpr (TSApp (TSApp (TSVar "id") (TSLit (TSBool True))) (TSLit (TSInt 1)))
`shouldBe` "id(true)(1)"
it "infix operators" $ do
printExpr (TSInfix TSEquals (TSLit (TSInt 1)) (TSLit (TSInt 2)))
`shouldBe` "1 === 2"
it "record" $ do
printExpr
( TSRecord
( M.fromList
[ ( "a",
TSLit (TSInt 1)
),
("b", TSLit (TSBool True))
]
)
)
`shouldBe` "{ a: 1, b: true }"
it "pair" $ do
printExpr (TSTuple [TSLit (TSInt 1), TSLit (TSInt 2)]) `shouldBe` "[1,2] as const"
it "record access" $ do
printExpr (TSRecordAccess "a" (TSVar "record")) `shouldBe` "record.a"
it "array" $ do
printExpr
( TSArray
[ TSArrayItem (TSLit (TSInt 1)),
TSArrayItem (TSLit (TSInt 2)),
TSArraySpread (TSVar "rest")
]
)
`shouldBe` "[1,2,...rest]"
it "array access" $ do
printExpr (TSArrayAccess 2 (TSVar "array"))
`shouldBe` "array[2]"
it "ternary" $ do
printExpr
( TSTernary
(TSLit (TSBool True))
(TSLit (TSInt 1))
(TSLit (TSInt 2))
)
`shouldBe` "true ? 1 : 2"
describe "patterns" $ do
it "destructure" $ do
let destructure' = mconcat . fmap printStatement . destructure
destructure' (TSPatternVar "a") `shouldBe` "const a = value; "
destructure' TSPatternWildcard `shouldBe` ""
destructure'
( TSPatternTuple
[ TSPatternVar "a",
TSPatternVar "b"
]
)
`shouldBe` "const [a,b] = value; "
destructure'
( TSPatternRecord
( M.fromList
[("a", TSPatternVar "a"), ("b", TSPatternVar "b")]
)
)
`shouldBe` "const { a: a, b: b } = value; "
destructure' (TSPatternConstructor "Just" [TSPatternVar "a"])
`shouldBe` "const { vars: [a] } = value; "
destructure' (TSPatternConstructor "Just" [TSPatternWildcard])
`shouldBe` ""
destructure' (TSPatternString (TSStringVar "d") (TSStringVar "og"))
`shouldBe` "const d = value.charAt(0); const og = value.slice(1); "
destructure' (TSPatternConstructor "Just" [TSPatternString (TSStringVar "d") (TSStringVar "og")])
`shouldBe` "const d = value.vars[0].charAt(0); const og = value.vars[0].slice(1); "
it "conditions" $ do
let conditions' = printExpr . conditions
conditions' (TSPatternVar "a") `shouldBe` "true"
conditions' TSPatternWildcard `shouldBe` "true"
conditions'
( TSPatternTuple
[ TSPatternLit (TSInt 11),
TSPatternLit (TSInt 23)
]
)
`shouldBe` "value[0] === 11 && value[1] === 23"
conditions'
( TSPatternRecord
( M.fromList
[("a", TSPatternLit (TSInt 11)), ("b", TSPatternVar "b")]
)
)
`shouldBe` "value.a === 11"
conditions' (TSPatternConstructor "Just" [TSPatternLit (TSBool True)])
`shouldBe` "value.type === `Just` && value.vars[0] === true"
conditions' (TSPatternConstructor "Just" [TSPatternWildcard])
`shouldBe` "value.type === `Just`"
conditions' (TSPatternString (TSStringVar "d") (TSStringVar "og"))
`shouldBe` "value.length >= 1"
it "top level module" $ do
printModule (TSModule mempty (TSBody mempty (TSLit (TSBool True))))
`shouldBe` "export const main = true"
printModule
( TSModule
mempty
( TSBody
[ TSAssignment
(TSVar "a")
Nothing
(TSLetBody (TSBody mempty (TSLit (TSBool True))))
]
(TSVar "a")
)
)
`shouldBe` "const a = true; export const main = a"
describe "from typed expression" $ do
it "Namespaced constructor" $ do
testFromExpr (MyConstructor mtBool Nothing "Dog")
`shouldBe` ( TSModule mempty (TSBody [] $ TSRecordAccess "Dog" (TSVar "Pet")),
"export const main = Pet.Dog"
)
it "Namespaced constructor with same" $ do
testFromExpr (MyConstructor mtBool Nothing "Same")
`shouldBe` ( TSModule mempty (TSBody [] $ TSRecordAccess "Same" (TSVar "Same")),
"export const main = Same.Same"
)
it "Namespaced constructor with blah" $ do
testFromExpr (MyConstructor mtBool (Just "distraction") "Dog")
`shouldBe` ( TSModule mempty (TSBody [] $ TSRecordAccess "Dog" (TSVar "Pet")),
"export const main = Pet.Dog"
)
it "Not namespaced constructor" $ do
testFromExpr (MyConstructor mtBool Nothing "Log")
`shouldBe` (TSModule mempty (TSBody [] (TSVar "Log")), "export const main = Log")
it "const bool" $
testFromExpr (MyLiteral mtBool (MyBool True))
`shouldBe` ( TSModule mempty (TSBody [] (TSLit (TSBool True))),
"export const main = true"
)
it "let a = true in a" $
snd
( testFromExpr
( MyLet
mtBool
(Identifier mtBool "a")
( MyLiteral mtBool (MyBool True)
)
(MyVar mtBool Nothing "a")
)
)
`shouldBe` "const a = true; export const main = a"
it "let (a,_) = (true,false) in a" $ do
snd
( testFromExpr
( MyLetPattern
(MTTuple mempty mtBool (NE.singleton mtBool))
(PTuple (MTTuple mempty mtBool (NE.singleton mtBool)) (PVar mtBool "a") (NE.singleton $ PWildcard mtBool))
( MyTuple
(MTTuple mempty mtBool (NE.singleton mtBool))
(MyLiteral mtBool (MyBool True))
(NE.singleton $ MyLiteral mtBool (MyBool False))
)
(MyVar mtBool Nothing "a")
)
)
`shouldBe` "const [a,_] = [true,false] as const; export const main = a"
it "function with known type" $ do
snd
( testFromExpr
( MyLambda
(MTFunction mempty mtString mtString)
(Identifier mtString "str")
(MyVar mtString Nothing "str")
)
)
`shouldBe` "export const main = (str: string) => str"
it "function with generic type used multiple times" $ do
snd
( testFromExpr
( MyLambda
(MTFunction mempty (mtVar "a") (mtVar "a"))
(Identifier (mtVar "a") "a")
( MyLambda
(MTFunction mempty (mtVar "a") (mtVar "a"))
(Identifier (mtVar "a") "a2")
(MyVar (mtVar "a") Nothing "a")
)
)
)
`shouldBe` "export const main = <A>(a: A) => (a2: A) => a"
describe "Create constructor functions" $ do
let tsMaybe =
TSDataType
"Maybe"
["A"]
[ TSConstructor "Just" [TSTypeVar "A"],
TSConstructor "Nothing" mempty
]
tsThese =
TSDataType
"These"
["A", "B"]
[ TSConstructor "This" [TSTypeVar "A"],
TSConstructor "That" [TSTypeVar "B"],
TSConstructor "These" [TSTypeVar "A", TSTypeVar "B"]
]
tsMonoid =
TSDataType
"Monoid"
["A"]
[ TSConstructor
"Monoid"
[ TSTypeFun
"arg"
(TSTypeVar "A")
(TSTypeFun "arg" (TSTypeVar "A") (TSTypeVar "A")),
TSTypeVar "A"
]
]
it "Maybe" $ do
printStatement <$> createConstructorFunctions tsMaybe
`shouldBe` [ "const Just = <A>(a: A): Maybe<A> => ({ type: \"Just\", vars: [a] }); ",
"const Nothing: Maybe<never> = { type: \"Nothing\", vars: [] }; "
]
it "These" $ do
printStatement <$> createConstructorFunctions tsThese
`shouldBe` [ "const This = <A>(a: A): These<A,never> => ({ type: \"This\", vars: [a] }); ",
"const That = <B>(b: B): These<never,B> => ({ type: \"That\", vars: [b] }); ",
"const These = <A>(a: A) => <B>(b: B): These<A,B> => ({ type: \"These\", vars: [a,b] }); "
]
it "Monoid" $ do
printStatement <$> createConstructorFunctions tsMonoid
`shouldBe` [ "const Monoid = <A>(u1: (arg: A) => (arg: A) => A) => (a: A): Monoid<A> => ({ type: \"Monoid\", vars: [u1,a] }); "
]
| null | https://raw.githubusercontent.com/danieljharvey/mimsa/8154c07fcd394739d6d9543dd029d06470f738c2/backends/test/Test/Backend/Typescript.hs | haskell | # LANGUAGE OverloadedStrings # |
module Test.Backend.Typescript
( spec,
)
where
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.Text (Text)
import qualified Data.Text as T
import Language.Mimsa.Backend.Typescript.DataType
import Language.Mimsa.Backend.Typescript.FromExpr
import Language.Mimsa.Backend.Typescript.Monad
import Language.Mimsa.Backend.Typescript.Patterns
import Language.Mimsa.Backend.Typescript.Printer
import Language.Mimsa.Backend.Typescript.Types
import Language.Mimsa.Core
import Test.Hspec
import Test.Utils.Helpers
testFromExpr :: Expr Name MonoType -> (TSModule, Text)
testFromExpr expr =
let readerState =
TSReaderState (M.fromList [("Dog", "Pet"), ("Same", "Same")]) mempty
startState = TSCodegenState mempty mempty mempty
in case fromExpr readerState startState expr of
Right (tsModule, _) -> (tsModule, printModule tsModule)
Left e -> error (T.unpack (prettyPrint e))
spec :: Spec
spec = do
describe "Typescript" $ do
describe "pretty print Typescript AST" $ do
it "literals" $ do
printLiteral (TSBool True) `shouldBe` "true"
printLiteral (TSInt 100) `shouldBe` "100"
printLiteral (TSString "egg") `shouldBe` "`egg`"
it "function" $ do
printExpr
( TSFunction
"a"
mempty
(TSType Nothing "boolean" [])
Nothing
(TSFunctionBody (TSBody mempty (TSLit (TSInt 1))))
)
`shouldBe` "(a: boolean) => 1"
printExpr
( TSFunction
"maybeA"
(S.singleton (TSGeneric "A"))
(TSType (Just "Maybe") "Maybe" [TSTypeVar "A"])
Nothing
(TSFunctionBody (TSBody mempty (TSLit (TSInt 1))))
)
`shouldBe` "<A>(maybeA: Maybe.Maybe<A>) => 1"
printExpr
( TSFunction
"maybeA"
(S.singleton (TSGeneric "A"))
(TSType (Just "Maybe") "Maybe" [TSTypeVar "A"])
Nothing
( TSFunctionBody
( TSBody
[ TSAssignment
(TSVar "b")
Nothing
(TSLetBody (TSBody [] (TSLit (TSBool True))))
]
(TSLit (TSInt 1))
)
)
)
`shouldBe` "<A>(maybeA: Maybe.Maybe<A>) => { const b = true; return 1; }"
it "function application" $ do
printExpr (TSApp (TSVar "id") (TSLit (TSBool True)))
`shouldBe` "id(true)"
printExpr (TSApp (TSApp (TSVar "id") (TSLit (TSBool True))) (TSLit (TSInt 1)))
`shouldBe` "id(true)(1)"
it "infix operators" $ do
printExpr (TSInfix TSEquals (TSLit (TSInt 1)) (TSLit (TSInt 2)))
`shouldBe` "1 === 2"
it "record" $ do
printExpr
( TSRecord
( M.fromList
[ ( "a",
TSLit (TSInt 1)
),
("b", TSLit (TSBool True))
]
)
)
`shouldBe` "{ a: 1, b: true }"
it "pair" $ do
printExpr (TSTuple [TSLit (TSInt 1), TSLit (TSInt 2)]) `shouldBe` "[1,2] as const"
it "record access" $ do
printExpr (TSRecordAccess "a" (TSVar "record")) `shouldBe` "record.a"
it "array" $ do
printExpr
( TSArray
[ TSArrayItem (TSLit (TSInt 1)),
TSArrayItem (TSLit (TSInt 2)),
TSArraySpread (TSVar "rest")
]
)
`shouldBe` "[1,2,...rest]"
it "array access" $ do
printExpr (TSArrayAccess 2 (TSVar "array"))
`shouldBe` "array[2]"
it "ternary" $ do
printExpr
( TSTernary
(TSLit (TSBool True))
(TSLit (TSInt 1))
(TSLit (TSInt 2))
)
`shouldBe` "true ? 1 : 2"
describe "patterns" $ do
it "destructure" $ do
let destructure' = mconcat . fmap printStatement . destructure
destructure' (TSPatternVar "a") `shouldBe` "const a = value; "
destructure' TSPatternWildcard `shouldBe` ""
destructure'
( TSPatternTuple
[ TSPatternVar "a",
TSPatternVar "b"
]
)
`shouldBe` "const [a,b] = value; "
destructure'
( TSPatternRecord
( M.fromList
[("a", TSPatternVar "a"), ("b", TSPatternVar "b")]
)
)
`shouldBe` "const { a: a, b: b } = value; "
destructure' (TSPatternConstructor "Just" [TSPatternVar "a"])
`shouldBe` "const { vars: [a] } = value; "
destructure' (TSPatternConstructor "Just" [TSPatternWildcard])
`shouldBe` ""
destructure' (TSPatternString (TSStringVar "d") (TSStringVar "og"))
`shouldBe` "const d = value.charAt(0); const og = value.slice(1); "
destructure' (TSPatternConstructor "Just" [TSPatternString (TSStringVar "d") (TSStringVar "og")])
`shouldBe` "const d = value.vars[0].charAt(0); const og = value.vars[0].slice(1); "
it "conditions" $ do
let conditions' = printExpr . conditions
conditions' (TSPatternVar "a") `shouldBe` "true"
conditions' TSPatternWildcard `shouldBe` "true"
conditions'
( TSPatternTuple
[ TSPatternLit (TSInt 11),
TSPatternLit (TSInt 23)
]
)
`shouldBe` "value[0] === 11 && value[1] === 23"
conditions'
( TSPatternRecord
( M.fromList
[("a", TSPatternLit (TSInt 11)), ("b", TSPatternVar "b")]
)
)
`shouldBe` "value.a === 11"
conditions' (TSPatternConstructor "Just" [TSPatternLit (TSBool True)])
`shouldBe` "value.type === `Just` && value.vars[0] === true"
conditions' (TSPatternConstructor "Just" [TSPatternWildcard])
`shouldBe` "value.type === `Just`"
conditions' (TSPatternString (TSStringVar "d") (TSStringVar "og"))
`shouldBe` "value.length >= 1"
it "top level module" $ do
printModule (TSModule mempty (TSBody mempty (TSLit (TSBool True))))
`shouldBe` "export const main = true"
printModule
( TSModule
mempty
( TSBody
[ TSAssignment
(TSVar "a")
Nothing
(TSLetBody (TSBody mempty (TSLit (TSBool True))))
]
(TSVar "a")
)
)
`shouldBe` "const a = true; export const main = a"
describe "from typed expression" $ do
it "Namespaced constructor" $ do
testFromExpr (MyConstructor mtBool Nothing "Dog")
`shouldBe` ( TSModule mempty (TSBody [] $ TSRecordAccess "Dog" (TSVar "Pet")),
"export const main = Pet.Dog"
)
it "Namespaced constructor with same" $ do
testFromExpr (MyConstructor mtBool Nothing "Same")
`shouldBe` ( TSModule mempty (TSBody [] $ TSRecordAccess "Same" (TSVar "Same")),
"export const main = Same.Same"
)
it "Namespaced constructor with blah" $ do
testFromExpr (MyConstructor mtBool (Just "distraction") "Dog")
`shouldBe` ( TSModule mempty (TSBody [] $ TSRecordAccess "Dog" (TSVar "Pet")),
"export const main = Pet.Dog"
)
it "Not namespaced constructor" $ do
testFromExpr (MyConstructor mtBool Nothing "Log")
`shouldBe` (TSModule mempty (TSBody [] (TSVar "Log")), "export const main = Log")
it "const bool" $
testFromExpr (MyLiteral mtBool (MyBool True))
`shouldBe` ( TSModule mempty (TSBody [] (TSLit (TSBool True))),
"export const main = true"
)
it "let a = true in a" $
snd
( testFromExpr
( MyLet
mtBool
(Identifier mtBool "a")
( MyLiteral mtBool (MyBool True)
)
(MyVar mtBool Nothing "a")
)
)
`shouldBe` "const a = true; export const main = a"
it "let (a,_) = (true,false) in a" $ do
snd
( testFromExpr
( MyLetPattern
(MTTuple mempty mtBool (NE.singleton mtBool))
(PTuple (MTTuple mempty mtBool (NE.singleton mtBool)) (PVar mtBool "a") (NE.singleton $ PWildcard mtBool))
( MyTuple
(MTTuple mempty mtBool (NE.singleton mtBool))
(MyLiteral mtBool (MyBool True))
(NE.singleton $ MyLiteral mtBool (MyBool False))
)
(MyVar mtBool Nothing "a")
)
)
`shouldBe` "const [a,_] = [true,false] as const; export const main = a"
it "function with known type" $ do
snd
( testFromExpr
( MyLambda
(MTFunction mempty mtString mtString)
(Identifier mtString "str")
(MyVar mtString Nothing "str")
)
)
`shouldBe` "export const main = (str: string) => str"
it "function with generic type used multiple times" $ do
snd
( testFromExpr
( MyLambda
(MTFunction mempty (mtVar "a") (mtVar "a"))
(Identifier (mtVar "a") "a")
( MyLambda
(MTFunction mempty (mtVar "a") (mtVar "a"))
(Identifier (mtVar "a") "a2")
(MyVar (mtVar "a") Nothing "a")
)
)
)
`shouldBe` "export const main = <A>(a: A) => (a2: A) => a"
describe "Create constructor functions" $ do
let tsMaybe =
TSDataType
"Maybe"
["A"]
[ TSConstructor "Just" [TSTypeVar "A"],
TSConstructor "Nothing" mempty
]
tsThese =
TSDataType
"These"
["A", "B"]
[ TSConstructor "This" [TSTypeVar "A"],
TSConstructor "That" [TSTypeVar "B"],
TSConstructor "These" [TSTypeVar "A", TSTypeVar "B"]
]
tsMonoid =
TSDataType
"Monoid"
["A"]
[ TSConstructor
"Monoid"
[ TSTypeFun
"arg"
(TSTypeVar "A")
(TSTypeFun "arg" (TSTypeVar "A") (TSTypeVar "A")),
TSTypeVar "A"
]
]
it "Maybe" $ do
printStatement <$> createConstructorFunctions tsMaybe
`shouldBe` [ "const Just = <A>(a: A): Maybe<A> => ({ type: \"Just\", vars: [a] }); ",
"const Nothing: Maybe<never> = { type: \"Nothing\", vars: [] }; "
]
it "These" $ do
printStatement <$> createConstructorFunctions tsThese
`shouldBe` [ "const This = <A>(a: A): These<A,never> => ({ type: \"This\", vars: [a] }); ",
"const That = <B>(b: B): These<never,B> => ({ type: \"That\", vars: [b] }); ",
"const These = <A>(a: A) => <B>(b: B): These<A,B> => ({ type: \"These\", vars: [a,b] }); "
]
it "Monoid" $ do
printStatement <$> createConstructorFunctions tsMonoid
`shouldBe` [ "const Monoid = <A>(u1: (arg: A) => (arg: A) => A) => (a: A): Monoid<A> => ({ type: \"Monoid\", vars: [u1,a] }); "
]
|
a7f384863d75177ebaeceb2423f29245aa5dee8d7bdf3420b18c12759ab47f66 | mstewartgallus/hs-callbypushvalue | AsCps.hs | # LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module AsCps (extract, AsCps) where
import Cbpv
import Common
import qualified Constant
import qualified Cps
import Global
import HasCall
import HasCode
import HasConstants
import HasData
import HasLet
import HasStack
import HasTerminal
import HasTuple
import NatTrans
extract :: Cps.Cps t => Data (AsCps t) :~> Data t
extract = NatTrans $ \(D _ x) -> x
data AsCps t
instance HasCode t => HasCode (AsCps t) where
data Code (AsCps t) a = C (SAlgebra a) (Stack t a -> Code t Void)
instance HasData t => HasData (AsCps t) where
data Data (AsCps t) a = D (SSet a) (Data t a)
instance HasConstants t => HasConstants (AsCps t) where
constant k = D (SU (fromType (Constant.typeOf k))) $ constant k
instance HasTerminal t => HasTerminal (AsCps t) where
terminal = D SUnit terminal
instance HasLet t => HasLet (AsCps t) where
letBe (D t x) f =
let C b _ = f (D t x)
in C b $ \k ->
letBe x $ \val ->
case f (D t val) of
C _ f' -> f' k
instance Cps.Cps t => HasReturn (AsCps t) where
returns (D t x) = C (SF t) (Cps.returns x)
letTo (C (SF t) x) f =
let C b _ = f (D t undefined)
in C b $ \k -> x $
Cps.letTo t $ \val ->
case f (D t val) of
C _ f' -> f' k
instance Cps.Cps t => HasTuple (AsCps t)
instance Cps.HasThunk t => HasThunk (AsCps t) where
force (D (SU t) th) = C t (Cps.force th)
thunk (C t code) = D (SU t) (Cps.thunk t code)
instance Cps.HasFn t => HasFn (AsCps t) where
C (_ `SFn` b) f <*> D _ x = C b $ \k -> f (x Cps.<*> k)
lambda t f =
let C bt _ = f (D t undefined)
in C (t `SFn` bt) $ \k -> Cps.lambda k $ \x next ->
let C _ body = f (D t x)
in body next
instance (Cps.HasThunk t, Cps.HasCall t) => HasCall (AsCps t) where
call g@(Global t _) = C (fromType t) (\k -> Cps.force (Cps.call g) k)
| null | https://raw.githubusercontent.com/mstewartgallus/hs-callbypushvalue/d8770b7e9e444e1261901f5ee435fcefb0f7ad75/src/AsCps.hs | haskell | # LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module AsCps (extract, AsCps) where
import Cbpv
import Common
import qualified Constant
import qualified Cps
import Global
import HasCall
import HasCode
import HasConstants
import HasData
import HasLet
import HasStack
import HasTerminal
import HasTuple
import NatTrans
extract :: Cps.Cps t => Data (AsCps t) :~> Data t
extract = NatTrans $ \(D _ x) -> x
data AsCps t
instance HasCode t => HasCode (AsCps t) where
data Code (AsCps t) a = C (SAlgebra a) (Stack t a -> Code t Void)
instance HasData t => HasData (AsCps t) where
data Data (AsCps t) a = D (SSet a) (Data t a)
instance HasConstants t => HasConstants (AsCps t) where
constant k = D (SU (fromType (Constant.typeOf k))) $ constant k
instance HasTerminal t => HasTerminal (AsCps t) where
terminal = D SUnit terminal
instance HasLet t => HasLet (AsCps t) where
letBe (D t x) f =
let C b _ = f (D t x)
in C b $ \k ->
letBe x $ \val ->
case f (D t val) of
C _ f' -> f' k
instance Cps.Cps t => HasReturn (AsCps t) where
returns (D t x) = C (SF t) (Cps.returns x)
letTo (C (SF t) x) f =
let C b _ = f (D t undefined)
in C b $ \k -> x $
Cps.letTo t $ \val ->
case f (D t val) of
C _ f' -> f' k
instance Cps.Cps t => HasTuple (AsCps t)
instance Cps.HasThunk t => HasThunk (AsCps t) where
force (D (SU t) th) = C t (Cps.force th)
thunk (C t code) = D (SU t) (Cps.thunk t code)
instance Cps.HasFn t => HasFn (AsCps t) where
C (_ `SFn` b) f <*> D _ x = C b $ \k -> f (x Cps.<*> k)
lambda t f =
let C bt _ = f (D t undefined)
in C (t `SFn` bt) $ \k -> Cps.lambda k $ \x next ->
let C _ body = f (D t x)
in body next
instance (Cps.HasThunk t, Cps.HasCall t) => HasCall (AsCps t) where
call g@(Global t _) = C (fromType t) (\k -> Cps.force (Cps.call g) k)
| |
9a56df9b20604897bd0e9ee5ed67eb0f2b27d1203a60bf23c4d123f6312d8968 | iskandr/parakeet-retired | MachineModel.ml | (* pp: -parser o pa_macro.cmo *)
type gpu_t = {
gpu_id : int;
name : string;
global_mem : int;
shared_mem_per_sm : int;
regs_per_block : int;
warp_size : int;
mem_pitch : int;
max_threads_per_block : int;
max_threads_per_x : int;
max_threads_per_y : int;
max_threads_per_z : int;
max_grid_size_x : int;
max_grid_size_y : int;
gpu_clock_rate_ghz : float;
total_const_mem : int;
accessible_peers : int array;
global_mem_id : int;
peak_global_bw : float;
}
type cache_t = {
cache_id : int;
level : int;
core_ids : int array;
size_kb : int;
line_size_bytes : int;
associativity : int;
}
type core_t = {
core_id : int;
cache_ids : int array;
thread_affinity_ids : int array;
}
type cpu_t = {
cpu_id : int;
cpu_clock_rate_ghz : float;
cores : core_t array;
caches : cache_t array;
vector_bitwidth : int;
}
type t = {
gpus : gpu_t array;
cpus : cpu_t array;
total_ram : int;
}
let print_cpu cpu =
Printf.printf "CPU id: %d\n" cpu.cpu_id;
Printf.printf "CPU clock rate: %f\n" cpu.cpu_clock_rate_ghz;
Printf.printf "CPU number of cores: %d\n" (Array.length cpu.cores);
let print_core core =
Printf.printf " Core id: %d\n" core.core_id;
let cache_ids = List.map string_of_int (Array.to_list core.cache_ids) in
Printf.printf " Core cache ids: %s\n" (String.concat " " cache_ids);
let affinities =
List.map string_of_int (Array.to_list core.thread_affinity_ids)
in
Printf.printf " Core affinity ids: %s\n" (String.concat " " affinities)
in
Array.iter print_core cpu.cores;
Printf.printf "CPU Vector bitwidth: %d\n%!" cpu.vector_bitwidth;
Printf.printf "CPU number of caches: %d\n%!" (Array.length cpu.caches);
let print_cache cache =
Printf.printf " Cache id: %d\n" cache.cache_id;
Printf.printf " Cache level: %d\n" cache.level;
let core_ids = List.map string_of_int (Array.to_list cache.core_ids) in
Printf.printf " Cache core ids: %s\n" (String.concat " " core_ids);
Printf.printf " Cache size (KB): %d\n" cache.size_kb;
Printf.printf " Cache line size: %d\n" cache.line_size_bytes;
Printf.printf " Cache associativity: %d\n" cache.associativity
in
Array.iter print_cache cpu.caches
let test_tag (node:Xml.xml) (name:string) =
String.compare (Xml.tag node) name == 0
let force_tag (node:Xml.xml) (name:string) =
if (String.compare (Xml.tag node) name) != 0 then
failwith "Malformed XML configuration file."
let get_tag_val (node:Xml.xml) =
let children = Xml.children node in
assert(List.length children == 1);
Xml.pcdata (List.hd children)
let consume_cache_child (cache:cache_t) (node:Xml.xml) =
if test_tag node "Id" then
let id = int_of_string (get_tag_val node) in
{cache with cache_id = id}
else if test_tag node "Level" then
let level = int_of_string (get_tag_val node) in
{cache with level = level}
else if test_tag node "Cores" then
let core_nodes = Xml.children node in
let num_cores = (List.length core_nodes) in
let cores = Array.make num_cores (-1) in
let rec get_core_ids i = function
| hd :: rest ->
Array.set cores i (int_of_string (get_tag_val hd));
get_core_ids (i+1) rest
| [] -> ()
in
get_core_ids 0 core_nodes;
{cache with core_ids = cores}
else if test_tag node "Size" then
let size = int_of_string (get_tag_val node) in
{cache with size_kb = size}
else if test_tag node "LineSize" then
let line_size = int_of_string (get_tag_val node) in
{cache with line_size_bytes = line_size}
else if test_tag node "Associativity" then
let associativity = int_of_string (get_tag_val node) in
{cache with associativity = associativity}
else failwith ("Unexpected Cache XML child: " ^ (Xml.tag node))
let build_cache (node:Xml.xml) (cpu:cpu_t) =
let children = Xml.children node in
let dummy_cache = {
cache_id = -1;
level = -1;
core_ids = Array.make 0 0;
size_kb = -1;
line_size_bytes = -1;
associativity = -1
} in
List.fold_left consume_cache_child dummy_cache children
let consume_core_child (core:core_t) (node:Xml.xml) =
if test_tag node "Id" then
let id = int_of_string (get_tag_val node) in
{core with core_id = id}
else if test_tag node "Threads" then
let affinity_nodes = Xml.children node in
let get_affinity_id n =
force_tag n "AffinityId";
int_of_string (get_tag_val n)
in
let affinity_ids = Array.of_list (List.map get_affinity_id affinity_nodes)
in
{core with thread_affinity_ids = affinity_ids}
else if test_tag node "Caches" then
let cache_nodes = Xml.children node in
let num_caches = (List.length cache_nodes) in
let caches = Array.make num_caches (-1) in
let get_cache_id n =
let id = int_of_string (String.sub (Xml.tag n) 1 1) in
if id < 1 or id > num_caches then
failwith ("Unexpected Cache level: " ^ (Xml.tag n));
Array.set caches (id-1) (int_of_string (get_tag_val n))
in
List.iter get_cache_id cache_nodes;
{core with cache_ids = caches}
else failwith ("Unexpected Core XML child: " ^ (Xml.tag node))
let build_core (node:Xml.xml) (cpu:cpu_t) =
let children = Xml.children node in
let dummy_core = {
core_id = -1;
cache_ids = Array.make 0 0;
thread_affinity_ids = Array.make 0 0
} in
List.fold_left consume_core_child dummy_core children
let consume_cpu_child (cpu:cpu_t) (node:Xml.xml) =
if test_tag node "Id" then
let id = int_of_string (get_tag_val node) in
{cpu with cpu_id = id}
else if test_tag node "VectorBitwidth" then
let bitwidth = int_of_string (get_tag_val node) in
{cpu with vector_bitwidth = bitwidth}
else if test_tag node "Core" then
let core = build_core node cpu in
let new_cores = Array.append cpu.cores (Array.make 1 core) in
{cpu with cores = new_cores}
else if test_tag node "Cache" then
let cache = build_cache node cpu in
let new_caches = Array.append cpu.caches (Array.make 1 cache) in
{cpu with caches = new_caches}
else failwith ("Unexpected CPU XML child: " ^ (Xml.tag node))
let build_cpu (node:Xml.xml) =
match node with
| Xml.Element _ ->
if not (test_tag node "Machine") then
failwith "CPU XML file must start with Machine node.";
let cpus = Xml.children node in
TODO : for now only support 1 CPU
assert(List.length cpus == 1);
let cpunode = List.hd cpus in
let dummy_core = {
core_id = -1;
cache_ids = Array.make 0 0;
thread_affinity_ids = Array.make 0 0
} in
let dummy_cache = {
cache_id = -1;
level = -1;
core_ids = Array.make 0 0;
size_kb = -1;
line_size_bytes = -1;
associativity = -1
} in
let initialcpu = {
cpu_id = -1;
cpu_clock_rate_ghz = 0.0;
cores = Array.make 0 dummy_core;
caches = Array.make 0 dummy_cache;
vector_bitwidth = 0
} in
let cpu_children = Xml.children cpunode in
let cpu = List.fold_left consume_cpu_child initialcpu cpu_children in
cpu
| _ -> failwith "Expected Machine node in CPU XML configuration file"
let dummy_gpu =
{
gpu_id = -1;
name = "GPU0";
global_mem = -1;
shared_mem_per_sm = -1;
regs_per_block = -1;
warp_size = -1;
mem_pitch = -1;
max_threads_per_block = -1;
max_threads_per_x = -1;
max_threads_per_y = -1;
max_threads_per_z = -1;
max_grid_size_x = -1;
max_grid_size_y = -1;
gpu_clock_rate_ghz = 0.0;
total_const_mem = 0;
accessible_peers = Array.make 0 0;
global_mem_id = 0;
peak_global_bw = 0.0;
}
let build_gpu (node:Xml.xml) = dummy_gpu
let build_machine_model () =
let homedir = Sys.getenv "HOME" in
let gpus =
IFDEF GPU THEN
let gpufile = homedir ^ "/.parakeet/parakeetgpuconf.xml" in
let gpuxml = Xml.parse_file gpufile in
Array.make 1 (build_gpu gpuxml)
ELSE Array.make 0 dummy_gpu
ENDIF;
in
let cpufile = homedir ^ "/.parakeet/parakeetcpuconf.xml" in
let cpuxml = Xml.parse_file cpufile in
let cpus = Array.make 1 (build_cpu cpuxml) in
{gpus = gpus; cpus = cpus; total_ram = 16384}
let machine_model = build_machine_model ()
let num_hw_threads =
let affinity_counts =
Array.map (fun a -> Array.length a.thread_affinity_ids)
machine_model.cpus.(0).cores
in
Array.fold_left (fun x y -> x + y) 0 affinity_counts
| null | https://raw.githubusercontent.com/iskandr/parakeet-retired/3d7e6e5b699f83ce8a1c01290beed0b78c0d0945/Runtime/MachineModel.ml | ocaml | pp: -parser o pa_macro.cmo |
type gpu_t = {
gpu_id : int;
name : string;
global_mem : int;
shared_mem_per_sm : int;
regs_per_block : int;
warp_size : int;
mem_pitch : int;
max_threads_per_block : int;
max_threads_per_x : int;
max_threads_per_y : int;
max_threads_per_z : int;
max_grid_size_x : int;
max_grid_size_y : int;
gpu_clock_rate_ghz : float;
total_const_mem : int;
accessible_peers : int array;
global_mem_id : int;
peak_global_bw : float;
}
type cache_t = {
cache_id : int;
level : int;
core_ids : int array;
size_kb : int;
line_size_bytes : int;
associativity : int;
}
type core_t = {
core_id : int;
cache_ids : int array;
thread_affinity_ids : int array;
}
type cpu_t = {
cpu_id : int;
cpu_clock_rate_ghz : float;
cores : core_t array;
caches : cache_t array;
vector_bitwidth : int;
}
type t = {
gpus : gpu_t array;
cpus : cpu_t array;
total_ram : int;
}
let print_cpu cpu =
Printf.printf "CPU id: %d\n" cpu.cpu_id;
Printf.printf "CPU clock rate: %f\n" cpu.cpu_clock_rate_ghz;
Printf.printf "CPU number of cores: %d\n" (Array.length cpu.cores);
let print_core core =
Printf.printf " Core id: %d\n" core.core_id;
let cache_ids = List.map string_of_int (Array.to_list core.cache_ids) in
Printf.printf " Core cache ids: %s\n" (String.concat " " cache_ids);
let affinities =
List.map string_of_int (Array.to_list core.thread_affinity_ids)
in
Printf.printf " Core affinity ids: %s\n" (String.concat " " affinities)
in
Array.iter print_core cpu.cores;
Printf.printf "CPU Vector bitwidth: %d\n%!" cpu.vector_bitwidth;
Printf.printf "CPU number of caches: %d\n%!" (Array.length cpu.caches);
let print_cache cache =
Printf.printf " Cache id: %d\n" cache.cache_id;
Printf.printf " Cache level: %d\n" cache.level;
let core_ids = List.map string_of_int (Array.to_list cache.core_ids) in
Printf.printf " Cache core ids: %s\n" (String.concat " " core_ids);
Printf.printf " Cache size (KB): %d\n" cache.size_kb;
Printf.printf " Cache line size: %d\n" cache.line_size_bytes;
Printf.printf " Cache associativity: %d\n" cache.associativity
in
Array.iter print_cache cpu.caches
let test_tag (node:Xml.xml) (name:string) =
String.compare (Xml.tag node) name == 0
let force_tag (node:Xml.xml) (name:string) =
if (String.compare (Xml.tag node) name) != 0 then
failwith "Malformed XML configuration file."
let get_tag_val (node:Xml.xml) =
let children = Xml.children node in
assert(List.length children == 1);
Xml.pcdata (List.hd children)
let consume_cache_child (cache:cache_t) (node:Xml.xml) =
if test_tag node "Id" then
let id = int_of_string (get_tag_val node) in
{cache with cache_id = id}
else if test_tag node "Level" then
let level = int_of_string (get_tag_val node) in
{cache with level = level}
else if test_tag node "Cores" then
let core_nodes = Xml.children node in
let num_cores = (List.length core_nodes) in
let cores = Array.make num_cores (-1) in
let rec get_core_ids i = function
| hd :: rest ->
Array.set cores i (int_of_string (get_tag_val hd));
get_core_ids (i+1) rest
| [] -> ()
in
get_core_ids 0 core_nodes;
{cache with core_ids = cores}
else if test_tag node "Size" then
let size = int_of_string (get_tag_val node) in
{cache with size_kb = size}
else if test_tag node "LineSize" then
let line_size = int_of_string (get_tag_val node) in
{cache with line_size_bytes = line_size}
else if test_tag node "Associativity" then
let associativity = int_of_string (get_tag_val node) in
{cache with associativity = associativity}
else failwith ("Unexpected Cache XML child: " ^ (Xml.tag node))
let build_cache (node:Xml.xml) (cpu:cpu_t) =
let children = Xml.children node in
let dummy_cache = {
cache_id = -1;
level = -1;
core_ids = Array.make 0 0;
size_kb = -1;
line_size_bytes = -1;
associativity = -1
} in
List.fold_left consume_cache_child dummy_cache children
let consume_core_child (core:core_t) (node:Xml.xml) =
if test_tag node "Id" then
let id = int_of_string (get_tag_val node) in
{core with core_id = id}
else if test_tag node "Threads" then
let affinity_nodes = Xml.children node in
let get_affinity_id n =
force_tag n "AffinityId";
int_of_string (get_tag_val n)
in
let affinity_ids = Array.of_list (List.map get_affinity_id affinity_nodes)
in
{core with thread_affinity_ids = affinity_ids}
else if test_tag node "Caches" then
let cache_nodes = Xml.children node in
let num_caches = (List.length cache_nodes) in
let caches = Array.make num_caches (-1) in
let get_cache_id n =
let id = int_of_string (String.sub (Xml.tag n) 1 1) in
if id < 1 or id > num_caches then
failwith ("Unexpected Cache level: " ^ (Xml.tag n));
Array.set caches (id-1) (int_of_string (get_tag_val n))
in
List.iter get_cache_id cache_nodes;
{core with cache_ids = caches}
else failwith ("Unexpected Core XML child: " ^ (Xml.tag node))
let build_core (node:Xml.xml) (cpu:cpu_t) =
let children = Xml.children node in
let dummy_core = {
core_id = -1;
cache_ids = Array.make 0 0;
thread_affinity_ids = Array.make 0 0
} in
List.fold_left consume_core_child dummy_core children
let consume_cpu_child (cpu:cpu_t) (node:Xml.xml) =
if test_tag node "Id" then
let id = int_of_string (get_tag_val node) in
{cpu with cpu_id = id}
else if test_tag node "VectorBitwidth" then
let bitwidth = int_of_string (get_tag_val node) in
{cpu with vector_bitwidth = bitwidth}
else if test_tag node "Core" then
let core = build_core node cpu in
let new_cores = Array.append cpu.cores (Array.make 1 core) in
{cpu with cores = new_cores}
else if test_tag node "Cache" then
let cache = build_cache node cpu in
let new_caches = Array.append cpu.caches (Array.make 1 cache) in
{cpu with caches = new_caches}
else failwith ("Unexpected CPU XML child: " ^ (Xml.tag node))
let build_cpu (node:Xml.xml) =
match node with
| Xml.Element _ ->
if not (test_tag node "Machine") then
failwith "CPU XML file must start with Machine node.";
let cpus = Xml.children node in
TODO : for now only support 1 CPU
assert(List.length cpus == 1);
let cpunode = List.hd cpus in
let dummy_core = {
core_id = -1;
cache_ids = Array.make 0 0;
thread_affinity_ids = Array.make 0 0
} in
let dummy_cache = {
cache_id = -1;
level = -1;
core_ids = Array.make 0 0;
size_kb = -1;
line_size_bytes = -1;
associativity = -1
} in
let initialcpu = {
cpu_id = -1;
cpu_clock_rate_ghz = 0.0;
cores = Array.make 0 dummy_core;
caches = Array.make 0 dummy_cache;
vector_bitwidth = 0
} in
let cpu_children = Xml.children cpunode in
let cpu = List.fold_left consume_cpu_child initialcpu cpu_children in
cpu
| _ -> failwith "Expected Machine node in CPU XML configuration file"
let dummy_gpu =
{
gpu_id = -1;
name = "GPU0";
global_mem = -1;
shared_mem_per_sm = -1;
regs_per_block = -1;
warp_size = -1;
mem_pitch = -1;
max_threads_per_block = -1;
max_threads_per_x = -1;
max_threads_per_y = -1;
max_threads_per_z = -1;
max_grid_size_x = -1;
max_grid_size_y = -1;
gpu_clock_rate_ghz = 0.0;
total_const_mem = 0;
accessible_peers = Array.make 0 0;
global_mem_id = 0;
peak_global_bw = 0.0;
}
let build_gpu (node:Xml.xml) = dummy_gpu
let build_machine_model () =
let homedir = Sys.getenv "HOME" in
let gpus =
IFDEF GPU THEN
let gpufile = homedir ^ "/.parakeet/parakeetgpuconf.xml" in
let gpuxml = Xml.parse_file gpufile in
Array.make 1 (build_gpu gpuxml)
ELSE Array.make 0 dummy_gpu
ENDIF;
in
let cpufile = homedir ^ "/.parakeet/parakeetcpuconf.xml" in
let cpuxml = Xml.parse_file cpufile in
let cpus = Array.make 1 (build_cpu cpuxml) in
{gpus = gpus; cpus = cpus; total_ram = 16384}
let machine_model = build_machine_model ()
let num_hw_threads =
let affinity_counts =
Array.map (fun a -> Array.length a.thread_affinity_ids)
machine_model.cpus.(0).cores
in
Array.fold_left (fun x y -> x + y) 0 affinity_counts
|
005fae0d5d2750ad07d9d4212714b0a0f9472bdd73ca7e7ff095a4092c65794b | jeapostrophe/opencl | 5-7.rkt | #lang at-exp racket/base
(require ffi/unsafe
(except-in racket/contract ->)
(prefix-in c: racket/contract)
scribble/srcdoc
"include/cl.rkt"
"lib.rkt"
"syntax.rkt"
"types.rkt")
(require/doc racket/base
scribble/manual
(for-label "types.rkt"))
;;;; clWaitForEvents
(define-opencl clWaitForEvents
(_fun [num_events : _cl_uint = (vector-length event_list)]
[event_list : (_vector i _cl_event)]
-> [status : _cl_int]
->
(cond [(= status CL_SUCCESS)
(void)]
[(= status CL_INVALID_VALUE)
(error 'clWaitForEvents "num_events is zero")]
[(= status CL_INVALID_CONTEXT)
(error 'clWaitForEvents "events specified in event_list do not belong to the same context")]
[(= status CL_INVALID_EVENT)
(error 'clWaitForEvents "event objects specified in event_list are not valid event objects")]
[else
(error 'clWaitForEvents "Invalid error code: ~e" status)])))
(provide/doc
[proc-doc/names clWaitForEvents
(c:-> (vectorof _cl_event/c) void)
(wait-list)
@{}])
;;;; clGetEventInfo
(define-opencl-info
clGetEventInfo
(clGetEventInfo:length clGetEventInfo:generic)
_cl_event_info _cl_event_info/c
(args [event : _cl_event _cl_event/c])
(error status
(cond [(= status CL_INVALID_VALUE)
(error 'clGetEventInfo "param_name is not valid or if size in bytes specified by param_value_size is < size of return type and param_value is not NULL")]
[(= status CL_INVALID_EVENT)
(error 'clGetEventInfo "event is not a valid event object")]
[else
(error 'clGetEventInfo "Invalid error code: ~e" status)]))
(variable param_value_size)
(fixed [_cl_command_queue _cl_command_queue/c CL_EVENT_COMMAND_QUEUE]
[_cl_command_type _cl_command_type/c CL_EVENT_COMMAND_TYPE]
[_command_execution_status _command_execution_status/c CL_EVENT_COMMAND_EXECUTION_STATUS]
[_cl_uint _cl_uint/c CL_EVENT_REFERENCE_COUNT]))
;;;;
(define-opencl clRetainEvent
(_fun [event : _cl_event]
-> [status : _cl_int]
-> (cond [(= status CL_SUCCESS) (void)]
[(= status CL_INVALID_EVENT)
(error 'clRetainEvent "event is not a valid event object")]
[else
(error 'clRetainEvent "Invalid error code: ~e" status)])))
(provide/doc
[proc-doc/names clRetainEvent (c:-> _cl_event/c void)
(evt) @{}])
(define-opencl clReleaseEvent
(_fun [event : _cl_event]
-> [status : _cl_int]
-> (cond [(= status CL_SUCCESS) (void)]
[(= status CL_INVALID_EVENT)
(error 'clReleaseEvent "event is not a valid event object")]
[else
(error 'clReleaseEvent "Invalid error code: ~e" status)])))
(provide/doc
[proc-doc/names clReleaseEvent (c:-> _cl_event/c void)
(evt) @{}])
| null | https://raw.githubusercontent.com/jeapostrophe/opencl/f984050b0c02beb6df186d1d531c4a92a98df1a1/opencl/c/5-7.rkt | racket | clWaitForEvents
clGetEventInfo
| #lang at-exp racket/base
(require ffi/unsafe
(except-in racket/contract ->)
(prefix-in c: racket/contract)
scribble/srcdoc
"include/cl.rkt"
"lib.rkt"
"syntax.rkt"
"types.rkt")
(require/doc racket/base
scribble/manual
(for-label "types.rkt"))
(define-opencl clWaitForEvents
(_fun [num_events : _cl_uint = (vector-length event_list)]
[event_list : (_vector i _cl_event)]
-> [status : _cl_int]
->
(cond [(= status CL_SUCCESS)
(void)]
[(= status CL_INVALID_VALUE)
(error 'clWaitForEvents "num_events is zero")]
[(= status CL_INVALID_CONTEXT)
(error 'clWaitForEvents "events specified in event_list do not belong to the same context")]
[(= status CL_INVALID_EVENT)
(error 'clWaitForEvents "event objects specified in event_list are not valid event objects")]
[else
(error 'clWaitForEvents "Invalid error code: ~e" status)])))
(provide/doc
[proc-doc/names clWaitForEvents
(c:-> (vectorof _cl_event/c) void)
(wait-list)
@{}])
(define-opencl-info
clGetEventInfo
(clGetEventInfo:length clGetEventInfo:generic)
_cl_event_info _cl_event_info/c
(args [event : _cl_event _cl_event/c])
(error status
(cond [(= status CL_INVALID_VALUE)
(error 'clGetEventInfo "param_name is not valid or if size in bytes specified by param_value_size is < size of return type and param_value is not NULL")]
[(= status CL_INVALID_EVENT)
(error 'clGetEventInfo "event is not a valid event object")]
[else
(error 'clGetEventInfo "Invalid error code: ~e" status)]))
(variable param_value_size)
(fixed [_cl_command_queue _cl_command_queue/c CL_EVENT_COMMAND_QUEUE]
[_cl_command_type _cl_command_type/c CL_EVENT_COMMAND_TYPE]
[_command_execution_status _command_execution_status/c CL_EVENT_COMMAND_EXECUTION_STATUS]
[_cl_uint _cl_uint/c CL_EVENT_REFERENCE_COUNT]))
(define-opencl clRetainEvent
(_fun [event : _cl_event]
-> [status : _cl_int]
-> (cond [(= status CL_SUCCESS) (void)]
[(= status CL_INVALID_EVENT)
(error 'clRetainEvent "event is not a valid event object")]
[else
(error 'clRetainEvent "Invalid error code: ~e" status)])))
(provide/doc
[proc-doc/names clRetainEvent (c:-> _cl_event/c void)
(evt) @{}])
(define-opencl clReleaseEvent
(_fun [event : _cl_event]
-> [status : _cl_int]
-> (cond [(= status CL_SUCCESS) (void)]
[(= status CL_INVALID_EVENT)
(error 'clReleaseEvent "event is not a valid event object")]
[else
(error 'clReleaseEvent "Invalid error code: ~e" status)])))
(provide/doc
[proc-doc/names clReleaseEvent (c:-> _cl_event/c void)
(evt) @{}])
|
9758aeb19c83f645d07785f98a8371ccb9be3c38f6abb05f523c79e328b20cd6 | broadinstitute/firecloud-ui | wdl.cljs | (ns broadfcui.page.method-repo.method.wdl
(:require
[dmohs.react :as react]
[broadfcui.common.codemirror :refer [CodeMirror]]
[broadfcui.common.style :as style]
; TODO: address transitive vulnerability before re-enabling
epam / pipeline - builder 0.3.10 - dev.264 depends on lodash 3.10.1
;[broadfcui.components.pipeline-builder :refer [PipelineBuilder]]
[broadfcui.components.split-pane :refer [SplitPane]]
[broadfcui.utils :as utils]
))
(react/defc WDLViewer
{:render
(fn [{:keys [props #_state]}] ; TODO: uncomment state when re-enabling
[CodeMirror {:text (:wdl props) :read-only? true}] ; TODO: remove this line when re-enabling
#_(let [{:keys [mode]} @state ; TODO: un-comment this when re-enabling
{:keys [wdl]} props
mode (or mode :code)
tab (fn [mode-key label]
(let [selected? (= mode-key mode)]
[:div {:style {:display "inline-block"
:border style/standard-line :padding "3px 8px" :cursor "pointer"
:color (when selected? "white")
:backgroundColor ((if selected? :button-primary :background-light) style/colors)}
:onClick #(swap! state assoc :mode mode-key)}
label]))
pipeline-view [PipelineBuilder {:wdl wdl :read-only? true?}]
code-mirror [CodeMirror {:text wdl :read-only? true}]]
[:div {:style {:margin "2.5rem 1.5rem 1rem"}}
[:div {}
(tab :code "Code")
(tab :preview "Preview")
(tab :side-by-side "Side-by-side")]
(case mode
:code code-mirror
:preview [:div {:style {:height 500}} pipeline-view]
:side-by-side [SplitPane
{:left code-mirror :right pipeline-view
:height 500 :initial-slider-position 550}])]))
:refresh
(fn [{:keys [state]}]
(swap! state dissoc :mode))})
| null | https://raw.githubusercontent.com/broadinstitute/firecloud-ui/8eb077bc137ead105db5665a8fa47a7523145633/src/cljs/main/broadfcui/page/method_repo/method/wdl.cljs | clojure | TODO: address transitive vulnerability before re-enabling
[broadfcui.components.pipeline-builder :refer [PipelineBuilder]]
TODO: uncomment state when re-enabling
TODO: remove this line when re-enabling
TODO: un-comment this when re-enabling | (ns broadfcui.page.method-repo.method.wdl
(:require
[dmohs.react :as react]
[broadfcui.common.codemirror :refer [CodeMirror]]
[broadfcui.common.style :as style]
epam / pipeline - builder 0.3.10 - dev.264 depends on lodash 3.10.1
[broadfcui.components.split-pane :refer [SplitPane]]
[broadfcui.utils :as utils]
))
(react/defc WDLViewer
{:render
{:keys [wdl]} props
mode (or mode :code)
tab (fn [mode-key label]
(let [selected? (= mode-key mode)]
[:div {:style {:display "inline-block"
:border style/standard-line :padding "3px 8px" :cursor "pointer"
:color (when selected? "white")
:backgroundColor ((if selected? :button-primary :background-light) style/colors)}
:onClick #(swap! state assoc :mode mode-key)}
label]))
pipeline-view [PipelineBuilder {:wdl wdl :read-only? true?}]
code-mirror [CodeMirror {:text wdl :read-only? true}]]
[:div {:style {:margin "2.5rem 1.5rem 1rem"}}
[:div {}
(tab :code "Code")
(tab :preview "Preview")
(tab :side-by-side "Side-by-side")]
(case mode
:code code-mirror
:preview [:div {:style {:height 500}} pipeline-view]
:side-by-side [SplitPane
{:left code-mirror :right pipeline-view
:height 500 :initial-slider-position 550}])]))
:refresh
(fn [{:keys [state]}]
(swap! state dissoc :mode))})
|
0273bc59a7568f12392004694dffc9e59ec3c61e45cb3c27d1657e159addbd6f | haroldcarr/learn-haskell-coq-ml-etc | X_2_1_Prop_Syntax.hs | # OPTIONS_GHC -fno - warn - missing - signatures #
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE FlexibleContexts #
module X_2_1_Prop_Syntax where
import qualified Test.HUnit as U (Counts, Test (TestList),
runTestTT)
import qualified Test.HUnit.Util as U (t)
import qualified Text.Parsec as P (alphaNum, eof, letter,
oneOf, runP, (<?>), (<|>))
import qualified Text.Parsec.Expr as P (Assoc (AssocRight),
Operator (Infix, Prefix),
buildExpressionParser)
import qualified Text.Parsec.Token as P (GenLanguageDef (LanguageDef),
caseSensitive, commentEnd,
commentLine, commentStart,
identLetter, identStart,
identifier, makeTokenParser,
nestedComments, opLetter,
opStart, parens, reserved,
reservedNames, reservedOp,
reservedOpNames, whiteSpace)
import qualified Text.PrettyPrint.ANSI.Leijen as PP (text, (<>))
2.1
data Formula a =
F
| T
| Atom a
| Not (Formula a)
| And (Formula a) (Formula a)
| Or (Formula a) (Formula a)
| Impl (Formula a) (Formula a)
| Iff (Formula a) (Formula a)
| Forall String (Formula a)
| Exists String (Formula a)
deriving (Eq, Functor, Foldable, Show, Traversable)
------------------------------------------------------------------------------
Parser
langDef = P.LanguageDef
{ P.commentStart = "{-"
, P.commentEnd = "-}"
, P.commentLine = "--"
, P.nestedComments = True
, P.identStart = P.letter
, P.identLetter = P.alphaNum
, P.opStart = P.oneOf "~^v-<"
, P.opLetter = P.oneOf ">"
, P.reservedNames = ["T", "F", "v", "Forall", "Exists"]
, P.reservedOpNames = ["~","^","v","->","<->"]
, P.caseSensitive = True
}
lexer = P.makeTokenParser langDef
identifier = P.identifier lexer
parens = P.parens lexer
reserved = P.reserved lexer
reservedOp = P.reservedOp lexer
whiteSpace = P.whiteSpace lexer
-- parser that return Either
pe = P.runP start (3::Int) "foo"
-- parser that expects success
pr x = let (Right r) = pe x in r
{- parses a term, followed by whitespace and end-of-file -}
start = do
e <- formula
whiteSpace
P.eof
return e
formula = P.buildExpressionParser table operatorOrAtom P.<?> "formula"
operatorOrAtom =
parens formula
P.<|> boolean
P.<|> atom
P.<?> "operatorOrAtom"
boolean =
(reserved "T" >> return T)
P.<|> (reserved "F" >> return F)
atom = do
a <- identifier
return (Atom a)
table = [ [ prefix "~" Not ]
, [ binary "^" And P.AssocRight ]
, [ binary "v" Or P.AssocRight ]
TODO " -- > "
, [ binary "<->" Iff P.AssocRight ]
]
TMP
-- also see: -nerd.com/erikd/Blog/CodeHacking/Haskell/parsec_expression_parsing.html
pt x = P.runP (reservedOp x) (3::Int) "foo"
-- name fun assoc
binary name fun = P.Infix (reservedOp name >> return fun)
prefix name fun = P.Prefix (reservedOp name >> return fun)
tp0 = U.t "tp0"
(pr "~(~T ^ ~F)")
(Not (And (Not T) (Not F)))
tp1 = U.t "tp1"
(pr "p ^ q")
(And (Atom "p") (Atom "q"))
tp2 = U.t "tp2"
(pr "p v q ^ z")
(Or (Atom "p") (And (Atom "q") (Atom "z")))
tp3 = U.t "tp3"
(pr "p v q -> r")
(Impl (Or (Atom "p") (Atom "q")) (Atom "r"))
tp4 = U.t "tp4"
(pr "p <-> r")
(Iff (Atom "p") (Atom "r"))
------------------------------------------------------------------------------
-- pretty printer
data ComingFrom = A | O deriving Show
showFormula f0 = case f0 of
T -> PP.text "T"
F -> PP.text "F"
Atom a -> PP.text a
Not f -> PP.text "~" PP.<> showFormula f
And f1 f2 -> se f1 A PP.<> PP.text " ^ " PP.<> se f2 A
Or f1 f2 -> se f1 O PP.<> PP.text " v " PP.<> se f2 O
Impl f1 f2 -> showFormula f1 PP.<> PP.text " -> " PP.<> showFormula f2
Iff f1 f2 -> showFormula f1 PP.<> PP.text " <-> " PP.<> showFormula f2
_ -> error $ "showFormula: " ++ show f0
where
se f from = case (f, from) of
(a@(Atom _),_) -> showFormula a
(n@(Not _),_) -> showFormula n
(a@(And _ _),A) -> showFormula a
(o@(Or _ _),O) -> showFormula o
(f' ,_) -> PP.text "(" PP.<> showFormula f' PP.<> PP.text ")"
pp = show . showFormula
ts1 = U.t "tShowFormula"
(show (showFormula (pr "(p v q v r) ^ (p v q v r ^ x v y)")))
"(p v q v r) ^ (p v q v (r ^ x) v y)"
------------------------------------------------------------------------------
-- syntax operations
onAtomsContents :: Applicative f => (a -> f b) -> Formula a -> f (Formula b)
onAtomsContents = traverse
toa1 = U.t "toa1"
(let r = pr "p v q" in (r, onAtomsContents (const "z") r))
( Or (Atom "p") (Atom "q")
,[Or (Atom 'z') (Atom 'z')])
-- TODO : use library function
onAtoms :: (a -> Formula a) -> Formula a -> Formula a
onAtoms f fs = case fs of
(Atom a ) -> f a
(Not p ) -> Not (onAtoms f p)
(Or p q) -> Or (onAtoms f p) (onAtoms f q)
(And p q) -> And (onAtoms f p) (onAtoms f q)
(Impl p q) -> Impl (onAtoms f p) (onAtoms f q)
(Iff p q) -> Iff (onAtoms f p) (onAtoms f q)
(Forall x p) -> Forall x (onAtoms f p)
(Exists x p) -> Exists x (onAtoms f p)
_ -> fs
------------------------------------------------------------------------------
-- test
test :: IO U.Counts
test =
U.runTestTT $ U.TestList $
tp0 ++ tp1 ++ tp2 ++ tp3 ++ tp4 ++
ts1 ++
toa1
-- end of file ---
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/math-and-functional-programming/2009-Handbook_of_Practical_Logic_and_Automated_Reasoning/src/X_2_1_Prop_Syntax.hs | haskell | # LANGUAGE DeriveFunctor #
# LANGUAGE DeriveTraversable #
----------------------------------------------------------------------------
parser that return Either
parser that expects success
parses a term, followed by whitespace and end-of-file
also see: -nerd.com/erikd/Blog/CodeHacking/Haskell/parsec_expression_parsing.html
name fun assoc
----------------------------------------------------------------------------
pretty printer
----------------------------------------------------------------------------
syntax operations
TODO : use library function
----------------------------------------------------------------------------
test
end of file --- | # OPTIONS_GHC -fno - warn - missing - signatures #
# LANGUAGE FlexibleContexts #
module X_2_1_Prop_Syntax where
import qualified Test.HUnit as U (Counts, Test (TestList),
runTestTT)
import qualified Test.HUnit.Util as U (t)
import qualified Text.Parsec as P (alphaNum, eof, letter,
oneOf, runP, (<?>), (<|>))
import qualified Text.Parsec.Expr as P (Assoc (AssocRight),
Operator (Infix, Prefix),
buildExpressionParser)
import qualified Text.Parsec.Token as P (GenLanguageDef (LanguageDef),
caseSensitive, commentEnd,
commentLine, commentStart,
identLetter, identStart,
identifier, makeTokenParser,
nestedComments, opLetter,
opStart, parens, reserved,
reservedNames, reservedOp,
reservedOpNames, whiteSpace)
import qualified Text.PrettyPrint.ANSI.Leijen as PP (text, (<>))
2.1
data Formula a =
F
| T
| Atom a
| Not (Formula a)
| And (Formula a) (Formula a)
| Or (Formula a) (Formula a)
| Impl (Formula a) (Formula a)
| Iff (Formula a) (Formula a)
| Forall String (Formula a)
| Exists String (Formula a)
deriving (Eq, Functor, Foldable, Show, Traversable)
Parser
langDef = P.LanguageDef
{ P.commentStart = "{-"
, P.commentEnd = "-}"
, P.commentLine = "--"
, P.nestedComments = True
, P.identStart = P.letter
, P.identLetter = P.alphaNum
, P.opStart = P.oneOf "~^v-<"
, P.opLetter = P.oneOf ">"
, P.reservedNames = ["T", "F", "v", "Forall", "Exists"]
, P.reservedOpNames = ["~","^","v","->","<->"]
, P.caseSensitive = True
}
lexer = P.makeTokenParser langDef
identifier = P.identifier lexer
parens = P.parens lexer
reserved = P.reserved lexer
reservedOp = P.reservedOp lexer
whiteSpace = P.whiteSpace lexer
pe = P.runP start (3::Int) "foo"
pr x = let (Right r) = pe x in r
start = do
e <- formula
whiteSpace
P.eof
return e
formula = P.buildExpressionParser table operatorOrAtom P.<?> "formula"
operatorOrAtom =
parens formula
P.<|> boolean
P.<|> atom
P.<?> "operatorOrAtom"
boolean =
(reserved "T" >> return T)
P.<|> (reserved "F" >> return F)
atom = do
a <- identifier
return (Atom a)
table = [ [ prefix "~" Not ]
, [ binary "^" And P.AssocRight ]
, [ binary "v" Or P.AssocRight ]
TODO " -- > "
, [ binary "<->" Iff P.AssocRight ]
]
TMP
pt x = P.runP (reservedOp x) (3::Int) "foo"
binary name fun = P.Infix (reservedOp name >> return fun)
prefix name fun = P.Prefix (reservedOp name >> return fun)
tp0 = U.t "tp0"
(pr "~(~T ^ ~F)")
(Not (And (Not T) (Not F)))
tp1 = U.t "tp1"
(pr "p ^ q")
(And (Atom "p") (Atom "q"))
tp2 = U.t "tp2"
(pr "p v q ^ z")
(Or (Atom "p") (And (Atom "q") (Atom "z")))
tp3 = U.t "tp3"
(pr "p v q -> r")
(Impl (Or (Atom "p") (Atom "q")) (Atom "r"))
tp4 = U.t "tp4"
(pr "p <-> r")
(Iff (Atom "p") (Atom "r"))
data ComingFrom = A | O deriving Show
showFormula f0 = case f0 of
T -> PP.text "T"
F -> PP.text "F"
Atom a -> PP.text a
Not f -> PP.text "~" PP.<> showFormula f
And f1 f2 -> se f1 A PP.<> PP.text " ^ " PP.<> se f2 A
Or f1 f2 -> se f1 O PP.<> PP.text " v " PP.<> se f2 O
Impl f1 f2 -> showFormula f1 PP.<> PP.text " -> " PP.<> showFormula f2
Iff f1 f2 -> showFormula f1 PP.<> PP.text " <-> " PP.<> showFormula f2
_ -> error $ "showFormula: " ++ show f0
where
se f from = case (f, from) of
(a@(Atom _),_) -> showFormula a
(n@(Not _),_) -> showFormula n
(a@(And _ _),A) -> showFormula a
(o@(Or _ _),O) -> showFormula o
(f' ,_) -> PP.text "(" PP.<> showFormula f' PP.<> PP.text ")"
pp = show . showFormula
ts1 = U.t "tShowFormula"
(show (showFormula (pr "(p v q v r) ^ (p v q v r ^ x v y)")))
"(p v q v r) ^ (p v q v (r ^ x) v y)"
onAtomsContents :: Applicative f => (a -> f b) -> Formula a -> f (Formula b)
onAtomsContents = traverse
toa1 = U.t "toa1"
(let r = pr "p v q" in (r, onAtomsContents (const "z") r))
( Or (Atom "p") (Atom "q")
,[Or (Atom 'z') (Atom 'z')])
onAtoms :: (a -> Formula a) -> Formula a -> Formula a
onAtoms f fs = case fs of
(Atom a ) -> f a
(Not p ) -> Not (onAtoms f p)
(Or p q) -> Or (onAtoms f p) (onAtoms f q)
(And p q) -> And (onAtoms f p) (onAtoms f q)
(Impl p q) -> Impl (onAtoms f p) (onAtoms f q)
(Iff p q) -> Iff (onAtoms f p) (onAtoms f q)
(Forall x p) -> Forall x (onAtoms f p)
(Exists x p) -> Exists x (onAtoms f p)
_ -> fs
test :: IO U.Counts
test =
U.runTestTT $ U.TestList $
tp0 ++ tp1 ++ tp2 ++ tp3 ++ tp4 ++
ts1 ++
toa1
|
b1bbe570a02addf71d6c0dab7c57b69d55caebb995afd30cd3337ad305d447b4 | DanielSchuessler/th-expand-syns | Types.hs | {-# LANGUAGE RankNTypes #-}
# LANGUAGE TemplateHaskell #
{-# LANGUAGE TypeFamilies #-}
# LANGUAGE KindSignatures #
module Types where
import Language.Haskell.TH.Lib
import Language.Haskell.TH.Syntax
import Util
-- type A = forall a. B a; type B a = Maybe a; expand [t|B A|]
type ListOf x = [x]
type ForAll f = forall x. f x
type ApplyToInteger f = f Integer
type Int' = Int
type Either' = Either
type Int'' = Int
type Id a = a
-- type E x = forall y. Either x y -> Int
$(sequence [tySynD (mkName "E") [plainTV (mkName "x")]
(forallT'' ["y"] (conT ''Either `appT` varT' "x" `appT` varT' "y" --> conT ''Int))
])
data family DF1 a
data instance DF1 Int = DInt (ListOf ())
type family TF1 a
type instance TF1 Int = ListOf ()
class Class1 a where
type AT1 a
instance Class1 Int where type AT1 Int = ListOf ()
| null | https://raw.githubusercontent.com/DanielSchuessler/th-expand-syns/ace23afbeff3d142ee2febcded6360ae0a5f642a/testing/Types.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE TypeFamilies #
type A = forall a. B a; type B a = Maybe a; expand [t|B A|]
type E x = forall y. Either x y -> Int
> conT ''Int)) | # LANGUAGE TemplateHaskell #
# LANGUAGE KindSignatures #
module Types where
import Language.Haskell.TH.Lib
import Language.Haskell.TH.Syntax
import Util
type ListOf x = [x]
type ForAll f = forall x. f x
type ApplyToInteger f = f Integer
type Int' = Int
type Either' = Either
type Int'' = Int
type Id a = a
$(sequence [tySynD (mkName "E") [plainTV (mkName "x")]
])
data family DF1 a
data instance DF1 Int = DInt (ListOf ())
type family TF1 a
type instance TF1 Int = ListOf ()
class Class1 a where
type AT1 a
instance Class1 Int where type AT1 Int = ListOf ()
|
40940d96e17349dcc5ebabecdaaf5b74793d889053ea8fe163b24050064bb2ec | avsm/ocaml-orm-sqlite | array_simple.ml | TYPE_CONV_PATH "Array_simple"
type s = {
foo: int array;
bar: string
} with orm
open OUnit
open Test_utils
let name = "array_simple.db"
let t1 = { foo=[|1|]; bar="t1" }
let t2 = { foo=[|1;2;3|]; bar="t2" }
let t3 = { foo=[||]; bar="t3" }
let test_init () =
ignore(open_db s_init name);
ignore(open_db ~rm:false s_init name);
ignore(open_db ~rm:false s_init name)
let test_save () =
let db = open_db s_init name in
s_save db t1;
s_save db t2;
s_save db t3
let test_update () =
let db = open_db s_init name in
s_save db t1;
s_save db t2;
s_save db t3;
s_save db t1;
s_save db t2;
s_save db t3
let test_get () =
let db = open_db ~rm:false s_init name in
let i = s_get db in
"3 in db" @? (List.length i = 3);
let i = List.hd (List.rev i) in
"values match" @? (i.bar = t3.bar && (i.foo = t3.foo))
let test_save_get () =
let db = open_db s_init name in
s_save db t3;
let i = s_get db in
"1 in db" @? (List.length i = 1);
let i = List.hd i in
"structural values equal" @? ( t3 = i);
"physical values equal" @? ( t3 == i)
let test_delete () =
let db = open_db s_init name in
s_save db t1;
s_save db t2;
s_save db t3;
"3 in db" @? (List.length (s_get db) = 3);
s_delete db t2;
"2 in db" @? (List.length (s_get db) = 2);
(match s_get db with
[a1;a3] -> "equal" @? (a3=t3 && a1=t1)
|_ -> assert false);
s_delete db t1;
s_delete db t3;
"0 in db" @? (List.length (s_get db) = 0)
let suite = [
"array_simple_init" >:: test_init;
"array_simple_save" >:: test_save;
"array_simple_update" >:: test_update;
"array_simple_get" >:: test_get;
"array_simple_save_get" >:: test_save_get;
"array_simple_delete" >:: test_delete;
]
| null | https://raw.githubusercontent.com/avsm/ocaml-orm-sqlite/0c41dee6e254abd75706edcb785f657bfe55d08b/lib_test/array_simple.ml | ocaml | TYPE_CONV_PATH "Array_simple"
type s = {
foo: int array;
bar: string
} with orm
open OUnit
open Test_utils
let name = "array_simple.db"
let t1 = { foo=[|1|]; bar="t1" }
let t2 = { foo=[|1;2;3|]; bar="t2" }
let t3 = { foo=[||]; bar="t3" }
let test_init () =
ignore(open_db s_init name);
ignore(open_db ~rm:false s_init name);
ignore(open_db ~rm:false s_init name)
let test_save () =
let db = open_db s_init name in
s_save db t1;
s_save db t2;
s_save db t3
let test_update () =
let db = open_db s_init name in
s_save db t1;
s_save db t2;
s_save db t3;
s_save db t1;
s_save db t2;
s_save db t3
let test_get () =
let db = open_db ~rm:false s_init name in
let i = s_get db in
"3 in db" @? (List.length i = 3);
let i = List.hd (List.rev i) in
"values match" @? (i.bar = t3.bar && (i.foo = t3.foo))
let test_save_get () =
let db = open_db s_init name in
s_save db t3;
let i = s_get db in
"1 in db" @? (List.length i = 1);
let i = List.hd i in
"structural values equal" @? ( t3 = i);
"physical values equal" @? ( t3 == i)
let test_delete () =
let db = open_db s_init name in
s_save db t1;
s_save db t2;
s_save db t3;
"3 in db" @? (List.length (s_get db) = 3);
s_delete db t2;
"2 in db" @? (List.length (s_get db) = 2);
(match s_get db with
[a1;a3] -> "equal" @? (a3=t3 && a1=t1)
|_ -> assert false);
s_delete db t1;
s_delete db t3;
"0 in db" @? (List.length (s_get db) = 0)
let suite = [
"array_simple_init" >:: test_init;
"array_simple_save" >:: test_save;
"array_simple_update" >:: test_update;
"array_simple_get" >:: test_get;
"array_simple_save_get" >:: test_save_get;
"array_simple_delete" >:: test_delete;
]
| |
6cea4e18a5c0d7007db3a6bbfccc96b15abd5cdf7816b341f3126e6ff79b3ad0 | privet-kitty/cl-competitive | primality.lisp | (defpackage :cp/primality
(:use :cl :cp/tzcount)
(:export #:prime-p)
(:documentation "Provides deterministic Miller-Rabin algorithm for primality
test.
This module is tuned for SBCL on x86-64, i.e., here (integer 0
#.MOST-POSITIVE-FIXNUM) is assumed to be (UNSIGNED-BYTE 62)"))
(in-package :cp/primality)
(deftype uint () '(unsigned-byte 62))
(defun %strong-probable-prime-p (n base)
(declare (optimize (speed 3))
(uint n base))
(or (= n base)
(labels ((mod-power (base power)
(declare (uint base power))
(loop with res of-type uint = 1
while (> power 0)
when (oddp power)
do (setq res (mod (* res base) n))
do (setq base (mod (* base base) n)
power (ash power -1))
finally (return res))))
(let* ((d (floor (- n 1) (logand (- n 1) (- 1 n))))
(y (mod-power base d)))
(declare (uint y))
(or (= y 1)
(= y (- n 1))
(let ((s (tzcount (- n 1))))
(loop repeat (- s 1)
do (setq y (mod (* y y) n))
(when (<= y 1) (return nil))
(when (= y (- n 1)) (return t)))))))))
;;
;; -rabin.appspot.com/
(defun prime-p (n)
(declare (optimize (speed 3))
(uint n))
(cond ((<= n 1) nil)
((evenp n) (= n 2))
((< n 49141)
(or (= n 331)
(%strong-probable-prime-p n 921211727)))
((< n 4759123141)
(loop for base in '(2 7 61)
always (%strong-probable-prime-p n base)))
((< n 2152302898747)
(loop for base in '(2 3 5 7 11)
always (%strong-probable-prime-p n base)))
;; NOTE: following branch is not tested
(t
(loop for base in '(2 325 9375 28178 450775 9780504 1795265022)
always (%strong-probable-prime-p n base)))))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/bd278954ffc8be339dd40ca09d5b9c71a5eb5189/module/primality.lisp | lisp |
-rabin.appspot.com/
NOTE: following branch is not tested | (defpackage :cp/primality
(:use :cl :cp/tzcount)
(:export #:prime-p)
(:documentation "Provides deterministic Miller-Rabin algorithm for primality
test.
This module is tuned for SBCL on x86-64, i.e., here (integer 0
#.MOST-POSITIVE-FIXNUM) is assumed to be (UNSIGNED-BYTE 62)"))
(in-package :cp/primality)
(deftype uint () '(unsigned-byte 62))
(defun %strong-probable-prime-p (n base)
(declare (optimize (speed 3))
(uint n base))
(or (= n base)
(labels ((mod-power (base power)
(declare (uint base power))
(loop with res of-type uint = 1
while (> power 0)
when (oddp power)
do (setq res (mod (* res base) n))
do (setq base (mod (* base base) n)
power (ash power -1))
finally (return res))))
(let* ((d (floor (- n 1) (logand (- n 1) (- 1 n))))
(y (mod-power base d)))
(declare (uint y))
(or (= y 1)
(= y (- n 1))
(let ((s (tzcount (- n 1))))
(loop repeat (- s 1)
do (setq y (mod (* y y) n))
(when (<= y 1) (return nil))
(when (= y (- n 1)) (return t)))))))))
(defun prime-p (n)
(declare (optimize (speed 3))
(uint n))
(cond ((<= n 1) nil)
((evenp n) (= n 2))
((< n 49141)
(or (= n 331)
(%strong-probable-prime-p n 921211727)))
((< n 4759123141)
(loop for base in '(2 7 61)
always (%strong-probable-prime-p n base)))
((< n 2152302898747)
(loop for base in '(2 3 5 7 11)
always (%strong-probable-prime-p n base)))
(t
(loop for base in '(2 325 9375 28178 450775 9780504 1795265022)
always (%strong-probable-prime-p n base)))))
|
ca531094291887e828a424b507e3aadf51b866b8abadd5f3448e1d6d265fde47 | rmculpepper/crypto | info.rkt | Copyright 2020
SPDX - License - Identifier : Apache-2.0
#lang info
;; pkg info
(define version "1.0")
(define collection "x509")
(define deps
'("base"
["asn1-lib" #:version "1.3"]
"base64-lib"
["crypto-lib" #:version "1.8"]
"db-lib"
["scramble-lib" #:version "0.3"]))
(define pkg-authors '(ryanc))
(define license 'Apache-2.0)
;; collection info
(define name "x509")
| null | https://raw.githubusercontent.com/rmculpepper/crypto/75138461a74d6b4bc26c65e981ccfba6b60719de/x509-lib/info.rkt | racket | pkg info
collection info | Copyright 2020
SPDX - License - Identifier : Apache-2.0
#lang info
(define version "1.0")
(define collection "x509")
(define deps
'("base"
["asn1-lib" #:version "1.3"]
"base64-lib"
["crypto-lib" #:version "1.8"]
"db-lib"
["scramble-lib" #:version "0.3"]))
(define pkg-authors '(ryanc))
(define license 'Apache-2.0)
(define name "x509")
|
4bc21f80203dd858f3d17e9fd1e1fdcc8a18b1728ef260e1fd3245c379982743 | ghc/packages-Cabal | setup.test.hs | import Test.Cabal.Prelude
Check that preprocessors ( hsc2hs ) are run
main = setupAndCabalTest $ setup_build ["--enable-tests", "--enable-benchmarks"]
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/PackageTests/PreProcess/setup.test.hs | haskell | import Test.Cabal.Prelude
Check that preprocessors ( hsc2hs ) are run
main = setupAndCabalTest $ setup_build ["--enable-tests", "--enable-benchmarks"]
| |
0c48219835fcf55546824e0747a5d2ec3a32a2c08271dc65f4c7e058ba1f415b | informatimago/lisp | objc-support.lisp | -*- mode : lisp;coding : utf-8 -*-
;;;;**************************************************************************
FILE : objc-support.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
USER - INTERFACE :
;;;;DESCRIPTION
;;;;
;;;; This file loads Objective-C support.
;;;;
< PJB > < >
MODIFICATIONS
2014 - 05 - 02 < PJB > Created .
;;;;LEGAL
AGPL3
;;;;
Copyright 2014 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;;;; (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details .
;;;;
You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see </>.
;;;;**************************************************************************
(defpackage "COM.INFORMATIMAGO.OBJECTIVE-CL.READTABLE"
(:nicknames "COM.INFORMATIMAGO.OBJCL.READTABLE")
(:use "COMMON-LISP")
(:export "*CCL-READTABLE*" "*COCOA-READTABLE*"))
(in-package "COM.INFORMATIMAGO.OBJECTIVE-CL.READTABLE")
#+ccl
(defparameter *ccl-readtable* (copy-readtable ccl::%initial-readtable%))
;; We'll try to catch in this variable the objective-c reader macros
;; installed by ccl require cocoa.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *cocoa-readtable* nil))
for now , not on
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable*
#-(and ccl darwin)
(copy-readtable nil)
# + ccl ( require : cocoa ) needs the botched readtable .
(copy-readtable ccl::%initial-readtable%))
;; When we (require :objc-support) before (require :cocoa), ccl
;; can't find the main bundle. So we must require :cocoa for the
;; applications that need it.
#-darwin (require :objc-support)
#+darwin (require :cocoa)
(defun nsfun-reader-macro (stream subchar numarg)
(declare (ignorable subchar numarg))
(let* ((token (make-array 16 :element-type 'character :fill-pointer 0 :adjustable t)))
(loop
(let* ((char (read-char stream nil nil)))
(if (or (eql char #\:)
(eql char #\_)
(and char (digit-char-p char 36)))
(vector-push-extend char token)
(progn
(when char
(unread-char char stream))
(return)))))
(unless *read-suppress*
(unless (> (length token) 0)
" Invalid token after # /. "
#+ccl(ccl::check-objc-message-name token)
(intern token "NSFUN"))))
(unless *cocoa-readtable*
(setf *cocoa-readtable* (copy-readtable *readtable*))
(set-dispatch-macro-character #\# #\/ (function nsfun-reader-macro) *cocoa-readtable*))
(pushnew :objc-support *features*))
;;
ccl::%initial - readtable% CCL readtable
com.informatimago.objective - cl.readtable::*ccl - readtable * CCL readtable .
;; com.informatimago.objective-cl.readtable::*cocoa-readtable* cocoa readtable.
;;
;;;; THE END ;;;;
| null | https://raw.githubusercontent.com/informatimago/lisp/571af24c06ba466e01b4c9483f8bb7690bc46d03/objcl/objc-support.lisp | lisp | coding : utf-8 -*-
**************************************************************************
LANGUAGE: Common-Lisp
SYSTEM: Common-Lisp
DESCRIPTION
This file loads Objective-C support.
LEGAL
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
along with this program. If not, see </>.
**************************************************************************
We'll try to catch in this variable the objective-c reader macros
installed by ccl require cocoa.
When we (require :objc-support) before (require :cocoa), ccl
can't find the main bundle. So we must require :cocoa for the
applications that need it.
com.informatimago.objective-cl.readtable::*cocoa-readtable* cocoa readtable.
THE END ;;;; | FILE : objc-support.lisp
USER - INTERFACE :
< PJB > < >
MODIFICATIONS
2014 - 05 - 02 < PJB > Created .
AGPL3
Copyright 2014 - 2016
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation , either version 3 of the License , or
GNU Affero General Public License for more details .
You should have received a copy of the GNU Affero General Public License
(defpackage "COM.INFORMATIMAGO.OBJECTIVE-CL.READTABLE"
(:nicknames "COM.INFORMATIMAGO.OBJCL.READTABLE")
(:use "COMMON-LISP")
(:export "*CCL-READTABLE*" "*COCOA-READTABLE*"))
(in-package "COM.INFORMATIMAGO.OBJECTIVE-CL.READTABLE")
#+ccl
(defparameter *ccl-readtable* (copy-readtable ccl::%initial-readtable%))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defvar *cocoa-readtable* nil))
for now , not on
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable*
#-(and ccl darwin)
(copy-readtable nil)
# + ccl ( require : cocoa ) needs the botched readtable .
(copy-readtable ccl::%initial-readtable%))
#-darwin (require :objc-support)
#+darwin (require :cocoa)
(defun nsfun-reader-macro (stream subchar numarg)
(declare (ignorable subchar numarg))
(let* ((token (make-array 16 :element-type 'character :fill-pointer 0 :adjustable t)))
(loop
(let* ((char (read-char stream nil nil)))
(if (or (eql char #\:)
(eql char #\_)
(and char (digit-char-p char 36)))
(vector-push-extend char token)
(progn
(when char
(unread-char char stream))
(return)))))
(unless *read-suppress*
(unless (> (length token) 0)
" Invalid token after # /. "
#+ccl(ccl::check-objc-message-name token)
(intern token "NSFUN"))))
(unless *cocoa-readtable*
(setf *cocoa-readtable* (copy-readtable *readtable*))
(set-dispatch-macro-character #\# #\/ (function nsfun-reader-macro) *cocoa-readtable*))
(pushnew :objc-support *features*))
ccl::%initial - readtable% CCL readtable
com.informatimago.objective - cl.readtable::*ccl - readtable * CCL readtable .
|
49ef05233f7706ba2cef507c0a82a7949b1b4bc174428e8e013d8be04a817db4 | OCamlPro/liquidity | reason_comment.ml | open Location
type category =
| EndOfLine
| SingleLine
| Regular
let string_of_category = function
| Regular -> "Regular"
| EndOfLine -> "End of Line"
| SingleLine -> "SingleLine"
type t = {
location: Location.t;
category: category;
text: string;
}
let category t = t.category
let location t = t.location
let dump ppf t =
Format.fprintf ppf "%d (%d:%d)-%d (%d:%d) -- %s:||%s||"
t.location.loc_start.pos_cnum
t.location.loc_start.pos_lnum
(t.location.loc_start.pos_cnum - t.location.loc_start.pos_bol)
t.location.loc_end.pos_cnum
t.location.loc_end.pos_lnum
(t.location.loc_end.pos_cnum - t.location.loc_end.pos_bol)
(string_of_category t.category)
t.text
let dump_list ppf list =
List.iter (Format.fprintf ppf "%a\n" dump) list
let wrap t =
match t.text with
| "" | "*" -> "/***/"
| txt when Reason_syntax_util.isLineComment txt ->
"//"
(* single line comments of the form `// comment` have a `\n` at the end *)
^ (String.sub txt 0 (String.length txt - 1))
^ Reason_syntax_util.EOLMarker.string
| txt when txt.[0] = '*' && txt.[1] <> '*' -> "/**" ^ txt ^ "*/"
| txt -> "/*" ^ txt ^ "*/"
let is_doc t =
String.length t.text > 0 && t.text.[0] == '*'
let make ~location category text =
{ text; category; location }
let isLineComment {category; text} = match category with
| SingleLine -> Reason_syntax_util.isLineComment text
| EndOfLine | Regular -> false
| null | https://raw.githubusercontent.com/OCamlPro/liquidity/3578de34cf751f54b9e4c001a95625d2041b2962/tools/liquidity/reason/reason_comment.ml | ocaml | single line comments of the form `// comment` have a `\n` at the end | open Location
type category =
| EndOfLine
| SingleLine
| Regular
let string_of_category = function
| Regular -> "Regular"
| EndOfLine -> "End of Line"
| SingleLine -> "SingleLine"
type t = {
location: Location.t;
category: category;
text: string;
}
let category t = t.category
let location t = t.location
let dump ppf t =
Format.fprintf ppf "%d (%d:%d)-%d (%d:%d) -- %s:||%s||"
t.location.loc_start.pos_cnum
t.location.loc_start.pos_lnum
(t.location.loc_start.pos_cnum - t.location.loc_start.pos_bol)
t.location.loc_end.pos_cnum
t.location.loc_end.pos_lnum
(t.location.loc_end.pos_cnum - t.location.loc_end.pos_bol)
(string_of_category t.category)
t.text
let dump_list ppf list =
List.iter (Format.fprintf ppf "%a\n" dump) list
let wrap t =
match t.text with
| "" | "*" -> "/***/"
| txt when Reason_syntax_util.isLineComment txt ->
"//"
^ (String.sub txt 0 (String.length txt - 1))
^ Reason_syntax_util.EOLMarker.string
| txt when txt.[0] = '*' && txt.[1] <> '*' -> "/**" ^ txt ^ "*/"
| txt -> "/*" ^ txt ^ "*/"
let is_doc t =
String.length t.text > 0 && t.text.[0] == '*'
let make ~location category text =
{ text; category; location }
let isLineComment {category; text} = match category with
| SingleLine -> Reason_syntax_util.isLineComment text
| EndOfLine | Regular -> false
|
803861db73ee8071b0abf3a6df68e83c56d563d4e15ffa16d582afad4022d2b4 | GaloisInc/ivory | Module.hs | --
-- Module.hs --- Ivory module for 'ivory-hw'.
--
Copyright ( C ) 2013 , Galois , Inc.
All Rights Reserved .
--
module Ivory.HW.Module (
hw_moduledef,
hw_artifacts
) where
import Ivory.HW.Prim
import Ivory.Artifact
import qualified Paths_ivory_hw
hw_artifacts :: [Located Artifact]
hw_artifacts =
[Incl $ artifactCabalFile Paths_ivory_hw.getDataDir "support/ivory_hw_prim.h"]
| null | https://raw.githubusercontent.com/GaloisInc/ivory/53a0795b4fbeb0b7da0f6cdaccdde18849a78cd6/ivory-hw/src/Ivory/HW/Module.hs | haskell |
Module.hs --- Ivory module for 'ivory-hw'.
| Copyright ( C ) 2013 , Galois , Inc.
All Rights Reserved .
module Ivory.HW.Module (
hw_moduledef,
hw_artifacts
) where
import Ivory.HW.Prim
import Ivory.Artifact
import qualified Paths_ivory_hw
hw_artifacts :: [Located Artifact]
hw_artifacts =
[Incl $ artifactCabalFile Paths_ivory_hw.getDataDir "support/ivory_hw_prim.h"]
|
6b33a08457a5c7d0303eac661f3aa6388ca8bca9316a23e4280b2c7b46e43d2d | levand/prolin | commons_math.clj | (ns prolin.commons-math
(:require [prolin.protocols :as p]
[prolin.polynomial :as poly]
[clojure.string :as str]
[clojure.set :as set])
(:import [org.apache.commons.math3.optim.linear
SimplexSolver
LinearObjectiveFunction
LinearConstraint
LinearConstraintSet
Relationship]
[org.apache.commons.math3.optim.nonlinear.scalar GoalType]
[org.apache.commons.math3.optim OptimizationData]
[org.apache.commons.math3.optim.linear
UnboundedSolutionException
NoFeasibleSolutionException]))
(def ^:dynamic *debug* false)
(defmulti debug class)
(defmethod debug prolin.protocols.LinearPolynomial
[p]
(str (p/variables p) " " (p/constant p)))
(defmethod debug prolin.protocols.Constraint
[c]
(str (debug (p/polynomial c)) " " (p/relation c) " 0"))
(defmethod debug :default
[o]
(str o))
(defmethod debug org.apache.commons.math3.linear.RealVector
[v]
(str (seq (.toArray v))))
(defmethod debug LinearObjectiveFunction
[objective]
(str (.getConstantTerm objective) ", " (debug (.getCoefficients objective))))
(defmethod debug LinearConstraint
[c]
(str (debug (.getCoefficients c)) " " (debug (.getRelationship c)) " " (.getValue c)))
(defmethod debug LinearConstraintSet
[cs]
(str (str/join "\n" (map debug (.getConstraints cs)))))
(defn- print-cm-debug-info
[[objective constraints]]
(println "======")
(println "raw objective:" (debug objective))
(doseq [constraint (.getConstraints constraints)]
(println "raw constraint:" (debug constraint))))
(defn- print-debug-info
[objective constraints]
(println "======")
(println "objective:" (debug objective))
(doseq [constraint constraints]
(println "constraint:" (debug constraint))))
(defn- build-objective
"Build a LinearObjectiveFunction from a normalized
p/LinearPolynomial, with coefficients ordered by the supplied
ordered key sequence."
[poly key-sequence]
(LinearObjectiveFunction. (double-array (map (p/variables poly) key-sequence))
(double (p/constant poly))))
(def relationships {'= Relationship/EQ
'<= Relationship/LEQ
'>= Relationship/GEQ})
(defn- build-constraints
"Build a LinearConstraintSet from the provided p/Constraints, with
coefficients ordered by the supplied ordered key sequence."
[constraints key-sequence]
(LinearConstraintSet.
(map (fn [constraint]
(LinearConstraint. (double-array (map (p/variables (p/polynomial constraint))
key-sequence))
(relationships (p/relation constraint))
(double (* -1 (p/constant (p/polynomial constraint))))))
constraints)))
(def defaults
"Default options for constructing a SimplexSolver."
{:epsilon 1.0e-6
:max-ulps 10
:cutoff 1.0e-12})
(defn solver
"Return an implementation of Solver using the 2-stage Simplex
algorithm provided by Apache Commons Math.
Optionally takes an options map containing the following keys:
:epsilon - Amount of error to accept for algorithm convergence.
:max-ulps - Amount of error to accept in floating point comparisons.
:cutoff - Values smaller than the cutOff are treated as zero."
([] (solver {}))
([options]
(reify p/Solver
(optimize [_ objective constraints minimize?]
(try
(let [opts (merge defaults options)
solver (SimplexSolver. (:epsilon opts) (:max-ulps opts) (:cutoff opts))
zero (poly/zero (reduce set/union
(keys (p/variables objective))
(map (comp set keys p/variables p/polynomial)
constraints)))
coefficient-ordering (keys (p/variables zero))
normalized-objective (poly/add zero objective)
normalized-constraints (map (fn [constraint]
(p/constraint (p/relation constraint)
(poly/add zero (p/polynomial constraint))))
constraints)
optimization-data [(build-objective normalized-objective coefficient-ordering)
(build-constraints normalized-constraints coefficient-ordering)
(if minimize? GoalType/MINIMIZE GoalType/MAXIMIZE)]
_ (when *debug* (print-debug-info normalized-objective normalized-constraints))
_ (when *debug* (print-cm-debug-info optimization-data))
solution (.optimize solver (into-array OptimizationData optimization-data))]
(zipmap (keys (p/variables zero))
(.getPoint solution)))
(catch UnboundedSolutionException e
(throw (ex-info "Unbounded solution" {:reason :unbounded
:objective objective
:constraints constraints
:minimize? minimize?} e)))
(catch NoFeasibleSolutionException e
(throw (ex-info "No solution" {:reason :no-solution
:objective objective
:constraints constraints
:minimize? minimize?} e))))))))
| null | https://raw.githubusercontent.com/levand/prolin/1483d6503095e85f66e577262abfb1c90571cfd2/src/prolin/commons_math.clj | clojure | (ns prolin.commons-math
(:require [prolin.protocols :as p]
[prolin.polynomial :as poly]
[clojure.string :as str]
[clojure.set :as set])
(:import [org.apache.commons.math3.optim.linear
SimplexSolver
LinearObjectiveFunction
LinearConstraint
LinearConstraintSet
Relationship]
[org.apache.commons.math3.optim.nonlinear.scalar GoalType]
[org.apache.commons.math3.optim OptimizationData]
[org.apache.commons.math3.optim.linear
UnboundedSolutionException
NoFeasibleSolutionException]))
(def ^:dynamic *debug* false)
(defmulti debug class)
(defmethod debug prolin.protocols.LinearPolynomial
[p]
(str (p/variables p) " " (p/constant p)))
(defmethod debug prolin.protocols.Constraint
[c]
(str (debug (p/polynomial c)) " " (p/relation c) " 0"))
(defmethod debug :default
[o]
(str o))
(defmethod debug org.apache.commons.math3.linear.RealVector
[v]
(str (seq (.toArray v))))
(defmethod debug LinearObjectiveFunction
[objective]
(str (.getConstantTerm objective) ", " (debug (.getCoefficients objective))))
(defmethod debug LinearConstraint
[c]
(str (debug (.getCoefficients c)) " " (debug (.getRelationship c)) " " (.getValue c)))
(defmethod debug LinearConstraintSet
[cs]
(str (str/join "\n" (map debug (.getConstraints cs)))))
(defn- print-cm-debug-info
[[objective constraints]]
(println "======")
(println "raw objective:" (debug objective))
(doseq [constraint (.getConstraints constraints)]
(println "raw constraint:" (debug constraint))))
(defn- print-debug-info
[objective constraints]
(println "======")
(println "objective:" (debug objective))
(doseq [constraint constraints]
(println "constraint:" (debug constraint))))
(defn- build-objective
"Build a LinearObjectiveFunction from a normalized
p/LinearPolynomial, with coefficients ordered by the supplied
ordered key sequence."
[poly key-sequence]
(LinearObjectiveFunction. (double-array (map (p/variables poly) key-sequence))
(double (p/constant poly))))
(def relationships {'= Relationship/EQ
'<= Relationship/LEQ
'>= Relationship/GEQ})
(defn- build-constraints
"Build a LinearConstraintSet from the provided p/Constraints, with
coefficients ordered by the supplied ordered key sequence."
[constraints key-sequence]
(LinearConstraintSet.
(map (fn [constraint]
(LinearConstraint. (double-array (map (p/variables (p/polynomial constraint))
key-sequence))
(relationships (p/relation constraint))
(double (* -1 (p/constant (p/polynomial constraint))))))
constraints)))
(def defaults
"Default options for constructing a SimplexSolver."
{:epsilon 1.0e-6
:max-ulps 10
:cutoff 1.0e-12})
(defn solver
"Return an implementation of Solver using the 2-stage Simplex
algorithm provided by Apache Commons Math.
Optionally takes an options map containing the following keys:
:epsilon - Amount of error to accept for algorithm convergence.
:max-ulps - Amount of error to accept in floating point comparisons.
:cutoff - Values smaller than the cutOff are treated as zero."
([] (solver {}))
([options]
(reify p/Solver
(optimize [_ objective constraints minimize?]
(try
(let [opts (merge defaults options)
solver (SimplexSolver. (:epsilon opts) (:max-ulps opts) (:cutoff opts))
zero (poly/zero (reduce set/union
(keys (p/variables objective))
(map (comp set keys p/variables p/polynomial)
constraints)))
coefficient-ordering (keys (p/variables zero))
normalized-objective (poly/add zero objective)
normalized-constraints (map (fn [constraint]
(p/constraint (p/relation constraint)
(poly/add zero (p/polynomial constraint))))
constraints)
optimization-data [(build-objective normalized-objective coefficient-ordering)
(build-constraints normalized-constraints coefficient-ordering)
(if minimize? GoalType/MINIMIZE GoalType/MAXIMIZE)]
_ (when *debug* (print-debug-info normalized-objective normalized-constraints))
_ (when *debug* (print-cm-debug-info optimization-data))
solution (.optimize solver (into-array OptimizationData optimization-data))]
(zipmap (keys (p/variables zero))
(.getPoint solution)))
(catch UnboundedSolutionException e
(throw (ex-info "Unbounded solution" {:reason :unbounded
:objective objective
:constraints constraints
:minimize? minimize?} e)))
(catch NoFeasibleSolutionException e
(throw (ex-info "No solution" {:reason :no-solution
:objective objective
:constraints constraints
:minimize? minimize?} e))))))))
| |
55cb77c5e2561af56c3028e4f80f2637f8194a9e96b2e5182478be4464c54e1e | input-output-hk/project-icarus-importer | Mode.hs | # LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Pos.Web.Mode
( WebMode
, WebModeContext(..)
) where
import Universum
import Control.Lens (makeLensesWith)
import qualified Control.Monad.Reader as Mtl
import Mockable (Production)
import Pos.Context (HasPrimaryKey (..), HasSscContext (..), NodeContext)
import Pos.Core.Configuration (HasConfiguration)
import Pos.DB (NodeDBs)
import Pos.DB.Block (dbGetSerBlockRealDefault, dbGetSerUndoRealDefault,
dbPutSerBlundsRealDefault)
import Pos.DB.Class (MonadDB (..), MonadDBRead (..))
import Pos.DB.Rocks (dbDeleteDefault, dbGetDefault, dbIterSourceDefault, dbPutDefault,
dbWriteBatchDefault)
import Pos.Txp (GenericTxpLocalData, MempoolExt, TxpHolderTag)
import Pos.Util.Lens (postfixLFields)
import Pos.Util.Util (HasLens (..))
data WebModeContext ext = WebModeContext
{ wmcNodeDBs :: !NodeDBs
, wmcTxpLocalData :: !(GenericTxpLocalData ext)
, wmcNodeContext :: !NodeContext
}
makeLensesWith postfixLFields ''WebModeContext
instance HasLens NodeDBs (WebModeContext ext) NodeDBs where
lensOf = wmcNodeDBs_L
instance HasLens TxpHolderTag (WebModeContext ext) (GenericTxpLocalData ext) where
lensOf = wmcTxpLocalData_L
instance {-# OVERLAPPABLE #-}
HasLens tag NodeContext r =>
HasLens tag (WebModeContext ext) r
where
lensOf = wmcNodeContext_L . lensOf @tag
instance HasSscContext (WebModeContext ext) where
sscContext = wmcNodeContext_L . sscContext
instance HasPrimaryKey (WebModeContext ext) where
primaryKey = wmcNodeContext_L . primaryKey
type WebMode ext = Mtl.ReaderT (WebModeContext ext) Production
instance HasConfiguration => MonadDBRead (WebMode ext) where
dbGet = dbGetDefault
dbIterSource = dbIterSourceDefault
dbGetSerBlock = dbGetSerBlockRealDefault
dbGetSerUndo = dbGetSerUndoRealDefault
instance HasConfiguration => MonadDB (WebMode ext) where
dbPut = dbPutDefault
dbWriteBatch = dbWriteBatchDefault
dbDelete = dbDeleteDefault
dbPutSerBlunds = dbPutSerBlundsRealDefault
type instance MempoolExt (WebMode ext) = ext
| null | https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/lib/src/Pos/Web/Mode.hs | haskell | # OVERLAPPABLE # | # LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
module Pos.Web.Mode
( WebMode
, WebModeContext(..)
) where
import Universum
import Control.Lens (makeLensesWith)
import qualified Control.Monad.Reader as Mtl
import Mockable (Production)
import Pos.Context (HasPrimaryKey (..), HasSscContext (..), NodeContext)
import Pos.Core.Configuration (HasConfiguration)
import Pos.DB (NodeDBs)
import Pos.DB.Block (dbGetSerBlockRealDefault, dbGetSerUndoRealDefault,
dbPutSerBlundsRealDefault)
import Pos.DB.Class (MonadDB (..), MonadDBRead (..))
import Pos.DB.Rocks (dbDeleteDefault, dbGetDefault, dbIterSourceDefault, dbPutDefault,
dbWriteBatchDefault)
import Pos.Txp (GenericTxpLocalData, MempoolExt, TxpHolderTag)
import Pos.Util.Lens (postfixLFields)
import Pos.Util.Util (HasLens (..))
data WebModeContext ext = WebModeContext
{ wmcNodeDBs :: !NodeDBs
, wmcTxpLocalData :: !(GenericTxpLocalData ext)
, wmcNodeContext :: !NodeContext
}
makeLensesWith postfixLFields ''WebModeContext
instance HasLens NodeDBs (WebModeContext ext) NodeDBs where
lensOf = wmcNodeDBs_L
instance HasLens TxpHolderTag (WebModeContext ext) (GenericTxpLocalData ext) where
lensOf = wmcTxpLocalData_L
HasLens tag NodeContext r =>
HasLens tag (WebModeContext ext) r
where
lensOf = wmcNodeContext_L . lensOf @tag
instance HasSscContext (WebModeContext ext) where
sscContext = wmcNodeContext_L . sscContext
instance HasPrimaryKey (WebModeContext ext) where
primaryKey = wmcNodeContext_L . primaryKey
type WebMode ext = Mtl.ReaderT (WebModeContext ext) Production
instance HasConfiguration => MonadDBRead (WebMode ext) where
dbGet = dbGetDefault
dbIterSource = dbIterSourceDefault
dbGetSerBlock = dbGetSerBlockRealDefault
dbGetSerUndo = dbGetSerUndoRealDefault
instance HasConfiguration => MonadDB (WebMode ext) where
dbPut = dbPutDefault
dbWriteBatch = dbWriteBatchDefault
dbDelete = dbDeleteDefault
dbPutSerBlunds = dbPutSerBlundsRealDefault
type instance MempoolExt (WebMode ext) = ext
|
1e54daa48d774411437ad7f77ff6db30b83cb1c1f39ffd7020b3d5074dd4e27e | HuwCampbell/orc-haskell | Types.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DataKinds #
{-# LANGUAGE LambdaCase #-}
module Orc.Schema.Types (
CompressionKind (..)
, StreamKind (..)
, ColumnEncodingKind (..)
, Type (..)
, StripeInformation (..)
, ColumnEncoding (..)
, Stream (..)
, PostScript (..)
, Footer (..)
, StripeFooter (..)
, RowIndexEntry (..)
, RowIndex (..)
, UserMetadataItem (..)
, ColumnStatistics (..)
) where
import Data.Int
import Data.ByteString (ByteString)
import Data.Text (Text)
import Data.Word
import GHC.Generics (Generic)
import Orc.Data.Data (StructField (..))
data CompressionKind
= NONE
| ZLIB
| SNAPPY
| LZO
| LZ4
| ZSTD
deriving (Eq, Ord, Show, Enum)
data PostScript = PostScript {
-- the length of the footer section in bytes
-- NOTE: Changed to Required from Optional
footerLength :: Word64
-- the kind of generic compression used
, compression :: Maybe CompressionKind
-- the maximum size of each compression chunk
, compressionBlockSize :: Maybe Word64
-- the version of the writer
, version :: [Word32]
-- the length of the metadata section in bytes
, metadataLength :: Maybe Word64
the fixed string " ORC "
, magic :: Maybe Text
} deriving (Eq, Ord, Show)
data Footer = Footer {
the length of the file header in bytes ( always 3 )
headerLength :: Maybe Word64
-- the length of the file header and body in bytes
, contentLength :: Maybe Word64
-- the information about the stripes
, stripes :: [StripeInformation]
-- the schema information
, types :: Type
-- the user metadata that was added
, metadata :: [UserMetadataItem]
-- the total number of rows in the file
, numberOfRows :: Maybe Word64
-- the statistics of each column across the file
, statistics :: [ColumnStatistics]
-- the maximum number of rows in each index entry
, rowIndexStride :: Maybe Word32
} deriving (Eq, Ord, Show)
data StripeInformation = StripeInformation {
-- the start of the stripe within the file
offset :: Maybe Word64
-- the length of the indexes in bytes
, indexLength :: Maybe Word64
-- the length of the data in bytes
, dataLength :: Maybe Word64
-- the length of the footer in bytes
, siFooterLength :: Maybe Word64
-- the number of rows in the stripe
, siNumberOfRows :: Maybe Word64
} deriving (Eq, Ord, Show)
data Type =
BOOLEAN
| BYTE
| SHORT
| INT
| LONG
| FLOAT
| DOUBLE
| STRING
| BINARY
| TIMESTAMP
| LIST Type
| MAP Type Type
| STRUCT [StructField Type]
| UNION [Type]
| DECIMAL
| DATE
| VARCHAR
| CHAR
deriving (Show, Eq, Ord)
data ColumnStatistics = ColumnStatistics {
-- the number of values
numberOfValues :: Maybe Word64
-- At most one of these has a value for any column
, intStatistics : : Maybe IntegerStatistics
, doubleStatistics : : Maybe DoubleStatistics
-- , stringStatistics :: Maybe StringStatistics
, bucketStatistics : : Maybe BucketStatistics
, decimalStatistics : : Maybe DecimalStatistics
, dateStatistics : : Maybe DateStatistics
, binaryStatistics : : Maybe BinaryStatistics
, timestampStatistics : : Maybe TimestampStatistics
, hasNull :: Maybe Bool
} deriving (Eq, Ord, Show, Generic)
data IntegerStatistics = IntegerStatistics {
intMinimum :: Maybe Int64
, intMaximum :: Maybe Int64
, intSum :: Maybe Int64
} deriving (Eq, Ord, Show, Generic)
data DoubleStatistics = DoubleStatistics {
doubleMinimum :: Maybe Double
, doubleMaximum :: Maybe Double
, doubleSum :: Maybe Double
} deriving (Eq, Ord, Show, Generic)
data StringStatistics = StringStatistics {
stringMinimum :: Maybe Text
, stringMaximum :: Maybe Text
-- sum will store the total length of all strings
, stringSum :: Maybe Int64
} deriving (Eq, Ord, Show, Generic)
data DecimalStatistics = DecimalStatistics {
decimalMinimum :: Maybe Text
, decimalMaximum :: Maybe Text
, decimalSum :: Maybe Text
} deriving (Eq, Ord, Show, Generic)
newtype StripeStatistics = StripeStatistics {
colStats :: [ColumnStatistics]
} deriving (Eq, Ord, Show, Generic)
newtype BucketStatistics = BucketStatistics {
bucketCount :: Word64
} deriving (Eq, Ord, Show, Generic)
data DateStatistics = DateStatistics {
min , values saved as days since epoch
dataMinimum :: Maybe Int32
, dataMaximum :: Maybe Int32
} deriving (Eq, Ord, Show, Generic)
data TimestampStatistics = TimestampStatistics {
min , values saved as milliseconds since epoch
timestampMinimum :: Maybe Int64
, timestampMaximum :: Maybe Int64
min , values saved as milliseconds since UNIX epoch
, timestampMinimumUtc :: Maybe Int64
, timestampMaximumUtc :: Maybe Int64
} deriving (Eq, Ord, Show, Generic)
newtype BinaryStatistics = BinaryStatistics {
-- sum will store the total binary blob length
binarySum :: Maybe Int64
} deriving (Eq, Ord, Show, Generic)
data UserMetadataItem = UserMetadataItem {
-- the user defined key
name :: Text
-- the user defined binary value
, value :: ByteString
} deriving (Eq, Ord, Show, Generic)
data RowIndexEntry = RowIndexEntry {
positions :: [Word64]
, rowIndexStatistics :: Maybe ColumnStatistics
} deriving (Eq, Ord, Show)
newtype RowIndex = RowIndex {
entry :: [RowIndexEntry]
} deriving (Eq, Ord, Show)
data StripeFooter = StripeFooter {
-- the location of each stream
streams :: [Stream]
-- the encoding of each column
, columns :: [ColumnEncoding]
, writerTimezone :: Maybe Text
} deriving (Eq, Ord, Show)
data StreamKind
= SK_PRESENT
| SK_DATA
| SK_LENGTH
| SK_DICTIONARY_DATA
| SK_DICTIONARY_COUNT
| SK_SECONDARY
| SK_ROW_INDEX
| SK_BLOOM_FILTER
deriving (Eq, Ord, Show, Enum)
data Stream = Stream {
-- if you add new index stream kinds, you need to make sure to update
-- StreamName to ensure it is added to the stripe in the right area
streamKind :: Maybe StreamKind
, streamColumn :: Maybe Word32
, streamLength :: Maybe Word64
} deriving (Eq, Ord, Show)
data ColumnEncodingKind
= DIRECT
| DICTIONARY
| DIRECT_V2
| DICTIONARY_V2
deriving (Eq, Ord, Show, Enum)
data ColumnEncoding = ColumnEncoding {
columnEncodingKind :: ColumnEncodingKind
, columnEncodingdictionarySize :: Maybe Word32
} deriving (Eq, Ord, Show)
| null | https://raw.githubusercontent.com/HuwCampbell/orc-haskell/259649bc5fa5c6d8bd850fdad0517af6c028e00e/src/Orc/Schema/Types.hs | haskell | # LANGUAGE LambdaCase #
the length of the footer section in bytes
NOTE: Changed to Required from Optional
the kind of generic compression used
the maximum size of each compression chunk
the version of the writer
the length of the metadata section in bytes
the length of the file header and body in bytes
the information about the stripes
the schema information
the user metadata that was added
the total number of rows in the file
the statistics of each column across the file
the maximum number of rows in each index entry
the start of the stripe within the file
the length of the indexes in bytes
the length of the data in bytes
the length of the footer in bytes
the number of rows in the stripe
the number of values
At most one of these has a value for any column
, stringStatistics :: Maybe StringStatistics
sum will store the total length of all strings
sum will store the total binary blob length
the user defined key
the user defined binary value
the location of each stream
the encoding of each column
if you add new index stream kinds, you need to make sure to update
StreamName to ensure it is added to the stripe in the right area | # LANGUAGE DeriveGeneric #
# LANGUAGE DataKinds #
module Orc.Schema.Types (
CompressionKind (..)
, StreamKind (..)
, ColumnEncodingKind (..)
, Type (..)
, StripeInformation (..)
, ColumnEncoding (..)
, Stream (..)
, PostScript (..)
, Footer (..)
, StripeFooter (..)
, RowIndexEntry (..)
, RowIndex (..)
, UserMetadataItem (..)
, ColumnStatistics (..)
) where
import Data.Int
import Data.ByteString (ByteString)
import Data.Text (Text)
import Data.Word
import GHC.Generics (Generic)
import Orc.Data.Data (StructField (..))
data CompressionKind
= NONE
| ZLIB
| SNAPPY
| LZO
| LZ4
| ZSTD
deriving (Eq, Ord, Show, Enum)
data PostScript = PostScript {
footerLength :: Word64
, compression :: Maybe CompressionKind
, compressionBlockSize :: Maybe Word64
, version :: [Word32]
, metadataLength :: Maybe Word64
the fixed string " ORC "
, magic :: Maybe Text
} deriving (Eq, Ord, Show)
data Footer = Footer {
the length of the file header in bytes ( always 3 )
headerLength :: Maybe Word64
, contentLength :: Maybe Word64
, stripes :: [StripeInformation]
, types :: Type
, metadata :: [UserMetadataItem]
, numberOfRows :: Maybe Word64
, statistics :: [ColumnStatistics]
, rowIndexStride :: Maybe Word32
} deriving (Eq, Ord, Show)
data StripeInformation = StripeInformation {
offset :: Maybe Word64
, indexLength :: Maybe Word64
, dataLength :: Maybe Word64
, siFooterLength :: Maybe Word64
, siNumberOfRows :: Maybe Word64
} deriving (Eq, Ord, Show)
data Type =
BOOLEAN
| BYTE
| SHORT
| INT
| LONG
| FLOAT
| DOUBLE
| STRING
| BINARY
| TIMESTAMP
| LIST Type
| MAP Type Type
| STRUCT [StructField Type]
| UNION [Type]
| DECIMAL
| DATE
| VARCHAR
| CHAR
deriving (Show, Eq, Ord)
data ColumnStatistics = ColumnStatistics {
numberOfValues :: Maybe Word64
, intStatistics : : Maybe IntegerStatistics
, doubleStatistics : : Maybe DoubleStatistics
, bucketStatistics : : Maybe BucketStatistics
, decimalStatistics : : Maybe DecimalStatistics
, dateStatistics : : Maybe DateStatistics
, binaryStatistics : : Maybe BinaryStatistics
, timestampStatistics : : Maybe TimestampStatistics
, hasNull :: Maybe Bool
} deriving (Eq, Ord, Show, Generic)
data IntegerStatistics = IntegerStatistics {
intMinimum :: Maybe Int64
, intMaximum :: Maybe Int64
, intSum :: Maybe Int64
} deriving (Eq, Ord, Show, Generic)
data DoubleStatistics = DoubleStatistics {
doubleMinimum :: Maybe Double
, doubleMaximum :: Maybe Double
, doubleSum :: Maybe Double
} deriving (Eq, Ord, Show, Generic)
data StringStatistics = StringStatistics {
stringMinimum :: Maybe Text
, stringMaximum :: Maybe Text
, stringSum :: Maybe Int64
} deriving (Eq, Ord, Show, Generic)
data DecimalStatistics = DecimalStatistics {
decimalMinimum :: Maybe Text
, decimalMaximum :: Maybe Text
, decimalSum :: Maybe Text
} deriving (Eq, Ord, Show, Generic)
newtype StripeStatistics = StripeStatistics {
colStats :: [ColumnStatistics]
} deriving (Eq, Ord, Show, Generic)
newtype BucketStatistics = BucketStatistics {
bucketCount :: Word64
} deriving (Eq, Ord, Show, Generic)
data DateStatistics = DateStatistics {
min , values saved as days since epoch
dataMinimum :: Maybe Int32
, dataMaximum :: Maybe Int32
} deriving (Eq, Ord, Show, Generic)
data TimestampStatistics = TimestampStatistics {
min , values saved as milliseconds since epoch
timestampMinimum :: Maybe Int64
, timestampMaximum :: Maybe Int64
min , values saved as milliseconds since UNIX epoch
, timestampMinimumUtc :: Maybe Int64
, timestampMaximumUtc :: Maybe Int64
} deriving (Eq, Ord, Show, Generic)
newtype BinaryStatistics = BinaryStatistics {
binarySum :: Maybe Int64
} deriving (Eq, Ord, Show, Generic)
data UserMetadataItem = UserMetadataItem {
name :: Text
, value :: ByteString
} deriving (Eq, Ord, Show, Generic)
data RowIndexEntry = RowIndexEntry {
positions :: [Word64]
, rowIndexStatistics :: Maybe ColumnStatistics
} deriving (Eq, Ord, Show)
newtype RowIndex = RowIndex {
entry :: [RowIndexEntry]
} deriving (Eq, Ord, Show)
data StripeFooter = StripeFooter {
streams :: [Stream]
, columns :: [ColumnEncoding]
, writerTimezone :: Maybe Text
} deriving (Eq, Ord, Show)
data StreamKind
= SK_PRESENT
| SK_DATA
| SK_LENGTH
| SK_DICTIONARY_DATA
| SK_DICTIONARY_COUNT
| SK_SECONDARY
| SK_ROW_INDEX
| SK_BLOOM_FILTER
deriving (Eq, Ord, Show, Enum)
data Stream = Stream {
streamKind :: Maybe StreamKind
, streamColumn :: Maybe Word32
, streamLength :: Maybe Word64
} deriving (Eq, Ord, Show)
data ColumnEncodingKind
= DIRECT
| DICTIONARY
| DIRECT_V2
| DICTIONARY_V2
deriving (Eq, Ord, Show, Enum)
data ColumnEncoding = ColumnEncoding {
columnEncodingKind :: ColumnEncodingKind
, columnEncodingdictionarySize :: Maybe Word32
} deriving (Eq, Ord, Show)
|
9ae3de061b63d699d84f8569e11eab4396e550c7b56c4a1a8f9dfa7cfcebba57 | mathematical-systems/clml | grovel.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
grovel.lisp --- The CFFI Groveller .
;;;
Copyright ( C ) 2005 - 2006 , < >
Copyright ( C ) 2005 - 2006 , < >
Copyright ( C ) 2007 , < >
Copyright ( C ) 2007 ,
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
files ( the " Software " ) , to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software , and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
;;;
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(in-package #:cffi-grovel)
(defun trim-whitespace (strings)
(loop for s in strings
collect (string-trim '(#\Space #\Tab) s)))
;;;# Error Conditions
;;; This warning is signalled when cffi-grovel can't find some macro.
Signalled by CONSTANT or CONSTANTENUM .
(define-condition missing-definition (warning)
((%name :initarg :name :reader name-of))
(:report (lambda (condition stream)
(format stream "No definition for ~A"
(name-of condition)))))
;;;# Grovelling
(defparameter *cc*
#+(or cygwin (not windows)) "cc"
#+(and windows (not cygwin)) "c:/msys/1.0/bin/gcc.exe")
(defparameter *cc-flags* nil)
;;; The header of the intermediate C file.
(defparameter *header*
"/*
* This file has been automatically generated by cffi-grovel.
* Do not edit it by hand.
*/
")
;;; C code generated by cffi-grovel is inserted between the contents
;;; of *PROLOGUE* and *POSTSCRIPT*, inside the main function's body.
(defparameter *prologue*
"
#include <grovel/common.h>
int main(int argc, char**argv) {
FILE *output = argc > 1 ? fopen(argv[1], \"w\") : stdout;
fprintf(output, \";;;; This file has been automatically generated by \"
\"cffi-grovel.\\n;;;; Do not edit it by hand.\\n\\n\");
")
(defparameter *postscript*
"
if (output != stdout)
fclose(output);
return 0;
}
")
(defun unescape-for-c (text)
(with-output-to-string (result)
(loop for i below (length text)
for char = (char text i) do
(cond ((eql char #\") (princ "\\\"" result))
((eql char #\newline) (princ "\\n" result))
(t (princ char result))))))
(defun c-format (out fmt &rest args)
(let ((text (unescape-for-c (format nil "~?" fmt args))))
(format out "~& fprintf(output, \"~A\");~%" text)))
(defun c-printf (out fmt &rest args)
(flet ((item (item)
(format out "~A" (unescape-for-c (format nil item)))))
(format out "~& fprintf(output, \"")
(item fmt)
(format out "\"")
(loop for arg in args do
(format out ", ")
(item arg))
(format out ");~%")))
TODO : handle packages in a better way . One way is to process each
;;; grovel form as it is read (like we already do for wrapper
;;; forms). This way in can expect *PACKAGE* to have sane values.
;;; This would require that "header forms" come before any other
;;; forms.
(defun c-print-symbol (out symbol &optional no-package)
(c-format out
(let ((package (symbol-package symbol)))
(cond
((eq (find-package '#:keyword) package) ":~(~A~)")
(no-package "~(~A~)")
((eq (find-package '#:cl) package) "cl:~(~A~)")
(t "~(~A~)")))
symbol))
(defun c-write (out form &key recursive)
(cond
((and (listp form)
(eq 'quote (car form)))
(c-format out "'")
(c-write out (cadr form) :recursive t))
((listp form)
(c-format out "(")
(loop for subform in form
for first-p = t then nil
unless first-p do (c-format out " ")
do (c-write out subform :recursive t))
(c-format out ")"))
((symbolp form)
(c-print-symbol out form)))
(unless recursive
(c-format out "~%")))
Always NIL for now , add { ENABLE , DISABLE}-AUTO - EXPORT grovel forms
;;; later, if necessary.
(defvar *auto-export* nil)
(defun c-export (out symbol)
(when (and *auto-export* (not (keywordp symbol)))
(c-format out "(cl:export '")
(c-print-symbol out symbol t)
(c-format out ")~%")))
(defun c-section-header (out section-type section-symbol)
(format out "~% /* ~A section for ~S */~%"
section-type
section-symbol))
(defun remove-suffix (string suffix)
(let ((suffix-start (- (length string) (length suffix))))
(if (and (> suffix-start 0)
(string= string suffix :start1 suffix-start))
(subseq string 0 suffix-start)
string)))
(defun strcat (&rest strings)
(apply #'concatenate 'string strings))
(defgeneric %process-grovel-form (name out arguments)
(:method (name out arguments)
(declare (ignore out arguments))
(error "Unknown Grovel syntax: ~S" name)))
(defun process-grovel-form (out form)
(%process-grovel-form (form-kind form) out (cdr form)))
(defun form-kind (form)
;; Using INTERN here instead of FIND-SYMBOL will result in less
;; cryptic error messages when an undefined grovel/wrapper form is
;; found.
(intern (symbol-name (car form)) '#:cffi-grovel))
(defvar *header-forms* '(c include define flag typedef))
(defun header-form-p (form)
(member (form-kind form) *header-forms*))
(defun generate-c-file (input-file output-defaults)
(let ((c-file (make-pathname :type "c" :defaults output-defaults)))
(with-open-file (out c-file :direction :output :if-exists :supersede)
(with-open-file (in input-file :direction :input)
(flet ((read-forms (s)
(do ((forms ())
(form (read s nil nil) (read s nil nil)))
((null form) (nreverse forms))
(labels
((process-form (f)
(case (form-kind f)
(flag (warn "Groveler clause FLAG is deprecated, use CC-FLAGS instead.")))
(case (form-kind f)
(in-package
(setf *package* (find-package (second f)))
(push f forms))
(progn
;; flatten progn forms
(mapc #'process-form (rest f)))
(t (push f forms)))))
(process-form form)))))
(let* ((forms (read-forms in))
(header-forms (remove-if-not #'header-form-p forms))
(body-forms (remove-if #'header-form-p forms)))
(write-string *header* out)
(dolist (form header-forms)
(process-grovel-form out form))
(write-string *prologue* out)
(dolist (form body-forms)
(process-grovel-form out form))
(write-string *postscript* out)))))
c-file))
(defparameter *exe-extension* #-windows nil #+windows "exe")
(defun exe-filename (defaults)
(let ((path (make-pathname :type *exe-extension*
:defaults defaults)))
It 's necessary to prepend " ./ " to relative paths because some
implementations of INVOKE use a shell .
(when (or (not (pathname-directory path))
(eq :relative (car (pathname-directory path))))
(setf path (make-pathname
:directory (list* :relative "."
(cdr (pathname-directory path)))
:defaults path)))
path))
(defun tmp-lisp-filename (defaults)
(make-pathname :name (strcat (pathname-name defaults) ".grovel-tmp")
:type "lisp" :defaults defaults))
(cffi:defcfun "getenv" :string
(name :string))
;;; FIXME: is there a better way to detect whether these flags
;;; are necessary?
(defparameter *cpu-word-size-flags*
(ecase (cffi:foreign-type-size :long)
(4 (list "-m32"))
(8 (list "-m64"))))
(defparameter *platform-library-flags*
(list #+darwin "-bundle" #-darwin "-shared"))
(defun cc-compile-and-link (input-file output-file &key library)
(let ((arglist
`(,(or (getenv "CC") *cc*)
,@*cpu-word-size-flags*
,@*cc-flags*
;; add the cffi directory to the include path to make common.h visible
,(format nil "-I~A"
(directory-namestring
(truename
(asdf:system-definition-pathname :cffi-grovel))))
,@(when library *platform-library-flags*)
"-fPIC" "-o"
,(native-namestring output-file)
,(native-namestring input-file))))
(apply #'invoke arglist)))
;;; *PACKAGE* is rebound so that the IN-PACKAGE form can set it during
;;; *the extent of a given grovel file.
(defun process-grovel-file (input-file &optional (output-defaults input-file))
(with-standard-io-syntax
(let* ((c-file (generate-c-file input-file output-defaults))
(exe-file (exe-filename c-file))
(lisp-file (tmp-lisp-filename c-file)))
(cc-compile-and-link c-file exe-file)
(invoke exe-file (native-namestring lisp-file))
lisp-file)))
;;; OUT is lexically bound to the output stream within BODY.
(defmacro define-grovel-syntax (name lambda-list &body body)
(with-unique-names (name-var args)
`(defmethod %process-grovel-form ((,name-var (eql ',name)) out ,args)
(declare (ignorable out))
(destructuring-bind ,lambda-list ,args
,@body))))
(define-grovel-syntax c (body)
(format out "~%~A~%" body))
(define-grovel-syntax include (&rest includes)
(format out "~{#include <~A>~%~}" includes))
(define-grovel-syntax define (name &optional value)
(format out "#define ~A~@[ ~A~]~%" name value))
(define-grovel-syntax typedef (base-type new-type)
(format out "typedef ~A ~A;~%" base-type new-type))
;;; Is this really needed?
(define-grovel-syntax ffi-typedef (new-type base-type)
(c-format out "(cffi:defctype ~S ~S)~%" new-type base-type))
(define-grovel-syntax flag (&rest flags)
(appendf *cc-flags* (trim-whitespace flags)))
(define-grovel-syntax cc-flags (&rest flags)
(appendf *cc-flags* (trim-whitespace flags)))
;;; This form also has some "read time" effects. See GENERATE-C-FILE.
(define-grovel-syntax in-package (name)
(c-format out "(cl:in-package #:~A)~%~%" name))
(define-grovel-syntax ctype (lisp-name size-designator)
(c-section-header out "ctype" lisp-name)
(c-export out lisp-name)
(c-format out "(cffi:defctype ")
(c-print-symbol out lisp-name t)
(c-format out " ")
(format out "~& type_name(output, SIGNEDP(~A), ~:[sizeof(~A)~;~D~]);~%"
size-designator
(etypecase size-designator
(string nil)
(integer t))
size-designator)
(c-format out ")~%")
(unless (keywordp lisp-name)
(c-export out lisp-name))
(let ((size-of-constant-name (symbolicate '#:size-of- lisp-name)))
(c-export out size-of-constant-name)
(c-format out "(cl:defconstant "
size-of-constant-name lisp-name)
(c-print-symbol out size-of-constant-name)
(c-format out " (cffi:foreign-type-size '")
(c-print-symbol out lisp-name)
(c-format out "))~%")))
Syntax differs from anything else in CFFI . Fix ?
(define-grovel-syntax constant ((lisp-name &rest c-names)
&key (type 'integer) documentation optional)
(when (keywordp lisp-name)
(setf lisp-name (format-symbol "~A" lisp-name)))
(c-section-header out "constant" lisp-name)
(dolist (c-name c-names)
(format out "~&#ifdef ~A~%" c-name)
(c-export out lisp-name)
(c-format out "(cl:defconstant ")
(c-print-symbol out lisp-name t)
(c-format out " ")
(ecase type
(integer
(format out "~& if(SIGNED64P(~A))~%" c-name)
(format out " fprintf(output, \"%lli\", (int64_t) ~A);" c-name)
(format out "~& else~%")
(format out " fprintf(output, \"%llu\", (uint64_t) ~A);" c-name))
(double-float
(format out "~& fprintf(output, \"%s\", print_double_for_lisp((double)~A));~%" c-name)))
(when documentation
(c-format out " ~S" documentation))
(c-format out ")~%")
(format out "~&#else~%"))
(unless optional
(c-format out "(cl:warn 'cffi-grovel:missing-definition :name '~A)~%"
lisp-name))
(dotimes (i (length c-names))
(format out "~&#endif~%")))
(define-grovel-syntax cunion (union-lisp-name union-c-name &rest slots)
(let ((documentation (when (stringp (car slots)) (pop slots))))
(c-section-header out "cunion" union-lisp-name)
(c-export out union-lisp-name)
(dolist (slot slots)
(let ((slot-lisp-name (car slot)))
(c-export out slot-lisp-name)))
(c-format out "(cffi:defcunion (")
(c-print-symbol out union-lisp-name t)
(c-printf out " :size %i)" (format nil "sizeof(~A)" union-c-name))
(when documentation
(c-format out "~% ~S" documentation))
(dolist (slot slots)
(destructuring-bind (slot-lisp-name slot-c-name &key type count)
slot
(declare (ignore slot-c-name))
(c-format out "~% (")
(c-print-symbol out slot-lisp-name t)
(c-format out " ")
(c-print-symbol out type)
(etypecase count
(integer
(c-format out " :count ~D" count))
((eql :auto)
;; nb, works like :count :auto does in cstruct below
(c-printf out " :count %i"
(format nil "sizeof(~A)" union-c-name)))
(null t))
(c-format out ")")))
(c-format out ")~%")))
(defun make-from-pointer-function-name (type-name)
(symbolicate '#:make- type-name '#:-from-pointer))
;;; DEFINE-C-STRUCT-WRAPPER (in ../src/types.lisp) seems like a much
;;; cleaner way to do this. Unless I can find any advantage in doing
;;; it this way I'll delete this soon. --luis
(define-grovel-syntax cstruct-and-class-item (&rest arguments)
(process-grovel-form out (cons 'cstruct arguments))
(destructuring-bind (struct-lisp-name struct-c-name &rest slots)
arguments
(declare (ignore struct-c-name))
(let* ((slot-names (mapcar #'car slots))
(reader-names (mapcar
(lambda (slot-name)
(intern
(strcat (symbol-name struct-lisp-name) "-"
(symbol-name slot-name))))
slot-names))
(initarg-names (mapcar
(lambda (slot-name)
(intern (symbol-name slot-name) "KEYWORD"))
slot-names))
(slot-decoders (mapcar (lambda (slot)
(destructuring-bind
(lisp-name c-name
&key type count
&allow-other-keys)
slot
(declare (ignore lisp-name c-name))
(cond ((and (eq type :char) count)
'cffi:foreign-string-to-lisp)
(t nil))))
slots))
(defclass-form
`(defclass ,struct-lisp-name ()
,(mapcar (lambda (slot-name initarg-name reader-name)
`(,slot-name :initarg ,initarg-name
:reader ,reader-name))
slot-names
initarg-names
reader-names)))
(make-function-name
(make-from-pointer-function-name struct-lisp-name))
(make-defun-form
;; this function is then used as a constructor for this class.
`(defun ,make-function-name (pointer)
(cffi:with-foreign-slots
(,slot-names pointer ,struct-lisp-name)
(make-instance ',struct-lisp-name
,@(loop for slot-name in slot-names
for initarg-name in initarg-names
for slot-decoder in slot-decoders
collect initarg-name
if slot-decoder
collect `(,slot-decoder ,slot-name)
else collect slot-name))))))
(c-export out make-function-name)
(dolist (reader-name reader-names)
(c-export out reader-name))
(c-write out defclass-form)
(c-write out make-defun-form))))
(define-grovel-syntax cstruct (struct-lisp-name struct-c-name &rest slots)
(let ((documentation (when (stringp (car slots)) (pop slots))))
(c-section-header out "cstruct" struct-lisp-name)
(c-export out struct-lisp-name)
(dolist (slot slots)
(let ((slot-lisp-name (car slot)))
(c-export out slot-lisp-name)))
(c-format out "(cffi:defcstruct (")
(c-print-symbol out struct-lisp-name t)
(c-printf out " :size %i)"
(format nil "sizeof(~A)" struct-c-name))
(when documentation
(c-format out "~% ~S" documentation))
(dolist (slot slots)
(destructuring-bind (slot-lisp-name slot-c-name &key type count)
slot
(c-format out "~% (")
(c-print-symbol out slot-lisp-name t)
(c-format out " ")
(c-print-symbol out type)
(etypecase count
(null t)
(integer
(c-format out " :count ~D" count))
((eql :auto)
(c-printf out " :count %i"
(format nil "sizeof(~A) - offsetof(~A, ~A)"
struct-c-name
struct-c-name
slot-c-name)))
((or symbol string)
(format out "~&#ifdef ~A~%" count)
(c-printf out " :count %i"
(format nil "~A" count))
(format out "~&#endif~%")))
(c-printf out " :offset %i)"
(format nil "offsetof(~A, ~A)"
struct-c-name
slot-c-name))))
(c-format out ")~%")
(let ((size-of-constant-name
(symbolicate '#:size-of- struct-lisp-name)))
(c-export out size-of-constant-name)
(c-format out "(cl:defconstant "
size-of-constant-name struct-lisp-name)
(c-print-symbol out size-of-constant-name)
(c-format out " (cffi:foreign-type-size '")
(c-print-symbol out struct-lisp-name)
(c-format out "))~%"))))
(defmacro define-pseudo-cvar (str name type &key read-only)
(let ((c-parse (let ((*read-eval* nil)
(*readtable* (copy-readtable nil)))
(setf (readtable-case *readtable*) :preserve)
(read-from-string str))))
(typecase c-parse
(symbol `(cffi:defcvar (,(symbol-name c-parse) ,name) ,type
:read-only ,read-only))
(list (unless (and (= (length c-parse) 2)
(null (second c-parse))
(symbolp (first c-parse))
(eql #\* (char (symbol-name (first c-parse)) 0)))
(error "Unable to parse c-string ~s." str))
(let ((func-name (symbolicate "%" name '#:-accessor)))
`(progn
(declaim (inline ,func-name))
(cffi:defcfun (,(string-trim "*" (symbol-name (first c-parse)))
,func-name) :pointer)
(define-symbol-macro ,name
(cffi:mem-ref (,func-name) ',type)))))
(t (error "Unable to parse c-string ~s." str)))))
(defun foreign-name-to-symbol (s)
(intern (substitute #\- #\_ (string-upcase s))))
(defun choose-lisp-and-foreign-names (string-or-list)
(etypecase string-or-list
(string (values string-or-list (foreign-name-to-symbol string-or-list)))
(list (destructuring-bind (fname lname &rest args) string-or-list
(declare (ignore args))
(assert (and (stringp fname) (symbolp lname)))
(values fname lname)))))
(define-grovel-syntax cvar (name type &key read-only)
(multiple-value-bind (c-name lisp-name)
(choose-lisp-and-foreign-names name)
(c-section-header out "cvar" lisp-name)
(c-export out lisp-name)
(c-printf out "(cffi-grovel::define-pseudo-cvar \"%s\" "
(format nil "indirect_stringify(~A)" c-name))
(c-print-symbol out lisp-name t)
(c-format out " ")
(c-print-symbol out type)
(when read-only
(c-format out " :read-only t"))
(c-format out ")~%")))
;;; FIXME: where would docs on enum elements go?
(define-grovel-syntax cenum (name &rest enum-list)
(destructuring-bind (name &key base-type define-constants)
(ensure-list name)
(c-section-header out "cenum" name)
(c-export out name)
(c-format out "(cffi:defcenum (")
(c-print-symbol out name t)
(when base-type
(c-printf out " ")
(c-print-symbol out base-type t))
(c-format out ")")
(dolist (enum enum-list)
(destructuring-bind ((lisp-name &rest c-names) &key documentation)
enum
(declare (ignore documentation))
(check-type lisp-name keyword)
(loop :for c-name :in c-names :do
(check-type c-name string)
(c-format out " (")
(c-print-symbol out lisp-name)
(c-format out " ")
(c-printf out "%i" c-name)
(c-format out ")~%"))))
(c-format out ")~%")
(when define-constants
(define-constants-from-enum out enum-list))))
(define-grovel-syntax constantenum (name &rest enum-list)
(destructuring-bind (name &key base-type define-constants)
(ensure-list name)
(c-section-header out "constantenum" name)
(c-export out name)
(c-format out "(cffi:defcenum (")
(c-print-symbol out name t)
(when base-type
(c-printf out " ")
(c-print-symbol out base-type t))
(c-format out ")")
(dolist (enum enum-list)
(destructuring-bind ((lisp-name &rest c-names)
&key optional documentation) enum
(declare (ignore documentation))
(check-type lisp-name keyword)
(c-format out "~% (")
(c-print-symbol out lisp-name)
(loop for c-name in c-names do
(check-type c-name string)
(format out "~&#ifdef ~A~%" c-name)
(c-format out " ")
(c-printf out "%i" c-name)
(format out "~&#else~%"))
(unless optional
(c-format out
"~% #.(cl:progn ~
(cl:warn 'cffi-grovel:missing-definition :name '~A) ~
-1)"
lisp-name))
(dotimes (i (length c-names))
(format out "~&#endif~%"))
(c-format out ")")))
(c-format out ")~%")
(when define-constants
(define-constants-from-enum out enum-list))))
(defun define-constants-from-enum (out enum-list)
(dolist (enum enum-list)
(destructuring-bind ((lisp-name &rest c-names) &rest options)
enum
(%process-grovel-form
'constant out
`((,(intern (string lisp-name)) ,(car c-names))
,@options)))))
;;;# Wrapper Generation
;;;
;;; Here we generate a C file from a s-exp specification but instead
;;; of compiling and running it, we compile it as a shared library
;;; that can be subsequently loaded with LOAD-FOREIGN-LIBRARY.
;;;
;;; Useful to get at macro functionality, errno, system calls,
;;; functions that handle structures by value, etc...
;;;
;;; Matching CFFI bindings are generated along with said C file.
(defun process-wrapper-form (out form)
(%process-wrapper-form (form-kind form) out (cdr form)))
;;; The various operators push Lisp forms onto this list which will be
;;; written out by PROCESS-WRAPPER-FILE once everything is processed.
(defvar *lisp-forms*)
(defun generate-c-lib-file (input-file output-defaults)
(let ((*lisp-forms* nil)
(c-file (make-pathname :type "c" :defaults output-defaults)))
(with-open-file (out c-file :direction :output :if-exists :supersede)
(with-open-file (in input-file :direction :input)
(write-string *header* out)
(loop for form = (read in nil nil) while form
do (process-wrapper-form out form))))
(values c-file (nreverse *lisp-forms*))))
(defun lib-filename (defaults)
(make-pathname :type (subseq (cffi::default-library-suffix) 1)
:defaults defaults))
(defun generate-bindings-file (lib-file lib-soname lisp-forms output-defaults)
(let ((lisp-file (tmp-lisp-filename output-defaults)))
(with-open-file (out lisp-file :direction :output :if-exists :supersede)
(format out ";;;; This file was automatically generated by cffi-grovel.~%~
;;;; Do not edit by hand.~%")
(let ((*package* (find-package '#:cl))
(named-library-name
(let ((*package* (find-package :keyword))
(*read-eval* nil))
(read-from-string lib-soname))))
(pprint `(progn
(cffi:define-foreign-library
(,named-library-name
:type :grovel-wrapper
:search-path ,(directory-namestring lib-file))
(t ,(namestring (lib-filename lib-soname))))
(cffi:use-foreign-library ,named-library-name))
out)
(fresh-line out))
(dolist (form lisp-forms)
(print form out))
(terpri out))
lisp-file))
;;; *PACKAGE* is rebound so that the IN-PACKAGE form can set it during
;;; *the extent of a given wrapper file.
(defun process-wrapper-file (input-file output-defaults lib-soname)
(with-standard-io-syntax
(let ((lib-file
(lib-filename (make-pathname :name lib-soname
:defaults output-defaults))))
(multiple-value-bind (c-file lisp-forms)
(generate-c-lib-file input-file output-defaults)
(cc-compile-and-link c-file lib-file :library t)
;; FIXME: hardcoded library path.
(values (generate-bindings-file lib-file lib-soname lisp-forms output-defaults)
lib-file)))))
(defgeneric %process-wrapper-form (name out arguments)
(:method (name out arguments)
(declare (ignore out arguments))
(error "Unknown Grovel syntax: ~S" name)))
;;; OUT is lexically bound to the output stream within BODY.
(defmacro define-wrapper-syntax (name lambda-list &body body)
(with-unique-names (name-var args)
`(defmethod %process-wrapper-form ((,name-var (eql ',name)) out ,args)
(declare (ignorable out))
(destructuring-bind ,lambda-list ,args
,@body))))
(define-wrapper-syntax progn (&rest forms)
(dolist (form forms)
(process-wrapper-form out form)))
(define-wrapper-syntax in-package (name)
(setq *package* (find-package name))
(push `(in-package ,name) *lisp-forms*))
(define-wrapper-syntax c (&rest strings)
(dolist (string strings)
(write-line string out)))
(define-wrapper-syntax flag (&rest flags)
(appendf *cc-flags* (trim-whitespace flags)))
(define-wrapper-syntax proclaim (&rest proclamations)
(push `(proclaim ,@proclamations) *lisp-forms*))
(define-wrapper-syntax declaim (&rest declamations)
(push `(declaim ,@declamations) *lisp-forms*))
(define-wrapper-syntax define (name &optional value)
(format out "#define ~A~@[ ~A~]~%" name value))
(define-wrapper-syntax include (&rest includes)
(format out "~{#include <~A>~%~}" includes))
;;; FIXME: this function is not complete. Should probably follow
;;; typedefs? Should definitely understand pointer types.
(defun c-type-name (typespec)
(let ((spec (ensure-list typespec)))
(if (stringp (car spec))
(car spec)
(case (car spec)
((:uchar :unsigned-char) "unsigned char")
((:unsigned-short :ushort) "unsigned short")
((:unsigned-int :uint) "unsigned int")
((:unsigned-long :ulong) "unsigned long")
((:long-long :llong) "long long")
((:unsigned-long-long :ullong) "unsigned long long")
(:pointer "void*")
(:string "char*")
(t (cffi::foreign-name (car spec)))))))
(defun cffi-type (typespec)
(if (and (listp typespec) (stringp (car typespec)))
(second typespec)
typespec))
(define-wrapper-syntax defwrapper (name-and-options rettype &rest args)
(multiple-value-bind (lisp-name foreign-name options)
(cffi::parse-name-and-options name-and-options)
(let* ((foreign-name-wrap (strcat foreign-name "_cffi_wrap"))
(fargs (mapcar (lambda (arg)
(list (c-type-name (second arg))
(cffi::foreign-name (first arg))))
args))
(fargnames (mapcar #'second fargs)))
;; output C code
(format out "~A ~A" (c-type-name rettype) foreign-name-wrap)
(format out "(~{~{~A ~A~}~^, ~})~%" fargs)
(format out "{~% return ~A(~{~A~^, ~});~%}~%~%" foreign-name fargnames)
;; matching bindings
(push `(cffi:defcfun (,foreign-name-wrap ,lisp-name ,@options)
,(cffi-type rettype)
,@(mapcar (lambda (arg)
(list (cffi::lisp-name (first arg))
(cffi-type (second arg))))
args))
*lisp-forms*))))
(define-wrapper-syntax defwrapper* (name-and-options rettype args &rest c-lines)
;; output C code
(multiple-value-bind (lisp-name foreign-name options)
(cffi::parse-name-and-options name-and-options)
(let ((foreign-name-wrap (strcat foreign-name "_cffi_wrap"))
(fargs (mapcar (lambda (arg)
(list (c-type-name (second arg))
(cffi::foreign-name (first arg))))
args)))
(format out "~A ~A" (c-type-name rettype)
foreign-name-wrap)
(format out "(~{~{~A ~A~}~^, ~})~%" fargs)
(format out "{~%~{ ~A~%~}}~%~%" c-lines)
;; matching bindings
(push `(cffi:defcfun (,foreign-name-wrap ,lisp-name ,@options)
,(cffi-type rettype)
,@(mapcar (lambda (arg)
(list (cffi::lisp-name (first arg))
(cffi-type (second arg))))
args))
*lisp-forms*))))
| null | https://raw.githubusercontent.com/mathematical-systems/clml/918e41e67ee2a8102c55a84b4e6e85bbdde933f5/addons/cffi/grovel/grovel.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
# Error Conditions
This warning is signalled when cffi-grovel can't find some macro.
# Grovelling
The header of the intermediate C file.
C code generated by cffi-grovel is inserted between the contents
of *PROLOGUE* and *POSTSCRIPT*, inside the main function's body.
grovel form as it is read (like we already do for wrapper
forms). This way in can expect *PACKAGE* to have sane values.
This would require that "header forms" come before any other
forms.
later, if necessary.
Using INTERN here instead of FIND-SYMBOL will result in less
cryptic error messages when an undefined grovel/wrapper form is
found.
flatten progn forms
FIXME: is there a better way to detect whether these flags
are necessary?
add the cffi directory to the include path to make common.h visible
*PACKAGE* is rebound so that the IN-PACKAGE form can set it during
*the extent of a given grovel file.
OUT is lexically bound to the output stream within BODY.
Is this really needed?
This form also has some "read time" effects. See GENERATE-C-FILE.
nb, works like :count :auto does in cstruct below
DEFINE-C-STRUCT-WRAPPER (in ../src/types.lisp) seems like a much
cleaner way to do this. Unless I can find any advantage in doing
it this way I'll delete this soon. --luis
this function is then used as a constructor for this class.
FIXME: where would docs on enum elements go?
# Wrapper Generation
Here we generate a C file from a s-exp specification but instead
of compiling and running it, we compile it as a shared library
that can be subsequently loaded with LOAD-FOREIGN-LIBRARY.
Useful to get at macro functionality, errno, system calls,
functions that handle structures by value, etc...
Matching CFFI bindings are generated along with said C file.
The various operators push Lisp forms onto this list which will be
written out by PROCESS-WRAPPER-FILE once everything is processed.
This file was automatically generated by cffi-grovel.~%~
Do not edit by hand.~%")
*PACKAGE* is rebound so that the IN-PACKAGE form can set it during
*the extent of a given wrapper file.
FIXME: hardcoded library path.
OUT is lexically bound to the output stream within BODY.
FIXME: this function is not complete. Should probably follow
typedefs? Should definitely understand pointer types.
output C code
matching bindings
output C code
matching bindings | grovel.lisp --- The CFFI Groveller .
Copyright ( C ) 2005 - 2006 , < >
Copyright ( C ) 2005 - 2006 , < >
Copyright ( C ) 2007 , < >
Copyright ( C ) 2007 ,
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
(in-package #:cffi-grovel)
(defun trim-whitespace (strings)
(loop for s in strings
collect (string-trim '(#\Space #\Tab) s)))
Signalled by CONSTANT or CONSTANTENUM .
(define-condition missing-definition (warning)
((%name :initarg :name :reader name-of))
(:report (lambda (condition stream)
(format stream "No definition for ~A"
(name-of condition)))))
(defparameter *cc*
#+(or cygwin (not windows)) "cc"
#+(and windows (not cygwin)) "c:/msys/1.0/bin/gcc.exe")
(defparameter *cc-flags* nil)
(defparameter *header*
"/*
* This file has been automatically generated by cffi-grovel.
* Do not edit it by hand.
*/
")
(defparameter *prologue*
"
#include <grovel/common.h>
int main(int argc, char**argv) {
fprintf(output, \";;;; This file has been automatically generated by \"
")
(defparameter *postscript*
"
if (output != stdout)
}
")
(defun unescape-for-c (text)
(with-output-to-string (result)
(loop for i below (length text)
for char = (char text i) do
(cond ((eql char #\") (princ "\\\"" result))
((eql char #\newline) (princ "\\n" result))
(t (princ char result))))))
(defun c-format (out fmt &rest args)
(let ((text (unescape-for-c (format nil "~?" fmt args))))
(format out "~& fprintf(output, \"~A\");~%" text)))
(defun c-printf (out fmt &rest args)
(flet ((item (item)
(format out "~A" (unescape-for-c (format nil item)))))
(format out "~& fprintf(output, \"")
(item fmt)
(format out "\"")
(loop for arg in args do
(format out ", ")
(item arg))
(format out ");~%")))
TODO : handle packages in a better way . One way is to process each
(defun c-print-symbol (out symbol &optional no-package)
(c-format out
(let ((package (symbol-package symbol)))
(cond
((eq (find-package '#:keyword) package) ":~(~A~)")
(no-package "~(~A~)")
((eq (find-package '#:cl) package) "cl:~(~A~)")
(t "~(~A~)")))
symbol))
(defun c-write (out form &key recursive)
(cond
((and (listp form)
(eq 'quote (car form)))
(c-format out "'")
(c-write out (cadr form) :recursive t))
((listp form)
(c-format out "(")
(loop for subform in form
for first-p = t then nil
unless first-p do (c-format out " ")
do (c-write out subform :recursive t))
(c-format out ")"))
((symbolp form)
(c-print-symbol out form)))
(unless recursive
(c-format out "~%")))
Always NIL for now , add { ENABLE , DISABLE}-AUTO - EXPORT grovel forms
(defvar *auto-export* nil)
(defun c-export (out symbol)
(when (and *auto-export* (not (keywordp symbol)))
(c-format out "(cl:export '")
(c-print-symbol out symbol t)
(c-format out ")~%")))
(defun c-section-header (out section-type section-symbol)
(format out "~% /* ~A section for ~S */~%"
section-type
section-symbol))
(defun remove-suffix (string suffix)
(let ((suffix-start (- (length string) (length suffix))))
(if (and (> suffix-start 0)
(string= string suffix :start1 suffix-start))
(subseq string 0 suffix-start)
string)))
(defun strcat (&rest strings)
(apply #'concatenate 'string strings))
(defgeneric %process-grovel-form (name out arguments)
(:method (name out arguments)
(declare (ignore out arguments))
(error "Unknown Grovel syntax: ~S" name)))
(defun process-grovel-form (out form)
(%process-grovel-form (form-kind form) out (cdr form)))
(defun form-kind (form)
(intern (symbol-name (car form)) '#:cffi-grovel))
(defvar *header-forms* '(c include define flag typedef))
(defun header-form-p (form)
(member (form-kind form) *header-forms*))
(defun generate-c-file (input-file output-defaults)
(let ((c-file (make-pathname :type "c" :defaults output-defaults)))
(with-open-file (out c-file :direction :output :if-exists :supersede)
(with-open-file (in input-file :direction :input)
(flet ((read-forms (s)
(do ((forms ())
(form (read s nil nil) (read s nil nil)))
((null form) (nreverse forms))
(labels
((process-form (f)
(case (form-kind f)
(flag (warn "Groveler clause FLAG is deprecated, use CC-FLAGS instead.")))
(case (form-kind f)
(in-package
(setf *package* (find-package (second f)))
(push f forms))
(progn
(mapc #'process-form (rest f)))
(t (push f forms)))))
(process-form form)))))
(let* ((forms (read-forms in))
(header-forms (remove-if-not #'header-form-p forms))
(body-forms (remove-if #'header-form-p forms)))
(write-string *header* out)
(dolist (form header-forms)
(process-grovel-form out form))
(write-string *prologue* out)
(dolist (form body-forms)
(process-grovel-form out form))
(write-string *postscript* out)))))
c-file))
(defparameter *exe-extension* #-windows nil #+windows "exe")
(defun exe-filename (defaults)
(let ((path (make-pathname :type *exe-extension*
:defaults defaults)))
It 's necessary to prepend " ./ " to relative paths because some
implementations of INVOKE use a shell .
(when (or (not (pathname-directory path))
(eq :relative (car (pathname-directory path))))
(setf path (make-pathname
:directory (list* :relative "."
(cdr (pathname-directory path)))
:defaults path)))
path))
(defun tmp-lisp-filename (defaults)
(make-pathname :name (strcat (pathname-name defaults) ".grovel-tmp")
:type "lisp" :defaults defaults))
(cffi:defcfun "getenv" :string
(name :string))
(defparameter *cpu-word-size-flags*
(ecase (cffi:foreign-type-size :long)
(4 (list "-m32"))
(8 (list "-m64"))))
(defparameter *platform-library-flags*
(list #+darwin "-bundle" #-darwin "-shared"))
(defun cc-compile-and-link (input-file output-file &key library)
(let ((arglist
`(,(or (getenv "CC") *cc*)
,@*cpu-word-size-flags*
,@*cc-flags*
,(format nil "-I~A"
(directory-namestring
(truename
(asdf:system-definition-pathname :cffi-grovel))))
,@(when library *platform-library-flags*)
"-fPIC" "-o"
,(native-namestring output-file)
,(native-namestring input-file))))
(apply #'invoke arglist)))
(defun process-grovel-file (input-file &optional (output-defaults input-file))
(with-standard-io-syntax
(let* ((c-file (generate-c-file input-file output-defaults))
(exe-file (exe-filename c-file))
(lisp-file (tmp-lisp-filename c-file)))
(cc-compile-and-link c-file exe-file)
(invoke exe-file (native-namestring lisp-file))
lisp-file)))
(defmacro define-grovel-syntax (name lambda-list &body body)
(with-unique-names (name-var args)
`(defmethod %process-grovel-form ((,name-var (eql ',name)) out ,args)
(declare (ignorable out))
(destructuring-bind ,lambda-list ,args
,@body))))
(define-grovel-syntax c (body)
(format out "~%~A~%" body))
(define-grovel-syntax include (&rest includes)
(format out "~{#include <~A>~%~}" includes))
(define-grovel-syntax define (name &optional value)
(format out "#define ~A~@[ ~A~]~%" name value))
(define-grovel-syntax typedef (base-type new-type)
(format out "typedef ~A ~A;~%" base-type new-type))
(define-grovel-syntax ffi-typedef (new-type base-type)
(c-format out "(cffi:defctype ~S ~S)~%" new-type base-type))
(define-grovel-syntax flag (&rest flags)
(appendf *cc-flags* (trim-whitespace flags)))
(define-grovel-syntax cc-flags (&rest flags)
(appendf *cc-flags* (trim-whitespace flags)))
(define-grovel-syntax in-package (name)
(c-format out "(cl:in-package #:~A)~%~%" name))
(define-grovel-syntax ctype (lisp-name size-designator)
(c-section-header out "ctype" lisp-name)
(c-export out lisp-name)
(c-format out "(cffi:defctype ")
(c-print-symbol out lisp-name t)
(c-format out " ")
(format out "~& type_name(output, SIGNEDP(~A), ~:[sizeof(~A)~;~D~]);~%"
size-designator
(etypecase size-designator
(string nil)
(integer t))
size-designator)
(c-format out ")~%")
(unless (keywordp lisp-name)
(c-export out lisp-name))
(let ((size-of-constant-name (symbolicate '#:size-of- lisp-name)))
(c-export out size-of-constant-name)
(c-format out "(cl:defconstant "
size-of-constant-name lisp-name)
(c-print-symbol out size-of-constant-name)
(c-format out " (cffi:foreign-type-size '")
(c-print-symbol out lisp-name)
(c-format out "))~%")))
Syntax differs from anything else in CFFI . Fix ?
(define-grovel-syntax constant ((lisp-name &rest c-names)
&key (type 'integer) documentation optional)
(when (keywordp lisp-name)
(setf lisp-name (format-symbol "~A" lisp-name)))
(c-section-header out "constant" lisp-name)
(dolist (c-name c-names)
(format out "~&#ifdef ~A~%" c-name)
(c-export out lisp-name)
(c-format out "(cl:defconstant ")
(c-print-symbol out lisp-name t)
(c-format out " ")
(ecase type
(integer
(format out "~& if(SIGNED64P(~A))~%" c-name)
(format out " fprintf(output, \"%lli\", (int64_t) ~A);" c-name)
(format out "~& else~%")
(format out " fprintf(output, \"%llu\", (uint64_t) ~A);" c-name))
(double-float
(format out "~& fprintf(output, \"%s\", print_double_for_lisp((double)~A));~%" c-name)))
(when documentation
(c-format out " ~S" documentation))
(c-format out ")~%")
(format out "~&#else~%"))
(unless optional
(c-format out "(cl:warn 'cffi-grovel:missing-definition :name '~A)~%"
lisp-name))
(dotimes (i (length c-names))
(format out "~&#endif~%")))
(define-grovel-syntax cunion (union-lisp-name union-c-name &rest slots)
(let ((documentation (when (stringp (car slots)) (pop slots))))
(c-section-header out "cunion" union-lisp-name)
(c-export out union-lisp-name)
(dolist (slot slots)
(let ((slot-lisp-name (car slot)))
(c-export out slot-lisp-name)))
(c-format out "(cffi:defcunion (")
(c-print-symbol out union-lisp-name t)
(c-printf out " :size %i)" (format nil "sizeof(~A)" union-c-name))
(when documentation
(c-format out "~% ~S" documentation))
(dolist (slot slots)
(destructuring-bind (slot-lisp-name slot-c-name &key type count)
slot
(declare (ignore slot-c-name))
(c-format out "~% (")
(c-print-symbol out slot-lisp-name t)
(c-format out " ")
(c-print-symbol out type)
(etypecase count
(integer
(c-format out " :count ~D" count))
((eql :auto)
(c-printf out " :count %i"
(format nil "sizeof(~A)" union-c-name)))
(null t))
(c-format out ")")))
(c-format out ")~%")))
(defun make-from-pointer-function-name (type-name)
(symbolicate '#:make- type-name '#:-from-pointer))
(define-grovel-syntax cstruct-and-class-item (&rest arguments)
(process-grovel-form out (cons 'cstruct arguments))
(destructuring-bind (struct-lisp-name struct-c-name &rest slots)
arguments
(declare (ignore struct-c-name))
(let* ((slot-names (mapcar #'car slots))
(reader-names (mapcar
(lambda (slot-name)
(intern
(strcat (symbol-name struct-lisp-name) "-"
(symbol-name slot-name))))
slot-names))
(initarg-names (mapcar
(lambda (slot-name)
(intern (symbol-name slot-name) "KEYWORD"))
slot-names))
(slot-decoders (mapcar (lambda (slot)
(destructuring-bind
(lisp-name c-name
&key type count
&allow-other-keys)
slot
(declare (ignore lisp-name c-name))
(cond ((and (eq type :char) count)
'cffi:foreign-string-to-lisp)
(t nil))))
slots))
(defclass-form
`(defclass ,struct-lisp-name ()
,(mapcar (lambda (slot-name initarg-name reader-name)
`(,slot-name :initarg ,initarg-name
:reader ,reader-name))
slot-names
initarg-names
reader-names)))
(make-function-name
(make-from-pointer-function-name struct-lisp-name))
(make-defun-form
`(defun ,make-function-name (pointer)
(cffi:with-foreign-slots
(,slot-names pointer ,struct-lisp-name)
(make-instance ',struct-lisp-name
,@(loop for slot-name in slot-names
for initarg-name in initarg-names
for slot-decoder in slot-decoders
collect initarg-name
if slot-decoder
collect `(,slot-decoder ,slot-name)
else collect slot-name))))))
(c-export out make-function-name)
(dolist (reader-name reader-names)
(c-export out reader-name))
(c-write out defclass-form)
(c-write out make-defun-form))))
(define-grovel-syntax cstruct (struct-lisp-name struct-c-name &rest slots)
(let ((documentation (when (stringp (car slots)) (pop slots))))
(c-section-header out "cstruct" struct-lisp-name)
(c-export out struct-lisp-name)
(dolist (slot slots)
(let ((slot-lisp-name (car slot)))
(c-export out slot-lisp-name)))
(c-format out "(cffi:defcstruct (")
(c-print-symbol out struct-lisp-name t)
(c-printf out " :size %i)"
(format nil "sizeof(~A)" struct-c-name))
(when documentation
(c-format out "~% ~S" documentation))
(dolist (slot slots)
(destructuring-bind (slot-lisp-name slot-c-name &key type count)
slot
(c-format out "~% (")
(c-print-symbol out slot-lisp-name t)
(c-format out " ")
(c-print-symbol out type)
(etypecase count
(null t)
(integer
(c-format out " :count ~D" count))
((eql :auto)
(c-printf out " :count %i"
(format nil "sizeof(~A) - offsetof(~A, ~A)"
struct-c-name
struct-c-name
slot-c-name)))
((or symbol string)
(format out "~&#ifdef ~A~%" count)
(c-printf out " :count %i"
(format nil "~A" count))
(format out "~&#endif~%")))
(c-printf out " :offset %i)"
(format nil "offsetof(~A, ~A)"
struct-c-name
slot-c-name))))
(c-format out ")~%")
(let ((size-of-constant-name
(symbolicate '#:size-of- struct-lisp-name)))
(c-export out size-of-constant-name)
(c-format out "(cl:defconstant "
size-of-constant-name struct-lisp-name)
(c-print-symbol out size-of-constant-name)
(c-format out " (cffi:foreign-type-size '")
(c-print-symbol out struct-lisp-name)
(c-format out "))~%"))))
(defmacro define-pseudo-cvar (str name type &key read-only)
(let ((c-parse (let ((*read-eval* nil)
(*readtable* (copy-readtable nil)))
(setf (readtable-case *readtable*) :preserve)
(read-from-string str))))
(typecase c-parse
(symbol `(cffi:defcvar (,(symbol-name c-parse) ,name) ,type
:read-only ,read-only))
(list (unless (and (= (length c-parse) 2)
(null (second c-parse))
(symbolp (first c-parse))
(eql #\* (char (symbol-name (first c-parse)) 0)))
(error "Unable to parse c-string ~s." str))
(let ((func-name (symbolicate "%" name '#:-accessor)))
`(progn
(declaim (inline ,func-name))
(cffi:defcfun (,(string-trim "*" (symbol-name (first c-parse)))
,func-name) :pointer)
(define-symbol-macro ,name
(cffi:mem-ref (,func-name) ',type)))))
(t (error "Unable to parse c-string ~s." str)))))
(defun foreign-name-to-symbol (s)
(intern (substitute #\- #\_ (string-upcase s))))
(defun choose-lisp-and-foreign-names (string-or-list)
(etypecase string-or-list
(string (values string-or-list (foreign-name-to-symbol string-or-list)))
(list (destructuring-bind (fname lname &rest args) string-or-list
(declare (ignore args))
(assert (and (stringp fname) (symbolp lname)))
(values fname lname)))))
(define-grovel-syntax cvar (name type &key read-only)
(multiple-value-bind (c-name lisp-name)
(choose-lisp-and-foreign-names name)
(c-section-header out "cvar" lisp-name)
(c-export out lisp-name)
(c-printf out "(cffi-grovel::define-pseudo-cvar \"%s\" "
(format nil "indirect_stringify(~A)" c-name))
(c-print-symbol out lisp-name t)
(c-format out " ")
(c-print-symbol out type)
(when read-only
(c-format out " :read-only t"))
(c-format out ")~%")))
(define-grovel-syntax cenum (name &rest enum-list)
(destructuring-bind (name &key base-type define-constants)
(ensure-list name)
(c-section-header out "cenum" name)
(c-export out name)
(c-format out "(cffi:defcenum (")
(c-print-symbol out name t)
(when base-type
(c-printf out " ")
(c-print-symbol out base-type t))
(c-format out ")")
(dolist (enum enum-list)
(destructuring-bind ((lisp-name &rest c-names) &key documentation)
enum
(declare (ignore documentation))
(check-type lisp-name keyword)
(loop :for c-name :in c-names :do
(check-type c-name string)
(c-format out " (")
(c-print-symbol out lisp-name)
(c-format out " ")
(c-printf out "%i" c-name)
(c-format out ")~%"))))
(c-format out ")~%")
(when define-constants
(define-constants-from-enum out enum-list))))
(define-grovel-syntax constantenum (name &rest enum-list)
(destructuring-bind (name &key base-type define-constants)
(ensure-list name)
(c-section-header out "constantenum" name)
(c-export out name)
(c-format out "(cffi:defcenum (")
(c-print-symbol out name t)
(when base-type
(c-printf out " ")
(c-print-symbol out base-type t))
(c-format out ")")
(dolist (enum enum-list)
(destructuring-bind ((lisp-name &rest c-names)
&key optional documentation) enum
(declare (ignore documentation))
(check-type lisp-name keyword)
(c-format out "~% (")
(c-print-symbol out lisp-name)
(loop for c-name in c-names do
(check-type c-name string)
(format out "~&#ifdef ~A~%" c-name)
(c-format out " ")
(c-printf out "%i" c-name)
(format out "~&#else~%"))
(unless optional
(c-format out
"~% #.(cl:progn ~
(cl:warn 'cffi-grovel:missing-definition :name '~A) ~
-1)"
lisp-name))
(dotimes (i (length c-names))
(format out "~&#endif~%"))
(c-format out ")")))
(c-format out ")~%")
(when define-constants
(define-constants-from-enum out enum-list))))
(defun define-constants-from-enum (out enum-list)
(dolist (enum enum-list)
(destructuring-bind ((lisp-name &rest c-names) &rest options)
enum
(%process-grovel-form
'constant out
`((,(intern (string lisp-name)) ,(car c-names))
,@options)))))
(defun process-wrapper-form (out form)
(%process-wrapper-form (form-kind form) out (cdr form)))
(defvar *lisp-forms*)
(defun generate-c-lib-file (input-file output-defaults)
(let ((*lisp-forms* nil)
(c-file (make-pathname :type "c" :defaults output-defaults)))
(with-open-file (out c-file :direction :output :if-exists :supersede)
(with-open-file (in input-file :direction :input)
(write-string *header* out)
(loop for form = (read in nil nil) while form
do (process-wrapper-form out form))))
(values c-file (nreverse *lisp-forms*))))
(defun lib-filename (defaults)
(make-pathname :type (subseq (cffi::default-library-suffix) 1)
:defaults defaults))
(defun generate-bindings-file (lib-file lib-soname lisp-forms output-defaults)
(let ((lisp-file (tmp-lisp-filename output-defaults)))
(with-open-file (out lisp-file :direction :output :if-exists :supersede)
(let ((*package* (find-package '#:cl))
(named-library-name
(let ((*package* (find-package :keyword))
(*read-eval* nil))
(read-from-string lib-soname))))
(pprint `(progn
(cffi:define-foreign-library
(,named-library-name
:type :grovel-wrapper
:search-path ,(directory-namestring lib-file))
(t ,(namestring (lib-filename lib-soname))))
(cffi:use-foreign-library ,named-library-name))
out)
(fresh-line out))
(dolist (form lisp-forms)
(print form out))
(terpri out))
lisp-file))
(defun process-wrapper-file (input-file output-defaults lib-soname)
(with-standard-io-syntax
(let ((lib-file
(lib-filename (make-pathname :name lib-soname
:defaults output-defaults))))
(multiple-value-bind (c-file lisp-forms)
(generate-c-lib-file input-file output-defaults)
(cc-compile-and-link c-file lib-file :library t)
(values (generate-bindings-file lib-file lib-soname lisp-forms output-defaults)
lib-file)))))
(defgeneric %process-wrapper-form (name out arguments)
(:method (name out arguments)
(declare (ignore out arguments))
(error "Unknown Grovel syntax: ~S" name)))
(defmacro define-wrapper-syntax (name lambda-list &body body)
(with-unique-names (name-var args)
`(defmethod %process-wrapper-form ((,name-var (eql ',name)) out ,args)
(declare (ignorable out))
(destructuring-bind ,lambda-list ,args
,@body))))
(define-wrapper-syntax progn (&rest forms)
(dolist (form forms)
(process-wrapper-form out form)))
(define-wrapper-syntax in-package (name)
(setq *package* (find-package name))
(push `(in-package ,name) *lisp-forms*))
(define-wrapper-syntax c (&rest strings)
(dolist (string strings)
(write-line string out)))
(define-wrapper-syntax flag (&rest flags)
(appendf *cc-flags* (trim-whitespace flags)))
(define-wrapper-syntax proclaim (&rest proclamations)
(push `(proclaim ,@proclamations) *lisp-forms*))
(define-wrapper-syntax declaim (&rest declamations)
(push `(declaim ,@declamations) *lisp-forms*))
(define-wrapper-syntax define (name &optional value)
(format out "#define ~A~@[ ~A~]~%" name value))
(define-wrapper-syntax include (&rest includes)
(format out "~{#include <~A>~%~}" includes))
(defun c-type-name (typespec)
(let ((spec (ensure-list typespec)))
(if (stringp (car spec))
(car spec)
(case (car spec)
((:uchar :unsigned-char) "unsigned char")
((:unsigned-short :ushort) "unsigned short")
((:unsigned-int :uint) "unsigned int")
((:unsigned-long :ulong) "unsigned long")
((:long-long :llong) "long long")
((:unsigned-long-long :ullong) "unsigned long long")
(:pointer "void*")
(:string "char*")
(t (cffi::foreign-name (car spec)))))))
(defun cffi-type (typespec)
(if (and (listp typespec) (stringp (car typespec)))
(second typespec)
typespec))
(define-wrapper-syntax defwrapper (name-and-options rettype &rest args)
(multiple-value-bind (lisp-name foreign-name options)
(cffi::parse-name-and-options name-and-options)
(let* ((foreign-name-wrap (strcat foreign-name "_cffi_wrap"))
(fargs (mapcar (lambda (arg)
(list (c-type-name (second arg))
(cffi::foreign-name (first arg))))
args))
(fargnames (mapcar #'second fargs)))
(format out "~A ~A" (c-type-name rettype) foreign-name-wrap)
(format out "(~{~{~A ~A~}~^, ~})~%" fargs)
(format out "{~% return ~A(~{~A~^, ~});~%}~%~%" foreign-name fargnames)
(push `(cffi:defcfun (,foreign-name-wrap ,lisp-name ,@options)
,(cffi-type rettype)
,@(mapcar (lambda (arg)
(list (cffi::lisp-name (first arg))
(cffi-type (second arg))))
args))
*lisp-forms*))))
(define-wrapper-syntax defwrapper* (name-and-options rettype args &rest c-lines)
(multiple-value-bind (lisp-name foreign-name options)
(cffi::parse-name-and-options name-and-options)
(let ((foreign-name-wrap (strcat foreign-name "_cffi_wrap"))
(fargs (mapcar (lambda (arg)
(list (c-type-name (second arg))
(cffi::foreign-name (first arg))))
args)))
(format out "~A ~A" (c-type-name rettype)
foreign-name-wrap)
(format out "(~{~{~A ~A~}~^, ~})~%" fargs)
(format out "{~%~{ ~A~%~}}~%~%" c-lines)
(push `(cffi:defcfun (,foreign-name-wrap ,lisp-name ,@options)
,(cffi-type rettype)
,@(mapcar (lambda (arg)
(list (cffi::lisp-name (first arg))
(cffi-type (second arg))))
args))
*lisp-forms*))))
|
7d165546e71e0921c0b385038205a5c56de3d8807ecbde80fb6e5d52e1bf58f6 | alavrik/piqi | piqi_json_type.mli |
Copyright 2009 , 2010 , 2011 , 2012 , 2013
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 .
This code is based on " yojson " library .
The original code was taken from here :
Below is the original copyright notice and the license :
Copyright ( c ) 2010
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions
are met :
1 . Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution .
3 . The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR
IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED .
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT
NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
Copyright 2009, 2010, 2011, 2012, 2013 Anton Lavrik
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.
This code is based on Martin Jambon's "yojson" library.
The original code was taken from here:
Below is the original copyright notice and the license:
Copyright (c) 2010 Martin Jambon
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
type json =
[
| `Null of unit (* using unit to turn Null into a boxed value *)
| `Bool of bool
| `Int of int64
big unsigned int64
| `Intlit of string
| `Float of float
| `Floatlit of string
| `String of string
| `Stringlit of string
| `Assoc of (string * json) list
| `List of json list
]
| null | https://raw.githubusercontent.com/alavrik/piqi/bcea4d44997966198dc295df0609591fa787b1d2/piqilib/piqi_json_type.mli | ocaml | using unit to turn Null into a boxed value |
Copyright 2009 , 2010 , 2011 , 2012 , 2013
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 .
This code is based on " yojson " library .
The original code was taken from here :
Below is the original copyright notice and the license :
Copyright ( c ) 2010
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions
are met :
1 . Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
2 . Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution .
3 . The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR
IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED .
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT , INDIRECT ,
INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT
NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
Copyright 2009, 2010, 2011, 2012, 2013 Anton Lavrik
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.
This code is based on Martin Jambon's "yojson" library.
The original code was taken from here:
Below is the original copyright notice and the license:
Copyright (c) 2010 Martin Jambon
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
type json =
[
| `Bool of bool
| `Int of int64
big unsigned int64
| `Intlit of string
| `Float of float
| `Floatlit of string
| `String of string
| `Stringlit of string
| `Assoc of (string * json) list
| `List of json list
]
|
a9cff312ecf31e552f0dd0e74a882c38f8cff22ef45e778f8f0b65292055d7b3 | GNOME/gimp-tiny-fu | chrome-it.scm | ; CHROME-IT
; State of the art chrome effect for user-specified mask
; This script requires a grayscale image containing a single layer.
; This layer is used as the mask for the SOTA chrome effect
(define (script-fu-sota-chrome-it mask-img mask-drawable chrome-saturation
chrome-lightness chrome-factor env-map hc cc carve-white)
(define (set-pt a index x y)
(begin
(aset a (* index 2) x)
(aset a (+ (* index 2) 1) y)
)
)
(define (spline-chrome-it)
(let* ((a (cons-array 18 'byte)))
(set-pt a 0 0 0)
(set-pt a 1 31 235)
(set-pt a 2 63 23)
(set-pt a 3 95 230)
(set-pt a 4 127 25)
(set-pt a 5 159 210)
(set-pt a 6 191 20)
(set-pt a 7 223 240)
(set-pt a 8 255 31)
a
)
)
(define (brush brush-size)
(cond ((<= brush-size 5) "Circle Fuzzy (05)")
((<= brush-size 7) "Circle Fuzzy (07)")
((<= brush-size 9) "Circle Fuzzy (09)")
((<= brush-size 11) "Circle Fuzzy (11)")
((<= brush-size 13) "Circle Fuzzy (13)")
((<= brush-size 15) "Circle Fuzzy (15)")
((<= brush-size 17) "Circle Fuzzy (17)")
(else "Circle Fuzzy (19)")
)
)
(define (shadows val)
(/ (* 0.96 val) 2.55)
)
(define (midtones val)
(/ val 2.55)
)
(define (highlights val)
; The result is used as "gimp-color-balance" color parameter
and thus must be restricted to -100.0 < = highlights < = 100.0 .
(min (/ (* 1.108 val) 2.55) 100.0)
)
(define (rval col)
(car col)
)
(define (gval col)
(cadr col)
)
(define (bval col)
(caddr col)
)
(define (sota-scale val scale chrome-factor)
(* (sqrt val) (* scale chrome-factor))
)
(define (copy-layer-chrome-it dest-image dest-drawable source-image source-drawable)
(gimp-selection-all dest-image)
(gimp-edit-clear dest-drawable)
(gimp-selection-none dest-image)
(gimp-selection-all source-image)
(gimp-edit-copy source-drawable)
(let (
(floating-sel (car (gimp-edit-paste dest-drawable FALSE)))
)
(gimp-floating-sel-anchor floating-sel)
)
)
(let* (
(banding-img (car (gimp-file-load RUN-NONINTERACTIVE env-map env-map)))
(banding-layer (car (gimp-image-get-active-drawable banding-img)))
(banding-height (car (gimp-drawable-height banding-layer)))
(banding-width (car (gimp-drawable-width banding-layer)))
(banding-type (car (gimp-drawable-type banding-layer)))
(width (car (gimp-drawable-width mask-drawable)))
(height (car (gimp-drawable-height mask-drawable)))
(img (car (gimp-image-new width height GRAY)))
(size (min width height))
(offx1 (sota-scale size 0.33 chrome-factor))
(offy1 (sota-scale size 0.25 chrome-factor))
(offx2 (sota-scale size (- 0.33) chrome-factor))
(offy2 (sota-scale size (- 0.25) chrome-factor))
(feather (sota-scale size 0.5 chrome-factor))
(brush-size (sota-scale size 0.5 chrome-factor))
(mask (car (gimp-channel-new img width height "Chrome Stencil" 50 '(0 0 0))))
(bg-layer (car (gimp-layer-new img width height GRAY-IMAGE _"Background" 100 NORMAL-MODE)))
(layer1 (car (gimp-layer-new img banding-width banding-height banding-type _"Layer 1" 100 NORMAL-MODE)))
(layer2 (car (gimp-layer-new img width height GRAYA-IMAGE _"Layer 2" 100 DIFFERENCE-MODE)))
(layer3 (car (gimp-layer-new img width height GRAYA-IMAGE _"Layer 3" 100 NORMAL-MODE)))
(shadow (car (gimp-layer-new img width height GRAYA-IMAGE _"Drop Shadow" 100 NORMAL-MODE)))
(mask-fs 0)
(layer-mask 0)
)
(gimp-context-push)
(gimp-context-set-defaults)
(gimp-image-undo-disable img)
(gimp-image-insert-channel img mask -1 0)
(gimp-image-insert-layer img bg-layer 0 0)
(gimp-image-insert-layer img shadow 0 0)
(gimp-image-insert-layer img layer3 0 0)
(gimp-image-insert-layer img layer2 0 0)
(gimp-edit-copy mask-drawable)
(set! mask-fs (car (gimp-edit-paste mask FALSE)))
(gimp-floating-sel-anchor mask-fs)
(if (= carve-white FALSE)
(gimp-invert mask)
)
(gimp-context-set-background '(255 255 255))
(gimp-selection-none img)
(gimp-edit-fill layer2 BACKGROUND-FILL)
(gimp-edit-fill layer3 BACKGROUND-FILL)
(gimp-edit-clear shadow)
(gimp-item-set-visible bg-layer FALSE)
(gimp-item-set-visible shadow FALSE)
(gimp-image-select-item img CHANNEL-OP-REPLACE mask)
(gimp-context-set-background '(0 0 0))
(gimp-selection-translate img offx1 offy1)
(gimp-selection-feather img feather)
(gimp-edit-fill layer2 BACKGROUND-FILL)
(gimp-selection-translate img (* 2 offx2) (* 2 offy2))
(gimp-edit-fill layer3 BACKGROUND-FILL)
(gimp-selection-none img)
(set! layer2 (car (gimp-image-merge-visible-layers img CLIP-TO-IMAGE)))
(gimp-invert layer2)
(gimp-image-insert-layer img layer1 0 0)
(copy-layer-chrome-it img layer1 banding-img banding-layer)
(gimp-image-delete banding-img)
(gimp-layer-scale layer1 width height FALSE)
(plug-in-gauss-iir RUN-NONINTERACTIVE img layer1 10 TRUE TRUE)
(gimp-layer-set-opacity layer1 50)
(set! layer1 (car (gimp-image-merge-visible-layers img CLIP-TO-IMAGE)))
(gimp-curves-spline layer1 HISTOGRAM-VALUE 18 (spline-chrome-it))
(set! layer-mask (car (gimp-layer-create-mask layer1 ADD-BLACK-MASK)))
(gimp-layer-add-mask layer1 layer-mask)
(gimp-image-select-item img CHANNEL-OP-REPLACE mask)
(gimp-context-set-background '(255 255 255))
(gimp-edit-fill layer-mask BACKGROUND-FILL)
(set! layer2 (car (gimp-layer-copy layer1 TRUE)))
(gimp-image-insert-layer img layer2 0 0)
(gimp-context-set-brush (brush brush-size))
(gimp-context-set-foreground '(255 255 255))
(gimp-edit-stroke layer-mask)
(gimp-context-set-background '(0 0 0))
(gimp-selection-feather img (* feather 1.5))
(gimp-selection-translate img (* 2.5 offx1) (* 2.5 offy1))
(gimp-edit-fill shadow BACKGROUND-FILL)
(gimp-selection-all img)
(gimp-context-set-pattern "Marble #1")
(gimp-edit-bucket-fill bg-layer PATTERN-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0)
(gimp-selection-none img)
(gimp-image-convert-rgb img)
(gimp-color-balance layer1 SHADOWS TRUE
(shadows (rval hc)) (shadows (gval hc)) (shadows (bval hc)))
(gimp-color-balance layer1 MIDTONES TRUE
(midtones (rval hc)) (midtones (gval hc)) (midtones (bval hc)))
(gimp-color-balance layer1 HIGHLIGHTS TRUE
(highlights (rval hc)) (highlights (gval hc)) (highlights (bval hc)))
(gimp-color-balance layer2 SHADOWS TRUE
(shadows (rval cc)) (shadows (gval cc)) (shadows (bval cc)))
(gimp-color-balance layer2 MIDTONES TRUE
(midtones (rval cc)) (midtones (gval cc)) (midtones (bval cc)))
(gimp-color-balance layer2 HIGHLIGHTS TRUE
(highlights (rval cc)) (highlights (gval cc)) (highlights (bval cc)))
(gimp-hue-saturation layer2 ALL-HUES 0.0 chrome-lightness chrome-saturation)
(gimp-item-set-visible shadow TRUE)
(gimp-item-set-visible bg-layer TRUE)
(gimp-item-set-name layer2 _"Chrome")
(gimp-item-set-name layer1 _"Highlight")
(gimp-image-remove-channel img mask)
(gimp-display-new img)
(gimp-image-undo-enable img)
(gimp-context-pop)
)
)
(script-fu-register "script-fu-sota-chrome-it"
_"Stencil C_hrome..."
_"Add a chrome effect to the selected region (or alpha) using a specified (grayscale) stencil"
"Spencer Kimball"
"Spencer Kimball"
"1997"
"GRAY"
SF-IMAGE "Chrome image" 0
SF-DRAWABLE "Chrome mask" 0
SF-ADJUSTMENT _"Chrome saturation" '(-80 -100 100 1 10 0 0)
SF-ADJUSTMENT _"Chrome lightness" '(-47 -100 100 1 10 0 0)
SF-ADJUSTMENT _"Chrome factor" '(0.75 0 1 0.1 0.01 2 0)
SF-FILENAME _"Environment map"
(string-append gimp-data-directory
"/scripts/images/beavis.jpg")
SF-COLOR _"Highlight balance" '(211 95 0)
SF-COLOR _"Chrome balance" "black"
SF-TOGGLE _"Chrome white areas" TRUE
)
(script-fu-menu-register "script-fu-sota-chrome-it"
"<Image>/Filters/Decor")
| null | https://raw.githubusercontent.com/GNOME/gimp-tiny-fu/a64d85eec23b997e535488d67f55b44395ba3f2e/scripts/chrome-it.scm | scheme | CHROME-IT
State of the art chrome effect for user-specified mask
This script requires a grayscale image containing a single layer.
This layer is used as the mask for the SOTA chrome effect
The result is used as "gimp-color-balance" color parameter |
(define (script-fu-sota-chrome-it mask-img mask-drawable chrome-saturation
chrome-lightness chrome-factor env-map hc cc carve-white)
(define (set-pt a index x y)
(begin
(aset a (* index 2) x)
(aset a (+ (* index 2) 1) y)
)
)
(define (spline-chrome-it)
(let* ((a (cons-array 18 'byte)))
(set-pt a 0 0 0)
(set-pt a 1 31 235)
(set-pt a 2 63 23)
(set-pt a 3 95 230)
(set-pt a 4 127 25)
(set-pt a 5 159 210)
(set-pt a 6 191 20)
(set-pt a 7 223 240)
(set-pt a 8 255 31)
a
)
)
(define (brush brush-size)
(cond ((<= brush-size 5) "Circle Fuzzy (05)")
((<= brush-size 7) "Circle Fuzzy (07)")
((<= brush-size 9) "Circle Fuzzy (09)")
((<= brush-size 11) "Circle Fuzzy (11)")
((<= brush-size 13) "Circle Fuzzy (13)")
((<= brush-size 15) "Circle Fuzzy (15)")
((<= brush-size 17) "Circle Fuzzy (17)")
(else "Circle Fuzzy (19)")
)
)
(define (shadows val)
(/ (* 0.96 val) 2.55)
)
(define (midtones val)
(/ val 2.55)
)
(define (highlights val)
and thus must be restricted to -100.0 < = highlights < = 100.0 .
(min (/ (* 1.108 val) 2.55) 100.0)
)
(define (rval col)
(car col)
)
(define (gval col)
(cadr col)
)
(define (bval col)
(caddr col)
)
(define (sota-scale val scale chrome-factor)
(* (sqrt val) (* scale chrome-factor))
)
(define (copy-layer-chrome-it dest-image dest-drawable source-image source-drawable)
(gimp-selection-all dest-image)
(gimp-edit-clear dest-drawable)
(gimp-selection-none dest-image)
(gimp-selection-all source-image)
(gimp-edit-copy source-drawable)
(let (
(floating-sel (car (gimp-edit-paste dest-drawable FALSE)))
)
(gimp-floating-sel-anchor floating-sel)
)
)
(let* (
(banding-img (car (gimp-file-load RUN-NONINTERACTIVE env-map env-map)))
(banding-layer (car (gimp-image-get-active-drawable banding-img)))
(banding-height (car (gimp-drawable-height banding-layer)))
(banding-width (car (gimp-drawable-width banding-layer)))
(banding-type (car (gimp-drawable-type banding-layer)))
(width (car (gimp-drawable-width mask-drawable)))
(height (car (gimp-drawable-height mask-drawable)))
(img (car (gimp-image-new width height GRAY)))
(size (min width height))
(offx1 (sota-scale size 0.33 chrome-factor))
(offy1 (sota-scale size 0.25 chrome-factor))
(offx2 (sota-scale size (- 0.33) chrome-factor))
(offy2 (sota-scale size (- 0.25) chrome-factor))
(feather (sota-scale size 0.5 chrome-factor))
(brush-size (sota-scale size 0.5 chrome-factor))
(mask (car (gimp-channel-new img width height "Chrome Stencil" 50 '(0 0 0))))
(bg-layer (car (gimp-layer-new img width height GRAY-IMAGE _"Background" 100 NORMAL-MODE)))
(layer1 (car (gimp-layer-new img banding-width banding-height banding-type _"Layer 1" 100 NORMAL-MODE)))
(layer2 (car (gimp-layer-new img width height GRAYA-IMAGE _"Layer 2" 100 DIFFERENCE-MODE)))
(layer3 (car (gimp-layer-new img width height GRAYA-IMAGE _"Layer 3" 100 NORMAL-MODE)))
(shadow (car (gimp-layer-new img width height GRAYA-IMAGE _"Drop Shadow" 100 NORMAL-MODE)))
(mask-fs 0)
(layer-mask 0)
)
(gimp-context-push)
(gimp-context-set-defaults)
(gimp-image-undo-disable img)
(gimp-image-insert-channel img mask -1 0)
(gimp-image-insert-layer img bg-layer 0 0)
(gimp-image-insert-layer img shadow 0 0)
(gimp-image-insert-layer img layer3 0 0)
(gimp-image-insert-layer img layer2 0 0)
(gimp-edit-copy mask-drawable)
(set! mask-fs (car (gimp-edit-paste mask FALSE)))
(gimp-floating-sel-anchor mask-fs)
(if (= carve-white FALSE)
(gimp-invert mask)
)
(gimp-context-set-background '(255 255 255))
(gimp-selection-none img)
(gimp-edit-fill layer2 BACKGROUND-FILL)
(gimp-edit-fill layer3 BACKGROUND-FILL)
(gimp-edit-clear shadow)
(gimp-item-set-visible bg-layer FALSE)
(gimp-item-set-visible shadow FALSE)
(gimp-image-select-item img CHANNEL-OP-REPLACE mask)
(gimp-context-set-background '(0 0 0))
(gimp-selection-translate img offx1 offy1)
(gimp-selection-feather img feather)
(gimp-edit-fill layer2 BACKGROUND-FILL)
(gimp-selection-translate img (* 2 offx2) (* 2 offy2))
(gimp-edit-fill layer3 BACKGROUND-FILL)
(gimp-selection-none img)
(set! layer2 (car (gimp-image-merge-visible-layers img CLIP-TO-IMAGE)))
(gimp-invert layer2)
(gimp-image-insert-layer img layer1 0 0)
(copy-layer-chrome-it img layer1 banding-img banding-layer)
(gimp-image-delete banding-img)
(gimp-layer-scale layer1 width height FALSE)
(plug-in-gauss-iir RUN-NONINTERACTIVE img layer1 10 TRUE TRUE)
(gimp-layer-set-opacity layer1 50)
(set! layer1 (car (gimp-image-merge-visible-layers img CLIP-TO-IMAGE)))
(gimp-curves-spline layer1 HISTOGRAM-VALUE 18 (spline-chrome-it))
(set! layer-mask (car (gimp-layer-create-mask layer1 ADD-BLACK-MASK)))
(gimp-layer-add-mask layer1 layer-mask)
(gimp-image-select-item img CHANNEL-OP-REPLACE mask)
(gimp-context-set-background '(255 255 255))
(gimp-edit-fill layer-mask BACKGROUND-FILL)
(set! layer2 (car (gimp-layer-copy layer1 TRUE)))
(gimp-image-insert-layer img layer2 0 0)
(gimp-context-set-brush (brush brush-size))
(gimp-context-set-foreground '(255 255 255))
(gimp-edit-stroke layer-mask)
(gimp-context-set-background '(0 0 0))
(gimp-selection-feather img (* feather 1.5))
(gimp-selection-translate img (* 2.5 offx1) (* 2.5 offy1))
(gimp-edit-fill shadow BACKGROUND-FILL)
(gimp-selection-all img)
(gimp-context-set-pattern "Marble #1")
(gimp-edit-bucket-fill bg-layer PATTERN-BUCKET-FILL NORMAL-MODE 100 0 FALSE 0 0)
(gimp-selection-none img)
(gimp-image-convert-rgb img)
(gimp-color-balance layer1 SHADOWS TRUE
(shadows (rval hc)) (shadows (gval hc)) (shadows (bval hc)))
(gimp-color-balance layer1 MIDTONES TRUE
(midtones (rval hc)) (midtones (gval hc)) (midtones (bval hc)))
(gimp-color-balance layer1 HIGHLIGHTS TRUE
(highlights (rval hc)) (highlights (gval hc)) (highlights (bval hc)))
(gimp-color-balance layer2 SHADOWS TRUE
(shadows (rval cc)) (shadows (gval cc)) (shadows (bval cc)))
(gimp-color-balance layer2 MIDTONES TRUE
(midtones (rval cc)) (midtones (gval cc)) (midtones (bval cc)))
(gimp-color-balance layer2 HIGHLIGHTS TRUE
(highlights (rval cc)) (highlights (gval cc)) (highlights (bval cc)))
(gimp-hue-saturation layer2 ALL-HUES 0.0 chrome-lightness chrome-saturation)
(gimp-item-set-visible shadow TRUE)
(gimp-item-set-visible bg-layer TRUE)
(gimp-item-set-name layer2 _"Chrome")
(gimp-item-set-name layer1 _"Highlight")
(gimp-image-remove-channel img mask)
(gimp-display-new img)
(gimp-image-undo-enable img)
(gimp-context-pop)
)
)
(script-fu-register "script-fu-sota-chrome-it"
_"Stencil C_hrome..."
_"Add a chrome effect to the selected region (or alpha) using a specified (grayscale) stencil"
"Spencer Kimball"
"Spencer Kimball"
"1997"
"GRAY"
SF-IMAGE "Chrome image" 0
SF-DRAWABLE "Chrome mask" 0
SF-ADJUSTMENT _"Chrome saturation" '(-80 -100 100 1 10 0 0)
SF-ADJUSTMENT _"Chrome lightness" '(-47 -100 100 1 10 0 0)
SF-ADJUSTMENT _"Chrome factor" '(0.75 0 1 0.1 0.01 2 0)
SF-FILENAME _"Environment map"
(string-append gimp-data-directory
"/scripts/images/beavis.jpg")
SF-COLOR _"Highlight balance" '(211 95 0)
SF-COLOR _"Chrome balance" "black"
SF-TOGGLE _"Chrome white areas" TRUE
)
(script-fu-menu-register "script-fu-sota-chrome-it"
"<Image>/Filters/Decor")
|
88ac6c6c980044725a9be3cbdd8d4cc3d98ff5beb588b0c75dd12e1205ada153 | ferdinand-beyer/init | discovery_test.clj | (ns init.discovery-test
(:require [clojure.test :refer [deftest is]]
[init.discovery :as discovery]))
(deftest ns-prefix-pred-test
(let [pred (#'discovery/ns-prefix-pred 'init.discovery-test)]
(is (pred 'init.discovery-test))
(is (pred 'init.discovery-test.child))
(is (pred 'init.discovery-test.deeply.nested.child))
(is (not (pred 'init)))
(is (not (pred 'init.discovery-test-sibling)))))
(deftest classpath-namespaces-test
(let [namespaces (discovery/classpath-namespaces)]
(is (contains? namespaces (ns-name *ns*)))
(is (contains? namespaces 'init.core)))
(let [namespaces (discovery/classpath-namespaces ['init])]
(is (contains? namespaces (ns-name *ns*)))
(is (contains? namespaces 'init.core)))
(let [namespaces (discovery/classpath-namespaces ['init.core 'init.foobar])]
(is (empty? namespaces))))
| null | https://raw.githubusercontent.com/ferdinand-beyer/init/62414dae2b7af6ea2e3036db0b2f6e2bdf3d8e65/test/init/discovery_test.clj | clojure | (ns init.discovery-test
(:require [clojure.test :refer [deftest is]]
[init.discovery :as discovery]))
(deftest ns-prefix-pred-test
(let [pred (#'discovery/ns-prefix-pred 'init.discovery-test)]
(is (pred 'init.discovery-test))
(is (pred 'init.discovery-test.child))
(is (pred 'init.discovery-test.deeply.nested.child))
(is (not (pred 'init)))
(is (not (pred 'init.discovery-test-sibling)))))
(deftest classpath-namespaces-test
(let [namespaces (discovery/classpath-namespaces)]
(is (contains? namespaces (ns-name *ns*)))
(is (contains? namespaces 'init.core)))
(let [namespaces (discovery/classpath-namespaces ['init])]
(is (contains? namespaces (ns-name *ns*)))
(is (contains? namespaces 'init.core)))
(let [namespaces (discovery/classpath-namespaces ['init.core 'init.foobar])]
(is (empty? namespaces))))
| |
86f8becee0aad827d58e302dd487b25f1dc83c473ef3067dc1863be9b01928a1 | avsm/platform | opamSwitchState.ml | (**************************************************************************)
(* *)
Copyright 2012 - 2015 OCamlPro
Copyright 2012 INRIA
(* *)
(* All rights reserved. This file is distributed under the terms of the *)
GNU Lesser General Public License version 2.1 , with the special
(* exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open OpamTypes
open OpamStd.Op
open OpamPackage.Set.Op
let log fmt = OpamConsole.log "STATE" fmt
let slog = OpamConsole.slog
open OpamStateTypes
let load_selections gt switch =
OpamFile.SwitchSelections.safe_read (OpamPath.Switch.selections gt.root switch)
let load_switch_config gt switch =
let f = OpamPath.Switch.switch_config gt.root switch in
match OpamFile.Switch_config.read_opt f with
| Some c -> c
| None ->
OpamConsole.error
"No config file found for switch %s. Switch broken?"
(OpamSwitch.to_string switch);
OpamFile.Switch_config.empty
let compute_available_packages gt switch switch_config ~pinned ~opams =
(* remove all versions of pinned packages, but the pinned-to version *)
let pinned_names = OpamPackage.names_of_packages pinned in
let opams =
OpamPackage.Map.filter
(fun nv _ ->
not (OpamPackage.Name.Set.mem nv.name pinned_names) ||
OpamPackage.Set.mem nv pinned)
opams
in
let avail_map =
OpamPackage.Map.filter (fun package opam ->
OpamFilter.eval_to_bool ~default:false
(OpamPackageVar.resolve_switch_raw ~package gt switch switch_config)
(OpamFile.OPAM.available opam))
opams
in
OpamPackage.keys avail_map
let repos_list_raw rt switch_config =
let global, repos =
match switch_config.OpamFile.Switch_config.repos with
| None -> true, OpamGlobalState.repos_list rt.repos_global
| Some repos -> false, repos
in
let found, notfound =
List.partition (fun r ->
OpamRepositoryName.Map.mem r rt.repositories)
repos
in
List.iter (fun r ->
log "Ignoring %s-selected repository %S, no configured repository by \
this name found"
(if global then "globally" else "switch")
(OpamRepositoryName.to_string r))
notfound;
found
let repos_list st =
repos_list_raw st.switch_repos st.switch_config
let load lock_kind gt rt switch =
let chrono = OpamConsole.timer () in
log "LOAD-SWITCH-STATE @ %a" (slog OpamSwitch.to_string) switch;
if not (OpamGlobalState.switch_exists gt switch) then
(log "The switch %a does not appear to be installed according to %a"
(slog OpamSwitch.to_string) switch
(slog @@ OpamFile.to_string @* OpamPath.config) gt.root;
OpamConsole.error_and_exit
(if OpamStateConfig.(!r.switch_from = `Command_line) then `Bad_arguments
else `Configuration_error)
"The selected switch %s is not installed.%s"
(OpamSwitch.to_string switch)
@@ match OpamStateConfig.(!r.switch_from) with
| `Command_line -> ""
| `Default ->
" Please choose a different one using 'opam switch <name>', or use the \
'--switch <name>' flag."
| `Env ->
" Please fix the value of the OPAMSWITCH environment variable, or use \
the '--switch <name>' flag")
else
let gt = OpamGlobalState.fix_switch_list gt in
let lock =
OpamFilename.flock lock_kind (OpamPath.Switch.lock gt.root switch)
in
let switch_config = load_switch_config gt switch in
if OpamVersion.compare
(OpamVersion.nopatch (switch_config.OpamFile.Switch_config.opam_version))
(OpamVersion.nopatch OpamFormatUpgrade.latest_version)
<> 0 then
OpamConsole.error_and_exit `Configuration_error
"Could not load opam switch %s: it reports version %s while %s was \
expected"
(OpamSwitch.to_string switch)
(OpamVersion.to_string
(switch_config.OpamFile.Switch_config.opam_version))
(OpamVersion.to_string OpamFormatUpgrade.latest_version);
let { sel_installed = installed; sel_roots = installed_roots;
sel_pinned = pinned; sel_compiler = compiler_packages; } =
load_selections gt switch
in
let pinned, pinned_opams =
OpamPackage.Set.fold (fun nv (pinned,opams) ->
let overlay_dir =
OpamPath.Switch.Overlay.package gt.root switch nv.name
in
match OpamFileTools.read_opam overlay_dir with
| None -> (* No overlay => just pinned to a version *)
OpamPackage.Set.add nv pinned, opams
| Some o ->
let version =
match OpamFile.OPAM.version_opt o with
| Some v when v <> nv.version ->
log "warn: %s has conflicting pinning versions between \
switch-state (%s) and overlay (%s). Using %s."
(OpamPackage.Name.to_string nv.name)
(OpamPackage.Version.to_string nv.version)
(OpamPackage.Version.to_string v)
(OpamPackage.Version.to_string v);
v
| _ -> nv.version
in
let nv = OpamPackage.create nv.name version in
let o = OpamFile.OPAM.with_version version o in
OpamPackage.Set.add nv pinned,
OpamPackage.Map.add nv o opams
)
pinned (OpamPackage.Set.empty, OpamPackage.Map.empty)
in
let installed_opams =
OpamPackage.Set.fold (fun nv opams ->
OpamStd.Option.Op.(
(OpamFile.OPAM.read_opt
(OpamPath.Switch.installed_opam gt.root switch nv)
>>| fun opam -> OpamPackage.Map.add nv opam opams)
+! opams))
installed OpamPackage.Map.empty
in
let repos_package_index =
OpamRepositoryState.build_index rt (repos_list_raw rt switch_config)
in
let opams =
OpamPackage.Map.union (fun _ x -> x) repos_package_index pinned_opams
in
let packages = OpamPackage.keys opams in
let available_packages =
lazy (compute_available_packages gt switch switch_config
~pinned ~opams)
in
let opams =
(* Keep definitions of installed packages, but lowest priority, and after
computing availability *)
OpamPackage.Map.union (fun _ x -> x) installed_opams opams
in
let installed_without_def =
OpamPackage.Set.fold (fun nv nodef ->
if OpamPackage.Map.mem nv installed_opams then nodef else
try
let o = OpamPackage.Map.find nv opams in
if lock_kind = `Lock_write then (* auto-repair *)
(log "Definition missing for installed package %s, \
copying from repo"
(OpamPackage.to_string nv);
OpamFile.OPAM.write
(OpamPath.Switch.installed_opam gt.root switch nv) o);
nodef
with Not_found -> OpamPackage.Set.add nv nodef)
installed OpamPackage.Set.empty
in
if not (OpamPackage.Set.is_empty installed_without_def) then
OpamConsole.error
"No definition found for the following installed packages: %s\n\
This switch may need to be reinstalled"
(OpamPackage.Set.to_string installed_without_def);
let changed =
(* Note: This doesn't detect changed _dev_ packages, since it's based on the
metadata or the archive hash changing and they don't have an archive
hash. Therefore, dev package update needs to add to the reinstall file *)
OpamPackage.Map.merge (fun _ opam_new opam_installed ->
match opam_new, opam_installed with
| Some r, Some i when not (OpamFile.OPAM.effectively_equal i r) ->
Some ()
| _ -> None)
opams installed_opams
|> OpamPackage.keys
in
let changed =
changed --
OpamPackage.Set.filter
(fun nv -> not (OpamPackage.has_name pinned nv.name))
compiler_packages
in
log "Detected changed packages (marked for reinstall): %a"
(slog OpamPackage.Set.to_string) changed;
(* Detect and initialise missing switch description *)
let switch_config =
if switch_config <> OpamFile.Switch_config.empty &&
switch_config.OpamFile.Switch_config.synopsis = "" then
let synopsis =
match OpamPackage.Set.elements (compiler_packages %% installed_roots)
with
| [] -> OpamSwitch.to_string switch
| [nv] ->
let open OpamStd.Option.Op in
(OpamPackage.Map.find_opt nv opams >>= OpamFile.OPAM.synopsis) +!
OpamPackage.to_string nv
| pkgs -> OpamStd.List.concat_map " " OpamPackage.to_string pkgs
in
let conf = { switch_config with OpamFile.Switch_config.synopsis } in
if lock_kind = `Lock_write then (* auto-repair *)
OpamFile.Switch_config.write
(OpamPath.Switch.switch_config gt.root switch)
conf;
conf
else switch_config
in
let conf_files =
OpamPackage.Set.fold (fun nv acc ->
OpamPackage.Map.add nv
(OpamFile.Dot_config.safe_read
(OpamPath.Switch.config gt.root switch nv.name))
acc)
installed OpamPackage.Map.empty
in
let ext_files_changed =
OpamPackage.Map.fold (fun nv conf acc ->
if
List.exists (fun (file, hash) ->
let exists = OpamFilename.exists file in
let should_exist =
let count_not_zero c =
function '0' -> c | _ -> succ c
in
OpamStd.String.fold_left count_not_zero 0 (OpamHash.contents hash) <> 0
in
let changed =
exists <> should_exist ||
exists && not (OpamHash.check_file (OpamFilename.to_string file) hash)
in
/!\ : the package removal instructions wo n't actually ever
be called in this case
be called in this case *)
if not exists && should_exist then
OpamConsole.error
"System file %s, which package %s depends upon, \
no longer exists.\n\
The package has been marked as removed, and opam will \
try to reinstall it if necessary, but you should reinstall \
its system dependencies first."
(OpamFilename.to_string file) (OpamPackage.to_string nv)
else if changed then
OpamConsole.warning
"File %s, which package %s depends upon, \
was changed on your system. \
%s has been marked as removed, and will be reinstalled if \
necessary."
(OpamFilename.to_string file) (OpamPackage.to_string nv)
(OpamPackage.name_to_string nv);
changed)
(OpamFile.Dot_config.file_depends conf)
then OpamPackage.Set.add nv acc
else acc)
conf_files
OpamPackage.Set.empty
in
let installed =
installed -- ext_files_changed
in
let reinstall =
OpamFile.PkgList.safe_read (OpamPath.Switch.reinstall gt.root switch) ++
changed
in
let st = {
switch_global = (gt :> unlocked global_state);
switch_repos = (rt :> unlocked repos_state);
switch_lock = lock;
switch; compiler_packages; switch_config;
repos_package_index; installed_opams;
installed; pinned; installed_roots;
opams; conf_files;
packages; available_packages; reinstall;
} in
log "Switch state loaded in %.3fs" (chrono ());
st
let load_virtual ?repos_list gt rt =
let repos_list = match repos_list with
| Some rl -> rl
| None -> OpamGlobalState.repos_list gt
in
let opams =
OpamRepositoryState.build_index rt repos_list
in
let packages = OpamPackage.keys opams in
{
switch_global = (gt :> unlocked global_state);
switch_repos = (rt :> unlocked repos_state);
switch_lock = OpamSystem.lock_none;
switch = OpamSwitch.unset;
compiler_packages = OpamPackage.Set.empty;
switch_config = {
OpamFile.Switch_config.empty
with OpamFile.Switch_config.repos = Some repos_list;
};
installed = OpamPackage.Set.empty;
installed_opams = OpamPackage.Map.empty;
pinned = OpamPackage.Set.empty;
installed_roots = OpamPackage.Set.empty;
repos_package_index = opams;
opams;
conf_files = OpamPackage.Map.empty;
packages;
available_packages = lazy packages;
reinstall = OpamPackage.Set.empty;
}
let selections st =
{ sel_installed = st.installed;
sel_roots = st.installed_roots;
sel_compiler = st.compiler_packages;
sel_pinned = st.pinned; }
let unlock st =
OpamSystem.funlock st.switch_lock;
(st :> unlocked switch_state)
let with_write_lock ?dontblock st f =
let ret, st =
OpamFilename.with_flock_upgrade `Lock_write ?dontblock st.switch_lock
@@ fun _ -> f ({ st with switch_lock = st.switch_lock } : rw switch_state)
(* We don't actually change the field value, but this makes restricting the
phantom lock type possible*)
in
ret, { st with switch_lock = st.switch_lock }
let opam st nv = OpamPackage.Map.find nv st.opams
let opam_opt st nv = try Some (opam st nv) with Not_found -> None
let descr_opt st nv =
OpamStd.Option.Op.(opam_opt st nv >>= OpamFile.OPAM.descr)
let descr st nv =
OpamStd.Option.Op.(descr_opt st nv +! OpamFile.Descr.empty)
let url st nv =
OpamStd.Option.Op.(opam_opt st nv >>= OpamFile.OPAM.url)
let primary_url st nv =
OpamStd.Option.Op.(url st nv >>| OpamFile.URL.url)
let files st nv =
match opam_opt st nv with
| None -> []
| Some opam ->
List.map (fun (file,_base,_hash) -> file)
(OpamFile.OPAM.get_extra_files opam)
let package_config st name =
OpamPackage.Map.find
(OpamPackage.package_of_name st.installed name)
st.conf_files
let is_name_installed st name =
OpamPackage.has_name st.installed name
let find_installed_package_by_name st name =
OpamPackage.package_of_name st.installed name
let packages_of_atoms st atoms = OpamFormula.packages_of_atoms st.packages atoms
let get_package st name =
try OpamPinned.package st name with Not_found ->
try find_installed_package_by_name st name with Not_found ->
try OpamPackage.max_version (Lazy.force st.available_packages) name
with Not_found ->
OpamPackage.max_version st.packages name
let is_dev_package st nv =
match opam_opt st nv with
| Some opam -> OpamPackageVar.is_dev_package st opam
| None -> false
let is_pinned st name =
OpamPackage.has_name st.pinned name
let is_version_pinned st name =
match OpamPackage.package_of_name_opt st.pinned name with
| None -> false
| Some nv ->
match opam_opt st nv with
| Some opam ->
OpamPackage.Map.find_opt nv st.repos_package_index = Some opam
| None -> false
let source_dir st nv =
if OpamPackage.Set.mem nv st.pinned
then OpamPath.Switch.pinned_package st.switch_global.root st.switch nv.name
else OpamPath.Switch.sources st.switch_global.root st.switch nv
let depexts st nv =
let env v = OpamPackageVar.resolve_switch ~package:nv st v in
match opam_opt st nv with
| None -> OpamStd.String.Set.empty
| Some opam ->
List.fold_left (fun depexts (names, filter) ->
if OpamFilter.eval_to_bool ~default:false env filter then
List.fold_left (fun depexts n -> OpamStd.String.Set.add n depexts)
depexts names
else depexts)
OpamStd.String.Set.empty
(OpamFile.OPAM.depexts opam)
let dev_packages st =
OpamPackage.Set.filter (is_dev_package st)
(st.installed ++ OpamPinned.packages st)
let conflicts_with st subset =
let forward_conflicts, conflict_classes =
OpamPackage.Set.fold (fun nv (cf,cfc) ->
try
let opam = OpamPackage.Map.find nv st.opams in
let conflicts =
OpamFilter.filter_formula ~default:false
(OpamPackageVar.resolve_switch ~package:nv st)
(OpamFile.OPAM.conflicts opam)
in
OpamFormula.ors [cf; conflicts],
List.fold_right OpamPackage.Name.Set.add
(OpamFile.OPAM.conflict_class opam) cfc
with Not_found -> cf, cfc)
subset (OpamFormula.Empty, OpamPackage.Name.Set.empty)
in
OpamPackage.Set.filter
(fun nv ->
not (OpamPackage.has_name subset nv.name) &&
(OpamFormula.verifies forward_conflicts nv ||
let opam = OpamPackage.Map.find nv st.opams in
List.exists (fun cl -> OpamPackage.Name.Set.mem cl conflict_classes)
(OpamFile.OPAM.conflict_class opam)
||
let backwards_conflicts =
OpamFilter.filter_formula ~default:false
(OpamPackageVar.resolve_switch ~package:nv st)
(OpamFile.OPAM.conflicts opam)
in
OpamPackage.Set.exists
(OpamFormula.verifies backwards_conflicts) subset))
let remove_conflicts st subset pkgs =
pkgs -- conflicts_with st subset pkgs
let get_conflicts st packages opams_map =
let conflict_classes =
OpamPackage.Map.fold (fun nv opam acc ->
List.fold_left (fun acc cc ->
OpamPackage.Name.Map.update cc
(OpamPackage.Set.add nv) OpamPackage.Set.empty acc)
acc
(OpamFile.OPAM.conflict_class opam))
opams_map
OpamPackage.Name.Map.empty
in
let conflict_class_formulas =
OpamPackage.Name.Map.map (fun pkgs ->
OpamPackage.to_map pkgs |>
OpamPackage.Name.Map.mapi (fun name versions ->
let all_versions = OpamPackage.versions_of_name packages name in
if OpamPackage.Version.Set.equal versions all_versions then Empty
else
(* OpamFormula.simplify_version_set all_versions (*a possible optimisation?*) *)
(OpamFormula.ors
(List.map (fun v -> Atom (`Eq, v))
(OpamPackage.Version.Set.elements versions)))))
conflict_classes
in
OpamPackage.Map.fold (fun nv opam acc ->
let conflicts =
OpamFilter.filter_formula ~default:false
(OpamPackageVar.resolve_switch ~package:nv st)
(OpamFile.OPAM.conflicts opam)
in
let conflicts =
List.fold_left (fun acc cl ->
let cmap =
OpamPackage.Name.Map.find cl conflict_class_formulas |>
OpamPackage.Name.Map.remove nv.name
in
OpamPackage.Name.Map.fold
(fun name vformula acc ->
OpamFormula.ors [acc; Atom (name, vformula)])
cmap acc)
conflicts
(OpamFile.OPAM.conflict_class opam)
in
OpamPackage.Map.add nv conflicts acc)
opams_map
OpamPackage.Map.empty
let universe st
?(test=OpamStateConfig.(!r.build_test))
?(doc=OpamStateConfig.(!r.build_doc))
?(force_dev_deps=false)
?reinstall
~requested
user_action =
let requested_allpkgs =
OpamPackage.packages_of_names st.packages requested
in
let env nv v =
if List.mem v OpamPackageVar.predefined_depends_variables then
match OpamVariable.Full.to_string v with
| "dev" ->
Some (B (force_dev_deps || is_dev_package st nv))
| "with-test" ->
Some (B (test && OpamPackage.Set.mem nv requested_allpkgs))
| "with-doc" ->
Some (B (doc && OpamPackage.Set.mem nv requested_allpkgs))
| _ -> None (* Computation delayed to the solver *)
else
let r = OpamPackageVar.resolve_switch ~package:nv st v in
if r = None then
(if OpamFormatConfig.(!r.strict) then
OpamConsole.error_and_exit `File_error
"undefined filter variable in dependencies of %s: %s"
else
log
"ERR: undefined filter variable in dependencies of %s: %s")
(OpamPackage.to_string nv) (OpamVariable.Full.to_string v);
r
in
let get_deps f opams =
OpamPackage.Map.mapi (fun nv opam ->
OpamFilter.partial_filter_formula (env nv) (f opam)
) opams
in
let u_depends =
let depend =
let ignored = OpamStateConfig.(!r.ignore_constraints_on) in
if OpamPackage.Name.Set.is_empty ignored then OpamFile.OPAM.depends
else fun opam ->
OpamFormula.map (fun (name, cstr as atom) ->
if OpamPackage.Name.Set.mem name ignored then
let cstr =
OpamFormula.map
(function Constraint _ -> Empty | Filter _ as f -> Atom f)
cstr
in
Atom (name, cstr)
else Atom atom)
(OpamFile.OPAM.depends opam)
in
get_deps depend st.opams
in
let u_conflicts = get_conflicts st st.packages st.opams in
let base =
if OpamStateConfig.(!r.unlock_base) then OpamPackage.Set.empty
else st.compiler_packages
in
let u_available =
remove_conflicts st base (Lazy.force st.available_packages)
in
let u_reinstall = match reinstall with
| Some set -> set
| None ->
OpamPackage.Set.filter
(fun nv -> OpamPackage.Name.Set.mem nv.name requested)
st.reinstall
in
let u =
{
u_packages = st.packages;
u_action = user_action;
u_installed = st.installed;
u_available;
u_depends;
u_depopts = get_deps OpamFile.OPAM.depopts st.opams;
u_conflicts;
u_installed_roots = st.installed_roots;
u_pinned = OpamPinned.packages st;
u_base = base;
u_reinstall;
u_attrs = ["opam-query", requested_allpkgs];
}
in
u
let dump_pef_state st oc =
let conflicts = get_conflicts st st.packages st.opams in
let print_def nv opam =
Printf.fprintf oc "package: %s\n" (OpamPackage.name_to_string nv);
Printf.fprintf oc "version: %s\n" (OpamPackage.version_to_string nv);
let installed = OpamPackage.Set.mem nv st.installed in
let root = OpamPackage.Set.mem nv st.installed_roots in
let base = OpamPackage.Set.mem nv st.compiler_packages in
let pinned = OpamPackage.Set.mem nv st.pinned in
let available = OpamPackage.Set.mem nv (Lazy.force st.available_packages) in
let reinstall = OpamPackage.Set.mem nv st.reinstall in
let dev = OpamPackageVar.is_dev_package st opam in
(* current state *)
Printf.fprintf oc "available: %b\n" available;
if installed then output_string oc "installed: true\n";
if pinned then output_string oc "pinned: true\n";
if base then output_string oc "base: true\n";
if reinstall then output_string oc "reinstall: true\n";
(* metadata (resolved for the current switch) *)
OpamStd.List.concat_map ~left:"maintainer: " ~right:"\n" ~nil:"" " , "
String.escaped (OpamFile.OPAM.maintainer opam) |>
output_string oc;
OpamFile.OPAM.depends opam |>
OpamPackageVar.filter_depends_formula ~default:false ~dev
~env:(OpamPackageVar.resolve_switch ~package:nv st) |>
OpamFormula.to_cnf |>
OpamStd.List.concat_map ~left:"depends: " ~right:"\n" ~nil:"" " , "
(OpamStd.List.concat_map " | " OpamFormula.string_of_atom) |>
output_string oc;
OpamFile.OPAM.depopts opam |>
OpamPackageVar.filter_depends_formula ~default:false ~dev
~env:(OpamPackageVar.resolve_switch ~package:nv st) |>
OpamFormula.to_cnf |>
OpamStd.List.concat_map ~left:"recommends: " ~right:"\n" ~nil:"" " , "
(OpamStd.List.concat_map " | " OpamFormula.string_of_atom) |>
output_string oc;
OpamFormula.ors
[Atom (nv.name, Empty); OpamPackage.Map.find nv conflicts] |>
OpamFormula.set_to_disjunction st.packages |>
OpamStd.List.concat_map ~left:"conflicts: " ~right:"\n" ~nil:"" " , "
OpamFormula.string_of_atom |>
output_string oc;
output_string oc "\n";
in
OpamPackage.Map.iter print_def st.opams
(* User-directed helpers *)
let is_switch_globally_set st =
OpamFile.Config.switch st.switch_global.config = Some st.switch
let not_found_message st (name, cstr) =
match cstr with
| Some (relop,v) when OpamPackage.has_name st.packages name ->
Printf.sprintf "Package %s has no version %s%s."
(OpamPackage.Name.to_string name)
(match relop with `Eq -> "" | r -> OpamPrinter.relop r)
(OpamPackage.Version.to_string v)
| _ ->
Printf.sprintf "No package named %s found."
(OpamPackage.Name.to_string name)
(* Display a meaningful error for an unavailable package *)
let unavailable_reason st ?(default="") (name, vformula) =
let candidates = OpamPackage.packages_of_name st.packages name in
let candidates =
OpamPackage.Set.filter
(fun nv -> OpamFormula.check_version_formula vformula nv.version)
candidates
in
if OpamPackage.Set.is_empty candidates then
(if OpamPackage.has_name st.packages name then "no matching version"
else "unknown package")
else
let nv =
try OpamPinned.package st name
with Not_found ->
match vformula with
| Atom (_, v) when
OpamPackage.Set.mem (OpamPackage.create name v) candidates ->
OpamPackage.create name v
| _ -> OpamPackage.max_version candidates name
in
match opam_opt st nv with
| None -> "no package definition found"
| Some opam ->
let avail = OpamFile.OPAM.available opam in
if not (OpamPackage.Set.mem nv candidates) then
Printf.sprintf
"not available because the package is pinned to version %s"
(OpamPackage.version_to_string nv)
else if not (OpamFilter.eval_to_bool ~default:false
(OpamPackageVar.resolve_switch ~package:nv st)
avail)
then
Printf.sprintf "unmet availability conditions%s%s"
(if OpamPackage.Set.cardinal candidates = 1 then ": "
else ", e.g. ")
(OpamFilter.to_string avail)
else if OpamPackage.has_name
(Lazy.force st.available_packages --
remove_conflicts st st.compiler_packages
(Lazy.force st.available_packages))
name
then
"conflict with the base packages of this switch"
else if OpamPackage.has_name st.compiler_packages name &&
not OpamStateConfig.(!r.unlock_base) then
"base of this switch (use `--unlock-base' to force)"
else
default
let update_package_metadata nv opam st =
{ st with
opams = OpamPackage.Map.add nv opam st.opams;
packages = OpamPackage.Set.add nv st.packages;
available_packages = lazy (
if OpamFilter.eval_to_bool ~default:false
(OpamPackageVar.resolve_switch_raw ~package:nv
st.switch_global st.switch st.switch_config)
(OpamFile.OPAM.available opam)
then OpamPackage.Set.add nv (Lazy.force st.available_packages)
else OpamPackage.Set.remove nv (Lazy.force st.available_packages)
);
reinstall =
(match OpamPackage.Map.find_opt nv st.installed_opams with
| Some inst ->
if OpamFile.OPAM.effectively_equal inst opam
then OpamPackage.Set.remove nv (st.reinstall)
else OpamPackage.Set.add nv (st.reinstall)
| _ -> st.reinstall);
}
let remove_package_metadata nv st =
{ st with
opams = OpamPackage.Map.remove nv st.opams;
packages = OpamPackage.Set.remove nv st.packages;
available_packages =
lazy (OpamPackage.Set.remove nv (Lazy.force st.available_packages));
}
let update_pin nv opam st =
let version =
OpamStd.Option.default nv.version (OpamFile.OPAM.version_opt opam)
in
let nv = OpamPackage.create nv.name version in
update_package_metadata nv opam @@
{ st with
pinned =
OpamPackage.Set.add nv
(OpamPackage.filter_name_out st.pinned nv.name);
available_packages = lazy (
OpamPackage.filter_name_out (Lazy.force st.available_packages) nv.name
);
}
let do_backup lock st = match lock with
| `Lock_write ->
let file = OpamPath.Switch.backup st.switch_global.root st.switch in
let previous_selections = selections st in
OpamFile.SwitchSelections.write file previous_selections;
(function
| true -> OpamFilename.remove (OpamFile.filename file)
| false ->
(* Reload, in order to skip the message if there were no changes *)
let new_selections = load_selections st.switch_global st.switch in
if new_selections.sel_installed = previous_selections.sel_installed
then OpamFilename.remove (OpamFile.filename file)
else
OpamConsole.errmsg "%s"
(OpamStd.Format.reformat
(Printf.sprintf
"\nThe former state can be restored with:\n\
\ %s switch import %S\n"
Sys.argv.(0) (OpamFile.to_string file) ^
if OpamPackage.Set.is_empty
(new_selections.sel_roots -- new_selections.sel_installed)
then "" else
Printf.sprintf
"Or you can retry to install your package selection with:\n\
\ %s install --restore\n"
Sys.argv.(0))))
| _ -> fun _ -> ()
let with_ lock ?rt ?(switch=OpamStateConfig.get_switch ()) gt f =
(match rt with
| Some rt -> fun f -> f (rt :> unlocked repos_state)
| None -> OpamRepositoryState.with_ `Lock_none gt)
@@ fun rt ->
let st = load lock gt rt switch in
let cleanup_backup = do_backup lock st in
try let r = f st in ignore (unlock st); cleanup_backup true; r
with e ->
OpamStd.Exn.finalise e @@ fun () ->
ignore (unlock st);
if not OpamCoreConfig.(!r.keep_log_dir) then cleanup_backup false
let update_repositories gt update_fun switch =
OpamFilename.with_flock `Lock_write (OpamPath.Switch.lock gt.root switch)
@@ fun _ ->
let conf = load_switch_config gt switch in
let repos =
match conf.OpamFile.Switch_config.repos with
| None -> OpamGlobalState.repos_list gt
| Some repos -> repos
in
let conf =
{ conf with
OpamFile.Switch_config.repos = Some (update_fun repos) }
in
OpamFile.Switch_config.write
(OpamPath.Switch.switch_config gt.root switch)
conf
| null | https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/opam-client.2.0.5%2Bdune/src/state/opamSwitchState.ml | ocaml | ************************************************************************
All rights reserved. This file is distributed under the terms of the
exception on linking described in the file LICENSE.
************************************************************************
remove all versions of pinned packages, but the pinned-to version
No overlay => just pinned to a version
Keep definitions of installed packages, but lowest priority, and after
computing availability
auto-repair
Note: This doesn't detect changed _dev_ packages, since it's based on the
metadata or the archive hash changing and they don't have an archive
hash. Therefore, dev package update needs to add to the reinstall file
Detect and initialise missing switch description
auto-repair
We don't actually change the field value, but this makes restricting the
phantom lock type possible
OpamFormula.simplify_version_set all_versions (*a possible optimisation?
Computation delayed to the solver
current state
metadata (resolved for the current switch)
User-directed helpers
Display a meaningful error for an unavailable package
Reload, in order to skip the message if there were no changes | Copyright 2012 - 2015 OCamlPro
Copyright 2012 INRIA
GNU Lesser General Public License version 2.1 , with the special
open OpamTypes
open OpamStd.Op
open OpamPackage.Set.Op
let log fmt = OpamConsole.log "STATE" fmt
let slog = OpamConsole.slog
open OpamStateTypes
let load_selections gt switch =
OpamFile.SwitchSelections.safe_read (OpamPath.Switch.selections gt.root switch)
let load_switch_config gt switch =
let f = OpamPath.Switch.switch_config gt.root switch in
match OpamFile.Switch_config.read_opt f with
| Some c -> c
| None ->
OpamConsole.error
"No config file found for switch %s. Switch broken?"
(OpamSwitch.to_string switch);
OpamFile.Switch_config.empty
let compute_available_packages gt switch switch_config ~pinned ~opams =
let pinned_names = OpamPackage.names_of_packages pinned in
let opams =
OpamPackage.Map.filter
(fun nv _ ->
not (OpamPackage.Name.Set.mem nv.name pinned_names) ||
OpamPackage.Set.mem nv pinned)
opams
in
let avail_map =
OpamPackage.Map.filter (fun package opam ->
OpamFilter.eval_to_bool ~default:false
(OpamPackageVar.resolve_switch_raw ~package gt switch switch_config)
(OpamFile.OPAM.available opam))
opams
in
OpamPackage.keys avail_map
let repos_list_raw rt switch_config =
let global, repos =
match switch_config.OpamFile.Switch_config.repos with
| None -> true, OpamGlobalState.repos_list rt.repos_global
| Some repos -> false, repos
in
let found, notfound =
List.partition (fun r ->
OpamRepositoryName.Map.mem r rt.repositories)
repos
in
List.iter (fun r ->
log "Ignoring %s-selected repository %S, no configured repository by \
this name found"
(if global then "globally" else "switch")
(OpamRepositoryName.to_string r))
notfound;
found
let repos_list st =
repos_list_raw st.switch_repos st.switch_config
let load lock_kind gt rt switch =
let chrono = OpamConsole.timer () in
log "LOAD-SWITCH-STATE @ %a" (slog OpamSwitch.to_string) switch;
if not (OpamGlobalState.switch_exists gt switch) then
(log "The switch %a does not appear to be installed according to %a"
(slog OpamSwitch.to_string) switch
(slog @@ OpamFile.to_string @* OpamPath.config) gt.root;
OpamConsole.error_and_exit
(if OpamStateConfig.(!r.switch_from = `Command_line) then `Bad_arguments
else `Configuration_error)
"The selected switch %s is not installed.%s"
(OpamSwitch.to_string switch)
@@ match OpamStateConfig.(!r.switch_from) with
| `Command_line -> ""
| `Default ->
" Please choose a different one using 'opam switch <name>', or use the \
'--switch <name>' flag."
| `Env ->
" Please fix the value of the OPAMSWITCH environment variable, or use \
the '--switch <name>' flag")
else
let gt = OpamGlobalState.fix_switch_list gt in
let lock =
OpamFilename.flock lock_kind (OpamPath.Switch.lock gt.root switch)
in
let switch_config = load_switch_config gt switch in
if OpamVersion.compare
(OpamVersion.nopatch (switch_config.OpamFile.Switch_config.opam_version))
(OpamVersion.nopatch OpamFormatUpgrade.latest_version)
<> 0 then
OpamConsole.error_and_exit `Configuration_error
"Could not load opam switch %s: it reports version %s while %s was \
expected"
(OpamSwitch.to_string switch)
(OpamVersion.to_string
(switch_config.OpamFile.Switch_config.opam_version))
(OpamVersion.to_string OpamFormatUpgrade.latest_version);
let { sel_installed = installed; sel_roots = installed_roots;
sel_pinned = pinned; sel_compiler = compiler_packages; } =
load_selections gt switch
in
let pinned, pinned_opams =
OpamPackage.Set.fold (fun nv (pinned,opams) ->
let overlay_dir =
OpamPath.Switch.Overlay.package gt.root switch nv.name
in
match OpamFileTools.read_opam overlay_dir with
OpamPackage.Set.add nv pinned, opams
| Some o ->
let version =
match OpamFile.OPAM.version_opt o with
| Some v when v <> nv.version ->
log "warn: %s has conflicting pinning versions between \
switch-state (%s) and overlay (%s). Using %s."
(OpamPackage.Name.to_string nv.name)
(OpamPackage.Version.to_string nv.version)
(OpamPackage.Version.to_string v)
(OpamPackage.Version.to_string v);
v
| _ -> nv.version
in
let nv = OpamPackage.create nv.name version in
let o = OpamFile.OPAM.with_version version o in
OpamPackage.Set.add nv pinned,
OpamPackage.Map.add nv o opams
)
pinned (OpamPackage.Set.empty, OpamPackage.Map.empty)
in
let installed_opams =
OpamPackage.Set.fold (fun nv opams ->
OpamStd.Option.Op.(
(OpamFile.OPAM.read_opt
(OpamPath.Switch.installed_opam gt.root switch nv)
>>| fun opam -> OpamPackage.Map.add nv opam opams)
+! opams))
installed OpamPackage.Map.empty
in
let repos_package_index =
OpamRepositoryState.build_index rt (repos_list_raw rt switch_config)
in
let opams =
OpamPackage.Map.union (fun _ x -> x) repos_package_index pinned_opams
in
let packages = OpamPackage.keys opams in
let available_packages =
lazy (compute_available_packages gt switch switch_config
~pinned ~opams)
in
let opams =
OpamPackage.Map.union (fun _ x -> x) installed_opams opams
in
let installed_without_def =
OpamPackage.Set.fold (fun nv nodef ->
if OpamPackage.Map.mem nv installed_opams then nodef else
try
let o = OpamPackage.Map.find nv opams in
(log "Definition missing for installed package %s, \
copying from repo"
(OpamPackage.to_string nv);
OpamFile.OPAM.write
(OpamPath.Switch.installed_opam gt.root switch nv) o);
nodef
with Not_found -> OpamPackage.Set.add nv nodef)
installed OpamPackage.Set.empty
in
if not (OpamPackage.Set.is_empty installed_without_def) then
OpamConsole.error
"No definition found for the following installed packages: %s\n\
This switch may need to be reinstalled"
(OpamPackage.Set.to_string installed_without_def);
let changed =
OpamPackage.Map.merge (fun _ opam_new opam_installed ->
match opam_new, opam_installed with
| Some r, Some i when not (OpamFile.OPAM.effectively_equal i r) ->
Some ()
| _ -> None)
opams installed_opams
|> OpamPackage.keys
in
let changed =
changed --
OpamPackage.Set.filter
(fun nv -> not (OpamPackage.has_name pinned nv.name))
compiler_packages
in
log "Detected changed packages (marked for reinstall): %a"
(slog OpamPackage.Set.to_string) changed;
let switch_config =
if switch_config <> OpamFile.Switch_config.empty &&
switch_config.OpamFile.Switch_config.synopsis = "" then
let synopsis =
match OpamPackage.Set.elements (compiler_packages %% installed_roots)
with
| [] -> OpamSwitch.to_string switch
| [nv] ->
let open OpamStd.Option.Op in
(OpamPackage.Map.find_opt nv opams >>= OpamFile.OPAM.synopsis) +!
OpamPackage.to_string nv
| pkgs -> OpamStd.List.concat_map " " OpamPackage.to_string pkgs
in
let conf = { switch_config with OpamFile.Switch_config.synopsis } in
OpamFile.Switch_config.write
(OpamPath.Switch.switch_config gt.root switch)
conf;
conf
else switch_config
in
let conf_files =
OpamPackage.Set.fold (fun nv acc ->
OpamPackage.Map.add nv
(OpamFile.Dot_config.safe_read
(OpamPath.Switch.config gt.root switch nv.name))
acc)
installed OpamPackage.Map.empty
in
let ext_files_changed =
OpamPackage.Map.fold (fun nv conf acc ->
if
List.exists (fun (file, hash) ->
let exists = OpamFilename.exists file in
let should_exist =
let count_not_zero c =
function '0' -> c | _ -> succ c
in
OpamStd.String.fold_left count_not_zero 0 (OpamHash.contents hash) <> 0
in
let changed =
exists <> should_exist ||
exists && not (OpamHash.check_file (OpamFilename.to_string file) hash)
in
/!\ : the package removal instructions wo n't actually ever
be called in this case
be called in this case *)
if not exists && should_exist then
OpamConsole.error
"System file %s, which package %s depends upon, \
no longer exists.\n\
The package has been marked as removed, and opam will \
try to reinstall it if necessary, but you should reinstall \
its system dependencies first."
(OpamFilename.to_string file) (OpamPackage.to_string nv)
else if changed then
OpamConsole.warning
"File %s, which package %s depends upon, \
was changed on your system. \
%s has been marked as removed, and will be reinstalled if \
necessary."
(OpamFilename.to_string file) (OpamPackage.to_string nv)
(OpamPackage.name_to_string nv);
changed)
(OpamFile.Dot_config.file_depends conf)
then OpamPackage.Set.add nv acc
else acc)
conf_files
OpamPackage.Set.empty
in
let installed =
installed -- ext_files_changed
in
let reinstall =
OpamFile.PkgList.safe_read (OpamPath.Switch.reinstall gt.root switch) ++
changed
in
let st = {
switch_global = (gt :> unlocked global_state);
switch_repos = (rt :> unlocked repos_state);
switch_lock = lock;
switch; compiler_packages; switch_config;
repos_package_index; installed_opams;
installed; pinned; installed_roots;
opams; conf_files;
packages; available_packages; reinstall;
} in
log "Switch state loaded in %.3fs" (chrono ());
st
let load_virtual ?repos_list gt rt =
let repos_list = match repos_list with
| Some rl -> rl
| None -> OpamGlobalState.repos_list gt
in
let opams =
OpamRepositoryState.build_index rt repos_list
in
let packages = OpamPackage.keys opams in
{
switch_global = (gt :> unlocked global_state);
switch_repos = (rt :> unlocked repos_state);
switch_lock = OpamSystem.lock_none;
switch = OpamSwitch.unset;
compiler_packages = OpamPackage.Set.empty;
switch_config = {
OpamFile.Switch_config.empty
with OpamFile.Switch_config.repos = Some repos_list;
};
installed = OpamPackage.Set.empty;
installed_opams = OpamPackage.Map.empty;
pinned = OpamPackage.Set.empty;
installed_roots = OpamPackage.Set.empty;
repos_package_index = opams;
opams;
conf_files = OpamPackage.Map.empty;
packages;
available_packages = lazy packages;
reinstall = OpamPackage.Set.empty;
}
let selections st =
{ sel_installed = st.installed;
sel_roots = st.installed_roots;
sel_compiler = st.compiler_packages;
sel_pinned = st.pinned; }
let unlock st =
OpamSystem.funlock st.switch_lock;
(st :> unlocked switch_state)
let with_write_lock ?dontblock st f =
let ret, st =
OpamFilename.with_flock_upgrade `Lock_write ?dontblock st.switch_lock
@@ fun _ -> f ({ st with switch_lock = st.switch_lock } : rw switch_state)
in
ret, { st with switch_lock = st.switch_lock }
let opam st nv = OpamPackage.Map.find nv st.opams
let opam_opt st nv = try Some (opam st nv) with Not_found -> None
let descr_opt st nv =
OpamStd.Option.Op.(opam_opt st nv >>= OpamFile.OPAM.descr)
let descr st nv =
OpamStd.Option.Op.(descr_opt st nv +! OpamFile.Descr.empty)
let url st nv =
OpamStd.Option.Op.(opam_opt st nv >>= OpamFile.OPAM.url)
let primary_url st nv =
OpamStd.Option.Op.(url st nv >>| OpamFile.URL.url)
let files st nv =
match opam_opt st nv with
| None -> []
| Some opam ->
List.map (fun (file,_base,_hash) -> file)
(OpamFile.OPAM.get_extra_files opam)
let package_config st name =
OpamPackage.Map.find
(OpamPackage.package_of_name st.installed name)
st.conf_files
let is_name_installed st name =
OpamPackage.has_name st.installed name
let find_installed_package_by_name st name =
OpamPackage.package_of_name st.installed name
let packages_of_atoms st atoms = OpamFormula.packages_of_atoms st.packages atoms
let get_package st name =
try OpamPinned.package st name with Not_found ->
try find_installed_package_by_name st name with Not_found ->
try OpamPackage.max_version (Lazy.force st.available_packages) name
with Not_found ->
OpamPackage.max_version st.packages name
let is_dev_package st nv =
match opam_opt st nv with
| Some opam -> OpamPackageVar.is_dev_package st opam
| None -> false
let is_pinned st name =
OpamPackage.has_name st.pinned name
let is_version_pinned st name =
match OpamPackage.package_of_name_opt st.pinned name with
| None -> false
| Some nv ->
match opam_opt st nv with
| Some opam ->
OpamPackage.Map.find_opt nv st.repos_package_index = Some opam
| None -> false
let source_dir st nv =
if OpamPackage.Set.mem nv st.pinned
then OpamPath.Switch.pinned_package st.switch_global.root st.switch nv.name
else OpamPath.Switch.sources st.switch_global.root st.switch nv
let depexts st nv =
let env v = OpamPackageVar.resolve_switch ~package:nv st v in
match opam_opt st nv with
| None -> OpamStd.String.Set.empty
| Some opam ->
List.fold_left (fun depexts (names, filter) ->
if OpamFilter.eval_to_bool ~default:false env filter then
List.fold_left (fun depexts n -> OpamStd.String.Set.add n depexts)
depexts names
else depexts)
OpamStd.String.Set.empty
(OpamFile.OPAM.depexts opam)
let dev_packages st =
OpamPackage.Set.filter (is_dev_package st)
(st.installed ++ OpamPinned.packages st)
let conflicts_with st subset =
let forward_conflicts, conflict_classes =
OpamPackage.Set.fold (fun nv (cf,cfc) ->
try
let opam = OpamPackage.Map.find nv st.opams in
let conflicts =
OpamFilter.filter_formula ~default:false
(OpamPackageVar.resolve_switch ~package:nv st)
(OpamFile.OPAM.conflicts opam)
in
OpamFormula.ors [cf; conflicts],
List.fold_right OpamPackage.Name.Set.add
(OpamFile.OPAM.conflict_class opam) cfc
with Not_found -> cf, cfc)
subset (OpamFormula.Empty, OpamPackage.Name.Set.empty)
in
OpamPackage.Set.filter
(fun nv ->
not (OpamPackage.has_name subset nv.name) &&
(OpamFormula.verifies forward_conflicts nv ||
let opam = OpamPackage.Map.find nv st.opams in
List.exists (fun cl -> OpamPackage.Name.Set.mem cl conflict_classes)
(OpamFile.OPAM.conflict_class opam)
||
let backwards_conflicts =
OpamFilter.filter_formula ~default:false
(OpamPackageVar.resolve_switch ~package:nv st)
(OpamFile.OPAM.conflicts opam)
in
OpamPackage.Set.exists
(OpamFormula.verifies backwards_conflicts) subset))
let remove_conflicts st subset pkgs =
pkgs -- conflicts_with st subset pkgs
let get_conflicts st packages opams_map =
let conflict_classes =
OpamPackage.Map.fold (fun nv opam acc ->
List.fold_left (fun acc cc ->
OpamPackage.Name.Map.update cc
(OpamPackage.Set.add nv) OpamPackage.Set.empty acc)
acc
(OpamFile.OPAM.conflict_class opam))
opams_map
OpamPackage.Name.Map.empty
in
let conflict_class_formulas =
OpamPackage.Name.Map.map (fun pkgs ->
OpamPackage.to_map pkgs |>
OpamPackage.Name.Map.mapi (fun name versions ->
let all_versions = OpamPackage.versions_of_name packages name in
if OpamPackage.Version.Set.equal versions all_versions then Empty
else
(OpamFormula.ors
(List.map (fun v -> Atom (`Eq, v))
(OpamPackage.Version.Set.elements versions)))))
conflict_classes
in
OpamPackage.Map.fold (fun nv opam acc ->
let conflicts =
OpamFilter.filter_formula ~default:false
(OpamPackageVar.resolve_switch ~package:nv st)
(OpamFile.OPAM.conflicts opam)
in
let conflicts =
List.fold_left (fun acc cl ->
let cmap =
OpamPackage.Name.Map.find cl conflict_class_formulas |>
OpamPackage.Name.Map.remove nv.name
in
OpamPackage.Name.Map.fold
(fun name vformula acc ->
OpamFormula.ors [acc; Atom (name, vformula)])
cmap acc)
conflicts
(OpamFile.OPAM.conflict_class opam)
in
OpamPackage.Map.add nv conflicts acc)
opams_map
OpamPackage.Map.empty
let universe st
?(test=OpamStateConfig.(!r.build_test))
?(doc=OpamStateConfig.(!r.build_doc))
?(force_dev_deps=false)
?reinstall
~requested
user_action =
let requested_allpkgs =
OpamPackage.packages_of_names st.packages requested
in
let env nv v =
if List.mem v OpamPackageVar.predefined_depends_variables then
match OpamVariable.Full.to_string v with
| "dev" ->
Some (B (force_dev_deps || is_dev_package st nv))
| "with-test" ->
Some (B (test && OpamPackage.Set.mem nv requested_allpkgs))
| "with-doc" ->
Some (B (doc && OpamPackage.Set.mem nv requested_allpkgs))
else
let r = OpamPackageVar.resolve_switch ~package:nv st v in
if r = None then
(if OpamFormatConfig.(!r.strict) then
OpamConsole.error_and_exit `File_error
"undefined filter variable in dependencies of %s: %s"
else
log
"ERR: undefined filter variable in dependencies of %s: %s")
(OpamPackage.to_string nv) (OpamVariable.Full.to_string v);
r
in
let get_deps f opams =
OpamPackage.Map.mapi (fun nv opam ->
OpamFilter.partial_filter_formula (env nv) (f opam)
) opams
in
let u_depends =
let depend =
let ignored = OpamStateConfig.(!r.ignore_constraints_on) in
if OpamPackage.Name.Set.is_empty ignored then OpamFile.OPAM.depends
else fun opam ->
OpamFormula.map (fun (name, cstr as atom) ->
if OpamPackage.Name.Set.mem name ignored then
let cstr =
OpamFormula.map
(function Constraint _ -> Empty | Filter _ as f -> Atom f)
cstr
in
Atom (name, cstr)
else Atom atom)
(OpamFile.OPAM.depends opam)
in
get_deps depend st.opams
in
let u_conflicts = get_conflicts st st.packages st.opams in
let base =
if OpamStateConfig.(!r.unlock_base) then OpamPackage.Set.empty
else st.compiler_packages
in
let u_available =
remove_conflicts st base (Lazy.force st.available_packages)
in
let u_reinstall = match reinstall with
| Some set -> set
| None ->
OpamPackage.Set.filter
(fun nv -> OpamPackage.Name.Set.mem nv.name requested)
st.reinstall
in
let u =
{
u_packages = st.packages;
u_action = user_action;
u_installed = st.installed;
u_available;
u_depends;
u_depopts = get_deps OpamFile.OPAM.depopts st.opams;
u_conflicts;
u_installed_roots = st.installed_roots;
u_pinned = OpamPinned.packages st;
u_base = base;
u_reinstall;
u_attrs = ["opam-query", requested_allpkgs];
}
in
u
let dump_pef_state st oc =
let conflicts = get_conflicts st st.packages st.opams in
let print_def nv opam =
Printf.fprintf oc "package: %s\n" (OpamPackage.name_to_string nv);
Printf.fprintf oc "version: %s\n" (OpamPackage.version_to_string nv);
let installed = OpamPackage.Set.mem nv st.installed in
let root = OpamPackage.Set.mem nv st.installed_roots in
let base = OpamPackage.Set.mem nv st.compiler_packages in
let pinned = OpamPackage.Set.mem nv st.pinned in
let available = OpamPackage.Set.mem nv (Lazy.force st.available_packages) in
let reinstall = OpamPackage.Set.mem nv st.reinstall in
let dev = OpamPackageVar.is_dev_package st opam in
Printf.fprintf oc "available: %b\n" available;
if installed then output_string oc "installed: true\n";
if pinned then output_string oc "pinned: true\n";
if base then output_string oc "base: true\n";
if reinstall then output_string oc "reinstall: true\n";
OpamStd.List.concat_map ~left:"maintainer: " ~right:"\n" ~nil:"" " , "
String.escaped (OpamFile.OPAM.maintainer opam) |>
output_string oc;
OpamFile.OPAM.depends opam |>
OpamPackageVar.filter_depends_formula ~default:false ~dev
~env:(OpamPackageVar.resolve_switch ~package:nv st) |>
OpamFormula.to_cnf |>
OpamStd.List.concat_map ~left:"depends: " ~right:"\n" ~nil:"" " , "
(OpamStd.List.concat_map " | " OpamFormula.string_of_atom) |>
output_string oc;
OpamFile.OPAM.depopts opam |>
OpamPackageVar.filter_depends_formula ~default:false ~dev
~env:(OpamPackageVar.resolve_switch ~package:nv st) |>
OpamFormula.to_cnf |>
OpamStd.List.concat_map ~left:"recommends: " ~right:"\n" ~nil:"" " , "
(OpamStd.List.concat_map " | " OpamFormula.string_of_atom) |>
output_string oc;
OpamFormula.ors
[Atom (nv.name, Empty); OpamPackage.Map.find nv conflicts] |>
OpamFormula.set_to_disjunction st.packages |>
OpamStd.List.concat_map ~left:"conflicts: " ~right:"\n" ~nil:"" " , "
OpamFormula.string_of_atom |>
output_string oc;
output_string oc "\n";
in
OpamPackage.Map.iter print_def st.opams
let is_switch_globally_set st =
OpamFile.Config.switch st.switch_global.config = Some st.switch
let not_found_message st (name, cstr) =
match cstr with
| Some (relop,v) when OpamPackage.has_name st.packages name ->
Printf.sprintf "Package %s has no version %s%s."
(OpamPackage.Name.to_string name)
(match relop with `Eq -> "" | r -> OpamPrinter.relop r)
(OpamPackage.Version.to_string v)
| _ ->
Printf.sprintf "No package named %s found."
(OpamPackage.Name.to_string name)
let unavailable_reason st ?(default="") (name, vformula) =
let candidates = OpamPackage.packages_of_name st.packages name in
let candidates =
OpamPackage.Set.filter
(fun nv -> OpamFormula.check_version_formula vformula nv.version)
candidates
in
if OpamPackage.Set.is_empty candidates then
(if OpamPackage.has_name st.packages name then "no matching version"
else "unknown package")
else
let nv =
try OpamPinned.package st name
with Not_found ->
match vformula with
| Atom (_, v) when
OpamPackage.Set.mem (OpamPackage.create name v) candidates ->
OpamPackage.create name v
| _ -> OpamPackage.max_version candidates name
in
match opam_opt st nv with
| None -> "no package definition found"
| Some opam ->
let avail = OpamFile.OPAM.available opam in
if not (OpamPackage.Set.mem nv candidates) then
Printf.sprintf
"not available because the package is pinned to version %s"
(OpamPackage.version_to_string nv)
else if not (OpamFilter.eval_to_bool ~default:false
(OpamPackageVar.resolve_switch ~package:nv st)
avail)
then
Printf.sprintf "unmet availability conditions%s%s"
(if OpamPackage.Set.cardinal candidates = 1 then ": "
else ", e.g. ")
(OpamFilter.to_string avail)
else if OpamPackage.has_name
(Lazy.force st.available_packages --
remove_conflicts st st.compiler_packages
(Lazy.force st.available_packages))
name
then
"conflict with the base packages of this switch"
else if OpamPackage.has_name st.compiler_packages name &&
not OpamStateConfig.(!r.unlock_base) then
"base of this switch (use `--unlock-base' to force)"
else
default
let update_package_metadata nv opam st =
{ st with
opams = OpamPackage.Map.add nv opam st.opams;
packages = OpamPackage.Set.add nv st.packages;
available_packages = lazy (
if OpamFilter.eval_to_bool ~default:false
(OpamPackageVar.resolve_switch_raw ~package:nv
st.switch_global st.switch st.switch_config)
(OpamFile.OPAM.available opam)
then OpamPackage.Set.add nv (Lazy.force st.available_packages)
else OpamPackage.Set.remove nv (Lazy.force st.available_packages)
);
reinstall =
(match OpamPackage.Map.find_opt nv st.installed_opams with
| Some inst ->
if OpamFile.OPAM.effectively_equal inst opam
then OpamPackage.Set.remove nv (st.reinstall)
else OpamPackage.Set.add nv (st.reinstall)
| _ -> st.reinstall);
}
let remove_package_metadata nv st =
{ st with
opams = OpamPackage.Map.remove nv st.opams;
packages = OpamPackage.Set.remove nv st.packages;
available_packages =
lazy (OpamPackage.Set.remove nv (Lazy.force st.available_packages));
}
let update_pin nv opam st =
let version =
OpamStd.Option.default nv.version (OpamFile.OPAM.version_opt opam)
in
let nv = OpamPackage.create nv.name version in
update_package_metadata nv opam @@
{ st with
pinned =
OpamPackage.Set.add nv
(OpamPackage.filter_name_out st.pinned nv.name);
available_packages = lazy (
OpamPackage.filter_name_out (Lazy.force st.available_packages) nv.name
);
}
let do_backup lock st = match lock with
| `Lock_write ->
let file = OpamPath.Switch.backup st.switch_global.root st.switch in
let previous_selections = selections st in
OpamFile.SwitchSelections.write file previous_selections;
(function
| true -> OpamFilename.remove (OpamFile.filename file)
| false ->
let new_selections = load_selections st.switch_global st.switch in
if new_selections.sel_installed = previous_selections.sel_installed
then OpamFilename.remove (OpamFile.filename file)
else
OpamConsole.errmsg "%s"
(OpamStd.Format.reformat
(Printf.sprintf
"\nThe former state can be restored with:\n\
\ %s switch import %S\n"
Sys.argv.(0) (OpamFile.to_string file) ^
if OpamPackage.Set.is_empty
(new_selections.sel_roots -- new_selections.sel_installed)
then "" else
Printf.sprintf
"Or you can retry to install your package selection with:\n\
\ %s install --restore\n"
Sys.argv.(0))))
| _ -> fun _ -> ()
let with_ lock ?rt ?(switch=OpamStateConfig.get_switch ()) gt f =
(match rt with
| Some rt -> fun f -> f (rt :> unlocked repos_state)
| None -> OpamRepositoryState.with_ `Lock_none gt)
@@ fun rt ->
let st = load lock gt rt switch in
let cleanup_backup = do_backup lock st in
try let r = f st in ignore (unlock st); cleanup_backup true; r
with e ->
OpamStd.Exn.finalise e @@ fun () ->
ignore (unlock st);
if not OpamCoreConfig.(!r.keep_log_dir) then cleanup_backup false
let update_repositories gt update_fun switch =
OpamFilename.with_flock `Lock_write (OpamPath.Switch.lock gt.root switch)
@@ fun _ ->
let conf = load_switch_config gt switch in
let repos =
match conf.OpamFile.Switch_config.repos with
| None -> OpamGlobalState.repos_list gt
| Some repos -> repos
in
let conf =
{ conf with
OpamFile.Switch_config.repos = Some (update_fun repos) }
in
OpamFile.Switch_config.write
(OpamPath.Switch.switch_config gt.root switch)
conf
|
f545172aae61061bd0a79a6419a9f59c6c79379f209c6f669e76eb2351f06b9e | yawaramin/ocaml_sql_query | sql.ml | Copyright 2022
This file is part of ocaml_sql_query .
ocaml_sql_query 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 .
ocaml_sql_query is distributed in the hope that it will be useful , but
WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more
details .
You should have received a copy of the GNU General Public License along with
ocaml_sql_query . If not , see < / > .
This file is part of ocaml_sql_query.
ocaml_sql_query 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.
ocaml_sql_query is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
ocaml_sql_query. If not, see </>. *)
type db = Sqlite3.db
type arg = Sqlite3.Data.t
type row = Sqlite3.Data.t array
type 'r ret = Unit : unit ret | Ret : (row -> 'r) -> 'r Seq.t ret
type 'a eval = ?args:arg list -> 'a Seq.t ret -> 'a Seq.t
type exec = ?args:arg list -> unit ret -> unit
open Sqlite3
let check_rc = function
| Rc.OK
| DONE -> ()
| rc -> failwith (Rc.to_string rc)
let query : type r. db -> string -> ?args:arg list -> r ret -> r =
fun db sql ->
let stmt = prepare db sql in
fun ?args ->
ignore @@ reset stmt;
Option.iter (fun arg -> check_rc @@ bind_values stmt arg) args;
function
| Unit ->
check_rc @@ step stmt;
check_rc @@ reset stmt
| Ret decode ->
let rows () = match step stmt with
| ROW ->
Some (stmt |> row_data |> decode, ())
| DONE ->
None
| rc ->
failwith @@ Rc.to_string rc
in
Seq.unfold rows ()
let rec exec_script db attempts stmt = match step stmt, attempts with
| Rc.BUSY, 0 ->
failwith "busy"
| BUSY, _ ->
exec_script db (pred attempts) stmt
| ROW, _ ->
exec_script db attempts stmt
| (DONE | OK), _ ->
check_rc @@ finalize stmt;
begin match prepare_tail stmt with
| Some stmt -> exec_script db attempts stmt
| None -> ()
end
| rc, _ ->
invalid_arg @@ Rc.to_string rc
let exec_script db sql = exec_script db 3 @@ prepare db sql
module Arg = struct
let text value = Data.TEXT value
let bool value = Data.INT (if value then 1L else 0L)
let int value = Data.INT (Int64.of_int value)
let nativeint value = Data.INT (Int64.of_nativeint value)
let int32 value = Data.INT (Int64.of_int32 value)
let int64 value = Data.INT value
let float value = Data.FLOAT value
let blob value = Data.TEXT value
let opt data = function
| Some value -> data value
| None -> Data.NULL
end
let unit = Unit
let ret decode = Ret decode
let int64 pos row = match row.(pos) with
| Data.INT value -> value
| _ -> failwith "Expected int"
let int pos row = Int64.to_int @@ int64 pos row
let bool pos row = Int64.compare (int64 pos row) Int64.zero > 0
let float pos row = match row.(pos) with
| Data.FLOAT value -> value
| _ -> failwith "Expected float"
let text pos row = match row.(pos) with
| Data.INT value -> Int64.to_string value
| FLOAT value -> string_of_float value
| BLOB value
| TEXT value -> value
| _ -> failwith "Expected text"
let opt dec col row = match row.(col) with
| Data.NULL -> None
| _ -> Some (dec col row)
let only_fail typ =
let msg = if typ then "more than one" else "none" in
failwith ("Seq.only: require exactly one item, found " ^ msg)
let only seq = match seq () with
| Seq.Nil ->
only_fail false
| Cons (a, seq) ->
match seq () with
| Nil -> a
| Cons (_, _) -> only_fail true
let optional seq = match seq () with
| Seq.Nil ->
None
| Cons (a, seq) ->
match seq () with
| Nil -> Some a
| Cons (_, _) -> only_fail true
let transaction db f =
query db "begin" unit;
match f () with
| r ->
query db "commit" unit;
r
| exception e ->
query db "rollback" unit;
raise e
(* We have to parse the value tuple of the insert statement to be able to
multiply it a number of times if needed for a batch insert. *)
let sp_r = Str.regexp " +"
let wsp_r = Str.regexp
@@ Printf.sprintf "[%c%c%c]+" (Char.chr 9) (Char.chr 10) (Char.chr 13)
let values_r = Str.regexp_case_fold
{|^\(insert into .* values *\)\(([^)]+)\)\(.*\)$|}
let pre_pos = 1
let tuple_pos = 2
let post_pos = 3
let batch_insert db sql objs obj_args =
let sql = sql
|> String.trim
|> Str.global_replace wsp_r " "
|> Str.global_replace sp_r " "
in
if Str.string_match values_r sql 0 then
let tuple = Str.matched_group tuple_pos sql in
let tuples = objs |> List.map (fun _ -> tuple) |> String.concat "," in
let sql =
Str.matched_group pre_pos sql ^ tuples ^ Str.matched_group post_pos sql
in
query db sql ~args:(objs |> List.map obj_args |> List.flatten)
else
failwith sql
let slurp file =
let inc = open_in file in
let contents = really_input_string inc (in_channel_length inc) in
close_in inc;
contents
exception Bad_migration of string
let migrate db dir =
query db
"
create table if not exists migration (
filename varchar(1024) not null primary key,
script text not null,
applied_at timestamp
)
"
unit;
let mark_ok = query db
"
insert into migration (filename, script, applied_at)
values (?, ?, current_timestamp)
"
in
let migrated = query db "select 1 from migration where filename = ?" in
let migrated filename = 0
|> bool
|> ret
|> migrated ~args:[filename]
|> optional
|> Option.fold ~none:false ~some:Fun.id
in
let files = Sys.readdir dir in
Array.sort compare files;
transaction db @@ fun () ->
files |> Array.iter @@ fun filename ->
let filename = dir ^ "/" ^ filename in
let arg_filename = Arg.text filename in
if String.ends_with ~suffix:".sql" filename && not (migrated arg_filename) then
let script = slurp filename in
match exec_script db script with
| () ->
mark_ok ~args:Arg.[arg_filename; text script] unit
| exception Failure _ ->
raise (Bad_migration (Sqlite3.errmsg db))
| null | https://raw.githubusercontent.com/yawaramin/ocaml_sql_query/ac6d0908bf881595c6a58c761e6f105596f94ccd/lib/sql.ml | ocaml | We have to parse the value tuple of the insert statement to be able to
multiply it a number of times if needed for a batch insert. | Copyright 2022
This file is part of ocaml_sql_query .
ocaml_sql_query 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 .
ocaml_sql_query is distributed in the hope that it will be useful , but
WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more
details .
You should have received a copy of the GNU General Public License along with
ocaml_sql_query . If not , see < / > .
This file is part of ocaml_sql_query.
ocaml_sql_query 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.
ocaml_sql_query is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
details.
You should have received a copy of the GNU General Public License along with
ocaml_sql_query. If not, see </>. *)
type db = Sqlite3.db
type arg = Sqlite3.Data.t
type row = Sqlite3.Data.t array
type 'r ret = Unit : unit ret | Ret : (row -> 'r) -> 'r Seq.t ret
type 'a eval = ?args:arg list -> 'a Seq.t ret -> 'a Seq.t
type exec = ?args:arg list -> unit ret -> unit
open Sqlite3
let check_rc = function
| Rc.OK
| DONE -> ()
| rc -> failwith (Rc.to_string rc)
let query : type r. db -> string -> ?args:arg list -> r ret -> r =
fun db sql ->
let stmt = prepare db sql in
fun ?args ->
ignore @@ reset stmt;
Option.iter (fun arg -> check_rc @@ bind_values stmt arg) args;
function
| Unit ->
check_rc @@ step stmt;
check_rc @@ reset stmt
| Ret decode ->
let rows () = match step stmt with
| ROW ->
Some (stmt |> row_data |> decode, ())
| DONE ->
None
| rc ->
failwith @@ Rc.to_string rc
in
Seq.unfold rows ()
let rec exec_script db attempts stmt = match step stmt, attempts with
| Rc.BUSY, 0 ->
failwith "busy"
| BUSY, _ ->
exec_script db (pred attempts) stmt
| ROW, _ ->
exec_script db attempts stmt
| (DONE | OK), _ ->
check_rc @@ finalize stmt;
begin match prepare_tail stmt with
| Some stmt -> exec_script db attempts stmt
| None -> ()
end
| rc, _ ->
invalid_arg @@ Rc.to_string rc
let exec_script db sql = exec_script db 3 @@ prepare db sql
module Arg = struct
let text value = Data.TEXT value
let bool value = Data.INT (if value then 1L else 0L)
let int value = Data.INT (Int64.of_int value)
let nativeint value = Data.INT (Int64.of_nativeint value)
let int32 value = Data.INT (Int64.of_int32 value)
let int64 value = Data.INT value
let float value = Data.FLOAT value
let blob value = Data.TEXT value
let opt data = function
| Some value -> data value
| None -> Data.NULL
end
let unit = Unit
let ret decode = Ret decode
let int64 pos row = match row.(pos) with
| Data.INT value -> value
| _ -> failwith "Expected int"
let int pos row = Int64.to_int @@ int64 pos row
let bool pos row = Int64.compare (int64 pos row) Int64.zero > 0
let float pos row = match row.(pos) with
| Data.FLOAT value -> value
| _ -> failwith "Expected float"
let text pos row = match row.(pos) with
| Data.INT value -> Int64.to_string value
| FLOAT value -> string_of_float value
| BLOB value
| TEXT value -> value
| _ -> failwith "Expected text"
let opt dec col row = match row.(col) with
| Data.NULL -> None
| _ -> Some (dec col row)
let only_fail typ =
let msg = if typ then "more than one" else "none" in
failwith ("Seq.only: require exactly one item, found " ^ msg)
let only seq = match seq () with
| Seq.Nil ->
only_fail false
| Cons (a, seq) ->
match seq () with
| Nil -> a
| Cons (_, _) -> only_fail true
let optional seq = match seq () with
| Seq.Nil ->
None
| Cons (a, seq) ->
match seq () with
| Nil -> Some a
| Cons (_, _) -> only_fail true
let transaction db f =
query db "begin" unit;
match f () with
| r ->
query db "commit" unit;
r
| exception e ->
query db "rollback" unit;
raise e
let sp_r = Str.regexp " +"
let wsp_r = Str.regexp
@@ Printf.sprintf "[%c%c%c]+" (Char.chr 9) (Char.chr 10) (Char.chr 13)
let values_r = Str.regexp_case_fold
{|^\(insert into .* values *\)\(([^)]+)\)\(.*\)$|}
let pre_pos = 1
let tuple_pos = 2
let post_pos = 3
let batch_insert db sql objs obj_args =
let sql = sql
|> String.trim
|> Str.global_replace wsp_r " "
|> Str.global_replace sp_r " "
in
if Str.string_match values_r sql 0 then
let tuple = Str.matched_group tuple_pos sql in
let tuples = objs |> List.map (fun _ -> tuple) |> String.concat "," in
let sql =
Str.matched_group pre_pos sql ^ tuples ^ Str.matched_group post_pos sql
in
query db sql ~args:(objs |> List.map obj_args |> List.flatten)
else
failwith sql
let slurp file =
let inc = open_in file in
let contents = really_input_string inc (in_channel_length inc) in
close_in inc;
contents
exception Bad_migration of string
let migrate db dir =
query db
"
create table if not exists migration (
filename varchar(1024) not null primary key,
script text not null,
applied_at timestamp
)
"
unit;
let mark_ok = query db
"
insert into migration (filename, script, applied_at)
values (?, ?, current_timestamp)
"
in
let migrated = query db "select 1 from migration where filename = ?" in
let migrated filename = 0
|> bool
|> ret
|> migrated ~args:[filename]
|> optional
|> Option.fold ~none:false ~some:Fun.id
in
let files = Sys.readdir dir in
Array.sort compare files;
transaction db @@ fun () ->
files |> Array.iter @@ fun filename ->
let filename = dir ^ "/" ^ filename in
let arg_filename = Arg.text filename in
if String.ends_with ~suffix:".sql" filename && not (migrated arg_filename) then
let script = slurp filename in
match exec_script db script with
| () ->
mark_ok ~args:Arg.[arg_filename; text script] unit
| exception Failure _ ->
raise (Bad_migration (Sqlite3.errmsg db))
|
883176941dbcb1527e959621f4c4b93402313e3efacd612f2ec4f3312041432e | chef/mixer | mixer.erl | %% -*- mode: erlang -*-
-*- tab - width : 4;erlang - indent - level : 4;indent - tabs - mode : nil -*-
%% ex: ts=4 sw=4 ft=erlang et
%%
Copyright 2012 Opscode , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
-module(mixer).
-export([parse_transform/2]).
-define(arity_limit, 26).
-record(mixin, {line,
mod,
fname,
alias,
arity}).
-spec parse_transform([term()], [term()]) -> [term()].
parse_transform(Forms, _Options) ->
set_mod_info(Forms),
{EOF, Forms1} = strip_eof(Forms),
case parse_and_expand_mixins(Forms1, []) of
[] ->
Forms;
Mixins ->
no_dupes(Mixins),
{EOF1, Forms2} = insert_stubs(Mixins, EOF, Forms1),
finalize(Mixins, EOF1, Forms2)
end.
Internal functions
set_mod_info([{attribute, _, file, {FileName, _}}|_]) ->
erlang:put(mixer_delegate_file, FileName);
set_mod_info([{attribute, _, module, Mod}|_]) ->
erlang:put(mixer_calling_mod, Mod).
get_file_name() ->
erlang:get(mixer_delegate_file).
%% get_calling_mod() ->
%% erlang:get(mixer_calling_mod).
finalize(Mixins, NewEOF, Forms) ->
insert_exports(Mixins, Forms, []) ++ [{eof, NewEOF}].
insert_exports([], Forms, Accum) ->
Accum ++ Forms;
insert_exports([#mixin{line=Line}|_]=Mixins, [{attribute, Line, mixin, _}|FT], Accum) ->
{Exports, Mixins1} = make_export_statement(Line, Mixins),
insert_exports(Mixins1, FT, Accum ++ Exports);
insert_exports([#mixin{line=Line}|_]=Mixins, [], Accum) ->
{Exports, Mixins1} = make_export_statement(Line, Mixins),
insert_exports(Mixins1, [], Accum ++ Exports);
insert_exports(Mixins, [H|T], Accum) ->
insert_exports(Mixins, T, Accum ++ [H]).
strip_eof(Forms) ->
strip_eof(Forms, []).
strip_eof([], Accum) ->
lists:reverse(Accum);
strip_eof([{eof, EOF}|T], Accum) ->
{EOF, lists:reverse(Accum) ++ T};
strip_eof([H|T], Accum) ->
strip_eof(T, [H|Accum]).
parse_and_expand_mixins([], []) ->
[];
parse_and_expand_mixins([], Accum) ->
group_mixins({none, 0}, lists:keysort(2, Accum), []);
parse_and_expand_mixins([{attribute, Line, mixin, Mixins0}|T], Accum) when is_list(Mixins0) ->
Mixins = [expand_mixin(Line, Mixin) || Mixin <- Mixins0],
parse_and_expand_mixins(T, lists:flatten([Accum, Mixins]));
parse_and_expand_mixins([_|T], Accum) ->
parse_and_expand_mixins(T, Accum).
group_mixins(_, [], Accum) ->
lists:keysort(2, Accum);
group_mixins({CMod, CLine}, [#mixin{mod=CMod, line=CLine}=H|T], Accum) ->
group_mixins({CMod, CLine}, T, [H|Accum]);
group_mixins({CMod, CLine}, [#mixin{mod=CMod}=H|T], Accum) ->
group_mixins({CMod, CLine}, T, [H#mixin{line=CLine}|Accum]);
group_mixins({_CMod, _}, [#mixin{mod=Mod, line=Line}=H|T], Accum) ->
group_mixins({Mod, Line}, T, [H|Accum]).
expand_mixin(Line, Name) when is_atom(Name) ->
case catch Name:module_info(exports) of
{'EXIT', _} ->
io:format("~s:~p Unable to resolve imported module ~p~n", [get_file_name(), Line, Name]),
exit({error, undef_mixin_module});
Exports ->
[#mixin{line=Line, mod=Name, fname=Fun, alias=Fun, arity=Arity} || {Fun, Arity} <- Exports,
Fun /= module_info]
end;
expand_mixin(Line, {Name, except, Funs}) when is_atom(Name),
is_list(Funs) ->
case catch Name:module_info(exports) of
{'EXIT', _} ->
io:format("~s:~p Unable to resolve imported module ~p~n", [get_file_name(), Line, Name]),
exit({error, undef_mixin_module});
Exports ->
[#mixin{line=Line, mod=Name, fname=Fun, alias=Fun, arity=Arity} || {Fun, Arity} <- Exports,
Fun /= module_info andalso not lists:member({Fun, Arity}, Funs)]
end;
expand_mixin(Line, {Name, Funs}) when is_atom(Name),
is_list(Funs) ->
[begin
{Fun, Arity, Alias} = parse_mixin_ref(MixinRef),
#mixin{line=Line, mod=Name, fname=Fun, arity=Arity, alias=Alias}
end || MixinRef <- Funs].
parse_mixin_ref({{Fun, Arity}, Alias}) ->
{Fun, Arity, Alias};
parse_mixin_ref({Fun, Arity}) ->
{Fun, Arity, Fun}.
no_dupes([]) ->
ok;
no_dupes([H|T]) ->
no_dupes(H, T),
no_dupes(T).
no_dupes(_, []) ->
ok;
no_dupes(#mixin{mod=Mod, fname=Fun, arity=Arity, line=Line}, Rest) ->
case find_dupe(Fun, Arity, Rest) of
{ok, {Mod1, Fun, Arity}} ->
io:format("~s:~p Duplicate mixin detected importing ~p/~p from ~p and ~p~n",
[get_file_name(), Line, Fun, Arity, Mod, Mod1]),
exit({error, duplicate_mixins});
not_found ->
ok
end.
find_dupe(_Fun, _Arity, []) ->
not_found;
find_dupe(Fun, Arity, [#mixin{mod=Name, fname=Fun, arity=Arity}|_]) ->
{ok, {Name, Fun, Arity}};
find_dupe(Fun, Arity, [_|T]) ->
find_dupe(Fun, Arity, T).
insert_stubs(Mixins, EOF, Forms) ->
F = fun(#mixin{mod=Mod, fname=Fun, arity=Arity, alias=Alias}, {CurrEOF, Acc}) ->
{CurrEOF + 1, [generate_stub(atom_to_list(Mod), atom_to_list(Alias), atom_to_list(Fun), Arity, CurrEOF)|Acc]} end,
{EOF1, Stubs} = lists:foldr(F, {EOF, []}, Mixins),
{EOF1, Forms ++ lists:reverse(Stubs)}.
generate_stub(Mixin, Alias, Name, Arity, CurrEOF) when Arity =< ?arity_limit ->
ArgList = "(" ++ make_param_list(Arity) ++ ")",
Code = Alias ++ ArgList ++ "-> " ++ Mixin ++ ":" ++ Name ++ ArgList ++ ".",
{ok, Tokens, _} = erl_scan:string(Code),
{ok, Form} = erl_parse:parse_form(Tokens),
replace_stub_linenum(CurrEOF, Form).
replace_stub_linenum(CurrEOF, {function, _, Name, Arity, Body}) ->
{function, CurrEOF, Name, Arity, replace_stub_linenum(CurrEOF, Body, [])}.
replace_stub_linenum(CurrEOF, [{clause, _, Vars, [], Call}], _) ->
[{clause, CurrEOF, replace_stub_linenum(CurrEOF, Vars, []), [], replace_stub_linenum(CurrEOF, Call, [])}];
replace_stub_linenum(_CurrEOF, [], Accum) ->
lists:reverse(Accum);
replace_stub_linenum(CurrEOF, [{var, _, Var}|T], Accum) ->
replace_stub_linenum(CurrEOF, T, [{var, CurrEOF, Var}|Accum]);
replace_stub_linenum(CurrEOF, [{call, _, {remote, _, {atom, _, Mod}, {atom, _, Fun}}, Args}], _Accum) ->
[{call, CurrEOF, {remote, CurrEOF, {atom, CurrEOF, Mod}, {atom, CurrEOF, Fun}},
replace_stub_linenum(CurrEOF, Args, [])}].
%% Use single upper-case letters for params
make_param_list(0) ->
"";
make_param_list(Arity) when Arity =< ?arity_limit ->
make_param_list(Arity, []).
make_param_list(1, Accum) ->
push_param(1, Accum);
make_param_list(Count, Accum) ->
make_param_list(Count - 1, push_param(Count, Accum)).
push_param(Pos, []) ->
[(64 + Pos)];
push_param(Pos, Accum) ->
[(64 + Pos), 44|Accum].
make_export_statement(Line, Mixins) ->
F = fun(Mixin) -> Mixin#mixin.line == Line end,
case lists:partition(F, Mixins) of
{[], Mixins} ->
{[], Mixins};
{ME, Mixins1} ->
Export = {attribute, Line, export, [{Alias, Arity} || #mixin{alias=Alias, arity=Arity} <- ME]},
{[Export], Mixins1}
end.
| null | https://raw.githubusercontent.com/chef/mixer/0d1322433e7e2237eb1270dc5a028fa014335134/src/mixer.erl | erlang | -*- mode: erlang -*-
ex: ts=4 sw=4 ft=erlang et
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
get_calling_mod() ->
erlang:get(mixer_calling_mod).
Use single upper-case letters for params | -*- tab - width : 4;erlang - indent - level : 4;indent - tabs - mode : nil -*-
Copyright 2012 Opscode , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(mixer).
-export([parse_transform/2]).
-define(arity_limit, 26).
-record(mixin, {line,
mod,
fname,
alias,
arity}).
-spec parse_transform([term()], [term()]) -> [term()].
parse_transform(Forms, _Options) ->
set_mod_info(Forms),
{EOF, Forms1} = strip_eof(Forms),
case parse_and_expand_mixins(Forms1, []) of
[] ->
Forms;
Mixins ->
no_dupes(Mixins),
{EOF1, Forms2} = insert_stubs(Mixins, EOF, Forms1),
finalize(Mixins, EOF1, Forms2)
end.
Internal functions
set_mod_info([{attribute, _, file, {FileName, _}}|_]) ->
erlang:put(mixer_delegate_file, FileName);
set_mod_info([{attribute, _, module, Mod}|_]) ->
erlang:put(mixer_calling_mod, Mod).
get_file_name() ->
erlang:get(mixer_delegate_file).
finalize(Mixins, NewEOF, Forms) ->
insert_exports(Mixins, Forms, []) ++ [{eof, NewEOF}].
insert_exports([], Forms, Accum) ->
Accum ++ Forms;
insert_exports([#mixin{line=Line}|_]=Mixins, [{attribute, Line, mixin, _}|FT], Accum) ->
{Exports, Mixins1} = make_export_statement(Line, Mixins),
insert_exports(Mixins1, FT, Accum ++ Exports);
insert_exports([#mixin{line=Line}|_]=Mixins, [], Accum) ->
{Exports, Mixins1} = make_export_statement(Line, Mixins),
insert_exports(Mixins1, [], Accum ++ Exports);
insert_exports(Mixins, [H|T], Accum) ->
insert_exports(Mixins, T, Accum ++ [H]).
strip_eof(Forms) ->
strip_eof(Forms, []).
strip_eof([], Accum) ->
lists:reverse(Accum);
strip_eof([{eof, EOF}|T], Accum) ->
{EOF, lists:reverse(Accum) ++ T};
strip_eof([H|T], Accum) ->
strip_eof(T, [H|Accum]).
parse_and_expand_mixins([], []) ->
[];
parse_and_expand_mixins([], Accum) ->
group_mixins({none, 0}, lists:keysort(2, Accum), []);
parse_and_expand_mixins([{attribute, Line, mixin, Mixins0}|T], Accum) when is_list(Mixins0) ->
Mixins = [expand_mixin(Line, Mixin) || Mixin <- Mixins0],
parse_and_expand_mixins(T, lists:flatten([Accum, Mixins]));
parse_and_expand_mixins([_|T], Accum) ->
parse_and_expand_mixins(T, Accum).
group_mixins(_, [], Accum) ->
lists:keysort(2, Accum);
group_mixins({CMod, CLine}, [#mixin{mod=CMod, line=CLine}=H|T], Accum) ->
group_mixins({CMod, CLine}, T, [H|Accum]);
group_mixins({CMod, CLine}, [#mixin{mod=CMod}=H|T], Accum) ->
group_mixins({CMod, CLine}, T, [H#mixin{line=CLine}|Accum]);
group_mixins({_CMod, _}, [#mixin{mod=Mod, line=Line}=H|T], Accum) ->
group_mixins({Mod, Line}, T, [H|Accum]).
expand_mixin(Line, Name) when is_atom(Name) ->
case catch Name:module_info(exports) of
{'EXIT', _} ->
io:format("~s:~p Unable to resolve imported module ~p~n", [get_file_name(), Line, Name]),
exit({error, undef_mixin_module});
Exports ->
[#mixin{line=Line, mod=Name, fname=Fun, alias=Fun, arity=Arity} || {Fun, Arity} <- Exports,
Fun /= module_info]
end;
expand_mixin(Line, {Name, except, Funs}) when is_atom(Name),
is_list(Funs) ->
case catch Name:module_info(exports) of
{'EXIT', _} ->
io:format("~s:~p Unable to resolve imported module ~p~n", [get_file_name(), Line, Name]),
exit({error, undef_mixin_module});
Exports ->
[#mixin{line=Line, mod=Name, fname=Fun, alias=Fun, arity=Arity} || {Fun, Arity} <- Exports,
Fun /= module_info andalso not lists:member({Fun, Arity}, Funs)]
end;
expand_mixin(Line, {Name, Funs}) when is_atom(Name),
is_list(Funs) ->
[begin
{Fun, Arity, Alias} = parse_mixin_ref(MixinRef),
#mixin{line=Line, mod=Name, fname=Fun, arity=Arity, alias=Alias}
end || MixinRef <- Funs].
parse_mixin_ref({{Fun, Arity}, Alias}) ->
{Fun, Arity, Alias};
parse_mixin_ref({Fun, Arity}) ->
{Fun, Arity, Fun}.
no_dupes([]) ->
ok;
no_dupes([H|T]) ->
no_dupes(H, T),
no_dupes(T).
no_dupes(_, []) ->
ok;
no_dupes(#mixin{mod=Mod, fname=Fun, arity=Arity, line=Line}, Rest) ->
case find_dupe(Fun, Arity, Rest) of
{ok, {Mod1, Fun, Arity}} ->
io:format("~s:~p Duplicate mixin detected importing ~p/~p from ~p and ~p~n",
[get_file_name(), Line, Fun, Arity, Mod, Mod1]),
exit({error, duplicate_mixins});
not_found ->
ok
end.
find_dupe(_Fun, _Arity, []) ->
not_found;
find_dupe(Fun, Arity, [#mixin{mod=Name, fname=Fun, arity=Arity}|_]) ->
{ok, {Name, Fun, Arity}};
find_dupe(Fun, Arity, [_|T]) ->
find_dupe(Fun, Arity, T).
insert_stubs(Mixins, EOF, Forms) ->
F = fun(#mixin{mod=Mod, fname=Fun, arity=Arity, alias=Alias}, {CurrEOF, Acc}) ->
{CurrEOF + 1, [generate_stub(atom_to_list(Mod), atom_to_list(Alias), atom_to_list(Fun), Arity, CurrEOF)|Acc]} end,
{EOF1, Stubs} = lists:foldr(F, {EOF, []}, Mixins),
{EOF1, Forms ++ lists:reverse(Stubs)}.
generate_stub(Mixin, Alias, Name, Arity, CurrEOF) when Arity =< ?arity_limit ->
ArgList = "(" ++ make_param_list(Arity) ++ ")",
Code = Alias ++ ArgList ++ "-> " ++ Mixin ++ ":" ++ Name ++ ArgList ++ ".",
{ok, Tokens, _} = erl_scan:string(Code),
{ok, Form} = erl_parse:parse_form(Tokens),
replace_stub_linenum(CurrEOF, Form).
replace_stub_linenum(CurrEOF, {function, _, Name, Arity, Body}) ->
{function, CurrEOF, Name, Arity, replace_stub_linenum(CurrEOF, Body, [])}.
replace_stub_linenum(CurrEOF, [{clause, _, Vars, [], Call}], _) ->
[{clause, CurrEOF, replace_stub_linenum(CurrEOF, Vars, []), [], replace_stub_linenum(CurrEOF, Call, [])}];
replace_stub_linenum(_CurrEOF, [], Accum) ->
lists:reverse(Accum);
replace_stub_linenum(CurrEOF, [{var, _, Var}|T], Accum) ->
replace_stub_linenum(CurrEOF, T, [{var, CurrEOF, Var}|Accum]);
replace_stub_linenum(CurrEOF, [{call, _, {remote, _, {atom, _, Mod}, {atom, _, Fun}}, Args}], _Accum) ->
[{call, CurrEOF, {remote, CurrEOF, {atom, CurrEOF, Mod}, {atom, CurrEOF, Fun}},
replace_stub_linenum(CurrEOF, Args, [])}].
make_param_list(0) ->
"";
make_param_list(Arity) when Arity =< ?arity_limit ->
make_param_list(Arity, []).
make_param_list(1, Accum) ->
push_param(1, Accum);
make_param_list(Count, Accum) ->
make_param_list(Count - 1, push_param(Count, Accum)).
push_param(Pos, []) ->
[(64 + Pos)];
push_param(Pos, Accum) ->
[(64 + Pos), 44|Accum].
make_export_statement(Line, Mixins) ->
F = fun(Mixin) -> Mixin#mixin.line == Line end,
case lists:partition(F, Mixins) of
{[], Mixins} ->
{[], Mixins};
{ME, Mixins1} ->
Export = {attribute, Line, export, [{Alias, Arity} || #mixin{alias=Alias, arity=Arity} <- ME]},
{[Export], Mixins1}
end.
|
2bd0de03e62761de1254dafaf45201085f153bc48044390915ecee4161d1137a | ocaml-multicore/ocaml-tsan | kind_mismatch.ml | (* TEST
* expect
*)
(** Error messages for kind mismatches. *)
module T0 : sig type t end = struct type t = unit end
type t0 = T0.t = { a0 : int };;
[%%expect {|
module T0 : sig type t end
Line 4, characters 0-29:
4 | type t0 = T0.t = { a0 : int };;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type T0.t
The original is abstract, but this is a record.
|}]
type t2a = ..
type t2b = t2a = A2 | B2;;
[%%expect {|
type t2a = ..
Line 2, characters 0-24:
2 | type t2b = t2a = A2 | B2;;
^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type t2a
The original is an extensible variant, but this is a variant.
|}]
| null | https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/ae9c1502103845550162a49fcd3f76276cdfa866/testsuite/tests/typing-kind/kind_mismatch.ml | ocaml | TEST
* expect
* Error messages for kind mismatches. |
module T0 : sig type t end = struct type t = unit end
type t0 = T0.t = { a0 : int };;
[%%expect {|
module T0 : sig type t end
Line 4, characters 0-29:
4 | type t0 = T0.t = { a0 : int };;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type T0.t
The original is abstract, but this is a record.
|}]
type t2a = ..
type t2b = t2a = A2 | B2;;
[%%expect {|
type t2a = ..
Line 2, characters 0-24:
2 | type t2b = t2a = A2 | B2;;
^^^^^^^^^^^^^^^^^^^^^^^^
Error: This variant or record definition does not match that of type t2a
The original is an extensible variant, but this is a variant.
|}]
|
4b4fff17e0c810b363773bf8cc3c4d53fcb92eb5b0660d00ed54b5e0d5ee7477 | sixohsix/tak | Replace.hs | module Tak.Editor.Replace where
import System.IO (hSetBinaryMode, hGetContents, hPutStr)
import System.Process (runInteractiveCommand)
import Control.Concurrent (forkIO)
import Control.Lens
import Tak.Types
import Tak.Buffer
import Tak.Buffer.LineSeq
import Tak.Editor.Selection
import Tak.Range
updateActiveBuffer :: (Buffer -> IO Buffer) -> GlobalState -> IO GlobalState
updateActiveBuffer f gst =
traverseOf editor (\ed -> (f $ buffer ed) >>= (\newBuf -> return $ ed { buffer = newBuf })) gst
processCmd :: String -> String -> IO String
processCmd command inputStr = do
(inp, out, err, pid) <- runInteractiveCommand command
hSetBinaryMode inp False
hSetBinaryMode out False
forkIO (hPutStr inp inputStr)
hGetContents out
processLineSeqIO :: (String -> IO String) -> LineSeq -> IO LineSeq
processLineSeqIO f lSeq = (f $ lineSeqToStr lSeq) >>= (return . strToLineSeq)
replaceRegion :: (LineSeq -> IO LineSeq) -> Buffer -> (Pos, Pos) -> IO Buffer
replaceRegion f buf r@(rStartPos, _) = do
let (ls, cutBuf) = cutSelection buf r
replacementLs <- f ls
return $ insertLineSeqIntoBuffer cutBuf rStartPos replacementLs
repRegionWithShellCmd :: String -> Buffer -> (Pos, Pos) -> IO Buffer
repRegionWithShellCmd cmd = replaceRegion (processLineSeqIO $ processCmd cmd)
replaceRegionWithShellCmd :: String -> GlobalState -> IO GlobalState
replaceRegionWithShellCmd cmd gst =
case currentSelection (view editor gst) of
Nothing -> return $ gst
Just region -> updateActiveBuffer (\buf -> repRegionWithShellCmd cmd buf $ asTuple region) gst
| null | https://raw.githubusercontent.com/sixohsix/tak/6310d19faa683156933dde38666c11dc087d79ea/src/Tak/Editor/Replace.hs | haskell | module Tak.Editor.Replace where
import System.IO (hSetBinaryMode, hGetContents, hPutStr)
import System.Process (runInteractiveCommand)
import Control.Concurrent (forkIO)
import Control.Lens
import Tak.Types
import Tak.Buffer
import Tak.Buffer.LineSeq
import Tak.Editor.Selection
import Tak.Range
updateActiveBuffer :: (Buffer -> IO Buffer) -> GlobalState -> IO GlobalState
updateActiveBuffer f gst =
traverseOf editor (\ed -> (f $ buffer ed) >>= (\newBuf -> return $ ed { buffer = newBuf })) gst
processCmd :: String -> String -> IO String
processCmd command inputStr = do
(inp, out, err, pid) <- runInteractiveCommand command
hSetBinaryMode inp False
hSetBinaryMode out False
forkIO (hPutStr inp inputStr)
hGetContents out
processLineSeqIO :: (String -> IO String) -> LineSeq -> IO LineSeq
processLineSeqIO f lSeq = (f $ lineSeqToStr lSeq) >>= (return . strToLineSeq)
replaceRegion :: (LineSeq -> IO LineSeq) -> Buffer -> (Pos, Pos) -> IO Buffer
replaceRegion f buf r@(rStartPos, _) = do
let (ls, cutBuf) = cutSelection buf r
replacementLs <- f ls
return $ insertLineSeqIntoBuffer cutBuf rStartPos replacementLs
repRegionWithShellCmd :: String -> Buffer -> (Pos, Pos) -> IO Buffer
repRegionWithShellCmd cmd = replaceRegion (processLineSeqIO $ processCmd cmd)
replaceRegionWithShellCmd :: String -> GlobalState -> IO GlobalState
replaceRegionWithShellCmd cmd gst =
case currentSelection (view editor gst) of
Nothing -> return $ gst
Just region -> updateActiveBuffer (\buf -> repRegionWithShellCmd cmd buf $ asTuple region) gst
| |
3b76ea01b37ddbca540cf2f4b5bbfe505284a23ee504adfee3d00c4bf83388f9 | district0x/cljs-ipfs-api | core.cljs | (ns cljs-ipfs-api.core
(:require [taoensso.timbre :as timbre :refer-macros [log
trace
debug
info
warn
error
fatal
report]]
[cljsjs.ipfs :as ipfs]))
(def *ipfs-instance* (atom nil))
(defn init-ipfs-web [param]
(let [i (new js/IpfsApi param)]
(reset! *ipfs-instance* i)
i))
(defn init-ipfs-node [param]
(let [ipfs-api (js/require "ipfs-api")
i (new ipfs-api param)]
(reset! *ipfs-instance* i)
i))
(defn init []
(info "INIT"))
| null | https://raw.githubusercontent.com/district0x/cljs-ipfs-api/01c5e6943d3cc5e0e54d436a796e98dc8145b0ba/src/cljs_ipfs_api/core.cljs | clojure | (ns cljs-ipfs-api.core
(:require [taoensso.timbre :as timbre :refer-macros [log
trace
debug
info
warn
error
fatal
report]]
[cljsjs.ipfs :as ipfs]))
(def *ipfs-instance* (atom nil))
(defn init-ipfs-web [param]
(let [i (new js/IpfsApi param)]
(reset! *ipfs-instance* i)
i))
(defn init-ipfs-node [param]
(let [ipfs-api (js/require "ipfs-api")
i (new ipfs-api param)]
(reset! *ipfs-instance* i)
i))
(defn init []
(info "INIT"))
| |
0e9c291678be5cc0025c4a449bbc8c977e1bfcd121986dce3adc7ba6663fbeac | let-def/cuite | cuite_lwt.ml | let engine = object
inherit Lwt_engine.select_based
method select = Qt.qselect
end
let set_engine () =
Lwt_engine.set engine
| null | https://raw.githubusercontent.com/let-def/cuite/42629a91c573ecbf1b01f213f1bf35a456d2b1af/lib/cuite_lwt.ml | ocaml | let engine = object
inherit Lwt_engine.select_based
method select = Qt.qselect
end
let set_engine () =
Lwt_engine.set engine
| |
d1199788a94ca81e8d95eb087722e6ac4cfad1e1b0c60b3b995ab6675ccec996 | mbj/stratosphere | ResourceUpdateConstraint.hs | module Stratosphere.ServiceCatalog.ResourceUpdateConstraint (
ResourceUpdateConstraint(..), mkResourceUpdateConstraint
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data ResourceUpdateConstraint
= ResourceUpdateConstraint {acceptLanguage :: (Prelude.Maybe (Value Prelude.Text)),
description :: (Prelude.Maybe (Value Prelude.Text)),
portfolioId :: (Value Prelude.Text),
productId :: (Value Prelude.Text),
tagUpdateOnProvisionedProduct :: (Value Prelude.Text)}
mkResourceUpdateConstraint ::
Value Prelude.Text
-> Value Prelude.Text
-> Value Prelude.Text -> ResourceUpdateConstraint
mkResourceUpdateConstraint
portfolioId
productId
tagUpdateOnProvisionedProduct
= ResourceUpdateConstraint
{portfolioId = portfolioId, productId = productId,
tagUpdateOnProvisionedProduct = tagUpdateOnProvisionedProduct,
acceptLanguage = Prelude.Nothing, description = Prelude.Nothing}
instance ToResourceProperties ResourceUpdateConstraint where
toResourceProperties ResourceUpdateConstraint {..}
= ResourceProperties
{awsType = "AWS::ServiceCatalog::ResourceUpdateConstraint",
supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["PortfolioId" JSON..= portfolioId, "ProductId" JSON..= productId,
"TagUpdateOnProvisionedProduct"
JSON..= tagUpdateOnProvisionedProduct]
(Prelude.catMaybes
[(JSON..=) "AcceptLanguage" Prelude.<$> acceptLanguage,
(JSON..=) "Description" Prelude.<$> description]))}
instance JSON.ToJSON ResourceUpdateConstraint where
toJSON ResourceUpdateConstraint {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["PortfolioId" JSON..= portfolioId, "ProductId" JSON..= productId,
"TagUpdateOnProvisionedProduct"
JSON..= tagUpdateOnProvisionedProduct]
(Prelude.catMaybes
[(JSON..=) "AcceptLanguage" Prelude.<$> acceptLanguage,
(JSON..=) "Description" Prelude.<$> description])))
instance Property "AcceptLanguage" ResourceUpdateConstraint where
type PropertyType "AcceptLanguage" ResourceUpdateConstraint = Value Prelude.Text
set newValue ResourceUpdateConstraint {..}
= ResourceUpdateConstraint
{acceptLanguage = Prelude.pure newValue, ..}
instance Property "Description" ResourceUpdateConstraint where
type PropertyType "Description" ResourceUpdateConstraint = Value Prelude.Text
set newValue ResourceUpdateConstraint {..}
= ResourceUpdateConstraint
{description = Prelude.pure newValue, ..}
instance Property "PortfolioId" ResourceUpdateConstraint where
type PropertyType "PortfolioId" ResourceUpdateConstraint = Value Prelude.Text
set newValue ResourceUpdateConstraint {..}
= ResourceUpdateConstraint {portfolioId = newValue, ..}
instance Property "ProductId" ResourceUpdateConstraint where
type PropertyType "ProductId" ResourceUpdateConstraint = Value Prelude.Text
set newValue ResourceUpdateConstraint {..}
= ResourceUpdateConstraint {productId = newValue, ..}
instance Property "TagUpdateOnProvisionedProduct" ResourceUpdateConstraint where
type PropertyType "TagUpdateOnProvisionedProduct" ResourceUpdateConstraint = Value Prelude.Text
set newValue ResourceUpdateConstraint {..}
= ResourceUpdateConstraint
{tagUpdateOnProvisionedProduct = newValue, ..} | null | https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/servicecatalog/gen/Stratosphere/ServiceCatalog/ResourceUpdateConstraint.hs | haskell | module Stratosphere.ServiceCatalog.ResourceUpdateConstraint (
ResourceUpdateConstraint(..), mkResourceUpdateConstraint
) where
import qualified Data.Aeson as JSON
import qualified Stratosphere.Prelude as Prelude
import Stratosphere.Property
import Stratosphere.ResourceProperties
import Stratosphere.Value
data ResourceUpdateConstraint
= ResourceUpdateConstraint {acceptLanguage :: (Prelude.Maybe (Value Prelude.Text)),
description :: (Prelude.Maybe (Value Prelude.Text)),
portfolioId :: (Value Prelude.Text),
productId :: (Value Prelude.Text),
tagUpdateOnProvisionedProduct :: (Value Prelude.Text)}
mkResourceUpdateConstraint ::
Value Prelude.Text
-> Value Prelude.Text
-> Value Prelude.Text -> ResourceUpdateConstraint
mkResourceUpdateConstraint
portfolioId
productId
tagUpdateOnProvisionedProduct
= ResourceUpdateConstraint
{portfolioId = portfolioId, productId = productId,
tagUpdateOnProvisionedProduct = tagUpdateOnProvisionedProduct,
acceptLanguage = Prelude.Nothing, description = Prelude.Nothing}
instance ToResourceProperties ResourceUpdateConstraint where
toResourceProperties ResourceUpdateConstraint {..}
= ResourceProperties
{awsType = "AWS::ServiceCatalog::ResourceUpdateConstraint",
supportsTags = Prelude.False,
properties = Prelude.fromList
((Prelude.<>)
["PortfolioId" JSON..= portfolioId, "ProductId" JSON..= productId,
"TagUpdateOnProvisionedProduct"
JSON..= tagUpdateOnProvisionedProduct]
(Prelude.catMaybes
[(JSON..=) "AcceptLanguage" Prelude.<$> acceptLanguage,
(JSON..=) "Description" Prelude.<$> description]))}
instance JSON.ToJSON ResourceUpdateConstraint where
toJSON ResourceUpdateConstraint {..}
= JSON.object
(Prelude.fromList
((Prelude.<>)
["PortfolioId" JSON..= portfolioId, "ProductId" JSON..= productId,
"TagUpdateOnProvisionedProduct"
JSON..= tagUpdateOnProvisionedProduct]
(Prelude.catMaybes
[(JSON..=) "AcceptLanguage" Prelude.<$> acceptLanguage,
(JSON..=) "Description" Prelude.<$> description])))
instance Property "AcceptLanguage" ResourceUpdateConstraint where
type PropertyType "AcceptLanguage" ResourceUpdateConstraint = Value Prelude.Text
set newValue ResourceUpdateConstraint {..}
= ResourceUpdateConstraint
{acceptLanguage = Prelude.pure newValue, ..}
instance Property "Description" ResourceUpdateConstraint where
type PropertyType "Description" ResourceUpdateConstraint = Value Prelude.Text
set newValue ResourceUpdateConstraint {..}
= ResourceUpdateConstraint
{description = Prelude.pure newValue, ..}
instance Property "PortfolioId" ResourceUpdateConstraint where
type PropertyType "PortfolioId" ResourceUpdateConstraint = Value Prelude.Text
set newValue ResourceUpdateConstraint {..}
= ResourceUpdateConstraint {portfolioId = newValue, ..}
instance Property "ProductId" ResourceUpdateConstraint where
type PropertyType "ProductId" ResourceUpdateConstraint = Value Prelude.Text
set newValue ResourceUpdateConstraint {..}
= ResourceUpdateConstraint {productId = newValue, ..}
instance Property "TagUpdateOnProvisionedProduct" ResourceUpdateConstraint where
type PropertyType "TagUpdateOnProvisionedProduct" ResourceUpdateConstraint = Value Prelude.Text
set newValue ResourceUpdateConstraint {..}
= ResourceUpdateConstraint
{tagUpdateOnProvisionedProduct = newValue, ..} | |
258d80a6d4275055c1706d091b64c683a906dacf14371c08858d8cc180376f83 | airalab/hs-web3 | Query.hs | -- |
-- Module : Network.Polkadot.Query
Copyright : 2016 - 2021
-- License : Apache-2.0
--
-- Maintainer :
-- Stability : experimental
-- Portability : unportable
--
-- Query storage for internal data.
--
module Network.Polkadot.Query where
import Codec.Scale (Decode, decode)
import Data.ByteArray.HexString (HexString)
import Data.Text (Text)
import Network.JsonRpc.TinyClient (JsonRpc)
import Network.Polkadot.Metadata (Metadata (Metadata),
metadataTypes, toLatest)
import Network.Polkadot.Rpc.State (getMetadata, getStorage)
import Network.Polkadot.Storage (Storage, fromMetadata,
storageKey)
import Network.Polkadot.Storage.Key (Argument)
-- | Loads metadata from runtime and create storage type.
storage :: JsonRpc m => m (Either String Storage)
storage = (fmap go . decode) <$> getMetadata
where
go raw = let (meta, _) = metadataTypes raw in fromMetadata (toLatest meta)
| Query data from blockchain via ' getStorage ' RPC call .
query :: (JsonRpc m, Decode a)
=> Text
-- ^ Module name.
-> Text
-- ^ Storage method name.
-> [Argument]
-- ^ Arguments (for mappings).
-> m (Either String a)
-- ^ Decoded storage item.
# INLINE query #
query = query' Nothing
-- | Similar to 'query' but get block hash for query as an argument.
query' :: (JsonRpc m, Decode a)
=> Maybe HexString
-- ^ Block hash for query ('Nothing' for best block).
-> Text
-- ^ Module name.
-> Text
-- ^ Storage method name.
-> [Argument]
-- ^ Arguments (for mappings).
-> m (Either String a)
-- ^ Decoded storage item.
query' blockHash section method args = go =<< storage
where
go (Right store) = case storageKey store section method args of
Just key -> decode <$> getStorage key blockHash
Nothing -> return (Left "Unable to find given section/method or wrong argument count")
go (Left err) = return (Left err)
| null | https://raw.githubusercontent.com/airalab/hs-web3/c03b86eb621f963886a78c39ee18bcec753f17ac/packages/polkadot/src/Network/Polkadot/Query.hs | haskell | |
Module : Network.Polkadot.Query
License : Apache-2.0
Maintainer :
Stability : experimental
Portability : unportable
Query storage for internal data.
| Loads metadata from runtime and create storage type.
^ Module name.
^ Storage method name.
^ Arguments (for mappings).
^ Decoded storage item.
| Similar to 'query' but get block hash for query as an argument.
^ Block hash for query ('Nothing' for best block).
^ Module name.
^ Storage method name.
^ Arguments (for mappings).
^ Decoded storage item. | Copyright : 2016 - 2021
module Network.Polkadot.Query where
import Codec.Scale (Decode, decode)
import Data.ByteArray.HexString (HexString)
import Data.Text (Text)
import Network.JsonRpc.TinyClient (JsonRpc)
import Network.Polkadot.Metadata (Metadata (Metadata),
metadataTypes, toLatest)
import Network.Polkadot.Rpc.State (getMetadata, getStorage)
import Network.Polkadot.Storage (Storage, fromMetadata,
storageKey)
import Network.Polkadot.Storage.Key (Argument)
storage :: JsonRpc m => m (Either String Storage)
storage = (fmap go . decode) <$> getMetadata
where
go raw = let (meta, _) = metadataTypes raw in fromMetadata (toLatest meta)
| Query data from blockchain via ' getStorage ' RPC call .
query :: (JsonRpc m, Decode a)
=> Text
-> Text
-> [Argument]
-> m (Either String a)
# INLINE query #
query = query' Nothing
query' :: (JsonRpc m, Decode a)
=> Maybe HexString
-> Text
-> Text
-> [Argument]
-> m (Either String a)
query' blockHash section method args = go =<< storage
where
go (Right store) = case storageKey store section method args of
Just key -> decode <$> getStorage key blockHash
Nothing -> return (Left "Unable to find given section/method or wrong argument count")
go (Left err) = return (Left err)
|
5b8184541ad3f50bd58409ba8a1db299d498cd6ec89a7246d55687897eeb4087 | slipstream/SlipStreamServer | order.clj | (ns com.sixsq.slipstream.db.es-rest.order)
(def sort-order {:asc "asc"
:desc "desc"})
(defn direction->sort-order
"Returns the elasticsearch SortOrder constant associated with the :asc and
:desc keywords. Any other value for direction will result in an
IllegalArgumentException being thrown."
[direction]
(or (sort-order direction)
(throw (IllegalArgumentException. (str "invalid sorting direction '" direction "', must be :asc or :desc")))))
(defn sort-entry
"Give a tuple with the field-name and direction, adds the sort clause to the
request builder. Intended to be used in a reduction."
[[field-name direction]]
{field-name (direction->sort-order direction)})
(defn sorters
"Given the sorting information in the :cimi-params parameter, add all of the
sorting clauses to the sort map."
[{:keys [orderby] :as cimi-params}]
(let [entries (mapv sort-entry orderby)]
(when (seq entries)
{:sort entries})))
| null | https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/db-binding/src/com/sixsq/slipstream/db/es_rest/order.clj | clojure | (ns com.sixsq.slipstream.db.es-rest.order)
(def sort-order {:asc "asc"
:desc "desc"})
(defn direction->sort-order
"Returns the elasticsearch SortOrder constant associated with the :asc and
:desc keywords. Any other value for direction will result in an
IllegalArgumentException being thrown."
[direction]
(or (sort-order direction)
(throw (IllegalArgumentException. (str "invalid sorting direction '" direction "', must be :asc or :desc")))))
(defn sort-entry
"Give a tuple with the field-name and direction, adds the sort clause to the
request builder. Intended to be used in a reduction."
[[field-name direction]]
{field-name (direction->sort-order direction)})
(defn sorters
"Given the sorting information in the :cimi-params parameter, add all of the
sorting clauses to the sort map."
[{:keys [orderby] :as cimi-params}]
(let [entries (mapv sort-entry orderby)]
(when (seq entries)
{:sort entries})))
| |
2cc1c09892ba8ab4d061410059843d4b0d6391ac38ebb15a5bccecddcd04d3ea | gregr/experiments | terminal-ui.rkt | #lang racket
(provide
interact-with
ui-loop
)
(require
"database.rkt"
"editor.rkt"
"interaction-model.rkt"
"presentation.rkt"
"workspace-model.rkt"
gregr-misc/cursor
gregr-misc/dict
gregr-misc/list
gregr-misc/maybe
gregr-misc/monad
gregr-misc/sugar
gregr-misc/terminal
gregr-misc/ui
)
(module+ test
(require
rackunit
))
(define (commands->keymap commands)
(make-immutable-hash
(forl
(list char desc cmd) <- commands
(cons char cmd))))
(define (workspace->focus-interaction-name ws)
(match (workspace->focus-widget ws)
((just (interaction-widget name)) (just name))
(_ (nothing))))
(define (workspace->focus-commands ws-name ws db)
(maybe-fold '() (lambda (name) (interaction->commands ws-name name db))
(workspace->focus-interaction-name ws)))
(def (db->editor-commands ws-name db)
; TODO: specialized commands based on state
cmd-table =
`((#\n "new interaction" ,eci-interaction-new)
(#\e "extract closed term" ,(curry eci-paste-subterm #f))
(#\E "replacE closed term" ,(curry eci-paste-subterm #t))
(#\return "rename binder" ,(lambda (_) (eci-rename-binder-start)))
)
(forl
(list char desc instr) <- cmd-table
(list char desc (compose1 (curry editor-command ws-name) instr))))
(def (db->workspace-commands-top name db)
; TODO: specialized commands based on workspace state
;ws = (:.* db 'workspaces name)
cmd-table =
`((#\q "pane close" ,wci-widget-close)
(#\H "pane left" ,wci-widget-left)
(#\L "pane right" ,wci-widget-right)
(#\R "pane reverse" ,wci-widget-reverse))
(forl
(list char desc instr) <- cmd-table
(list char desc (compose1 (curry workspace-command name) instr))))
(def (db->workspace-commands name db)
ws = (:.* db 'workspaces name)
editor-cmds = (db->editor-commands name db)
ws-top-cmds = (db->workspace-commands-top name db)
widget-cmds = (workspace->focus-commands name ws db)
cmds->char-assoc = (lambda (cmds)
(forl
cmd <- cmds
(list char _ _) = cmd
(cons char cmd)))
cmds-merge1 = (fn (cmds0 cmds1)
(list a0 a1) = (map cmds->char-assoc (list cmds0 cmds1))
a1 = (dict-subtract a1 a0)
(append* (map (curry map cdr) (list a0 a1))))
(cmds-merge1 editor-cmds (cmds-merge1 ws-top-cmds widget-cmds)))
(def ((event->workspace-command ws-name) db (keypress-cmd char count))
cmds = (db->workspace-commands ws-name db)
keymap = (commands->keymap cmds)
(begin/with-monad maybe-monad
cmd-new <- (dict-get keymap char)
(pure (cmd-new count))))
(define (interaction->commands ws-name name db)
; TODO: specialized commands based on interaction state
(forl
(list char desc instr) <-
`((#\h "traverse left" ,ici-traverse-left)
(#\j "traverse down" ,ici-traverse-down)
(#\k "traverse up" ,ici-traverse-up)
(#\l "traverse right" ,ici-traverse-right)
(#\i "move to next {}" ,ici-traverse-uno-next)
(#\I "move to prev {}" ,ici-traverse-uno-prev)
(#\space "jump to binder" ,(lambda (_) (ici-traverse-binder)))
(#\S "substitute completely" ,(lambda (_) (ici-substitute-complete)))
(#\s "step" ,ici-step)
(#\C "step completely" ,(lambda (_) (ici-step-complete)))
(#\c "close over free vars" ,(lambda (_) (ici-edit (ici-edit-close))))
(#\D "delete" ,(lambda (_) (ici-edit (ici-edit-delete))))
(#\d "delete outermost" ,(compose1 ici-edit ici-edit-trim))
(#\t "toggle" ,(compose1 ici-edit ici-edit-toggle))
(#\T "toggle reverse" ,(compose1 ici-edit ici-edit-toggle -))
(#\a "wrap lam" ,(compose ici-edit (curry ici-edit-wrap (ici-wrap-lam))))
(#\A "wrap apply"
,(compose1 ici-edit (curry ici-edit-wrap (ici-wrap-apply))))
(#\p "wrap pair"
,(compose1 ici-edit (curry ici-edit-wrap (ici-wrap-pair))))
(#\P "wrap pair-access"
,(compose1 ici-edit (curry ici-edit-wrap (ici-wrap-pair-access))))
(#\x "toggle-syntax" ,(lambda (_) (ici-toggle-syntax)))
(#\u "undo" ,ici-undo)
(#\U "redo" ,ici-redo))
(list char desc
(compose1 (curry interaction-command ws-name name) instr))))
(module+ test
(require (submod "database.rkt" test-support))
(define test-dbs (test-dbs-new interaction-widget))
(define test-db-0 (list-ref test-dbs 0))
(define test-db-1 (list-ref test-dbs 1))
(check-equal?
(list->string (map car (db->workspace-commands 'one test-db-1)))
"neE\rqHLRhjkliI SsCcDdtTaApPxuU"
))
(module+ test
(check-equal?
(lets
event->cmd = (event->workspace-command 'one)
(list
(event->cmd test-db-0 (keypress-cmd #\j 3))
(event->cmd test-db-1 (keypress-cmd #\j 3))
(event->cmd test-db-0 (keypress-cmd #\q 2))
))
(list
(nothing)
(just (interaction-command 'one 1 (ici-traverse-down 3)))
(just (workspace-command 'one (wci-widget-close 2)))
)))
(define (cmdchar->string char)
(match char
(#\return "ENTER")
(#\space "SPACE")
(_ (string-append (list->string (list char)) " "))))
(define (commands->desc commands)
(forl
(list char desc action) <- commands
(list (cmdchar->string char) desc)))
(def (workspace-preview name db)
ws = (:.* db 'workspaces name)
(list widgets fidx msg) = (map (curry :.* ws)
'(layout focus-index notification))
cmds = (db->workspace-commands name db)
cmd-desc = (commands->desc cmds)
idocs =
(forl
(interaction-widget iname) <- widgets
iaction = (:.* db 'interactions iname)
(list stx nav) = (map (curry :.* iaction) '(syntax nav))
nav->doc = (match stx
((isyntax-raw) nav-term-lifted-old->doc)
((isyntax-pretty) nav-term-lifted->doc))
(delay (nav->doc nav)))
(list msg cmd-desc fidx idocs))
(def (workspace-preview->str-thunk (list msg cmd-desc fidx idocs))
(thunk (view->string (tabular-view msg cmd-desc fidx idocs))))
(define (ui-loop ws-name db)
(define event-chan (make-channel))
(define display-chan (make-channel))
(define react (compose1 (lambda (_) (channel-get event-chan))
(curry channel-put display-chan)
workspace-preview->str-thunk
(curry workspace-preview ws-name)))
(define event->cmd (event->workspace-command ws-name))
(def (handle-events db (event-keypress char))
(values db (list ws result)) =
(:** db
kpm-path = `(workspaces ,ws-name keypress-mode)
:. kpmode kpm-path
(values kpmode result) = (keypress-add kpmode char)
:= kpmode kpm-path
:= (match result ((keypress-pending msg) msg) (_ ""))
`(workspaces ,ws-name notification)
:. ws `(workspaces ,ws-name)
(list ws result))
(match result
((keypress-cmd chr _)
(match (event->cmd db result)
((nothing)
(:=* db "invalid choice" 'workspaces ws-name 'notification))
((just cmd) (editor-update cmd db))))
((keypress-text-entry text)
(match (workspace->focus-interaction-name ws)
((nothing) db)
((just name)
(editor-update
(interaction-command
ws-name name (ici-rename-binder (string->symbol text))) db))))
(_ db)))
(define (loop db)
(if (empty? (:.* db 'workspaces ws-name 'layout))
"quitting: all interactions closed"
(loop (handle-events db (react db)))))
(with-cursor-hidden (with-stty-direct
(lets threads = (list (keypress-thread event-chan)
(display-view-thread 0.1 display-chan))
result = (loop db)
_ = (for-each kill-thread threads)
result))))
(def (interact-with terms)
ws-name = 'terminal-ui:interact-with
iactions = (map interaction-new terms)
ws = (workspace-new (map interaction-widget (range (length terms))))
db = (:** database-empty
:= ws `(workspaces ,ws-name)
:~+ (list->index-dict iactions) '(interactions))
(ui-loop ws-name db))
| null | https://raw.githubusercontent.com/gregr/experiments/cd4c7953f45102539081077bbd6195cf834ba2fa/supercompilation/cog/terminal-ui.rkt | racket | TODO: specialized commands based on state
TODO: specialized commands based on workspace state
ws = (:.* db 'workspaces name)
TODO: specialized commands based on interaction state | #lang racket
(provide
interact-with
ui-loop
)
(require
"database.rkt"
"editor.rkt"
"interaction-model.rkt"
"presentation.rkt"
"workspace-model.rkt"
gregr-misc/cursor
gregr-misc/dict
gregr-misc/list
gregr-misc/maybe
gregr-misc/monad
gregr-misc/sugar
gregr-misc/terminal
gregr-misc/ui
)
(module+ test
(require
rackunit
))
(define (commands->keymap commands)
(make-immutable-hash
(forl
(list char desc cmd) <- commands
(cons char cmd))))
(define (workspace->focus-interaction-name ws)
(match (workspace->focus-widget ws)
((just (interaction-widget name)) (just name))
(_ (nothing))))
(define (workspace->focus-commands ws-name ws db)
(maybe-fold '() (lambda (name) (interaction->commands ws-name name db))
(workspace->focus-interaction-name ws)))
(def (db->editor-commands ws-name db)
cmd-table =
`((#\n "new interaction" ,eci-interaction-new)
(#\e "extract closed term" ,(curry eci-paste-subterm #f))
(#\E "replacE closed term" ,(curry eci-paste-subterm #t))
(#\return "rename binder" ,(lambda (_) (eci-rename-binder-start)))
)
(forl
(list char desc instr) <- cmd-table
(list char desc (compose1 (curry editor-command ws-name) instr))))
(def (db->workspace-commands-top name db)
cmd-table =
`((#\q "pane close" ,wci-widget-close)
(#\H "pane left" ,wci-widget-left)
(#\L "pane right" ,wci-widget-right)
(#\R "pane reverse" ,wci-widget-reverse))
(forl
(list char desc instr) <- cmd-table
(list char desc (compose1 (curry workspace-command name) instr))))
(def (db->workspace-commands name db)
ws = (:.* db 'workspaces name)
editor-cmds = (db->editor-commands name db)
ws-top-cmds = (db->workspace-commands-top name db)
widget-cmds = (workspace->focus-commands name ws db)
cmds->char-assoc = (lambda (cmds)
(forl
cmd <- cmds
(list char _ _) = cmd
(cons char cmd)))
cmds-merge1 = (fn (cmds0 cmds1)
(list a0 a1) = (map cmds->char-assoc (list cmds0 cmds1))
a1 = (dict-subtract a1 a0)
(append* (map (curry map cdr) (list a0 a1))))
(cmds-merge1 editor-cmds (cmds-merge1 ws-top-cmds widget-cmds)))
(def ((event->workspace-command ws-name) db (keypress-cmd char count))
cmds = (db->workspace-commands ws-name db)
keymap = (commands->keymap cmds)
(begin/with-monad maybe-monad
cmd-new <- (dict-get keymap char)
(pure (cmd-new count))))
(define (interaction->commands ws-name name db)
(forl
(list char desc instr) <-
`((#\h "traverse left" ,ici-traverse-left)
(#\j "traverse down" ,ici-traverse-down)
(#\k "traverse up" ,ici-traverse-up)
(#\l "traverse right" ,ici-traverse-right)
(#\i "move to next {}" ,ici-traverse-uno-next)
(#\I "move to prev {}" ,ici-traverse-uno-prev)
(#\space "jump to binder" ,(lambda (_) (ici-traverse-binder)))
(#\S "substitute completely" ,(lambda (_) (ici-substitute-complete)))
(#\s "step" ,ici-step)
(#\C "step completely" ,(lambda (_) (ici-step-complete)))
(#\c "close over free vars" ,(lambda (_) (ici-edit (ici-edit-close))))
(#\D "delete" ,(lambda (_) (ici-edit (ici-edit-delete))))
(#\d "delete outermost" ,(compose1 ici-edit ici-edit-trim))
(#\t "toggle" ,(compose1 ici-edit ici-edit-toggle))
(#\T "toggle reverse" ,(compose1 ici-edit ici-edit-toggle -))
(#\a "wrap lam" ,(compose ici-edit (curry ici-edit-wrap (ici-wrap-lam))))
(#\A "wrap apply"
,(compose1 ici-edit (curry ici-edit-wrap (ici-wrap-apply))))
(#\p "wrap pair"
,(compose1 ici-edit (curry ici-edit-wrap (ici-wrap-pair))))
(#\P "wrap pair-access"
,(compose1 ici-edit (curry ici-edit-wrap (ici-wrap-pair-access))))
(#\x "toggle-syntax" ,(lambda (_) (ici-toggle-syntax)))
(#\u "undo" ,ici-undo)
(#\U "redo" ,ici-redo))
(list char desc
(compose1 (curry interaction-command ws-name name) instr))))
(module+ test
(require (submod "database.rkt" test-support))
(define test-dbs (test-dbs-new interaction-widget))
(define test-db-0 (list-ref test-dbs 0))
(define test-db-1 (list-ref test-dbs 1))
(check-equal?
(list->string (map car (db->workspace-commands 'one test-db-1)))
"neE\rqHLRhjkliI SsCcDdtTaApPxuU"
))
(module+ test
(check-equal?
(lets
event->cmd = (event->workspace-command 'one)
(list
(event->cmd test-db-0 (keypress-cmd #\j 3))
(event->cmd test-db-1 (keypress-cmd #\j 3))
(event->cmd test-db-0 (keypress-cmd #\q 2))
))
(list
(nothing)
(just (interaction-command 'one 1 (ici-traverse-down 3)))
(just (workspace-command 'one (wci-widget-close 2)))
)))
(define (cmdchar->string char)
(match char
(#\return "ENTER")
(#\space "SPACE")
(_ (string-append (list->string (list char)) " "))))
(define (commands->desc commands)
(forl
(list char desc action) <- commands
(list (cmdchar->string char) desc)))
(def (workspace-preview name db)
ws = (:.* db 'workspaces name)
(list widgets fidx msg) = (map (curry :.* ws)
'(layout focus-index notification))
cmds = (db->workspace-commands name db)
cmd-desc = (commands->desc cmds)
idocs =
(forl
(interaction-widget iname) <- widgets
iaction = (:.* db 'interactions iname)
(list stx nav) = (map (curry :.* iaction) '(syntax nav))
nav->doc = (match stx
((isyntax-raw) nav-term-lifted-old->doc)
((isyntax-pretty) nav-term-lifted->doc))
(delay (nav->doc nav)))
(list msg cmd-desc fidx idocs))
(def (workspace-preview->str-thunk (list msg cmd-desc fidx idocs))
(thunk (view->string (tabular-view msg cmd-desc fidx idocs))))
(define (ui-loop ws-name db)
(define event-chan (make-channel))
(define display-chan (make-channel))
(define react (compose1 (lambda (_) (channel-get event-chan))
(curry channel-put display-chan)
workspace-preview->str-thunk
(curry workspace-preview ws-name)))
(define event->cmd (event->workspace-command ws-name))
(def (handle-events db (event-keypress char))
(values db (list ws result)) =
(:** db
kpm-path = `(workspaces ,ws-name keypress-mode)
:. kpmode kpm-path
(values kpmode result) = (keypress-add kpmode char)
:= kpmode kpm-path
:= (match result ((keypress-pending msg) msg) (_ ""))
`(workspaces ,ws-name notification)
:. ws `(workspaces ,ws-name)
(list ws result))
(match result
((keypress-cmd chr _)
(match (event->cmd db result)
((nothing)
(:=* db "invalid choice" 'workspaces ws-name 'notification))
((just cmd) (editor-update cmd db))))
((keypress-text-entry text)
(match (workspace->focus-interaction-name ws)
((nothing) db)
((just name)
(editor-update
(interaction-command
ws-name name (ici-rename-binder (string->symbol text))) db))))
(_ db)))
(define (loop db)
(if (empty? (:.* db 'workspaces ws-name 'layout))
"quitting: all interactions closed"
(loop (handle-events db (react db)))))
(with-cursor-hidden (with-stty-direct
(lets threads = (list (keypress-thread event-chan)
(display-view-thread 0.1 display-chan))
result = (loop db)
_ = (for-each kill-thread threads)
result))))
(def (interact-with terms)
ws-name = 'terminal-ui:interact-with
iactions = (map interaction-new terms)
ws = (workspace-new (map interaction-widget (range (length terms))))
db = (:** database-empty
:= ws `(workspaces ,ws-name)
:~+ (list->index-dict iactions) '(interactions))
(ui-loop ws-name db))
|
e0f4e5c4e9d163cc989e19100e03a0c9748478893b644e13b25ee210f7580d2d | anik545/OwlPPL | dist.ml | open Monad
exception Undefined
module Prob = Sigs.LogProb
type prob = Prob.t
type likelihood = Prob.t
open Prob
type 'a samples = ('a * prob) list
(* enable watching intermediate variables through plots *)
(* type 'a var_dist = string * 'a dist *)
type _ dist =
| Return : 'a -> 'a dist
(* bind is lazy since it contains a function *)
| Bind : 'a dist * ('a -> 'b dist) -> 'b dist
(* | Bind_var: 'a var_dist * ('a -> 'b dist) -> 'b dist *)
| Primitive : 'a Primitive.t -> 'a dist
| Conditional : ('a -> prob) * 'a dist -> 'a dist
| Independent : 'a dist * 'b dist -> ('a * 'b) dist
(* | Conditional: ('a -> float) * 'a var_dist -> 'a dist *)
(* | Observe: 'a Primitive.primitive * 'a * 'a dist -> 'a dist *)
(* TODO: uncomment + fix *)
(* | Independent : 'a dist * 'b dist -> ('a * 'b) dist *)
(* let observe x dst d = Observe(dst,x,d) *)
let condition' c d = Conditional (Core.Fn.compose of_float c, d)
let condition b d = Conditional ((fun _ -> if b then one else zero), d)
let score s d = Conditional ((fun _ -> of_float s), d)
let observe x dst d = Conditional ((fun _ -> of_float @@ Primitive.pdf dst x), d)
let from_primitive p = Primitive p
(* TODO: *)
let observe_list lst dst d = Core . List.fold_left ~f:(observe )
include Make_Extended (struct
type 'a t = 'a dist
let return x = Return x
let bind d f = Bind (d, f)
end)
(* let ( and* ) d1 d2 =
let* x = d1 in
let* y = d2 in
Return (x, y) *)
let ( and* ) d1 d2 = Independent (d1, d2)
let discrete_uniform xs = Primitive (Primitive.discrete_uniform xs)
let categorical xs =
(* Core.List.iter ~f:(fun (_, y) -> Printf.printf "%f," y) xs;
Printf.printf "\n"; *)
let xs =
Core.List.filter
~f:(fun (_, x) -> Float.is_finite (exp x) || Float.equal x 0.)
xs
in
(* let xs = Core.List.map ~f:(fun (a, x) -> (a, exp x)) xs in *)
let normalise xs =
let open Core in
let norm = List.sum (module Float) ~f:snd xs in
if Float.(norm = 0.) then
let p' = 1. /. float_of_int (List.length xs) in
List.map ~f:(fun (v, _) -> (v, p')) xs
else List.map ~f:(fun (v, p) -> (v, p /. norm)) xs
in
let xs = normalise xs in
(* Core.List.iter ~f:(fun (_, y) -> Printf.printf "%f," y) xs;
Printf.printf "\n"; *)
Primitive (Primitive.categorical xs)
let bernoulli p = categorical [ (true, p); (false, 1. -. p) ]
let choice p x y = Bind (bernoulli p, fun c -> if c then x else y)
let binomial n p = Primitive (Primitive.binomial n p)
(* continuous *)
let normal mu sigma = Primitive (Primitive.normal mu sigma)
let gamma shape scale = Primitive (Primitive.gamma shape scale)
let beta a b = Primitive (Primitive.beta a b)
let continuous_uniform a b = Primitive (Primitive.continuous_uniform a b)
let rec sample : type a. a dist -> a = function
| Return x -> x
| Bind (d, f) ->
let y = f (sample d) in
sample y
| Primitive d -> Primitive.sample d
| Independent (d1, d2) -> (sample d1, sample d2)
| Conditional (_, _) -> raise Undefined
| Independent ( d1,d2 ) - > sample d1 , sample d2
let rec sample_n : type a. int -> a dist -> a array =
fun n -> function
| Return x -> Array.init n (fun _ -> x)
| Bind (d, f) ->
let y = Array.map f (sample_n n d) in
Array.map sample y
| Primitive d -> Array.init n (fun _ -> Primitive.sample d)
| Conditional (_, _) -> raise Undefined
| Independent (d1, d2) -> Core.Array.zip_exn (sample_n n d1) (sample_n n d2)
(* same as sample (prior_with_score d) *)
let rec sample_with_score : type a. a dist -> a * likelihood = function
| Return x -> (x, one)
| Bind (d, f) ->
let y, s = sample_with_score d in
let a, s1 = sample_with_score (f y) in
(a, s *. s1)
| Primitive d ->
let x = Primitive.sample d in
(x, of_float @@ Primitive.pdf d x)
(* this instead?? *)
(* this is how its done in prior - is it right??? *)
| Primitive d - > let x = Primitive.sample d in ( x , 1 . )
| Conditional (lik, d) ->
let x, s = sample_with_score d in
(x, s *. lik x)
| Independent (d1, d2) ->
let x1, s1 = sample_with_score d1 in
let x2, s2 = sample_with_score d2 in
((x1, x2), s1 *. s2)
let rec prior' : 'a. 'a dist -> 'a dist = function
| Conditional (_, d) -> prior' d
| Bind (d, f) -> Bind (prior' d, f)
| d -> d
let rec prior : 'a. 'a dist -> ('a * prob) dist = function
| Conditional (c, d) ->
let* x, s = prior d in
return (x, s *. c x)
| Bind (d, f) ->
let* x, s = prior d in
let* y = f x in
return (y, s)
| d ->
let* x = d in
return (x, one)
same as
let rec prior_with_score : type a. a dist -> (a * prob) dist = function
| Conditional (c, d) ->
let* x, s = prior_with_score d in
return (x, s *. c x)
| Bind (d, f) ->
let* x, s = prior_with_score d in
let* y, s1 = prior_with_score (f x) in
return (y, s *. s1)
| Primitive d ->
let* x = Primitive d in
return (x, of_float @@ Primitive.pdf d x)
| Return x -> return (x, one)
| Independent (d1, d2) ->
let* x, s1 = prior_with_score d1 and* y, s2 = prior_with_score d2 in
return ((x, y), s1 *. s2)
let dist_of_n_samples n (d : 'a dist) : 'a list dist =
sequence @@ Core.List.init n ~f:(fun _ -> d)
let rec support : type a. a dist -> a list = function
| Bind (d, f) ->
let supp = support d in
Core.List.concat_map ~f:(fun x -> support (f x)) supp
| Conditional (_, d) -> support d
| Primitive d -> (
match Primitive.support d with
| DiscreteFinite xs -> xs
| _ -> raise Undefined )
| Return x -> [ x ]
| Independent (d1, d2) -> Core.List.zip_exn (support d1) (support d2)
module PplOps = struct
let ( +~ ) = liftM2 Base.Int.( + )
let ( -~ ) = liftM2 ( - )
let ( *~ ) = liftM2 ( * )
let ( /~ ) = liftM2 ( / )
let ( +.~ ) = liftM2 Base.Float.( + )
let ( -.~ ) = liftM2 Base.Float.( - )
let ( *.~ ) = liftM2 Base.Float.( * )
let ( /.~ ) = liftM2 Base.Float.( / )
let ( &~ ) = liftM2 ( && )
let ( |~ ) = liftM2 ( || )
let not = liftM not
let ( ^~ ) = liftM2 ( ^ )
end
| null | https://raw.githubusercontent.com/anik545/OwlPPL/ad650219769d5f32564cc771d63c9a52289043a5/ppl/lib/dist.ml | ocaml | enable watching intermediate variables through plots
type 'a var_dist = string * 'a dist
bind is lazy since it contains a function
| Bind_var: 'a var_dist * ('a -> 'b dist) -> 'b dist
| Conditional: ('a -> float) * 'a var_dist -> 'a dist
| Observe: 'a Primitive.primitive * 'a * 'a dist -> 'a dist
TODO: uncomment + fix
| Independent : 'a dist * 'b dist -> ('a * 'b) dist
let observe x dst d = Observe(dst,x,d)
TODO:
let ( and* ) d1 d2 =
let* x = d1 in
let* y = d2 in
Return (x, y)
Core.List.iter ~f:(fun (_, y) -> Printf.printf "%f," y) xs;
Printf.printf "\n";
let xs = Core.List.map ~f:(fun (a, x) -> (a, exp x)) xs in
Core.List.iter ~f:(fun (_, y) -> Printf.printf "%f," y) xs;
Printf.printf "\n";
continuous
same as sample (prior_with_score d)
this instead??
this is how its done in prior - is it right??? | open Monad
exception Undefined
module Prob = Sigs.LogProb
type prob = Prob.t
type likelihood = Prob.t
open Prob
type 'a samples = ('a * prob) list
type _ dist =
| Return : 'a -> 'a dist
| Bind : 'a dist * ('a -> 'b dist) -> 'b dist
| Primitive : 'a Primitive.t -> 'a dist
| Conditional : ('a -> prob) * 'a dist -> 'a dist
| Independent : 'a dist * 'b dist -> ('a * 'b) dist
let condition' c d = Conditional (Core.Fn.compose of_float c, d)
let condition b d = Conditional ((fun _ -> if b then one else zero), d)
let score s d = Conditional ((fun _ -> of_float s), d)
let observe x dst d = Conditional ((fun _ -> of_float @@ Primitive.pdf dst x), d)
let from_primitive p = Primitive p
let observe_list lst dst d = Core . List.fold_left ~f:(observe )
include Make_Extended (struct
type 'a t = 'a dist
let return x = Return x
let bind d f = Bind (d, f)
end)
let ( and* ) d1 d2 = Independent (d1, d2)
let discrete_uniform xs = Primitive (Primitive.discrete_uniform xs)
let categorical xs =
let xs =
Core.List.filter
~f:(fun (_, x) -> Float.is_finite (exp x) || Float.equal x 0.)
xs
in
let normalise xs =
let open Core in
let norm = List.sum (module Float) ~f:snd xs in
if Float.(norm = 0.) then
let p' = 1. /. float_of_int (List.length xs) in
List.map ~f:(fun (v, _) -> (v, p')) xs
else List.map ~f:(fun (v, p) -> (v, p /. norm)) xs
in
let xs = normalise xs in
Primitive (Primitive.categorical xs)
let bernoulli p = categorical [ (true, p); (false, 1. -. p) ]
let choice p x y = Bind (bernoulli p, fun c -> if c then x else y)
let binomial n p = Primitive (Primitive.binomial n p)
let normal mu sigma = Primitive (Primitive.normal mu sigma)
let gamma shape scale = Primitive (Primitive.gamma shape scale)
let beta a b = Primitive (Primitive.beta a b)
let continuous_uniform a b = Primitive (Primitive.continuous_uniform a b)
let rec sample : type a. a dist -> a = function
| Return x -> x
| Bind (d, f) ->
let y = f (sample d) in
sample y
| Primitive d -> Primitive.sample d
| Independent (d1, d2) -> (sample d1, sample d2)
| Conditional (_, _) -> raise Undefined
| Independent ( d1,d2 ) - > sample d1 , sample d2
let rec sample_n : type a. int -> a dist -> a array =
fun n -> function
| Return x -> Array.init n (fun _ -> x)
| Bind (d, f) ->
let y = Array.map f (sample_n n d) in
Array.map sample y
| Primitive d -> Array.init n (fun _ -> Primitive.sample d)
| Conditional (_, _) -> raise Undefined
| Independent (d1, d2) -> Core.Array.zip_exn (sample_n n d1) (sample_n n d2)
let rec sample_with_score : type a. a dist -> a * likelihood = function
| Return x -> (x, one)
| Bind (d, f) ->
let y, s = sample_with_score d in
let a, s1 = sample_with_score (f y) in
(a, s *. s1)
| Primitive d ->
let x = Primitive.sample d in
(x, of_float @@ Primitive.pdf d x)
| Primitive d - > let x = Primitive.sample d in ( x , 1 . )
| Conditional (lik, d) ->
let x, s = sample_with_score d in
(x, s *. lik x)
| Independent (d1, d2) ->
let x1, s1 = sample_with_score d1 in
let x2, s2 = sample_with_score d2 in
((x1, x2), s1 *. s2)
let rec prior' : 'a. 'a dist -> 'a dist = function
| Conditional (_, d) -> prior' d
| Bind (d, f) -> Bind (prior' d, f)
| d -> d
let rec prior : 'a. 'a dist -> ('a * prob) dist = function
| Conditional (c, d) ->
let* x, s = prior d in
return (x, s *. c x)
| Bind (d, f) ->
let* x, s = prior d in
let* y = f x in
return (y, s)
| d ->
let* x = d in
return (x, one)
same as
let rec prior_with_score : type a. a dist -> (a * prob) dist = function
| Conditional (c, d) ->
let* x, s = prior_with_score d in
return (x, s *. c x)
| Bind (d, f) ->
let* x, s = prior_with_score d in
let* y, s1 = prior_with_score (f x) in
return (y, s *. s1)
| Primitive d ->
let* x = Primitive d in
return (x, of_float @@ Primitive.pdf d x)
| Return x -> return (x, one)
| Independent (d1, d2) ->
let* x, s1 = prior_with_score d1 and* y, s2 = prior_with_score d2 in
return ((x, y), s1 *. s2)
let dist_of_n_samples n (d : 'a dist) : 'a list dist =
sequence @@ Core.List.init n ~f:(fun _ -> d)
let rec support : type a. a dist -> a list = function
| Bind (d, f) ->
let supp = support d in
Core.List.concat_map ~f:(fun x -> support (f x)) supp
| Conditional (_, d) -> support d
| Primitive d -> (
match Primitive.support d with
| DiscreteFinite xs -> xs
| _ -> raise Undefined )
| Return x -> [ x ]
| Independent (d1, d2) -> Core.List.zip_exn (support d1) (support d2)
module PplOps = struct
let ( +~ ) = liftM2 Base.Int.( + )
let ( -~ ) = liftM2 ( - )
let ( *~ ) = liftM2 ( * )
let ( /~ ) = liftM2 ( / )
let ( +.~ ) = liftM2 Base.Float.( + )
let ( -.~ ) = liftM2 Base.Float.( - )
let ( *.~ ) = liftM2 Base.Float.( * )
let ( /.~ ) = liftM2 Base.Float.( / )
let ( &~ ) = liftM2 ( && )
let ( |~ ) = liftM2 ( || )
let not = liftM not
let ( ^~ ) = liftM2 ( ^ )
end
|
f68d835fc4b735cda8ac33dbbfe8578041afb535e74cdfb89fb522902ed9d221 | spwhitton/consfigurator | sshd.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
Copyright ( C ) 2021 < >
;;; This file 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 , or ( at your option )
;;; any later version.
;;; This file is distributed in the hope that it will be useful,
;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
You should have received a copy of the GNU General Public License
;;; along with this program. If not, see </>.
(in-package :consfigurator.property.sshd)
(named-readtables:in-readtable :consfigurator)
;;;; Basic configuration
(defproplist installed :posix ()
"Install an OpenSSH server."
(:desc "OpenSSH server installed")
(os:etypecase
(debianlike (apt:installed "openssh-server"))))
(defprop configured :posix (&rest pairs)
"Set key--value pairs in /etc/ssh/sshd_config."
(:desc (format nil "sshd configured ~{~A ~A~^, ~}" pairs))
(:apply
(if (eql :no-change
(apply #'file:contains-conf-space "/etc/ssh/sshd_config" pairs))
:no-change
(service:reloaded "sshd"))))
(defprop no-passwords :posix ()
"Configure SSH to disallow password logins.
To prevent lockouts, also enables logging in as root with an SSH key, and
refuses to proceed if root has no authorized_keys."
(:desc "SSH passwords disabled")
(:apply
(assert-remote-euid-root)
(unless (and (remote-exists-p ".ssh/authorized_keys")
(plusp (length (read-remote-file ".ssh/authorized_keys"))))
(failed-change "root has no authorized_keys"))
(configured "PermitRootLogin" "prohibit-password"
"PasswordAuthentication" "no")))
;;;; Host keys
(defprop has-host-public-key :posix (type public-key)
"Records an SSH public key of type TYPE as identifying this host."
(:desc #?"Has SSH host key of type ${type}")
(:hostattrs (push-hostattr 'host-public-keys (cons type public-key))))
(defproplist has-host-key :posix (type public-key)
"Installs the host key whose public part is PUBLIC-KEY and is of type TYPE.
The private key is obtained as an item of prerequisite data."
(:desc #?"SSH host key of type ${type} installed")
(has-host-public-key type public-key)
(file:has-content (merge-pathnames (strcat "ssh_host_" type "_key.pub")
#P"/etc/ssh/")
public-key)
(file:host-secret-uploaded (merge-pathnames (strcat "ssh_host_" type "_key")
#P"/etc/ssh/")))
| null | https://raw.githubusercontent.com/spwhitton/consfigurator/3959be03083f1a9710546ef8dc0f4a645c0d2f9e/src/property/sshd.lisp | lisp | Consfigurator -- Lisp declarative configuration management system
This file is free software; you can redistribute it and/or modify
either version 3 , or ( at your option )
any later version.
This file 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 </>.
Basic configuration
Host keys |
Copyright ( C ) 2021 < >
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
(in-package :consfigurator.property.sshd)
(named-readtables:in-readtable :consfigurator)
(defproplist installed :posix ()
"Install an OpenSSH server."
(:desc "OpenSSH server installed")
(os:etypecase
(debianlike (apt:installed "openssh-server"))))
(defprop configured :posix (&rest pairs)
"Set key--value pairs in /etc/ssh/sshd_config."
(:desc (format nil "sshd configured ~{~A ~A~^, ~}" pairs))
(:apply
(if (eql :no-change
(apply #'file:contains-conf-space "/etc/ssh/sshd_config" pairs))
:no-change
(service:reloaded "sshd"))))
(defprop no-passwords :posix ()
"Configure SSH to disallow password logins.
To prevent lockouts, also enables logging in as root with an SSH key, and
refuses to proceed if root has no authorized_keys."
(:desc "SSH passwords disabled")
(:apply
(assert-remote-euid-root)
(unless (and (remote-exists-p ".ssh/authorized_keys")
(plusp (length (read-remote-file ".ssh/authorized_keys"))))
(failed-change "root has no authorized_keys"))
(configured "PermitRootLogin" "prohibit-password"
"PasswordAuthentication" "no")))
(defprop has-host-public-key :posix (type public-key)
"Records an SSH public key of type TYPE as identifying this host."
(:desc #?"Has SSH host key of type ${type}")
(:hostattrs (push-hostattr 'host-public-keys (cons type public-key))))
(defproplist has-host-key :posix (type public-key)
"Installs the host key whose public part is PUBLIC-KEY and is of type TYPE.
The private key is obtained as an item of prerequisite data."
(:desc #?"SSH host key of type ${type} installed")
(has-host-public-key type public-key)
(file:has-content (merge-pathnames (strcat "ssh_host_" type "_key.pub")
#P"/etc/ssh/")
public-key)
(file:host-secret-uploaded (merge-pathnames (strcat "ssh_host_" type "_key")
#P"/etc/ssh/")))
|
aaa964608bdcf10624af61a0ded442c8f5b4f54a25607be69fc6cc66b47397be | dfinity/motoko | variance.mli | open Mo_types
(* Variance of type variables *)
(*
Given a type, a variable is
* Bivariant if it has no occurrence
* Covariant if it only occurs in positive positions
* Contraviant if it only occurs in negative positions
* Invariant if it occurs in both positive and negative positions
*)
type t = Bivariant | Covariant | Contravariant | Invariant
(* `variances cons typ` maps each variable in `cons` to
its variance in `typ`
*)
val variances : Type.ConSet.t -> Type.typ -> t Type.ConEnv.t
| null | https://raw.githubusercontent.com/dfinity/motoko/399b8e8b0b47890388cd38ee0ace7638d9092b1a/src/mo_frontend/variance.mli | ocaml | Variance of type variables
Given a type, a variable is
* Bivariant if it has no occurrence
* Covariant if it only occurs in positive positions
* Contraviant if it only occurs in negative positions
* Invariant if it occurs in both positive and negative positions
`variances cons typ` maps each variable in `cons` to
its variance in `typ`
| open Mo_types
type t = Bivariant | Covariant | Contravariant | Invariant
val variances : Type.ConSet.t -> Type.typ -> t Type.ConEnv.t
|
8fba61f4ec5eeaff96b52c2f1db03f5e3f71e61fedf5e5a8185e7c5446a15635 | lemmih/lhc | SimpleInline.hs | module Language.Haskell.Crux.SimpleInline
( simpleInline ) where
import Control.Monad.Reader
import Control.Monad.RWS (RWS, evalRWS)
import Control.Monad.State (gets, modify)
import Control.Monad.Writer (listen, tell)
import Data.Array
import Data.Graph
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Language.Haskell.Crux
import Language.Haskell.Crux.FreeVariables
SCC
-- inline everything & analyse whether current function can be inlined later
-- Functions can be inlineable iff:
They do not refer to any functons .
-- They only use their arguments once.
-- They are only used once.
-- Functions can be inlined iff:
-- They are called with all arguments supplied.
simpleInline :: Module -> Module
simpleInline m =
m{cruxDecls = fst (evalRWS (mapM worker flatDecls) emptyEnv emptyState) }
where
emptyEnv = Map.empty
emptyState = State 1 Map.empty Set.empty
(graph, fromVertex) = graphFromEdges'
[ (decl, declName decl, Set.toList free)
| decl <- cruxDecls m
, let free = freeVariablesDecl decl ]
graph' = transposeG graph
isOneShot v =
case graph'!v of
[] -> True
[_] -> True
_ -> False
flatDecls = topSort graph'
worker v = do
let (decl,_,_) = fromVertex v
name = declName decl
(args, body) = splitArguments (declBody decl)
(decl', usage) <- listen (uniqueDecl decl)
when (mayInline usage (isOneShot v)) $
modify $ \st ->
st{ stInline = Map.insert name (args, body) (stInline st) }
pure decl'
mayInline :: Cost -> Bool -> Bool
mayInline (Cheap n) _isOneShot | n < 20 = True
mayInline Expensive True = True
mayInline _ _ = False
splitArguments :: Expr -> ([Variable], Expr)
splitArguments (Lam vars e) = (vars, e)
-- splitArguments (WithCoercion _ e) = splitArguments e
splitArguments e = ([], e)
type Env = Map Name Expr
data State = State
{ stUnique :: Int
, stInline :: Map Name ([Variable], Expr)
, stCheap :: Set Name
}
data Cost = Prohibitive | Expensive | Cheap Int deriving (Eq,Show)
instance Semigroup Cost where
Cheap a <> Cheap b = Cheap (a+b)
_ <> Prohibitive = Prohibitive
Prohibitive <> _ = Prohibitive
_ <> _ = Expensive
instance Monoid Cost where
mempty = Cheap 0
mappend = (<>)
type M a = RWS Env Cost State a
uniqueDecl :: Declaration -> M Declaration
uniqueDecl decl = do
body <- uniqueExpr (declBody decl)
return decl{declBody = body}
uniqueExpr :: Expr -> M Expr
uniqueExpr expr = do
tell (Cheap 1)
case expr of
_ | (Var var, args) <- collectApp expr -> do
inline <- gets stInline
case Map.lookup (varName var) inline of
Nothing -> do
core <- uniqueVariable var
foldl App core <$> mapM uniqueExpr args
Just (fnArgs, fnBody)
| length fnArgs <= length args -> do
args' <- mapM uniqueExpr args
replaceMany (zip fnArgs args') $
uniqueExpr (foldl App fnBody (drop (length fnArgs) args'))
| otherwise -> do
core <- uniqueVariable var
foldl App core <$> mapM uniqueExpr args
Var var -> uniqueVariable var
Con name -> pure $ Con name
UnboxedTuple args ->
UnboxedTuple <$> mapM uniqueExpr args
Lit lit -> pure $ Lit lit
WithExternal out retS fn args st e ->
bind out $ \out' ->
bind retS $ \retS' ->
WithExternal out' retS' fn
<$> mapM uniqueExpr args
<*> uniqueExpr st
<*> uniqueExpr e
ExternalPure out fn args e ->
bind out $ \out' ->
ExternalPure out' fn
<$> mapM uniqueExpr args
<*> uniqueExpr e
App a b -> App <$> uniqueExpr a <*> uniqueExpr b
Lam vars e -> bindMany vars $ \vars' ->
Lam vars' <$> uniqueExpr e
Let (NonRec v e) body -> bind v $ \v' ->
Let <$> (NonRec v' <$> uniqueExpr e)
<*> uniqueExpr body
Let (Rec binds) body -> bindMany (map fst binds) $ \vars -> do
defs <- mapM uniqueExpr (map snd binds)
Let (Rec $ zip vars defs) <$> uniqueExpr body
LetStrict v e rest ->
bind v $ \v' ->
LetStrict v' <$> uniqueExpr e <*> uniqueExpr rest
Case e scrut mbDef alts -> do
e' <- uniqueExpr e
bind scrut $ \scrut' ->
Case
<$> pure e'
<*> pure scrut'
<*> uniqueMaybe uniqueExpr mbDef
<*> mapM uniqueAlt alts
Convert e ty ->
Convert <$> uniqueExpr e <*> pure ty
Cast -> pure Cast
uniqueAlt :: Alt -> M Alt
uniqueAlt (Alt pattern e) =
case pattern of
ConPat con vars -> bindMany vars $ \vars' ->
Alt (ConPat con vars') <$> uniqueExpr e
LitPat lit ->
Alt (LitPat lit) <$> uniqueExpr e
UnboxedPat vars -> bindMany vars $ \vars' ->
Alt (UnboxedPat vars') <$> uniqueExpr e
uniqueVariable :: Variable -> M Expr
uniqueVariable var@(Variable name _ty) = do
env <- ask
case Map.lookup name env of
Nothing -> do
consume var
pure (Var var)
Just expr -> pure expr
-- Just expr -> do
local ( Map.delete name ) $ uniqueExpr expr
collectApp :: Expr -> (Expr, [Expr])
collectApp = worker []
where
worker acc expr =
case expr of
App a b -> worker (b:acc) a
WithCoercion _ e - > worker acc e
_ -> (expr, acc)
consume :: Variable -> M ()
consume var = do
cheap <- gets stCheap
unless (varName var `Set.member` cheap) $ tell Prohibitive
modify $ \st -> st{ stCheap = Set.delete (varName var) (stCheap st) }
bind :: Variable -> (Variable -> M a) -> M a
bind var action = do
name' <- newName (varName var)
let var' = var{varName = name'}
modify $ \st -> st{ stCheap = Set.insert name' (stCheap st) }
local
(Map.insert (varName var) (Var var'))
(action var')
bindMany :: [Variable] -> ([Variable] -> M a) -> M a
bindMany vars action = worker [] vars
where
worker acc [] = action (reverse acc)
worker acc (x:xs) = bind x $ \x' -> worker (x':acc) xs
replace :: Variable -> Expr -> M a -> M a
replace old new = local (Map.insert (varName old) new)
replaceMany :: [(Variable, Expr)] -> M a -> M a
replaceMany vars action = worker vars
where
worker [] = action
worker ((key,val):xs) = replace key val $ worker xs
: : Variable - > M Variable
v = do
-- u <- get
-- put (u+1)
-- return v{varName = (varName v){nameUnique = u}}
newName :: Name -> M Name
newName n = do
u <- gets stUnique
modify $ \st -> st{stUnique = (u+1)}
return n{nameUnique = u}
uniqueMaybe :: (a -> M a) -> Maybe a -> M (Maybe a)
uniqueMaybe _ Nothing = pure Nothing
uniqueMaybe fn (Just v) = Just <$> fn v
simpleInline : : Module - > Module
simpleInline m =
m{coreDecls = worker Map.empty flatDecls }
where
graph =
[ ( , declName , Set.toList free )
| decl < - coreDecls m
, let free = freeVariablesDecl decl ]
scc = stronglyConnComp graph
flatDecls = flattenSCCs scc
worker env [ ] = [ ]
worker env ( : decls ) =
let ( decl ' , env ' ) = inlineDecl env in ' : worker env ' decls
data Usage
= Unuable
| Using ( Set Name )
deriving ( Show )
instance Monoid Usage where
mempty = Using Set.empty
mappend Unuable b = Unuable
mappend a Unuable = Unuable
mappend ( Using a ) ( Using b )
| Set.null ( a ` Set.intersection ` b ) = Using ( Set.union a b )
| otherwise = Unuable
type Env = Map Name ( [ Variable ] , )
type M a = ReaderT Env ( Writer Usage ) a
inlineDecl : : Env - > Decl - > ( Decl , Env )
inlineDecl env decl = ( ' , env ' )
where
( body , usage ) = ( runReaderT ( inlineExpr ( declBody ) ) env )
decl ' = decl{declBody = body }
env ' = case usage of
Unuable - > env
Using vars
| Set.null vars - > Map.insert ( ) ( splitArguments body ) env
| otherwise - > env
splitArguments : : Expr - > ( [ Variable ] , )
splitArguments ( vars e ) = ( vars , e )
-- splitArguments ( WithCoercion _ e ) = splitArguments e
splitArguments e = ( [ ] , e )
inlineExpr : : Expr - > M Expr
inlineExpr expr =
case expr of
Con { } - > pure expr
UnboxedTuple args - >
UnboxedTuple < $ > mapM inlineExpr args
-- WithExternal Variable String [ Variable ] Variable Expr
-- ExternalPure Variable String [ Variable ] Expr
] e - > inlineExpr e
-- App ( ( v : vs ) body ) e - >
-- replace ( varName v ) e ( inlineExpr vs body )
vars e - >
vars < $ > dropUsages ( map varName vars ) ( inlineExpr e )
-- Let -- LetStrict Variable Case e scrut mbDef alts - >
Case < $ > inlineExpr e
< * > pure scrut
< * > dropUsage ( varName scrut ) ( inlineMaybe inlineExpr mbDef )
< * > dropUsage ( varName scrut ) ( mapM inlineAlt alts )
Cast e ty - >
Cast < $ > inlineExpr e < * > pure ty
-- WithCoercion c e - >
-- WithCoercion c < $ > inlineExpr e
_ | ( vars e , args ) < - collectApp expr - > do
let extraArgs = drop ( length vars ) args
replaceMany ( zip ( map varName vars ) args ) $ do
e ' < - inlineExpr e
pure $ foldl App e ' extraArgs
_ | ( , args ) < - collectApp expr - > do
mbInline < - lookupInline ( varName var )
case of
Nothing - > do
tell $ Using $ Set.singleton ( varName var )
args < - mapM inlineExpr args
pure $ foldl App ( ) args
Just ( fnArgs , fnBody )
| extraArgs < - drop ( length fnArgs ) args
, length fnArgs < = length args - >
replaceMany ( zip ( map varName fnArgs ) args ) $
-- noReplace ( varName var ) $
inlineExpr ( foldl )
| otherwise - > do
tell $ Using $ Set.singleton ( varName var )
args < - mapM inlineExpr args
pure $ foldl App ( ) args
App a b - >
App < $ > inlineExpr a < * > inlineExpr b
_ - > do
tell Unuable
pure expr
: : Alt - > M Alt
inlineAlt ( Alt pattern e ) =
case pattern of
ConPat _ name vars - > dropUsages ( map varName vars ) $
Alt pattern < $ > inlineExpr e
LitPat { } - >
Alt pattern < $ > inlineExpr e
UnboxedPat vars - >
dropUsages ( map varName vars ) $
Alt pattern < $ > inlineExpr e
lookupInline : : Name - > M ( Maybe ( [ Variable ] , ) )
lookupInline var = asks $ Map.lookup var
dropUsage : : Name - > M a - > M a
dropUsage var = censor fn
where
fn Unuable = Unuable
fn ( Using lst ) = Using $ Set.delete var lst
dropUsages : : [ Name ] - > M a - > M a
dropUsages vars = censor fn
where
fn Unuable = Unuable
fn ( Using lst ) = Using $ lst ` Set.difference ` Set.fromList vars
replace : : Name - > Expr - > M a - > M a
replace v e = local $ Map.insert v ( [ ] , e )
replaceMany : : [ ( Name , ) ] - > M a - > M a
replaceMany [ ] = i d
replaceMany ( ( v , ) = replace v e . replaceMany xs
-- noReplace : : Name - > M a - > M a
-- noReplace v = local $ Map.delete v
-- noReplaceMany : : [ Name ] - > M a - > M a
-- noReplaceMany [ ] = i d
-- noReplaceMany ( v : vs ) = noReplace v . noReplaceMany vs
collectApp : : Expr - > ( , [ Expr ] )
collectApp = worker [ ]
where
worker acc expr =
case expr of
App a b - > worker ( b : acc ) a
-- WithCoercion _ e - > worker acc e
_ - > ( expr , acc )
inlineMaybe : : ( a - > M a ) - > Maybe a - > M ( Maybe a )
inlineMaybe _ Nothing = pure Nothing
inlineMaybe fn ( Just v ) = Just < $ > fn v
simpleInline :: Module -> Module
simpleInline m =
m{coreDecls = worker Map.empty flatDecls}
where
graph =
[ (decl, declName decl, Set.toList free)
| decl <- coreDecls m
, let free = freeVariablesDecl decl ]
scc = stronglyConnComp graph
flatDecls = flattenSCCs scc
worker env [] = []
worker env (decl:decls) =
let (decl', env') = inlineDecl env decl
in decl' : worker env' decls
data Usage
= Unuable
| Using (Set Name)
deriving (Show)
instance Monoid Usage where
mempty = Using Set.empty
mappend Unuable b = Unuable
mappend a Unuable = Unuable
mappend (Using a) (Using b)
| Set.null (a `Set.intersection` b) = Using (Set.union a b)
| otherwise = Unuable
type Env = Map Name ([Variable], Expr)
type M a = ReaderT Env (Writer Usage) a
inlineDecl :: Env -> Decl -> (Decl, Env)
inlineDecl env decl = (decl', env')
where
(body, usage) = runWriter (runReaderT (inlineExpr (declBody decl)) env)
decl' = decl{declBody = body}
env' = case usage of
Unuable -> env
Using vars
| Set.null vars -> Map.insert (declName decl) (splitArguments body) env
| otherwise -> env
splitArguments :: Expr -> ([Variable], Expr)
splitArguments (Lam vars e) = (vars, e)
-- splitArguments (WithCoercion _ e) = splitArguments e
splitArguments e = ([], e)
inlineExpr :: Expr -> M Expr
inlineExpr expr =
case expr of
Con{} -> pure expr
UnboxedTuple args ->
UnboxedTuple <$> mapM inlineExpr args
-- WithExternal Variable String [Variable] Variable Expr
-- ExternalPure Variable String [Variable] Expr
-- Lam [] e -> inlineExpr e
-- App (Lam (v:vs) body) e ->
-- replace (varName v) e (inlineExpr $ Lam vs body)
Lam vars e ->
Lam vars <$> dropUsages (map varName vars) (inlineExpr e)
-- Let LetBind Expr
-- LetStrict Variable Expr Expr
Case e scrut mbDef alts ->
Case <$> inlineExpr e
<*> pure scrut
<*> dropUsage (varName scrut) (inlineMaybe inlineExpr mbDef)
<*> dropUsage (varName scrut) (mapM inlineAlt alts)
Cast e ty ->
Cast <$> inlineExpr e <*> pure ty
-- WithCoercion c e ->
-- WithCoercion c <$> inlineExpr e
_ | (Lam vars e, args) <- collectApp expr -> do
let extraArgs = drop (length vars) args
replaceMany (zip (map varName vars) args) $ do
e' <- inlineExpr e
pure $ foldl App e' extraArgs
_ | (Var var, args) <- collectApp expr -> do
mbInline <- lookupInline (varName var)
case mbInline of
Nothing -> do
tell $ Using $ Set.singleton (varName var)
args <- mapM inlineExpr args
pure $ foldl App (Var var) args
Just (fnArgs, fnBody)
| extraArgs <- drop (length fnArgs) args
, length fnArgs <= length args ->
replaceMany (zip (map varName fnArgs) args) $
-- noReplace (varName var) $
inlineExpr (foldl App fnBody extraArgs)
| otherwise -> do
tell $ Using $ Set.singleton (varName var)
args <- mapM inlineExpr args
pure $ foldl App (Var var) args
App a b ->
App <$> inlineExpr a <*> inlineExpr b
_ -> do
tell Unuable
pure expr
inlineAlt :: Alt -> M Alt
inlineAlt (Alt pattern e) =
case pattern of
ConPat _name vars -> dropUsages (map varName vars) $
Alt pattern <$> inlineExpr e
LitPat{} ->
Alt pattern <$> inlineExpr e
UnboxedPat vars ->
dropUsages (map varName vars) $
Alt pattern <$> inlineExpr e
lookupInline :: Name -> M (Maybe ([Variable], Expr))
lookupInline var = asks $ Map.lookup var
dropUsage :: Name -> M a -> M a
dropUsage var = censor fn
where
fn Unuable = Unuable
fn (Using lst) = Using $ Set.delete var lst
dropUsages :: [Name] -> M a -> M a
dropUsages vars = censor fn
where
fn Unuable = Unuable
fn (Using lst) = Using $ lst `Set.difference` Set.fromList vars
replace :: Name -> Expr -> M a -> M a
replace v e = local $ Map.insert v ([], e)
replaceMany :: [(Name, Expr)] -> M a -> M a
replaceMany [] = id
replaceMany ((v,e):xs) = replace v e . replaceMany xs
-- noReplace :: Name -> M a -> M a
-- noReplace v = local $ Map.delete v
-- noReplaceMany :: [Name] -> M a -> M a
-- noReplaceMany [] = id
-- noReplaceMany (v:vs) = noReplace v . noReplaceMany vs
collectApp :: Expr -> (Expr, [Expr])
collectApp = worker []
where
worker acc expr =
case expr of
App a b -> worker (b:acc) a
-- WithCoercion _ e -> worker acc e
_ -> (expr, acc)
inlineMaybe :: (a -> M a) -> Maybe a -> M (Maybe a)
inlineMaybe _ Nothing = pure Nothing
inlineMaybe fn (Just v) = Just <$> fn v
-}
| null | https://raw.githubusercontent.com/lemmih/lhc/53bfa57b9b7275b7737dcf9dd620533d0261be66/haskell-crux/src/Language/Haskell/Crux/SimpleInline.hs | haskell | inline everything & analyse whether current function can be inlined later
Functions can be inlineable iff:
They only use their arguments once.
They are only used once.
Functions can be inlined iff:
They are called with all arguments supplied.
splitArguments (WithCoercion _ e) = splitArguments e
Just expr -> do
u <- get
put (u+1)
return v{varName = (varName v){nameUnique = u}}
splitArguments ( WithCoercion _ e ) = splitArguments e
WithExternal Variable String [ Variable ] Variable Expr
ExternalPure Variable String [ Variable ] Expr
App ( ( v : vs ) body ) e - >
replace ( varName v ) e ( inlineExpr vs body )
Let -- LetStrict Variable Case e scrut mbDef alts - >
WithCoercion c e - >
WithCoercion c < $ > inlineExpr e
noReplace ( varName var ) $
noReplace : : Name - > M a - > M a
noReplace v = local $ Map.delete v
noReplaceMany : : [ Name ] - > M a - > M a
noReplaceMany [ ] = i d
noReplaceMany ( v : vs ) = noReplace v . noReplaceMany vs
WithCoercion _ e - > worker acc e
splitArguments (WithCoercion _ e) = splitArguments e
WithExternal Variable String [Variable] Variable Expr
ExternalPure Variable String [Variable] Expr
Lam [] e -> inlineExpr e
App (Lam (v:vs) body) e ->
replace (varName v) e (inlineExpr $ Lam vs body)
Let LetBind Expr
LetStrict Variable Expr Expr
WithCoercion c e ->
WithCoercion c <$> inlineExpr e
noReplace (varName var) $
noReplace :: Name -> M a -> M a
noReplace v = local $ Map.delete v
noReplaceMany :: [Name] -> M a -> M a
noReplaceMany [] = id
noReplaceMany (v:vs) = noReplace v . noReplaceMany vs
WithCoercion _ e -> worker acc e | module Language.Haskell.Crux.SimpleInline
( simpleInline ) where
import Control.Monad.Reader
import Control.Monad.RWS (RWS, evalRWS)
import Control.Monad.State (gets, modify)
import Control.Monad.Writer (listen, tell)
import Data.Array
import Data.Graph
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Language.Haskell.Crux
import Language.Haskell.Crux.FreeVariables
SCC
They do not refer to any functons .
simpleInline :: Module -> Module
simpleInline m =
m{cruxDecls = fst (evalRWS (mapM worker flatDecls) emptyEnv emptyState) }
where
emptyEnv = Map.empty
emptyState = State 1 Map.empty Set.empty
(graph, fromVertex) = graphFromEdges'
[ (decl, declName decl, Set.toList free)
| decl <- cruxDecls m
, let free = freeVariablesDecl decl ]
graph' = transposeG graph
isOneShot v =
case graph'!v of
[] -> True
[_] -> True
_ -> False
flatDecls = topSort graph'
worker v = do
let (decl,_,_) = fromVertex v
name = declName decl
(args, body) = splitArguments (declBody decl)
(decl', usage) <- listen (uniqueDecl decl)
when (mayInline usage (isOneShot v)) $
modify $ \st ->
st{ stInline = Map.insert name (args, body) (stInline st) }
pure decl'
mayInline :: Cost -> Bool -> Bool
mayInline (Cheap n) _isOneShot | n < 20 = True
mayInline Expensive True = True
mayInline _ _ = False
splitArguments :: Expr -> ([Variable], Expr)
splitArguments (Lam vars e) = (vars, e)
splitArguments e = ([], e)
type Env = Map Name Expr
data State = State
{ stUnique :: Int
, stInline :: Map Name ([Variable], Expr)
, stCheap :: Set Name
}
data Cost = Prohibitive | Expensive | Cheap Int deriving (Eq,Show)
instance Semigroup Cost where
Cheap a <> Cheap b = Cheap (a+b)
_ <> Prohibitive = Prohibitive
Prohibitive <> _ = Prohibitive
_ <> _ = Expensive
instance Monoid Cost where
mempty = Cheap 0
mappend = (<>)
type M a = RWS Env Cost State a
uniqueDecl :: Declaration -> M Declaration
uniqueDecl decl = do
body <- uniqueExpr (declBody decl)
return decl{declBody = body}
uniqueExpr :: Expr -> M Expr
uniqueExpr expr = do
tell (Cheap 1)
case expr of
_ | (Var var, args) <- collectApp expr -> do
inline <- gets stInline
case Map.lookup (varName var) inline of
Nothing -> do
core <- uniqueVariable var
foldl App core <$> mapM uniqueExpr args
Just (fnArgs, fnBody)
| length fnArgs <= length args -> do
args' <- mapM uniqueExpr args
replaceMany (zip fnArgs args') $
uniqueExpr (foldl App fnBody (drop (length fnArgs) args'))
| otherwise -> do
core <- uniqueVariable var
foldl App core <$> mapM uniqueExpr args
Var var -> uniqueVariable var
Con name -> pure $ Con name
UnboxedTuple args ->
UnboxedTuple <$> mapM uniqueExpr args
Lit lit -> pure $ Lit lit
WithExternal out retS fn args st e ->
bind out $ \out' ->
bind retS $ \retS' ->
WithExternal out' retS' fn
<$> mapM uniqueExpr args
<*> uniqueExpr st
<*> uniqueExpr e
ExternalPure out fn args e ->
bind out $ \out' ->
ExternalPure out' fn
<$> mapM uniqueExpr args
<*> uniqueExpr e
App a b -> App <$> uniqueExpr a <*> uniqueExpr b
Lam vars e -> bindMany vars $ \vars' ->
Lam vars' <$> uniqueExpr e
Let (NonRec v e) body -> bind v $ \v' ->
Let <$> (NonRec v' <$> uniqueExpr e)
<*> uniqueExpr body
Let (Rec binds) body -> bindMany (map fst binds) $ \vars -> do
defs <- mapM uniqueExpr (map snd binds)
Let (Rec $ zip vars defs) <$> uniqueExpr body
LetStrict v e rest ->
bind v $ \v' ->
LetStrict v' <$> uniqueExpr e <*> uniqueExpr rest
Case e scrut mbDef alts -> do
e' <- uniqueExpr e
bind scrut $ \scrut' ->
Case
<$> pure e'
<*> pure scrut'
<*> uniqueMaybe uniqueExpr mbDef
<*> mapM uniqueAlt alts
Convert e ty ->
Convert <$> uniqueExpr e <*> pure ty
Cast -> pure Cast
uniqueAlt :: Alt -> M Alt
uniqueAlt (Alt pattern e) =
case pattern of
ConPat con vars -> bindMany vars $ \vars' ->
Alt (ConPat con vars') <$> uniqueExpr e
LitPat lit ->
Alt (LitPat lit) <$> uniqueExpr e
UnboxedPat vars -> bindMany vars $ \vars' ->
Alt (UnboxedPat vars') <$> uniqueExpr e
uniqueVariable :: Variable -> M Expr
uniqueVariable var@(Variable name _ty) = do
env <- ask
case Map.lookup name env of
Nothing -> do
consume var
pure (Var var)
Just expr -> pure expr
local ( Map.delete name ) $ uniqueExpr expr
collectApp :: Expr -> (Expr, [Expr])
collectApp = worker []
where
worker acc expr =
case expr of
App a b -> worker (b:acc) a
WithCoercion _ e - > worker acc e
_ -> (expr, acc)
consume :: Variable -> M ()
consume var = do
cheap <- gets stCheap
unless (varName var `Set.member` cheap) $ tell Prohibitive
modify $ \st -> st{ stCheap = Set.delete (varName var) (stCheap st) }
bind :: Variable -> (Variable -> M a) -> M a
bind var action = do
name' <- newName (varName var)
let var' = var{varName = name'}
modify $ \st -> st{ stCheap = Set.insert name' (stCheap st) }
local
(Map.insert (varName var) (Var var'))
(action var')
bindMany :: [Variable] -> ([Variable] -> M a) -> M a
bindMany vars action = worker [] vars
where
worker acc [] = action (reverse acc)
worker acc (x:xs) = bind x $ \x' -> worker (x':acc) xs
replace :: Variable -> Expr -> M a -> M a
replace old new = local (Map.insert (varName old) new)
replaceMany :: [(Variable, Expr)] -> M a -> M a
replaceMany vars action = worker vars
where
worker [] = action
worker ((key,val):xs) = replace key val $ worker xs
: : Variable - > M Variable
v = do
newName :: Name -> M Name
newName n = do
u <- gets stUnique
modify $ \st -> st{stUnique = (u+1)}
return n{nameUnique = u}
uniqueMaybe :: (a -> M a) -> Maybe a -> M (Maybe a)
uniqueMaybe _ Nothing = pure Nothing
uniqueMaybe fn (Just v) = Just <$> fn v
simpleInline : : Module - > Module
simpleInline m =
m{coreDecls = worker Map.empty flatDecls }
where
graph =
[ ( , declName , Set.toList free )
| decl < - coreDecls m
, let free = freeVariablesDecl decl ]
scc = stronglyConnComp graph
flatDecls = flattenSCCs scc
worker env [ ] = [ ]
worker env ( : decls ) =
let ( decl ' , env ' ) = inlineDecl env in ' : worker env ' decls
data Usage
= Unuable
| Using ( Set Name )
deriving ( Show )
instance Monoid Usage where
mempty = Using Set.empty
mappend Unuable b = Unuable
mappend a Unuable = Unuable
mappend ( Using a ) ( Using b )
| Set.null ( a ` Set.intersection ` b ) = Using ( Set.union a b )
| otherwise = Unuable
type Env = Map Name ( [ Variable ] , )
type M a = ReaderT Env ( Writer Usage ) a
inlineDecl : : Env - > Decl - > ( Decl , Env )
inlineDecl env decl = ( ' , env ' )
where
( body , usage ) = ( runReaderT ( inlineExpr ( declBody ) ) env )
decl ' = decl{declBody = body }
env ' = case usage of
Unuable - > env
Using vars
| Set.null vars - > Map.insert ( ) ( splitArguments body ) env
| otherwise - > env
splitArguments : : Expr - > ( [ Variable ] , )
splitArguments ( vars e ) = ( vars , e )
splitArguments e = ( [ ] , e )
inlineExpr : : Expr - > M Expr
inlineExpr expr =
case expr of
Con { } - > pure expr
UnboxedTuple args - >
UnboxedTuple < $ > mapM inlineExpr args
] e - > inlineExpr e
vars e - >
vars < $ > dropUsages ( map varName vars ) ( inlineExpr e )
Case < $ > inlineExpr e
< * > pure scrut
< * > dropUsage ( varName scrut ) ( inlineMaybe inlineExpr mbDef )
< * > dropUsage ( varName scrut ) ( mapM inlineAlt alts )
Cast e ty - >
Cast < $ > inlineExpr e < * > pure ty
_ | ( vars e , args ) < - collectApp expr - > do
let extraArgs = drop ( length vars ) args
replaceMany ( zip ( map varName vars ) args ) $ do
e ' < - inlineExpr e
pure $ foldl App e ' extraArgs
_ | ( , args ) < - collectApp expr - > do
mbInline < - lookupInline ( varName var )
case of
Nothing - > do
tell $ Using $ Set.singleton ( varName var )
args < - mapM inlineExpr args
pure $ foldl App ( ) args
Just ( fnArgs , fnBody )
| extraArgs < - drop ( length fnArgs ) args
, length fnArgs < = length args - >
replaceMany ( zip ( map varName fnArgs ) args ) $
inlineExpr ( foldl )
| otherwise - > do
tell $ Using $ Set.singleton ( varName var )
args < - mapM inlineExpr args
pure $ foldl App ( ) args
App a b - >
App < $ > inlineExpr a < * > inlineExpr b
_ - > do
tell Unuable
pure expr
: : Alt - > M Alt
inlineAlt ( Alt pattern e ) =
case pattern of
ConPat _ name vars - > dropUsages ( map varName vars ) $
Alt pattern < $ > inlineExpr e
LitPat { } - >
Alt pattern < $ > inlineExpr e
UnboxedPat vars - >
dropUsages ( map varName vars ) $
Alt pattern < $ > inlineExpr e
lookupInline : : Name - > M ( Maybe ( [ Variable ] , ) )
lookupInline var = asks $ Map.lookup var
dropUsage : : Name - > M a - > M a
dropUsage var = censor fn
where
fn Unuable = Unuable
fn ( Using lst ) = Using $ Set.delete var lst
dropUsages : : [ Name ] - > M a - > M a
dropUsages vars = censor fn
where
fn Unuable = Unuable
fn ( Using lst ) = Using $ lst ` Set.difference ` Set.fromList vars
replace : : Name - > Expr - > M a - > M a
replace v e = local $ Map.insert v ( [ ] , e )
replaceMany : : [ ( Name , ) ] - > M a - > M a
replaceMany [ ] = i d
replaceMany ( ( v , ) = replace v e . replaceMany xs
collectApp : : Expr - > ( , [ Expr ] )
collectApp = worker [ ]
where
worker acc expr =
case expr of
App a b - > worker ( b : acc ) a
_ - > ( expr , acc )
inlineMaybe : : ( a - > M a ) - > Maybe a - > M ( Maybe a )
inlineMaybe _ Nothing = pure Nothing
inlineMaybe fn ( Just v ) = Just < $ > fn v
simpleInline :: Module -> Module
simpleInline m =
m{coreDecls = worker Map.empty flatDecls}
where
graph =
[ (decl, declName decl, Set.toList free)
| decl <- coreDecls m
, let free = freeVariablesDecl decl ]
scc = stronglyConnComp graph
flatDecls = flattenSCCs scc
worker env [] = []
worker env (decl:decls) =
let (decl', env') = inlineDecl env decl
in decl' : worker env' decls
data Usage
= Unuable
| Using (Set Name)
deriving (Show)
instance Monoid Usage where
mempty = Using Set.empty
mappend Unuable b = Unuable
mappend a Unuable = Unuable
mappend (Using a) (Using b)
| Set.null (a `Set.intersection` b) = Using (Set.union a b)
| otherwise = Unuable
type Env = Map Name ([Variable], Expr)
type M a = ReaderT Env (Writer Usage) a
inlineDecl :: Env -> Decl -> (Decl, Env)
inlineDecl env decl = (decl', env')
where
(body, usage) = runWriter (runReaderT (inlineExpr (declBody decl)) env)
decl' = decl{declBody = body}
env' = case usage of
Unuable -> env
Using vars
| Set.null vars -> Map.insert (declName decl) (splitArguments body) env
| otherwise -> env
splitArguments :: Expr -> ([Variable], Expr)
splitArguments (Lam vars e) = (vars, e)
splitArguments e = ([], e)
inlineExpr :: Expr -> M Expr
inlineExpr expr =
case expr of
Con{} -> pure expr
UnboxedTuple args ->
UnboxedTuple <$> mapM inlineExpr args
Lam vars e ->
Lam vars <$> dropUsages (map varName vars) (inlineExpr e)
Case e scrut mbDef alts ->
Case <$> inlineExpr e
<*> pure scrut
<*> dropUsage (varName scrut) (inlineMaybe inlineExpr mbDef)
<*> dropUsage (varName scrut) (mapM inlineAlt alts)
Cast e ty ->
Cast <$> inlineExpr e <*> pure ty
_ | (Lam vars e, args) <- collectApp expr -> do
let extraArgs = drop (length vars) args
replaceMany (zip (map varName vars) args) $ do
e' <- inlineExpr e
pure $ foldl App e' extraArgs
_ | (Var var, args) <- collectApp expr -> do
mbInline <- lookupInline (varName var)
case mbInline of
Nothing -> do
tell $ Using $ Set.singleton (varName var)
args <- mapM inlineExpr args
pure $ foldl App (Var var) args
Just (fnArgs, fnBody)
| extraArgs <- drop (length fnArgs) args
, length fnArgs <= length args ->
replaceMany (zip (map varName fnArgs) args) $
inlineExpr (foldl App fnBody extraArgs)
| otherwise -> do
tell $ Using $ Set.singleton (varName var)
args <- mapM inlineExpr args
pure $ foldl App (Var var) args
App a b ->
App <$> inlineExpr a <*> inlineExpr b
_ -> do
tell Unuable
pure expr
inlineAlt :: Alt -> M Alt
inlineAlt (Alt pattern e) =
case pattern of
ConPat _name vars -> dropUsages (map varName vars) $
Alt pattern <$> inlineExpr e
LitPat{} ->
Alt pattern <$> inlineExpr e
UnboxedPat vars ->
dropUsages (map varName vars) $
Alt pattern <$> inlineExpr e
lookupInline :: Name -> M (Maybe ([Variable], Expr))
lookupInline var = asks $ Map.lookup var
dropUsage :: Name -> M a -> M a
dropUsage var = censor fn
where
fn Unuable = Unuable
fn (Using lst) = Using $ Set.delete var lst
dropUsages :: [Name] -> M a -> M a
dropUsages vars = censor fn
where
fn Unuable = Unuable
fn (Using lst) = Using $ lst `Set.difference` Set.fromList vars
replace :: Name -> Expr -> M a -> M a
replace v e = local $ Map.insert v ([], e)
replaceMany :: [(Name, Expr)] -> M a -> M a
replaceMany [] = id
replaceMany ((v,e):xs) = replace v e . replaceMany xs
collectApp :: Expr -> (Expr, [Expr])
collectApp = worker []
where
worker acc expr =
case expr of
App a b -> worker (b:acc) a
_ -> (expr, acc)
inlineMaybe :: (a -> M a) -> Maybe a -> M (Maybe a)
inlineMaybe _ Nothing = pure Nothing
inlineMaybe fn (Just v) = Just <$> fn v
-}
|
eab79880fb0922353b831c93a15ae2b415941112d7f81b00d69660e4edb1cebf | thheller/shadow-experiments | dom_scheduler.cljs | (ns shadow.experiments.arborist.dom-scheduler
(:require-macros [shadow.experiments.arborist.dom-scheduler]))
microtask based queue , maybe rAf ?
(def task-queue (js/Promise.resolve))
(def scheduled? false)
(def flushing? false)
(def read-tasks #js [])
(def write-tasks #js [])
(def update-tasks #js [])
(defn run-tasks! [^js arr]
;; (js/console.log "run-tasks!" (into [] arr))
(loop []
(when (pos? (alength arr))
(let [task (.pop arr)]
(task)
(recur)))))
(defn run-all! []
(when-not flushing?
(set! scheduled? false)
(set! flushing? true)
(run-tasks! read-tasks)
(run-tasks! write-tasks)
(run-tasks! update-tasks)
(set! flushing? false)))
(defn maybe-schedule! []
(when-not scheduled?
(set! scheduled? true)
(.then task-queue run-all!))
;; return task-queue so callers can .then additional stuff after their task?
;; not sure this will see too much use?
task-queue)
(defn read!! [cb]
(.push read-tasks cb)
(maybe-schedule!))
(defn write!! [cb]
(.push write-tasks cb)
(maybe-schedule!))
(defn after!! [cb]
(.push update-tasks cb)
(maybe-schedule!))
| null | https://raw.githubusercontent.com/thheller/shadow-experiments/a2170c2214778b6b9a9253166383396d64d395a4/src/main/shadow/experiments/arborist/dom_scheduler.cljs | clojure | (js/console.log "run-tasks!" (into [] arr))
return task-queue so callers can .then additional stuff after their task?
not sure this will see too much use? | (ns shadow.experiments.arborist.dom-scheduler
(:require-macros [shadow.experiments.arborist.dom-scheduler]))
microtask based queue , maybe rAf ?
(def task-queue (js/Promise.resolve))
(def scheduled? false)
(def flushing? false)
(def read-tasks #js [])
(def write-tasks #js [])
(def update-tasks #js [])
(defn run-tasks! [^js arr]
(loop []
(when (pos? (alength arr))
(let [task (.pop arr)]
(task)
(recur)))))
(defn run-all! []
(when-not flushing?
(set! scheduled? false)
(set! flushing? true)
(run-tasks! read-tasks)
(run-tasks! write-tasks)
(run-tasks! update-tasks)
(set! flushing? false)))
(defn maybe-schedule! []
(when-not scheduled?
(set! scheduled? true)
(.then task-queue run-all!))
task-queue)
(defn read!! [cb]
(.push read-tasks cb)
(maybe-schedule!))
(defn write!! [cb]
(.push write-tasks cb)
(maybe-schedule!))
(defn after!! [cb]
(.push update-tasks cb)
(maybe-schedule!))
|
c9b16f9eb947083ca417cac823b60456399078db1c292ffe172ff68aa12a6fbe | TerrorJack/ghc-alter | num004.hs | -- Exercising Numeric.readSigned a bit
--
module Main(main) where
import Numeric
import Data.Char
main =
let
rd :: ReadS Integer
rd = readSigned (readInt 10 (isDigit) (digitToInt))
in
do
print (rd (show (343023920121::Integer)))
print (rd (show (3430239::Int)))
print (rd (show (-0 :: Int)))
print (rd (show (591125662431 `div` (517::Int))))
print (rd (show (-111::Int)))
print (rd (show (232189458241::Integer)))
| null | https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/tests/Numeric/num004.hs | haskell | Exercising Numeric.readSigned a bit
| module Main(main) where
import Numeric
import Data.Char
main =
let
rd :: ReadS Integer
rd = readSigned (readInt 10 (isDigit) (digitToInt))
in
do
print (rd (show (343023920121::Integer)))
print (rd (show (3430239::Int)))
print (rd (show (-0 :: Int)))
print (rd (show (591125662431 `div` (517::Int))))
print (rd (show (-111::Int)))
print (rd (show (232189458241::Integer)))
|
350c1768eae50dae92f706d090707a84d2d2e754c690c84a2dae7025bd7acac5 | clojure-interop/google-cloud-clients | ProfileServiceStub.clj | (ns com.google.cloud.talent.v4beta1.stub.ProfileServiceStub
"Base stub class for Cloud Talent Solution API.
This class is for advanced usage and reflects the underlying API directly."
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.talent.v4beta1.stub ProfileServiceStub]))
(defn ->profile-service-stub
"Constructor."
(^ProfileServiceStub []
(new ProfileServiceStub )))
(defn search-profiles-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.SearchProfilesRequest,com.google.cloud.talent.v4beta1.ProfileServiceClient$SearchProfilesPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.searchProfilesPagedCallable))))
(defn list-profiles-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.ListProfilesRequest,com.google.cloud.talent.v4beta1.ProfileServiceClient$ListProfilesPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.listProfilesPagedCallable))))
(defn update-profile-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.UpdateProfileRequest,com.google.cloud.talent.v4beta1.Profile>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.updateProfileCallable))))
(defn delete-profile-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.DeleteProfileRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.deleteProfileCallable))))
(defn get-profile-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.GetProfileRequest,com.google.cloud.talent.v4beta1.Profile>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.getProfileCallable))))
(defn search-profiles-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.SearchProfilesRequest,com.google.cloud.talent.v4beta1.SearchProfilesResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.searchProfilesCallable))))
(defn list-profiles-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.ListProfilesRequest,com.google.cloud.talent.v4beta1.ListProfilesResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.listProfilesCallable))))
(defn close
""
([^ProfileServiceStub this]
(-> this (.close))))
(defn create-profile-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.CreateProfileRequest,com.google.cloud.talent.v4beta1.Profile>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.createProfileCallable))))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.talent/src/com/google/cloud/talent/v4beta1/stub/ProfileServiceStub.clj | clojure | (ns com.google.cloud.talent.v4beta1.stub.ProfileServiceStub
"Base stub class for Cloud Talent Solution API.
This class is for advanced usage and reflects the underlying API directly."
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.talent.v4beta1.stub ProfileServiceStub]))
(defn ->profile-service-stub
"Constructor."
(^ProfileServiceStub []
(new ProfileServiceStub )))
(defn search-profiles-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.SearchProfilesRequest,com.google.cloud.talent.v4beta1.ProfileServiceClient$SearchProfilesPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.searchProfilesPagedCallable))))
(defn list-profiles-paged-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.ListProfilesRequest,com.google.cloud.talent.v4beta1.ProfileServiceClient$ListProfilesPagedResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.listProfilesPagedCallable))))
(defn update-profile-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.UpdateProfileRequest,com.google.cloud.talent.v4beta1.Profile>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.updateProfileCallable))))
(defn delete-profile-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.DeleteProfileRequest,com.google.protobuf.Empty>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.deleteProfileCallable))))
(defn get-profile-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.GetProfileRequest,com.google.cloud.talent.v4beta1.Profile>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.getProfileCallable))))
(defn search-profiles-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.SearchProfilesRequest,com.google.cloud.talent.v4beta1.SearchProfilesResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.searchProfilesCallable))))
(defn list-profiles-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.ListProfilesRequest,com.google.cloud.talent.v4beta1.ListProfilesResponse>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.listProfilesCallable))))
(defn close
""
([^ProfileServiceStub this]
(-> this (.close))))
(defn create-profile-callable
"returns: `com.google.api.gax.rpc.UnaryCallable<com.google.cloud.talent.v4beta1.CreateProfileRequest,com.google.cloud.talent.v4beta1.Profile>`"
(^com.google.api.gax.rpc.UnaryCallable [^ProfileServiceStub this]
(-> this (.createProfileCallable))))
| |
1befd16d40438ac57de46451ee549c172eab1601be32178c353c672284d79d0f | owainlewis/ocaml-datastructures-algorithms | quick.ml | (* Quick sort *)
module type QUICK =
sig
val quick_sort : 'a list -> 'a list
end
module Sorting : QUICK = struct
let rec quick_sort = function
| [] -> []
| x::xs -> let smaller, larger = List.partition (fun y -> y < x) xs
in let x = (quick_sort smaller)
and y = (x::quick_sort larger)
in x @ y
end
| null | https://raw.githubusercontent.com/owainlewis/ocaml-datastructures-algorithms/4696fa4f5a015fc18e903b0b9ba2a1a8013a40ce/archive/quick.ml | ocaml | Quick sort | module type QUICK =
sig
val quick_sort : 'a list -> 'a list
end
module Sorting : QUICK = struct
let rec quick_sort = function
| [] -> []
| x::xs -> let smaller, larger = List.partition (fun y -> y < x) xs
in let x = (quick_sort smaller)
and y = (x::quick_sort larger)
in x @ y
end
|
29d5d2ad4abe99e01dd533125c155f7a696b52dbae8cdbe762eab273ff4108e2 | avsm/ocaml-ssh | printer_utils.ml |
* Copyright ( c ) 2009 Anil Madhavapeddy < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2009 Anil Madhavapeddy <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Printf
module Printer = struct
type env = {
fn: int -> string -> unit;
p: string -> unit; (* printer function *)
i: int; (* indent level *)
nl: unit -> unit; (* new line *)
dbg: bool;
}
let indent e = { e with i = succ e.i; p = e.fn (succ e.i) }
let indent_fn e fn =
let e = indent e in
fn e
let list_iter_indent e fn l =
List.iter (indent_fn e fn) l
let hashtbl_iter_indent e fn h =
Hashtbl.iter (indent_fn e fn) h
let may fn = function
|None -> ()
|Some x -> fn x
let must fn = function
|None -> failwith "must"
|Some x -> fn x
let init_printer ?(msg=None) ?(debug=false) fout =
let ind i s = String.make (i * 2) ' ' ^ s in
let out i s = output_string fout ((ind i s) ^ "\n") in
may (out 0) msg;
{
fn = out;
i = 0;
p = (out 0);
nl = (fun (x:unit) -> out 0 "");
dbg = debug;
}
let print_module e n fn =
e.p (sprintf "module %s = struct" (String.capitalize n));
indent_fn e fn;
e.p "end";
e.nl ()
let print_module_sig e n fn =
e.p (sprintf "module %s : sig" (String.capitalize n));
indent_fn e fn;
e.p "end"
let print_record e nm fn =
e.p (sprintf "type %s = {" nm);
indent_fn e fn;
e.p "}";
e.nl ()
let print_object e nm fn =
e.p (sprintf "type %s = <" nm);
indent_fn e fn;
e.p ">";
e.nl ()
let print_comment e fmt =
let xfn s = e.p ("(* " ^ s ^ " *)") in
kprintf xfn fmt
let print_ocamldoc e ?(raises="") ?(args="") body =
e.p (sprintf "(** %s%s" (match args with "" -> "" |x -> sprintf "[%s] " x) body);
(match raises with "" -> () |r -> e.p (" @raise " ^ r));
e.p " *)"
let pfn e fmt =
let xfn s = e.p s in
kprintf xfn fmt
let dbg e fmt =
let xfn s = if e.dbg then pfn e "print_endline (%s);" s in
kprintf xfn fmt
let (--*) = print_comment
let (-->) e fn = indent_fn e fn
let (+=) = pfn
let (-=) = dbg
let ($) f x = f x
end
| null | https://raw.githubusercontent.com/avsm/ocaml-ssh/26577d1501e7a43e4b520239b08da114c542eda4/mpl/printer_utils.ml | ocaml | printer function
indent level
new line |
* Copyright ( c ) 2009 Anil Madhavapeddy < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2009 Anil Madhavapeddy <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Printf
module Printer = struct
type env = {
fn: int -> string -> unit;
dbg: bool;
}
let indent e = { e with i = succ e.i; p = e.fn (succ e.i) }
let indent_fn e fn =
let e = indent e in
fn e
let list_iter_indent e fn l =
List.iter (indent_fn e fn) l
let hashtbl_iter_indent e fn h =
Hashtbl.iter (indent_fn e fn) h
let may fn = function
|None -> ()
|Some x -> fn x
let must fn = function
|None -> failwith "must"
|Some x -> fn x
let init_printer ?(msg=None) ?(debug=false) fout =
let ind i s = String.make (i * 2) ' ' ^ s in
let out i s = output_string fout ((ind i s) ^ "\n") in
may (out 0) msg;
{
fn = out;
i = 0;
p = (out 0);
nl = (fun (x:unit) -> out 0 "");
dbg = debug;
}
let print_module e n fn =
e.p (sprintf "module %s = struct" (String.capitalize n));
indent_fn e fn;
e.p "end";
e.nl ()
let print_module_sig e n fn =
e.p (sprintf "module %s : sig" (String.capitalize n));
indent_fn e fn;
e.p "end"
let print_record e nm fn =
e.p (sprintf "type %s = {" nm);
indent_fn e fn;
e.p "}";
e.nl ()
let print_object e nm fn =
e.p (sprintf "type %s = <" nm);
indent_fn e fn;
e.p ">";
e.nl ()
let print_comment e fmt =
let xfn s = e.p ("(* " ^ s ^ " *)") in
kprintf xfn fmt
let print_ocamldoc e ?(raises="") ?(args="") body =
e.p (sprintf "(** %s%s" (match args with "" -> "" |x -> sprintf "[%s] " x) body);
(match raises with "" -> () |r -> e.p (" @raise " ^ r));
e.p " *)"
let pfn e fmt =
let xfn s = e.p s in
kprintf xfn fmt
let dbg e fmt =
let xfn s = if e.dbg then pfn e "print_endline (%s);" s in
kprintf xfn fmt
let (--*) = print_comment
let (-->) e fn = indent_fn e fn
let (+=) = pfn
let (-=) = dbg
let ($) f x = f x
end
|
57acf9067cdc50e20ca65173d6aa3aab01c7746ea6efd8095111f5f1e71943be | death/zonquerer | game.lisp | ;;;; +----------------------------------------------------------------+
;;;; | zonquerer |
;;;; +----------------------------------------------------------------+
| Copyright ( C ) 2021 death |
;;;; | |
;;;; | This program is free software: you can redistribute it and/or |
| modify it under the terms of the GNU Affero General Public |
| License as published by the Free Software Foundation , either |
| version 3 of the License , or ( at your option ) any later |
;;;; | version. |
;;;; | |
;;;; | This program is distributed in the hope that it will be |
;;;; | useful, but WITHOUT ANY WARRANTY; without even the implied |
;;;; | warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR |
;;;; | PURPOSE. See the GNU Affero General Public License for more |
;;;; | details. |
;;;; | |
;;;; | You should have received a copy of the GNU Affero General |
;;;; | Public License along with this program. If not, see |
;;;; | </>. |
;;;; +----------------------------------------------------------------+
(defpackage #:zonquerer/game
(:use
#:cl
#:zonquerer/protocols
#:zonquerer/resources
#:zonquerer/utils)
(:import-from
#:sdl2)
(:import-from
#:autowrap)
(:import-from
#:deploy)
(:import-from
#:asdf)
(:export
#:standard-game
#:standard-event
#:driver))
(in-package #:zonquerer/game)
(defclass standard-game (game)
((video-dimensions :initform #C(320 200) :reader video-dimensions)
(window :initform nil :accessor window)
(renderer :initform nil :accessor renderer)
(keys :initform nil :accessor keys)
(mouse-position :initform #C(0 0) :accessor mouse-position)
(ticks :initform 0 :accessor ticks)
(current-cursor :initform nil :accessor current-cursor)
(next-cursor :initform nil :accessor next-cursor)
(resources :initform (make-hash-table :test 'equal) :reader resources)
(events :initform '() :accessor events)))
(defclass standard-event (event)
())
(defmethod push-event ((game standard-game) event)
(setf (events game) (nconc (events game) (list event))))
(defun pop-event (game)
(pop (events game)))
(defmethod process-event ((game standard-game) event dt)
(declare (ignore dt))
(warn "Unprocessed event ~S." event))
(defmethod assets-directory ((game standard-game))
(if (deploy:deployed-p)
#p"assets/"
(asdf:system-relative-pathname "zonquerer" "assets/")))
(defmethod find-resource ((game standard-game) kind name)
(gethash (list kind name) (resources game)))
(defmethod (setf find-resource) (resource (game standard-game) kind name)
(setf (gethash (list kind name) (resources game)) resource))
(defmethod free-all-resources ((game standard-game))
(let* ((resources (resources game))
(list (loop for resource being each hash-value of resources
collect resource)))
(dolist (resource list)
(free resource))
(assert (zerop (hash-table-count resources)))))
(defmethod remove-resource ((game standard-game) kind name)
(remhash (list kind name) (resources game)))
(defmethod update :before ((game standard-game) dt)
(loop for event = (pop-event game)
while event
do (process-event game event dt)))
(defmethod update :after ((game standard-game) dt)
(declare (ignore dt))
(when (member :scancode-escape (keys game))
(sdl2:push-quit-event)))
(defmethod draw :around ((game standard-game) dt)
(declare (ignore dt))
(let ((current-cursor (current-cursor game))
(next-cursor (next-cursor game)))
(when (not (eq current-cursor next-cursor))
(set-cursor game next-cursor)))
(let ((renderer (renderer game)))
(sdl2:set-render-draw-color renderer 0 0 0 255)
(sdl2:render-clear renderer)
(call-next-method)
(sdl2:render-present renderer)))
(defmethod mouse-event ((game standard-game) state button position)
;; Do nothing.
)
(defun window-event (game id)
(declare (ignore game id)))
(defmethod request-cursor ((game standard-game) name)
(setf (next-cursor game) name))
(defun set-cursor (game name)
(sdl2-ffi.functions:sdl-set-cursor
(external (intern-resource game 'cursor name)))
(setf (current-cursor game) name))
(defmethod game-loop ((game standard-game))
(setf (ticks game) (sdl2:get-ticks))
(sdl2:with-event-loop (:recursive t)
(:quit () t)
(:keydown
(:keysym keysym)
(let ((scancode (sdl2:scancode keysym)))
(pushnew scancode (keys game))))
(:keyup
(:keysym keysym)
(let ((scancode (sdl2:scancode keysym)))
(setf (keys game)
(delete scancode (keys game) :count 1))))
(:mousemotion
(:x x :y y)
(setf (mouse-position game) (point x y)))
(:mousebuttondown
(:button button :x x :y y)
(mouse-event game :down button (point x y)))
(:mousebuttonup
(:button button :x x :y y)
(mouse-event game :up button (point x y)))
(:idle
()
(let* ((ticks (sdl2:get-ticks))
(dt (* (- ticks (ticks game)) 1e-3)))
(setf (ticks game) ticks)
(update game dt)
(draw game dt)))
(:windowevent
(:event event)
(let ((id (autowrap:enum-key 'sdl2-ffi:sdl-window-event-id event)))
(window-event game id)))))
(defun driver (game)
(sdl2:with-init (:video)
(destructure-point (width height) (video-dimensions game)
(sdl2:with-window (window :w 0 :h 0 :flags '(:shown :fullscreen-desktop))
(sdl2:with-renderer (renderer window :flags '(:accelerated :presentvsync))
(sdl2-ffi.functions:sdl-set-hint sdl2-ffi:+sdl-hint-render-scale-quality+ "nearest")
(sdl2-ffi.functions:sdl-render-set-logical-size renderer width height)
(sdl2-ffi.functions:sdl-set-window-grab window :true)
(setf (window game) window)
(setf (renderer game) renderer)
(unwind-protect
(game-loop game)
(free-all-resources game))))))
game)
| null | https://raw.githubusercontent.com/death/zonquerer/2a0ff29b9d974fc66addb9126f1638f4d5d071cb/game.lisp | lisp | +----------------------------------------------------------------+
| zonquerer |
+----------------------------------------------------------------+
| |
| This program is free software: you can redistribute it and/or |
| version. |
| |
| This program is distributed in the hope that it will be |
| useful, but WITHOUT ANY WARRANTY; without even the implied |
| warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR |
| PURPOSE. See the GNU Affero General Public License for more |
| details. |
| |
| You should have received a copy of the GNU Affero General |
| Public License along with this program. If not, see |
| </>. |
+----------------------------------------------------------------+
Do nothing. | | Copyright ( C ) 2021 death |
| modify it under the terms of the GNU Affero General Public |
| License as published by the Free Software Foundation , either |
| version 3 of the License , or ( at your option ) any later |
(defpackage #:zonquerer/game
(:use
#:cl
#:zonquerer/protocols
#:zonquerer/resources
#:zonquerer/utils)
(:import-from
#:sdl2)
(:import-from
#:autowrap)
(:import-from
#:deploy)
(:import-from
#:asdf)
(:export
#:standard-game
#:standard-event
#:driver))
(in-package #:zonquerer/game)
(defclass standard-game (game)
((video-dimensions :initform #C(320 200) :reader video-dimensions)
(window :initform nil :accessor window)
(renderer :initform nil :accessor renderer)
(keys :initform nil :accessor keys)
(mouse-position :initform #C(0 0) :accessor mouse-position)
(ticks :initform 0 :accessor ticks)
(current-cursor :initform nil :accessor current-cursor)
(next-cursor :initform nil :accessor next-cursor)
(resources :initform (make-hash-table :test 'equal) :reader resources)
(events :initform '() :accessor events)))
(defclass standard-event (event)
())
(defmethod push-event ((game standard-game) event)
(setf (events game) (nconc (events game) (list event))))
(defun pop-event (game)
(pop (events game)))
(defmethod process-event ((game standard-game) event dt)
(declare (ignore dt))
(warn "Unprocessed event ~S." event))
(defmethod assets-directory ((game standard-game))
(if (deploy:deployed-p)
#p"assets/"
(asdf:system-relative-pathname "zonquerer" "assets/")))
(defmethod find-resource ((game standard-game) kind name)
(gethash (list kind name) (resources game)))
(defmethod (setf find-resource) (resource (game standard-game) kind name)
(setf (gethash (list kind name) (resources game)) resource))
(defmethod free-all-resources ((game standard-game))
(let* ((resources (resources game))
(list (loop for resource being each hash-value of resources
collect resource)))
(dolist (resource list)
(free resource))
(assert (zerop (hash-table-count resources)))))
(defmethod remove-resource ((game standard-game) kind name)
(remhash (list kind name) (resources game)))
(defmethod update :before ((game standard-game) dt)
(loop for event = (pop-event game)
while event
do (process-event game event dt)))
(defmethod update :after ((game standard-game) dt)
(declare (ignore dt))
(when (member :scancode-escape (keys game))
(sdl2:push-quit-event)))
(defmethod draw :around ((game standard-game) dt)
(declare (ignore dt))
(let ((current-cursor (current-cursor game))
(next-cursor (next-cursor game)))
(when (not (eq current-cursor next-cursor))
(set-cursor game next-cursor)))
(let ((renderer (renderer game)))
(sdl2:set-render-draw-color renderer 0 0 0 255)
(sdl2:render-clear renderer)
(call-next-method)
(sdl2:render-present renderer)))
(defmethod mouse-event ((game standard-game) state button position)
)
(defun window-event (game id)
(declare (ignore game id)))
(defmethod request-cursor ((game standard-game) name)
(setf (next-cursor game) name))
(defun set-cursor (game name)
(sdl2-ffi.functions:sdl-set-cursor
(external (intern-resource game 'cursor name)))
(setf (current-cursor game) name))
(defmethod game-loop ((game standard-game))
(setf (ticks game) (sdl2:get-ticks))
(sdl2:with-event-loop (:recursive t)
(:quit () t)
(:keydown
(:keysym keysym)
(let ((scancode (sdl2:scancode keysym)))
(pushnew scancode (keys game))))
(:keyup
(:keysym keysym)
(let ((scancode (sdl2:scancode keysym)))
(setf (keys game)
(delete scancode (keys game) :count 1))))
(:mousemotion
(:x x :y y)
(setf (mouse-position game) (point x y)))
(:mousebuttondown
(:button button :x x :y y)
(mouse-event game :down button (point x y)))
(:mousebuttonup
(:button button :x x :y y)
(mouse-event game :up button (point x y)))
(:idle
()
(let* ((ticks (sdl2:get-ticks))
(dt (* (- ticks (ticks game)) 1e-3)))
(setf (ticks game) ticks)
(update game dt)
(draw game dt)))
(:windowevent
(:event event)
(let ((id (autowrap:enum-key 'sdl2-ffi:sdl-window-event-id event)))
(window-event game id)))))
(defun driver (game)
(sdl2:with-init (:video)
(destructure-point (width height) (video-dimensions game)
(sdl2:with-window (window :w 0 :h 0 :flags '(:shown :fullscreen-desktop))
(sdl2:with-renderer (renderer window :flags '(:accelerated :presentvsync))
(sdl2-ffi.functions:sdl-set-hint sdl2-ffi:+sdl-hint-render-scale-quality+ "nearest")
(sdl2-ffi.functions:sdl-render-set-logical-size renderer width height)
(sdl2-ffi.functions:sdl-set-window-grab window :true)
(setf (window game) window)
(setf (renderer game) renderer)
(unwind-protect
(game-loop game)
(free-all-resources game))))))
game)
|
78f99b6f056410c298fce7f7e8033f76a9f144ad84bbaa4ce95dc8b4d9254c34 | input-output-hk/cardano-sl | Logic.hs | # LANGUAGE RecordWildCards #
-- | Main Toss logic.
module Pos.Chain.Ssc.Toss.Logic
( verifyAndApplySscPayload
, applyGenesisBlock
, rollbackSsc
, normalizeToss
, refreshToss
) where
import Universum hiding (id)
import Control.Lens (at)
import Control.Monad.Except (MonadError, runExceptT, throwError)
import Crypto.Random (MonadRandom)
import qualified Data.HashMap.Strict as HM
import Pos.Chain.Block.IsHeader (IsMainHeader, headerSlotL)
import Pos.Chain.Genesis as Genesis (Config (..),
configSlotSecurityParam)
import Pos.Chain.Ssc.Commitment (SignedCommitment)
import Pos.Chain.Ssc.CommitmentsMap (CommitmentsMap (..),
getCommitmentsMap, mkCommitmentsMapUnsafe)
import Pos.Chain.Ssc.Error (SscVerifyError (..))
import Pos.Chain.Ssc.Functions (verifySscPayload)
import Pos.Chain.Ssc.Opening (Opening)
import Pos.Chain.Ssc.Payload (SscPayload (..), checkSscPayload, spVss)
import Pos.Chain.Ssc.SharesMap (InnerSharesMap)
import Pos.Chain.Ssc.Toss.Base (checkPayload)
import Pos.Chain.Ssc.Toss.Class (MonadToss (..), MonadTossEnv (..))
import Pos.Chain.Ssc.Toss.Types (TossModifier (..))
import Pos.Chain.Ssc.VssCertificate (VssCertificate)
import Pos.Chain.Ssc.VssCertificatesMap (getVssCertificatesMap,
mkVssCertificatesMapSingleton)
import Pos.Core (EpochIndex, EpochOrSlot (..), LocalSlotIndex,
SlotCount, SlotId (siSlot), StakeholderId, epochIndexL,
epochOrSlot, epochOrSlotPred, epochOrSlotToEnum,
getEpochOrSlot, getSlotIndex, mkCoin)
import Pos.Core.Chrono (NewestFirst (..))
import Pos.Util.AssertMode (inAssertMode)
import Pos.Util.Some (Some)
import Pos.Util.Util (sortWithMDesc)
import Pos.Util.Wlog (logError)
| Verify ' SscPayload ' with respect to data provided by
MonadToss . If data is valid it is also applied . Otherwise
SscVerifyError is thrown using ' MonadError ' type class .
verifyAndApplySscPayload
:: ( MonadToss m
, MonadTossEnv m
, MonadError SscVerifyError m
, MonadRandom m
)
=> Genesis.Config
-> Either EpochIndex (Some IsMainHeader)
-> SscPayload
-> m ()
verifyAndApplySscPayload genesisConfig eoh payload = do
-- Check the payload for internal consistency.
either (throwError . SscInvalidPayload)
pure
(checkSscPayload (configProtocolMagic genesisConfig) payload)
We ca n't trust payload from , so we must call
-- @verifySscPayload@.
whenLeft eoh $ const $ verifySscPayload genesisConfig eoh payload
-- We perform @verifySscPayload@ for block when we construct it
-- (in the 'recreateGenericBlock'). So this check is just in case.
NOTE : in block verification ` verifySscPayload ` on ` MainBlock ` is run
-- by `Pos.Block.BHelper.verifyMainBlock`
inAssertMode $
whenRight eoh $ const $ verifySscPayload genesisConfig eoh payload
let blockCerts = spVss payload
let curEpoch = either identity (^. epochIndexL) eoh
checkPayload genesisConfig curEpoch payload
-- Apply
case eoh of
Left _ -> pass
Right header -> do
let eos = EpochOrSlot $ Right $ header ^. headerSlotL
setEpochOrSlot eos
-- We can freely clear shares after 'slotSecurityParam' because
-- it's guaranteed that rollback on more than 'slotSecurityParam'
-- can't happen
let indexToCount :: LocalSlotIndex -> SlotCount
indexToCount = fromIntegral . getSlotIndex
let slot = epochOrSlot (const 0) (indexToCount . siSlot) eos
slotSecurityParam = configSlotSecurityParam genesisConfig
when (slotSecurityParam <= slot && slot < 2 * slotSecurityParam) $
resetShares
mapM_ putCertificate blockCerts
case payload of
CommitmentsPayload comms _ ->
mapM_ putCommitment $ toList $ getCommitmentsMap comms
OpeningsPayload opens _ ->
mapM_ (uncurry putOpening) $ HM.toList opens
SharesPayload shares _ ->
mapM_ (uncurry putShares) $ HM.toList shares
CertificatesPayload _ ->
pass
-- | Apply genesis block for given epoch to 'Toss' state.
applyGenesisBlock :: MonadToss m => EpochIndex -> m ()
applyGenesisBlock epoch = do
setEpochOrSlot $ getEpochOrSlot epoch
-- We don't clear shares on genesis block because
-- there aren't 'slotSecurityParam' slots after shares phase,
-- so we won't have shares after rollback
We store shares until ' slotSecurityParam ' slots of next epoch passed
-- and clear their after that
resetCO
| Rollback application of ' SscPayload 's in ' Toss ' . First argument is
-- 'EpochOrSlot' of oldest block which is subject to rollback.
rollbackSsc
:: MonadToss m
=> SlotCount
-> EpochOrSlot
-> NewestFirst [] SscPayload
-> m ()
rollbackSsc epochSlots oldestEOS (NewestFirst payloads)
| oldestEOS == epochOrSlotToEnum epochSlots 0 = do
logError "rollbackSsc: most genesis block is passed to rollback"
setEpochOrSlot oldestEOS
resetCO
resetShares
| otherwise = do
setEpochOrSlot (epochOrSlotPred epochSlots oldestEOS)
mapM_ rollbackSscDo payloads
where
rollbackSscDo (CommitmentsPayload comms _) =
mapM_ delCommitment $ HM.keys $ getCommitmentsMap comms
rollbackSscDo (OpeningsPayload opens _) = mapM_ delOpening $ HM.keys opens
rollbackSscDo (SharesPayload shares _) = mapM_ delShares $ HM.keys shares
rollbackSscDo (CertificatesPayload _) = pass
| Apply as much data from given ' TossModifier ' as possible .
normalizeToss
:: (MonadToss m, MonadTossEnv m, MonadRandom m)
=> Genesis.Config
-> EpochIndex
-> TossModifier
-> m ()
normalizeToss genesisConfig epoch TossModifier {..} =
normalizeTossDo
genesisConfig
epoch
( HM.toList (getCommitmentsMap _tmCommitments)
, HM.toList _tmOpenings
, HM.toList _tmShares
, HM.toList (getVssCertificatesMap _tmCertificates))
| Apply the most valuable from given ' TossModifier ' and drop the
rest . This function can be used if is exhausted .
refreshToss
:: (MonadToss m, MonadTossEnv m, MonadRandom m)
=> Genesis.Config
-> EpochIndex
-> TossModifier
-> m ()
refreshToss genesisConfig epoch TossModifier {..} = do
comms <-
takeMostValuable epoch (HM.toList (getCommitmentsMap _tmCommitments))
opens <- takeMostValuable epoch (HM.toList _tmOpenings)
shares <- takeMostValuable epoch (HM.toList _tmShares)
certs <- takeMostValuable epoch (HM.toList (getVssCertificatesMap _tmCertificates))
normalizeTossDo genesisConfig epoch (comms, opens, shares, certs)
takeMostValuable
:: (MonadToss m, MonadTossEnv m)
=> EpochIndex
-> [(StakeholderId, x)]
-> m [(StakeholderId, x)]
takeMostValuable epoch items = take toTake <$> sortWithMDesc resolver items
where
toTake = 2 * length items `div` 3
resolver (id, _) =
fromMaybe (mkCoin 0) . (view (at id)) . fromMaybe mempty <$>
getRichmen epoch
type TossModifierLists
= ( [(StakeholderId, SignedCommitment)]
, [(StakeholderId, Opening)]
, [(StakeholderId, InnerSharesMap)]
, [(StakeholderId, VssCertificate)])
normalizeTossDo
:: forall m
. (MonadToss m, MonadTossEnv m, MonadRandom m)
=> Genesis.Config
-> EpochIndex
-> TossModifierLists
-> m ()
normalizeTossDo genesisConfig epoch (comms, opens, shares, certs) = do
putsUseful $
map (flip CommitmentsPayload mempty . mkCommitmentsMapUnsafe . one) $
comms
putsUseful $ map (flip OpeningsPayload mempty . one) opens
putsUseful $ map (flip SharesPayload mempty . one) shares
putsUseful $ map (CertificatesPayload . mkVssCertificatesMapSingleton . snd) certs
where
putsUseful :: [SscPayload] -> m ()
putsUseful entries = do
let verifyAndApply = runExceptT . verifyAndApplySscPayload genesisConfig
(Left epoch)
mapM_ verifyAndApply entries
| null | https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/chain/src/Pos/Chain/Ssc/Toss/Logic.hs | haskell | | Main Toss logic.
Check the payload for internal consistency.
@verifySscPayload@.
We perform @verifySscPayload@ for block when we construct it
(in the 'recreateGenericBlock'). So this check is just in case.
by `Pos.Block.BHelper.verifyMainBlock`
Apply
We can freely clear shares after 'slotSecurityParam' because
it's guaranteed that rollback on more than 'slotSecurityParam'
can't happen
| Apply genesis block for given epoch to 'Toss' state.
We don't clear shares on genesis block because
there aren't 'slotSecurityParam' slots after shares phase,
so we won't have shares after rollback
and clear their after that
'EpochOrSlot' of oldest block which is subject to rollback. | # LANGUAGE RecordWildCards #
module Pos.Chain.Ssc.Toss.Logic
( verifyAndApplySscPayload
, applyGenesisBlock
, rollbackSsc
, normalizeToss
, refreshToss
) where
import Universum hiding (id)
import Control.Lens (at)
import Control.Monad.Except (MonadError, runExceptT, throwError)
import Crypto.Random (MonadRandom)
import qualified Data.HashMap.Strict as HM
import Pos.Chain.Block.IsHeader (IsMainHeader, headerSlotL)
import Pos.Chain.Genesis as Genesis (Config (..),
configSlotSecurityParam)
import Pos.Chain.Ssc.Commitment (SignedCommitment)
import Pos.Chain.Ssc.CommitmentsMap (CommitmentsMap (..),
getCommitmentsMap, mkCommitmentsMapUnsafe)
import Pos.Chain.Ssc.Error (SscVerifyError (..))
import Pos.Chain.Ssc.Functions (verifySscPayload)
import Pos.Chain.Ssc.Opening (Opening)
import Pos.Chain.Ssc.Payload (SscPayload (..), checkSscPayload, spVss)
import Pos.Chain.Ssc.SharesMap (InnerSharesMap)
import Pos.Chain.Ssc.Toss.Base (checkPayload)
import Pos.Chain.Ssc.Toss.Class (MonadToss (..), MonadTossEnv (..))
import Pos.Chain.Ssc.Toss.Types (TossModifier (..))
import Pos.Chain.Ssc.VssCertificate (VssCertificate)
import Pos.Chain.Ssc.VssCertificatesMap (getVssCertificatesMap,
mkVssCertificatesMapSingleton)
import Pos.Core (EpochIndex, EpochOrSlot (..), LocalSlotIndex,
SlotCount, SlotId (siSlot), StakeholderId, epochIndexL,
epochOrSlot, epochOrSlotPred, epochOrSlotToEnum,
getEpochOrSlot, getSlotIndex, mkCoin)
import Pos.Core.Chrono (NewestFirst (..))
import Pos.Util.AssertMode (inAssertMode)
import Pos.Util.Some (Some)
import Pos.Util.Util (sortWithMDesc)
import Pos.Util.Wlog (logError)
| Verify ' SscPayload ' with respect to data provided by
MonadToss . If data is valid it is also applied . Otherwise
SscVerifyError is thrown using ' MonadError ' type class .
verifyAndApplySscPayload
:: ( MonadToss m
, MonadTossEnv m
, MonadError SscVerifyError m
, MonadRandom m
)
=> Genesis.Config
-> Either EpochIndex (Some IsMainHeader)
-> SscPayload
-> m ()
verifyAndApplySscPayload genesisConfig eoh payload = do
either (throwError . SscInvalidPayload)
pure
(checkSscPayload (configProtocolMagic genesisConfig) payload)
We ca n't trust payload from , so we must call
whenLeft eoh $ const $ verifySscPayload genesisConfig eoh payload
NOTE : in block verification ` verifySscPayload ` on ` MainBlock ` is run
inAssertMode $
whenRight eoh $ const $ verifySscPayload genesisConfig eoh payload
let blockCerts = spVss payload
let curEpoch = either identity (^. epochIndexL) eoh
checkPayload genesisConfig curEpoch payload
case eoh of
Left _ -> pass
Right header -> do
let eos = EpochOrSlot $ Right $ header ^. headerSlotL
setEpochOrSlot eos
let indexToCount :: LocalSlotIndex -> SlotCount
indexToCount = fromIntegral . getSlotIndex
let slot = epochOrSlot (const 0) (indexToCount . siSlot) eos
slotSecurityParam = configSlotSecurityParam genesisConfig
when (slotSecurityParam <= slot && slot < 2 * slotSecurityParam) $
resetShares
mapM_ putCertificate blockCerts
case payload of
CommitmentsPayload comms _ ->
mapM_ putCommitment $ toList $ getCommitmentsMap comms
OpeningsPayload opens _ ->
mapM_ (uncurry putOpening) $ HM.toList opens
SharesPayload shares _ ->
mapM_ (uncurry putShares) $ HM.toList shares
CertificatesPayload _ ->
pass
applyGenesisBlock :: MonadToss m => EpochIndex -> m ()
applyGenesisBlock epoch = do
setEpochOrSlot $ getEpochOrSlot epoch
We store shares until ' slotSecurityParam ' slots of next epoch passed
resetCO
| Rollback application of ' SscPayload 's in ' Toss ' . First argument is
rollbackSsc
:: MonadToss m
=> SlotCount
-> EpochOrSlot
-> NewestFirst [] SscPayload
-> m ()
rollbackSsc epochSlots oldestEOS (NewestFirst payloads)
| oldestEOS == epochOrSlotToEnum epochSlots 0 = do
logError "rollbackSsc: most genesis block is passed to rollback"
setEpochOrSlot oldestEOS
resetCO
resetShares
| otherwise = do
setEpochOrSlot (epochOrSlotPred epochSlots oldestEOS)
mapM_ rollbackSscDo payloads
where
rollbackSscDo (CommitmentsPayload comms _) =
mapM_ delCommitment $ HM.keys $ getCommitmentsMap comms
rollbackSscDo (OpeningsPayload opens _) = mapM_ delOpening $ HM.keys opens
rollbackSscDo (SharesPayload shares _) = mapM_ delShares $ HM.keys shares
rollbackSscDo (CertificatesPayload _) = pass
| Apply as much data from given ' TossModifier ' as possible .
normalizeToss
:: (MonadToss m, MonadTossEnv m, MonadRandom m)
=> Genesis.Config
-> EpochIndex
-> TossModifier
-> m ()
normalizeToss genesisConfig epoch TossModifier {..} =
normalizeTossDo
genesisConfig
epoch
( HM.toList (getCommitmentsMap _tmCommitments)
, HM.toList _tmOpenings
, HM.toList _tmShares
, HM.toList (getVssCertificatesMap _tmCertificates))
| Apply the most valuable from given ' TossModifier ' and drop the
rest . This function can be used if is exhausted .
refreshToss
:: (MonadToss m, MonadTossEnv m, MonadRandom m)
=> Genesis.Config
-> EpochIndex
-> TossModifier
-> m ()
refreshToss genesisConfig epoch TossModifier {..} = do
comms <-
takeMostValuable epoch (HM.toList (getCommitmentsMap _tmCommitments))
opens <- takeMostValuable epoch (HM.toList _tmOpenings)
shares <- takeMostValuable epoch (HM.toList _tmShares)
certs <- takeMostValuable epoch (HM.toList (getVssCertificatesMap _tmCertificates))
normalizeTossDo genesisConfig epoch (comms, opens, shares, certs)
takeMostValuable
:: (MonadToss m, MonadTossEnv m)
=> EpochIndex
-> [(StakeholderId, x)]
-> m [(StakeholderId, x)]
takeMostValuable epoch items = take toTake <$> sortWithMDesc resolver items
where
toTake = 2 * length items `div` 3
resolver (id, _) =
fromMaybe (mkCoin 0) . (view (at id)) . fromMaybe mempty <$>
getRichmen epoch
type TossModifierLists
= ( [(StakeholderId, SignedCommitment)]
, [(StakeholderId, Opening)]
, [(StakeholderId, InnerSharesMap)]
, [(StakeholderId, VssCertificate)])
normalizeTossDo
:: forall m
. (MonadToss m, MonadTossEnv m, MonadRandom m)
=> Genesis.Config
-> EpochIndex
-> TossModifierLists
-> m ()
normalizeTossDo genesisConfig epoch (comms, opens, shares, certs) = do
putsUseful $
map (flip CommitmentsPayload mempty . mkCommitmentsMapUnsafe . one) $
comms
putsUseful $ map (flip OpeningsPayload mempty . one) opens
putsUseful $ map (flip SharesPayload mempty . one) shares
putsUseful $ map (CertificatesPayload . mkVssCertificatesMapSingleton . snd) certs
where
putsUseful :: [SscPayload] -> m ()
putsUseful entries = do
let verifyAndApply = runExceptT . verifyAndApplySscPayload genesisConfig
(Left epoch)
mapM_ verifyAndApply entries
|
d19d114277a224e4351925a32b1d54e69b6f2552cb5447ee112a601f4b233fd1 | Bogdanp/marionette | json.rkt | #lang racket/base
(require (for-syntax racket/base)
json
racket/match)
(provide
json-null?
js-null)
(define (json-null? v)
(eq? v (json-null)))
(define-match-expander js-null
(lambda (stx)
(syntax-case stx ()
[(_) #'(? json-null?)])))
| null | https://raw.githubusercontent.com/Bogdanp/marionette/46af32a3b37d28dd9bc3e1ea6c5a6e483561b6e5/marionette-lib/private/json.rkt | racket | #lang racket/base
(require (for-syntax racket/base)
json
racket/match)
(provide
json-null?
js-null)
(define (json-null? v)
(eq? v (json-null)))
(define-match-expander js-null
(lambda (stx)
(syntax-case stx ()
[(_) #'(? json-null?)])))
| |
38d6e7b7e7a09d9c6ec658187d15c45309eab075507cd505a62cf594eddd7527 | alexandergunnarson/quantum | jvm.clj | (ns quantum.test.benchmarks.jvm
(:require
[quantum.core.macros.defnt
:refer [defnt defnt' defntp]]
[quantum.core.collections :as coll
:refer [reduce-pair]]
[quantum.core.meta.bench
:refer [bench complete-bench]]
[quantum.untyped.core.form.type-hint
:refer [static-cast]])
(:import
[quantum.core Numeric Fn]
[quantum.core.data Array]
[clojure.lang BigInt]
[java.util Map HashMap IdentityHashMap]
[java.lang.invoke MethodHandle MethodHandles MethodType]
#_[cern.colt.map OpenIntObjectHashMap]))
TODO try to use static methods instead of ` invokevirtual ` on the ` reify ` ?
; ===== STATIC ===== ;
(defnt' +*-static
([#{byte char short int long float double} x
#{byte char short int long float double} y]
(Numeric/add x y)))
(defnt' +*-static-boxed
(^Object [#{byte char short int long float double} x
#{byte char short int long float double} y]
(.cast Object (Numeric/add x y))))
(defnt' +*-static-interface-boxed
([^Comparable x #{long double} y]
(.cast Object true)))
; ===== PROTOCOL ===== ;
(defntp +*-protocol-1-byte
([^byte y x] (Numeric/add (byte x) y))
([^char y x] (Numeric/add (byte x) y))
([^short y x] (Numeric/add (byte x) y))
([^int y x] (Numeric/add (byte x) y))
([^long y x] (Numeric/add (byte x) y))
([^float y x] (Numeric/add (byte x) y))
([^double y x] (Numeric/add (byte x) y)))
(defntp +*-protocol-1-char
([^byte y x] (Numeric/add (char x) y))
([^char y x] (Numeric/add (char x) y))
([^short y x] (Numeric/add (char x) y))
([^int y x] (Numeric/add (char x) y))
([^long y x] (Numeric/add (char x) y))
([^float y x] (Numeric/add (char x) y))
([^double y x] (Numeric/add (char x) y)))
(defntp +*-protocol-1-short
([^byte y x] (Numeric/add (short x) y))
([^char y x] (Numeric/add (short x) y))
([^short y x] (Numeric/add (short x) y))
([^int y x] (Numeric/add (short x) y))
([^long y x] (Numeric/add (short x) y))
([^float y x] (Numeric/add (short x) y))
([^double y x] (Numeric/add (short x) y)))
(defntp +*-protocol-1-int
([^byte y x] (Numeric/add (int x) y))
([^char y x] (Numeric/add (int x) y))
([^short y x] (Numeric/add (int x) y))
([^int y x] (Numeric/add (int x) y))
([^long y x] (Numeric/add (int x) y))
([^float y x] (Numeric/add (int x) y))
([^double y x] (Numeric/add (int x) y)))
(defntp +*-protocol-1-long
([^byte y x] (Numeric/add (long x) y))
([^char y x] (Numeric/add (long x) y))
([^short y x] (Numeric/add (long x) y))
([^int y x] (Numeric/add (long x) y))
([^long y x] (Numeric/add (long x) y))
([^float y x] (Numeric/add (long x) y))
([^double y x] (Numeric/add (long x) y)))
(defntp +*-protocol-1-float
([^byte y x] (Numeric/add (float x) y))
([^char y x] (Numeric/add (float x) y))
([^short y x] (Numeric/add (float x) y))
([^int y x] (Numeric/add (float x) y))
([^long y x] (Numeric/add (float x) y))
([^float y x] (Numeric/add (float x) y))
([^double y x] (Numeric/add (float x) y)))
(defntp +*-protocol-1-double
([^byte y x] (Numeric/add (double x) y))
([^char y x] (Numeric/add (double x) y))
([^short y x] (Numeric/add (double x) y))
([^int y x] (Numeric/add (double x) y))
([^long y x] (Numeric/add (double x) y))
([^float y x] (Numeric/add (double x) y))
([^double y x] (Numeric/add (double x) y)))
(defntp +*-protocol-0
([^byte x y] (+*-protocol-1-byte y x))
([^char x y] (+*-protocol-1-char y x))
([^short x y] (+*-protocol-1-short y x))
([^int x y] (+*-protocol-1-int y x))
([^long x y] (+*-protocol-1-long y x))
([^float x y] (+*-protocol-1-float y x))
([^double x y] (+*-protocol-1-double y x)))
; ===== `INSTANCE?` DISPATCH ===== ;
(defn dispatch [x y]
(cond (instance? Byte x) (cond (instance? Byte y) (+*-static (byte x) (byte y))
(instance? Character y) (+*-static (byte x) (char y))
(instance? Short y) (+*-static (byte x) (short y))
(instance? Integer y) (+*-static (byte x) (int y))
(instance? Long y) (+*-static (byte x) (long y))
(instance? Float y) (+*-static (byte x) (float y))
(instance? Double y) (+*-static (byte x) (double y)))
(instance? Character x) (cond (instance? Byte y) (+*-static (char x) (byte y))
(instance? Character y) (+*-static (char x) (char y))
(instance? Short y) (+*-static (char x) (short y))
(instance? Integer y) (+*-static (char x) (int y))
(instance? Long y) (+*-static (char x) (long y))
(instance? Float y) (+*-static (char x) (float y))
(instance? Double y) (+*-static (char x) (double y)))
(instance? Short x) (cond (instance? Byte y) (+*-static (short x) (byte y))
(instance? Character y) (+*-static (short x) (char y))
(instance? Short y) (+*-static (short x) (short y))
(instance? Integer y) (+*-static (short x) (int y))
(instance? Long y) (+*-static (short x) (long y))
(instance? Float y) (+*-static (short x) (float y))
(instance? Double y) (+*-static (short x) (double y)))
(instance? Integer x) (cond (instance? Byte y) (+*-static (int x) (byte y))
(instance? Character y) (+*-static (int x) (char y))
(instance? Short y) (+*-static (int x) (short y))
(instance? Integer y) (+*-static (int x) (int y))
(instance? Long y) (+*-static (int x) (long y))
(instance? Float y) (+*-static (int x) (float y))
(instance? Double y) (+*-static (int x) (double y)))
(instance? Long x) (cond (instance? Byte y) (+*-static (long x) (byte y))
(instance? Character y) (+*-static (long x) (char y))
(instance? Short y) (+*-static (long x) (short y))
(instance? Integer y) (+*-static (long x) (int y))
(instance? Long y) (+*-static (long x) (long y))
(instance? Float y) (+*-static (long x) (float y))
(instance? Double y) (+*-static (long x) (double y)))
(instance? Float x) (cond (instance? Byte y) (+*-static (float x) (byte y))
(instance? Character y) (+*-static (float x) (char y))
(instance? Short y) (+*-static (float x) (short y))
(instance? Integer y) (+*-static (float x) (int y))
(instance? Long y) (+*-static (float x) (long y))
(instance? Float y) (+*-static (float x) (float y))
(instance? Double y) (+*-static (float x) (double y)))
(instance? Double x) (cond (instance? Byte y) (+*-static (double x) (byte y))
(instance? Character y) (+*-static (double x) (char y))
(instance? Short y) (+*-static (double x) (short y))
(instance? Integer y) (+*-static (double x) (int y))
(instance? Long y) (+*-static (double x) (long y))
(instance? Float y) (+*-static (double x) (float y))
(instance? Double y) (+*-static (double x) (double y)))))
(defn case-string-dispatch [^Object x ^Object y]
(case (if (nil? x) nil (-> x .getClass .getName))
"java.lang.Byte" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (byte x) (byte y))
"java.lang.Character" (+*-static (byte x) (char y))
"java.lang.Short" (+*-static (byte x) (short y))
"java.lang.Integer" (+*-static (byte x) (int y))
"java.lang.Long" (+*-static (byte x) (long y))
"java.lang.Float" (+*-static (byte x) (float y))
"java.lang.Double" (+*-static (byte x) (double y)))
"java.lang.Character" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (char x) (byte y))
"java.lang.Character" (+*-static (char x) (char y))
"java.lang.Short" (+*-static (char x) (short y))
"java.lang.Integer" (+*-static (char x) (int y))
"java.lang.Long" (+*-static (char x) (long y))
"java.lang.Float" (+*-static (char x) (float y))
"java.lang.Double" (+*-static (char x) (double y)))
"java.lang.Short" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (short x) (byte y))
"java.lang.Character" (+*-static (short x) (char y))
"java.lang.Short" (+*-static (short x) (short y))
"java.lang.Integer" (+*-static (short x) (int y))
"java.lang.Long" (+*-static (short x) (long y))
"java.lang.Float" (+*-static (short x) (float y))
"java.lang.Double" (+*-static (short x) (double y)))
"java.lang.Integer" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (int x) (byte y))
"java.lang.Character" (+*-static (int x) (char y))
"java.lang.Short" (+*-static (int x) (short y))
"java.lang.Integer" (+*-static (int x) (int y))
"java.lang.Long" (+*-static (int x) (long y))
"java.lang.Float" (+*-static (int x) (float y))
"java.lang.Double" (+*-static (int x) (double y)))
"java.lang.Long" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (long x) (byte y))
"java.lang.Character" (+*-static (long x) (char y))
"java.lang.Short" (+*-static (long x) (short y))
"java.lang.Integer" (+*-static (long x) (int y))
"java.lang.Long" (+*-static (long x) (long y))
"java.lang.Float" (+*-static (long x) (float y))
"java.lang.Double" (+*-static (long x) (double y)))
"java.lang.Float" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (float x) (byte y))
"java.lang.Character" (+*-static (float x) (char y))
"java.lang.Short" (+*-static (float x) (short y))
"java.lang.Integer" (+*-static (float x) (int y))
"java.lang.Long" (+*-static (float x) (long y))
"java.lang.Float" (+*-static (float x) (float y))
"java.lang.Double" (+*-static (float x) (double y)))
"java.lang.Double" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (double x) (byte y))
"java.lang.Character" (+*-static (double x) (char y))
"java.lang.Short" (+*-static (double x) (short y))
"java.lang.Integer" (+*-static (double x) (int y))
"java.lang.Long" (+*-static (double x) (long y))
"java.lang.Float" (+*-static (double x) (float y))
"java.lang.Double" (+*-static (double x) (double y)))))
(defmacro compile-hash [class-sym] (-> class-sym eval System/identityHashCode))
(eval
`(defn ~'case-hash-dispatch [^Object x# ^Object y#]
(case (if (nil? x#) (int 0) (-> x# .getClass System/identityHashCode))
~(compile-hash Byte) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (byte x#) (byte y#))
~(compile-hash Character) (+*-static (byte x#) (char y#))
~(compile-hash Short) (+*-static (byte x#) (short y#))
~(compile-hash Integer) (+*-static (byte x#) (int y#))
~(compile-hash Long) (+*-static (byte x#) (long y#))
~(compile-hash Float) (+*-static (byte x#) (float y#))
~(compile-hash Double) (+*-static (byte x#) (double y#)))
~(compile-hash Character) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (char x#) (byte y#))
~(compile-hash Character) (+*-static (char x#) (char y#))
~(compile-hash Short) (+*-static (char x#) (short y#))
~(compile-hash Integer) (+*-static (char x#) (int y#))
~(compile-hash Long) (+*-static (char x#) (long y#))
~(compile-hash Float) (+*-static (char x#) (float y#))
~(compile-hash Double) (+*-static (char x#) (double y#)))
~(compile-hash Short) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (short x#) (byte y#))
~(compile-hash Character) (+*-static (short x#) (char y#))
~(compile-hash Short) (+*-static (short x#) (short y#))
~(compile-hash Integer) (+*-static (short x#) (int y#))
~(compile-hash Long) (+*-static (short x#) (long y#))
~(compile-hash Float) (+*-static (short x#) (float y#))
~(compile-hash Double) (+*-static (short x#) (double y#)))
~(compile-hash Integer) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (int x#) (byte y#))
~(compile-hash Character) (+*-static (int x#) (char y#))
~(compile-hash Short) (+*-static (int x#) (short y#))
~(compile-hash Integer) (+*-static (int x#) (int y#))
~(compile-hash Long) (+*-static (int x#) (long y#))
~(compile-hash Float) (+*-static (int x#) (float y#))
~(compile-hash Double) (+*-static (int x#) (double y#)))
~(compile-hash Long) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (long x#) (byte y#))
~(compile-hash Character) (+*-static (long x#) (char y#))
~(compile-hash Short) (+*-static (long x#) (short y#))
~(compile-hash Integer) (+*-static (long x#) (int y#))
~(compile-hash Long) (+*-static (long x#) (long y#))
~(compile-hash Float) (+*-static (long x#) (float y#))
~(compile-hash Double) (+*-static (long x#) (double y#)))
~(compile-hash Float) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (float x#) (byte y#))
~(compile-hash Character) (+*-static (float x#) (char y#))
~(compile-hash Short) (+*-static (float x#) (short y#))
~(compile-hash Integer) (+*-static (float x#) (int y#))
~(compile-hash Long) (+*-static (float x#) (long y#))
~(compile-hash Float) (+*-static (float x#) (float y#))
~(compile-hash Double) (+*-static (float x#) (double y#)))
~(compile-hash Double) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (double x#) (byte y#))
~(compile-hash Character) (+*-static (double x#) (char y#))
~(compile-hash Short) (+*-static (double x#) (short y#))
~(compile-hash Integer) (+*-static (double x#) (int y#))
~(compile-hash Long) (+*-static (double x#) (long y#))
~(compile-hash Float) (+*-static (double x#) (float y#))
~(compile-hash Double) (+*-static (double x#) (double y#))))))
; ===== LOOKUP MAP, IMMUTABLE ===== ;
(defn gen-dispatch-map [create-map]
(create-map
Byte (create-map
Byte (fn [x y] (+*-static (byte x) (byte y)))
Character (fn [x y] (+*-static (byte x) (char y)))
Short (fn [x y] (+*-static (byte x) (short y)))
Integer (fn [x y] (+*-static (byte x) (int y)))
Long (fn [x y] (+*-static (byte x) (long y)))
Float (fn [x y] (+*-static (byte x) (float y)))
Double (fn [x y] (+*-static (byte x) (double y))))
Character (create-map
Byte (fn [x y] (+*-static (char x) (byte y)))
Character (fn [x y] (+*-static (char x) (char y)))
Short (fn [x y] (+*-static (char x) (short y)))
Integer (fn [x y] (+*-static (char x) (int y)))
Long (fn [x y] (+*-static (char x) (long y)))
Float (fn [x y] (+*-static (char x) (float y)))
Double (fn [x y] (+*-static (char x) (double y))))
Short (create-map
Byte (fn [x y] (+*-static (short x) (byte y)))
Character (fn [x y] (+*-static (short x) (char y)))
Short (fn [x y] (+*-static (short x) (short y)))
Integer (fn [x y] (+*-static (short x) (int y)))
Long (fn [x y] (+*-static (short x) (long y)))
Float (fn [x y] (+*-static (short x) (float y)))
Double (fn [x y] (+*-static (short x) (double y))))
Integer (create-map
Byte (fn [x y] (+*-static (int x) (byte y)))
Character (fn [x y] (+*-static (int x) (char y)))
Short (fn [x y] (+*-static (int x) (short y)))
Integer (fn [x y] (+*-static (int x) (int y)))
Long (fn [x y] (+*-static (int x) (long y)))
Float (fn [x y] (+*-static (int x) (float y)))
Double (fn [x y] (+*-static (int x) (double y))))
Long (create-map
Byte (fn [x y] (+*-static (long x) (byte y)))
Character (fn [x y] (+*-static (long x) (char y)))
Short (fn [x y] (+*-static (long x) (short y)))
Integer (fn [x y] (+*-static (long x) (int y)))
Long (fn [x y] (+*-static (long x) (long y)))
Float (fn [x y] (+*-static (long x) (float y)))
Double (fn [x y] (+*-static (long x) (double y))))
Float (create-map
Byte (fn [x y] (+*-static (float x) (byte y)))
Character (fn [x y] (+*-static (float x) (char y)))
Short (fn [x y] (+*-static (float x) (short y)))
Integer (fn [x y] (+*-static (float x) (int y)))
Long (fn [x y] (+*-static (float x) (long y)))
Float (fn [x y] (+*-static (float x) (float y)))
Double (fn [x y] (+*-static (float x) (double y))))
Double (create-map
Byte (fn [x y] (+*-static (double x) (byte y)))
Character (fn [x y] (+*-static (double x) (char y)))
Short (fn [x y] (+*-static (double x) (short y)))
Integer (fn [x y] (+*-static (double x) (int y)))
Long (fn [x y] (+*-static (double x) (long y)))
Float (fn [x y] (+*-static (double x) (float y)))
Double (fn [x y] (+*-static (double x) (double y))))))
(defn gen-inlined-dispatch-map [create-map]
(create-map
Byte (create-map
Byte (fn [x y] (Numeric/add (byte x) (byte y)))
Character (fn [x y] (Numeric/add (byte x) (char y)))
Short (fn [x y] (Numeric/add (byte x) (short y)))
Integer (fn [x y] (Numeric/add (byte x) (int y)))
Long (fn [x y] (Numeric/add (byte x) (long y)))
Float (fn [x y] (Numeric/add (byte x) (float y)))
Double (fn [x y] (Numeric/add (byte x) (double y))))
Character (create-map
Byte (fn [x y] (Numeric/add (char x) (byte y)))
Character (fn [x y] (Numeric/add (char x) (char y)))
Short (fn [x y] (Numeric/add (char x) (short y)))
Integer (fn [x y] (Numeric/add (char x) (int y)))
Long (fn [x y] (Numeric/add (char x) (long y)))
Float (fn [x y] (Numeric/add (char x) (float y)))
Double (fn [x y] (Numeric/add (char x) (double y))))
Short (create-map
Byte (fn [x y] (Numeric/add (short x) (byte y)))
Character (fn [x y] (Numeric/add (short x) (char y)))
Short (fn [x y] (Numeric/add (short x) (short y)))
Integer (fn [x y] (Numeric/add (short x) (int y)))
Long (fn [x y] (Numeric/add (short x) (long y)))
Float (fn [x y] (Numeric/add (short x) (float y)))
Double (fn [x y] (Numeric/add (short x) (double y))))
Integer (create-map
Byte (fn [x y] (Numeric/add (int x) (byte y)))
Character (fn [x y] (Numeric/add (int x) (char y)))
Short (fn [x y] (Numeric/add (int x) (short y)))
Integer (fn [x y] (Numeric/add (int x) (int y)))
Long (fn [x y] (Numeric/add (int x) (long y)))
Float (fn [x y] (Numeric/add (int x) (float y)))
Double (fn [x y] (Numeric/add (int x) (double y))))
Long (create-map
Byte (fn [x y] (Numeric/add (long x) (byte y)))
Character (fn [x y] (Numeric/add (long x) (char y)))
Short (fn [x y] (Numeric/add (long x) (short y)))
Integer (fn [x y] (Numeric/add (long x) (int y)))
Long (fn [x y] (Numeric/add (long x) (long y)))
Float (fn [x y] (Numeric/add (long x) (float y)))
Double (fn [x y] (Numeric/add (long x) (double y))))
Float (create-map
Byte (fn [x y] (Numeric/add (float x) (byte y)))
Character (fn [x y] (Numeric/add (float x) (char y)))
Short (fn [x y] (Numeric/add (float x) (short y)))
Integer (fn [x y] (Numeric/add (float x) (int y)))
Long (fn [x y] (Numeric/add (float x) (long y)))
Float (fn [x y] (Numeric/add (float x) (float y)))
Double (fn [x y] (Numeric/add (float x) (double y))))
Double (create-map
Byte (fn [x y] (Numeric/add (double x) (byte y)))
Character (fn [x y] (Numeric/add (double x) (char y)))
Short (fn [x y] (Numeric/add (double x) (short y)))
Integer (fn [x y] (Numeric/add (double x) (int y)))
Long (fn [x y] (Numeric/add (double x) (long y)))
Float (fn [x y] (Numeric/add (double x) (float y)))
Double (fn [x y] (Numeric/add (double x) (double y))))))
(def dispatch-map (gen-dispatch-map hash-map))
(defn dispatch-with-map [x y]
(let [f (some-> dispatch-map (get (class x)) (get (class y)))]
(assert (some? f))
(f x y)))
; ===== LOOKUP MAP, MUTABLE ===== ;
(defn map!* [constructor & args]
(assert (-> args count even?))
(reduce-pair (fn [ret k v] (.put ^Map ret k v) ret) (constructor) args))
(def hash-map! (partial map!* #(HashMap.)))
(def ^HashMap dispatch-map-mutable (gen-dispatch-map hash-map!))
(defn dispatch-with-map-mutable [x y]
(let [f (some-> dispatch-map-mutable ^HashMap (.get (class x)) (.get (class y)))]
(assert (some? f))
(f x y)))
; ===== LOOKUP MAP, IDENTITY MUTABLE ===== ;
(def identity-hash-map! (partial map!* #(IdentityHashMap.)))
(def ^IdentityHashMap dispatch-identity-map-mutable (gen-dispatch-map identity-hash-map!))
(defn dispatch-with-identity-map-mutable [x y]
(if-let [a0 (.get dispatch-identity-map-mutable (clojure.lang.Util/classOf x))]
(if-let [a1 (.get ^IdentityHashMap a0 (clojure.lang.Util/classOf y))]
(a1 x y)
(throw (Exception. "Method not found")))
(throw (Exception. "Method not found"))))
; ===== LOOKUP MAP, INT->OBJECT MUTABLE ===== ;
Colt 's OpenIntObjectHashMap does n't help here
= = = = = CUSTOMIZED ( CLOJURE NUMERICS ) = = = = = ;
(defn argtypes-unknown [a b] (+ a b))
= = = = = INVOKEDYNAMIC ( 8 METHOD HANDLES ) = = = = = ;
(defmacro compile-time-class [x] (class (eval x)))
(def ^MethodHandle method-double-double
(.findVirtual Fn/fnLookup (compile-time-class +*-static-reified) "_PLUS__STAR_Static"
(Fn/methodType Double/TYPE Double/TYPE Double/TYPE)))
(def ^MethodHandle method
(.unreflect Fn/fnLookup (.getMethod (class +*-static-reified) "_PLUS__STAR_Static")))
13.650164 ns
(complete-bench (do (Fn/invoke method-double-double +*-static-reified 1.0 3.0)
#_(Fn/invoke method +*-static-reified 1 3 )))
(complete-bench (do (Fn/invoke method +*-static-reified 1.0 3.0)
#_(Fn/invoke method +*-static-reified 1 3 )))
; ===== BENCHMARKS ===== ;
All benchmarks use the lower quantile ( 2.5 % ) instead of considering outliers .
; It's more fair to benchmark this way.
; Also, all benchmarks were run multiple times to ensure complete and utter JVM warmup.
4.911254 ns
(complete-bench (do (+ 1.0 3.0)
(+ 1 3 )))
; Same time
(complete-bench (do (Numeric/add 1.0 3.0)
(Numeric/add 1 3 )))
5.970614 ns
May currently have slightly worse performance since it is n't inlined , and is an instance instead of a static method
(let [^quantum.test.benchmarks.jvm._PLUS__STAR_StaticInterface
to get rid of var indirection , which ca n't be optimized away by the JVM because is marked as ` volatile `
(complete-bench (do (. +*-static-reified-direct _PLUS__STAR_Static 1.0 3.0)
(. +*-static-reified-direct _PLUS__STAR_Static 1 3 ))))
6.361026 ns
May currently have slightly worse performance since it is n't inlined , and is an instance instead of a static method
(complete-bench (do (+*-static 1.0 3.0)
(+*-static 1 3 )))
22.369795 ns ( 4.55x )
(complete-bench (do (argtypes-unknown 1.0 3.0)
(argtypes-unknown 1 3 )))
30.778042 ns ( 6.27x ) ( on first run is 23.467812 ns , 4.78x )
(complete-bench (do (Fn/dispatch2 dispatch-identity-map-mutable 1.0 3.0)
(Fn/dispatch2 dispatch-identity-map-mutable 1 3 )))
34.343497 ns
#_(complete-bench (do (Fn/dispatch2 dispatch-map-mutable 1.0 3.0)
(Fn/dispatch2 dispatch-map-mutable 1 3 )))
37.636059 ns ( 7.66x )
(complete-bench (do (case-hash-dispatch 1.0 3.0)
(case-hash-dispatch 1 3 )))
38.843166 ns
(complete-bench (do (case-string-dispatch 1.0 3.0)
(case-string-dispatch 1 3 )))
51.184897 ns ( 10.42x ) ( on first run is 33.707466 ns , 6.86x )
(complete-bench (do (+*-protocol-0 1.0 3.0)
(+*-protocol-0 1 3 )))
40.611242 ns
(complete-bench (do (dispatch-with-identity-map-mutable 1.0 3.0)
(dispatch-with-identity-map-mutable 1 3 )))
42.714549 ns
(complete-bench (do (dispatch-with-map-mutable 1.0 3.0)
(dispatch-with-map-mutable 1 3 )))
48.844710 ns
(complete-bench (do (dispatch 1.0 3.0)
(dispatch 1 3 )))
79.343540 ns
#_(complete-bench (do (dispatch-with-int->object-map-mutable 1.0 3.0)
(dispatch-with-int->object-map-mutable 1 3 )))
188.686935 ns
(complete-bench (.invokeWithArguments method (Array/newObjectArray +*-static-reified 1.0 3.0)))
212.066270 ns
(complete-bench (do (dispatch-with-map 1.0 3.0)
(dispatch-with-map 1 3 )))
; Didn't even complete
(complete-bench
(Fn/invoke (.findVirtual Fn/fnLookup
(compile-time-class +*-static-boxed-reified)
"_PLUS__STAR_StaticBoxed"
(.unwrap (Fn/methodType Object Long Long)))
+*-static-boxed-reified 1 2))
#_"Resolved:
- Protocols may be 7.2x slower in this case but they're currently the only viable choice for multi-arg dispatch.
- Explore -std.org/jtc1/sc22/wg21/docs/papers/2007/n2216.pdf — perhaps a Clojure(Script)
implementation might yield the same speed benefits — i.e. *no statistical difference in performance
with direct dispatch*!
"
; With `(dotimes [i 1000000000] ...)`
" Elapsed time : 365.916154 msecs " + , Add
" Elapsed time : 941.336378 msecs " Static
" Elapsed time : 20147.633612 msecs " Boxed math
" Elapsed time : 34638.789978 msecs " Dispatch , Dispatch Inlined
" Elapsed time : 46755.719601 msecs " Protocol
" Elapsed time : 68588.693153 msecs " Hash Dispatch
; ===== SINGLE DISPATCH ===== ;
; Takeaways: - quantum `get` is just as good as handwritten.
- one protocol dispatch here is ~2x a direct call ; often wo n't have to do N dispatches depending on type info known at compile time
5.580126 ns
(let [v [1 2 3 4 5]]
(complete-bench (.get v 3)))
7.644827 ns ; will be same as direct dispatch when inlined
(let [v [1 2 3 4 5]]
(complete-bench (quantum.core.collections.core/get v 3)))
10.542661 ns
(let [v [1 2 3 4 5]]
(complete-bench (clojure.core/get v 3)))
10.686585 ns ; because it 's on the fast track
(let [v [1 2 3 4 5]]
(complete-bench (quantum.core.collections.core/get-protocol v 3)))
; 7.438636 ns
(let [v (long-array [1 2 3 4 5])]
(complete-bench (clojure.core/aget v 3)))
; 7.649213 ns — statistically equivalent
(let [v (long-array [1 2 3 4 5])]
(complete-bench (quantum.core.data.Array/get v 3)))
8.691139 ns
(let [v (long-array [1 2 3 4 5])]
(complete-bench (quantum.core.collections.core/get v 3)))
15.832480 ns ; good performance , but not on the fast track
(let [v (long-array [1 2 3 4 5])]
(complete-bench (quantum.core.collections.core/get-protocol v 3)))
53.855997 ns ; semi - reflection going on here
(let [v (long-array [1 2 3 4 5])]
(complete-bench (clojure.core/get v 3)))
| null | https://raw.githubusercontent.com/alexandergunnarson/quantum/0c655af439734709566110949f9f2f482e468509/benchmarks/jvm.clj | clojure | ===== STATIC ===== ;
===== PROTOCOL ===== ;
===== `INSTANCE?` DISPATCH ===== ;
===== LOOKUP MAP, IMMUTABLE ===== ;
===== LOOKUP MAP, MUTABLE ===== ;
===== LOOKUP MAP, IDENTITY MUTABLE ===== ;
===== LOOKUP MAP, INT->OBJECT MUTABLE ===== ;
===== BENCHMARKS ===== ;
It's more fair to benchmark this way.
Also, all benchmarks were run multiple times to ensure complete and utter JVM warmup.
Same time
Didn't even complete
With `(dotimes [i 1000000000] ...)`
===== SINGLE DISPATCH ===== ;
Takeaways: - quantum `get` is just as good as handwritten.
often wo n't have to do N dispatches depending on type info known at compile time
will be same as direct dispatch when inlined
because it 's on the fast track
7.438636 ns
7.649213 ns — statistically equivalent
good performance , but not on the fast track
semi - reflection going on here | (ns quantum.test.benchmarks.jvm
(:require
[quantum.core.macros.defnt
:refer [defnt defnt' defntp]]
[quantum.core.collections :as coll
:refer [reduce-pair]]
[quantum.core.meta.bench
:refer [bench complete-bench]]
[quantum.untyped.core.form.type-hint
:refer [static-cast]])
(:import
[quantum.core Numeric Fn]
[quantum.core.data Array]
[clojure.lang BigInt]
[java.util Map HashMap IdentityHashMap]
[java.lang.invoke MethodHandle MethodHandles MethodType]
#_[cern.colt.map OpenIntObjectHashMap]))
TODO try to use static methods instead of ` invokevirtual ` on the ` reify ` ?
(defnt' +*-static
([#{byte char short int long float double} x
#{byte char short int long float double} y]
(Numeric/add x y)))
(defnt' +*-static-boxed
(^Object [#{byte char short int long float double} x
#{byte char short int long float double} y]
(.cast Object (Numeric/add x y))))
(defnt' +*-static-interface-boxed
([^Comparable x #{long double} y]
(.cast Object true)))
(defntp +*-protocol-1-byte
([^byte y x] (Numeric/add (byte x) y))
([^char y x] (Numeric/add (byte x) y))
([^short y x] (Numeric/add (byte x) y))
([^int y x] (Numeric/add (byte x) y))
([^long y x] (Numeric/add (byte x) y))
([^float y x] (Numeric/add (byte x) y))
([^double y x] (Numeric/add (byte x) y)))
(defntp +*-protocol-1-char
([^byte y x] (Numeric/add (char x) y))
([^char y x] (Numeric/add (char x) y))
([^short y x] (Numeric/add (char x) y))
([^int y x] (Numeric/add (char x) y))
([^long y x] (Numeric/add (char x) y))
([^float y x] (Numeric/add (char x) y))
([^double y x] (Numeric/add (char x) y)))
(defntp +*-protocol-1-short
([^byte y x] (Numeric/add (short x) y))
([^char y x] (Numeric/add (short x) y))
([^short y x] (Numeric/add (short x) y))
([^int y x] (Numeric/add (short x) y))
([^long y x] (Numeric/add (short x) y))
([^float y x] (Numeric/add (short x) y))
([^double y x] (Numeric/add (short x) y)))
(defntp +*-protocol-1-int
([^byte y x] (Numeric/add (int x) y))
([^char y x] (Numeric/add (int x) y))
([^short y x] (Numeric/add (int x) y))
([^int y x] (Numeric/add (int x) y))
([^long y x] (Numeric/add (int x) y))
([^float y x] (Numeric/add (int x) y))
([^double y x] (Numeric/add (int x) y)))
(defntp +*-protocol-1-long
([^byte y x] (Numeric/add (long x) y))
([^char y x] (Numeric/add (long x) y))
([^short y x] (Numeric/add (long x) y))
([^int y x] (Numeric/add (long x) y))
([^long y x] (Numeric/add (long x) y))
([^float y x] (Numeric/add (long x) y))
([^double y x] (Numeric/add (long x) y)))
(defntp +*-protocol-1-float
([^byte y x] (Numeric/add (float x) y))
([^char y x] (Numeric/add (float x) y))
([^short y x] (Numeric/add (float x) y))
([^int y x] (Numeric/add (float x) y))
([^long y x] (Numeric/add (float x) y))
([^float y x] (Numeric/add (float x) y))
([^double y x] (Numeric/add (float x) y)))
(defntp +*-protocol-1-double
([^byte y x] (Numeric/add (double x) y))
([^char y x] (Numeric/add (double x) y))
([^short y x] (Numeric/add (double x) y))
([^int y x] (Numeric/add (double x) y))
([^long y x] (Numeric/add (double x) y))
([^float y x] (Numeric/add (double x) y))
([^double y x] (Numeric/add (double x) y)))
(defntp +*-protocol-0
([^byte x y] (+*-protocol-1-byte y x))
([^char x y] (+*-protocol-1-char y x))
([^short x y] (+*-protocol-1-short y x))
([^int x y] (+*-protocol-1-int y x))
([^long x y] (+*-protocol-1-long y x))
([^float x y] (+*-protocol-1-float y x))
([^double x y] (+*-protocol-1-double y x)))
(defn dispatch [x y]
(cond (instance? Byte x) (cond (instance? Byte y) (+*-static (byte x) (byte y))
(instance? Character y) (+*-static (byte x) (char y))
(instance? Short y) (+*-static (byte x) (short y))
(instance? Integer y) (+*-static (byte x) (int y))
(instance? Long y) (+*-static (byte x) (long y))
(instance? Float y) (+*-static (byte x) (float y))
(instance? Double y) (+*-static (byte x) (double y)))
(instance? Character x) (cond (instance? Byte y) (+*-static (char x) (byte y))
(instance? Character y) (+*-static (char x) (char y))
(instance? Short y) (+*-static (char x) (short y))
(instance? Integer y) (+*-static (char x) (int y))
(instance? Long y) (+*-static (char x) (long y))
(instance? Float y) (+*-static (char x) (float y))
(instance? Double y) (+*-static (char x) (double y)))
(instance? Short x) (cond (instance? Byte y) (+*-static (short x) (byte y))
(instance? Character y) (+*-static (short x) (char y))
(instance? Short y) (+*-static (short x) (short y))
(instance? Integer y) (+*-static (short x) (int y))
(instance? Long y) (+*-static (short x) (long y))
(instance? Float y) (+*-static (short x) (float y))
(instance? Double y) (+*-static (short x) (double y)))
(instance? Integer x) (cond (instance? Byte y) (+*-static (int x) (byte y))
(instance? Character y) (+*-static (int x) (char y))
(instance? Short y) (+*-static (int x) (short y))
(instance? Integer y) (+*-static (int x) (int y))
(instance? Long y) (+*-static (int x) (long y))
(instance? Float y) (+*-static (int x) (float y))
(instance? Double y) (+*-static (int x) (double y)))
(instance? Long x) (cond (instance? Byte y) (+*-static (long x) (byte y))
(instance? Character y) (+*-static (long x) (char y))
(instance? Short y) (+*-static (long x) (short y))
(instance? Integer y) (+*-static (long x) (int y))
(instance? Long y) (+*-static (long x) (long y))
(instance? Float y) (+*-static (long x) (float y))
(instance? Double y) (+*-static (long x) (double y)))
(instance? Float x) (cond (instance? Byte y) (+*-static (float x) (byte y))
(instance? Character y) (+*-static (float x) (char y))
(instance? Short y) (+*-static (float x) (short y))
(instance? Integer y) (+*-static (float x) (int y))
(instance? Long y) (+*-static (float x) (long y))
(instance? Float y) (+*-static (float x) (float y))
(instance? Double y) (+*-static (float x) (double y)))
(instance? Double x) (cond (instance? Byte y) (+*-static (double x) (byte y))
(instance? Character y) (+*-static (double x) (char y))
(instance? Short y) (+*-static (double x) (short y))
(instance? Integer y) (+*-static (double x) (int y))
(instance? Long y) (+*-static (double x) (long y))
(instance? Float y) (+*-static (double x) (float y))
(instance? Double y) (+*-static (double x) (double y)))))
(defn case-string-dispatch [^Object x ^Object y]
(case (if (nil? x) nil (-> x .getClass .getName))
"java.lang.Byte" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (byte x) (byte y))
"java.lang.Character" (+*-static (byte x) (char y))
"java.lang.Short" (+*-static (byte x) (short y))
"java.lang.Integer" (+*-static (byte x) (int y))
"java.lang.Long" (+*-static (byte x) (long y))
"java.lang.Float" (+*-static (byte x) (float y))
"java.lang.Double" (+*-static (byte x) (double y)))
"java.lang.Character" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (char x) (byte y))
"java.lang.Character" (+*-static (char x) (char y))
"java.lang.Short" (+*-static (char x) (short y))
"java.lang.Integer" (+*-static (char x) (int y))
"java.lang.Long" (+*-static (char x) (long y))
"java.lang.Float" (+*-static (char x) (float y))
"java.lang.Double" (+*-static (char x) (double y)))
"java.lang.Short" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (short x) (byte y))
"java.lang.Character" (+*-static (short x) (char y))
"java.lang.Short" (+*-static (short x) (short y))
"java.lang.Integer" (+*-static (short x) (int y))
"java.lang.Long" (+*-static (short x) (long y))
"java.lang.Float" (+*-static (short x) (float y))
"java.lang.Double" (+*-static (short x) (double y)))
"java.lang.Integer" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (int x) (byte y))
"java.lang.Character" (+*-static (int x) (char y))
"java.lang.Short" (+*-static (int x) (short y))
"java.lang.Integer" (+*-static (int x) (int y))
"java.lang.Long" (+*-static (int x) (long y))
"java.lang.Float" (+*-static (int x) (float y))
"java.lang.Double" (+*-static (int x) (double y)))
"java.lang.Long" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (long x) (byte y))
"java.lang.Character" (+*-static (long x) (char y))
"java.lang.Short" (+*-static (long x) (short y))
"java.lang.Integer" (+*-static (long x) (int y))
"java.lang.Long" (+*-static (long x) (long y))
"java.lang.Float" (+*-static (long x) (float y))
"java.lang.Double" (+*-static (long x) (double y)))
"java.lang.Float" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (float x) (byte y))
"java.lang.Character" (+*-static (float x) (char y))
"java.lang.Short" (+*-static (float x) (short y))
"java.lang.Integer" (+*-static (float x) (int y))
"java.lang.Long" (+*-static (float x) (long y))
"java.lang.Float" (+*-static (float x) (float y))
"java.lang.Double" (+*-static (float x) (double y)))
"java.lang.Double" (case (if (nil? y) nil (-> y .getClass .getName))
"java.lang.Byte" (+*-static (double x) (byte y))
"java.lang.Character" (+*-static (double x) (char y))
"java.lang.Short" (+*-static (double x) (short y))
"java.lang.Integer" (+*-static (double x) (int y))
"java.lang.Long" (+*-static (double x) (long y))
"java.lang.Float" (+*-static (double x) (float y))
"java.lang.Double" (+*-static (double x) (double y)))))
(defmacro compile-hash [class-sym] (-> class-sym eval System/identityHashCode))
(eval
`(defn ~'case-hash-dispatch [^Object x# ^Object y#]
(case (if (nil? x#) (int 0) (-> x# .getClass System/identityHashCode))
~(compile-hash Byte) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (byte x#) (byte y#))
~(compile-hash Character) (+*-static (byte x#) (char y#))
~(compile-hash Short) (+*-static (byte x#) (short y#))
~(compile-hash Integer) (+*-static (byte x#) (int y#))
~(compile-hash Long) (+*-static (byte x#) (long y#))
~(compile-hash Float) (+*-static (byte x#) (float y#))
~(compile-hash Double) (+*-static (byte x#) (double y#)))
~(compile-hash Character) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (char x#) (byte y#))
~(compile-hash Character) (+*-static (char x#) (char y#))
~(compile-hash Short) (+*-static (char x#) (short y#))
~(compile-hash Integer) (+*-static (char x#) (int y#))
~(compile-hash Long) (+*-static (char x#) (long y#))
~(compile-hash Float) (+*-static (char x#) (float y#))
~(compile-hash Double) (+*-static (char x#) (double y#)))
~(compile-hash Short) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (short x#) (byte y#))
~(compile-hash Character) (+*-static (short x#) (char y#))
~(compile-hash Short) (+*-static (short x#) (short y#))
~(compile-hash Integer) (+*-static (short x#) (int y#))
~(compile-hash Long) (+*-static (short x#) (long y#))
~(compile-hash Float) (+*-static (short x#) (float y#))
~(compile-hash Double) (+*-static (short x#) (double y#)))
~(compile-hash Integer) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (int x#) (byte y#))
~(compile-hash Character) (+*-static (int x#) (char y#))
~(compile-hash Short) (+*-static (int x#) (short y#))
~(compile-hash Integer) (+*-static (int x#) (int y#))
~(compile-hash Long) (+*-static (int x#) (long y#))
~(compile-hash Float) (+*-static (int x#) (float y#))
~(compile-hash Double) (+*-static (int x#) (double y#)))
~(compile-hash Long) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (long x#) (byte y#))
~(compile-hash Character) (+*-static (long x#) (char y#))
~(compile-hash Short) (+*-static (long x#) (short y#))
~(compile-hash Integer) (+*-static (long x#) (int y#))
~(compile-hash Long) (+*-static (long x#) (long y#))
~(compile-hash Float) (+*-static (long x#) (float y#))
~(compile-hash Double) (+*-static (long x#) (double y#)))
~(compile-hash Float) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (float x#) (byte y#))
~(compile-hash Character) (+*-static (float x#) (char y#))
~(compile-hash Short) (+*-static (float x#) (short y#))
~(compile-hash Integer) (+*-static (float x#) (int y#))
~(compile-hash Long) (+*-static (float x#) (long y#))
~(compile-hash Float) (+*-static (float x#) (float y#))
~(compile-hash Double) (+*-static (float x#) (double y#)))
~(compile-hash Double) (case (if (nil? y#) (int 0) (-> y# .getClass System/identityHashCode))
~(compile-hash Byte) (+*-static (double x#) (byte y#))
~(compile-hash Character) (+*-static (double x#) (char y#))
~(compile-hash Short) (+*-static (double x#) (short y#))
~(compile-hash Integer) (+*-static (double x#) (int y#))
~(compile-hash Long) (+*-static (double x#) (long y#))
~(compile-hash Float) (+*-static (double x#) (float y#))
~(compile-hash Double) (+*-static (double x#) (double y#))))))
(defn gen-dispatch-map [create-map]
(create-map
Byte (create-map
Byte (fn [x y] (+*-static (byte x) (byte y)))
Character (fn [x y] (+*-static (byte x) (char y)))
Short (fn [x y] (+*-static (byte x) (short y)))
Integer (fn [x y] (+*-static (byte x) (int y)))
Long (fn [x y] (+*-static (byte x) (long y)))
Float (fn [x y] (+*-static (byte x) (float y)))
Double (fn [x y] (+*-static (byte x) (double y))))
Character (create-map
Byte (fn [x y] (+*-static (char x) (byte y)))
Character (fn [x y] (+*-static (char x) (char y)))
Short (fn [x y] (+*-static (char x) (short y)))
Integer (fn [x y] (+*-static (char x) (int y)))
Long (fn [x y] (+*-static (char x) (long y)))
Float (fn [x y] (+*-static (char x) (float y)))
Double (fn [x y] (+*-static (char x) (double y))))
Short (create-map
Byte (fn [x y] (+*-static (short x) (byte y)))
Character (fn [x y] (+*-static (short x) (char y)))
Short (fn [x y] (+*-static (short x) (short y)))
Integer (fn [x y] (+*-static (short x) (int y)))
Long (fn [x y] (+*-static (short x) (long y)))
Float (fn [x y] (+*-static (short x) (float y)))
Double (fn [x y] (+*-static (short x) (double y))))
Integer (create-map
Byte (fn [x y] (+*-static (int x) (byte y)))
Character (fn [x y] (+*-static (int x) (char y)))
Short (fn [x y] (+*-static (int x) (short y)))
Integer (fn [x y] (+*-static (int x) (int y)))
Long (fn [x y] (+*-static (int x) (long y)))
Float (fn [x y] (+*-static (int x) (float y)))
Double (fn [x y] (+*-static (int x) (double y))))
Long (create-map
Byte (fn [x y] (+*-static (long x) (byte y)))
Character (fn [x y] (+*-static (long x) (char y)))
Short (fn [x y] (+*-static (long x) (short y)))
Integer (fn [x y] (+*-static (long x) (int y)))
Long (fn [x y] (+*-static (long x) (long y)))
Float (fn [x y] (+*-static (long x) (float y)))
Double (fn [x y] (+*-static (long x) (double y))))
Float (create-map
Byte (fn [x y] (+*-static (float x) (byte y)))
Character (fn [x y] (+*-static (float x) (char y)))
Short (fn [x y] (+*-static (float x) (short y)))
Integer (fn [x y] (+*-static (float x) (int y)))
Long (fn [x y] (+*-static (float x) (long y)))
Float (fn [x y] (+*-static (float x) (float y)))
Double (fn [x y] (+*-static (float x) (double y))))
Double (create-map
Byte (fn [x y] (+*-static (double x) (byte y)))
Character (fn [x y] (+*-static (double x) (char y)))
Short (fn [x y] (+*-static (double x) (short y)))
Integer (fn [x y] (+*-static (double x) (int y)))
Long (fn [x y] (+*-static (double x) (long y)))
Float (fn [x y] (+*-static (double x) (float y)))
Double (fn [x y] (+*-static (double x) (double y))))))
(defn gen-inlined-dispatch-map [create-map]
(create-map
Byte (create-map
Byte (fn [x y] (Numeric/add (byte x) (byte y)))
Character (fn [x y] (Numeric/add (byte x) (char y)))
Short (fn [x y] (Numeric/add (byte x) (short y)))
Integer (fn [x y] (Numeric/add (byte x) (int y)))
Long (fn [x y] (Numeric/add (byte x) (long y)))
Float (fn [x y] (Numeric/add (byte x) (float y)))
Double (fn [x y] (Numeric/add (byte x) (double y))))
Character (create-map
Byte (fn [x y] (Numeric/add (char x) (byte y)))
Character (fn [x y] (Numeric/add (char x) (char y)))
Short (fn [x y] (Numeric/add (char x) (short y)))
Integer (fn [x y] (Numeric/add (char x) (int y)))
Long (fn [x y] (Numeric/add (char x) (long y)))
Float (fn [x y] (Numeric/add (char x) (float y)))
Double (fn [x y] (Numeric/add (char x) (double y))))
Short (create-map
Byte (fn [x y] (Numeric/add (short x) (byte y)))
Character (fn [x y] (Numeric/add (short x) (char y)))
Short (fn [x y] (Numeric/add (short x) (short y)))
Integer (fn [x y] (Numeric/add (short x) (int y)))
Long (fn [x y] (Numeric/add (short x) (long y)))
Float (fn [x y] (Numeric/add (short x) (float y)))
Double (fn [x y] (Numeric/add (short x) (double y))))
Integer (create-map
Byte (fn [x y] (Numeric/add (int x) (byte y)))
Character (fn [x y] (Numeric/add (int x) (char y)))
Short (fn [x y] (Numeric/add (int x) (short y)))
Integer (fn [x y] (Numeric/add (int x) (int y)))
Long (fn [x y] (Numeric/add (int x) (long y)))
Float (fn [x y] (Numeric/add (int x) (float y)))
Double (fn [x y] (Numeric/add (int x) (double y))))
Long (create-map
Byte (fn [x y] (Numeric/add (long x) (byte y)))
Character (fn [x y] (Numeric/add (long x) (char y)))
Short (fn [x y] (Numeric/add (long x) (short y)))
Integer (fn [x y] (Numeric/add (long x) (int y)))
Long (fn [x y] (Numeric/add (long x) (long y)))
Float (fn [x y] (Numeric/add (long x) (float y)))
Double (fn [x y] (Numeric/add (long x) (double y))))
Float (create-map
Byte (fn [x y] (Numeric/add (float x) (byte y)))
Character (fn [x y] (Numeric/add (float x) (char y)))
Short (fn [x y] (Numeric/add (float x) (short y)))
Integer (fn [x y] (Numeric/add (float x) (int y)))
Long (fn [x y] (Numeric/add (float x) (long y)))
Float (fn [x y] (Numeric/add (float x) (float y)))
Double (fn [x y] (Numeric/add (float x) (double y))))
Double (create-map
Byte (fn [x y] (Numeric/add (double x) (byte y)))
Character (fn [x y] (Numeric/add (double x) (char y)))
Short (fn [x y] (Numeric/add (double x) (short y)))
Integer (fn [x y] (Numeric/add (double x) (int y)))
Long (fn [x y] (Numeric/add (double x) (long y)))
Float (fn [x y] (Numeric/add (double x) (float y)))
Double (fn [x y] (Numeric/add (double x) (double y))))))
(def dispatch-map (gen-dispatch-map hash-map))
(defn dispatch-with-map [x y]
(let [f (some-> dispatch-map (get (class x)) (get (class y)))]
(assert (some? f))
(f x y)))
(defn map!* [constructor & args]
(assert (-> args count even?))
(reduce-pair (fn [ret k v] (.put ^Map ret k v) ret) (constructor) args))
(def hash-map! (partial map!* #(HashMap.)))
(def ^HashMap dispatch-map-mutable (gen-dispatch-map hash-map!))
(defn dispatch-with-map-mutable [x y]
(let [f (some-> dispatch-map-mutable ^HashMap (.get (class x)) (.get (class y)))]
(assert (some? f))
(f x y)))
(def identity-hash-map! (partial map!* #(IdentityHashMap.)))
(def ^IdentityHashMap dispatch-identity-map-mutable (gen-dispatch-map identity-hash-map!))
(defn dispatch-with-identity-map-mutable [x y]
(if-let [a0 (.get dispatch-identity-map-mutable (clojure.lang.Util/classOf x))]
(if-let [a1 (.get ^IdentityHashMap a0 (clojure.lang.Util/classOf y))]
(a1 x y)
(throw (Exception. "Method not found")))
(throw (Exception. "Method not found"))))
Colt 's OpenIntObjectHashMap does n't help here
(defn argtypes-unknown [a b] (+ a b))
(defmacro compile-time-class [x] (class (eval x)))
(def ^MethodHandle method-double-double
(.findVirtual Fn/fnLookup (compile-time-class +*-static-reified) "_PLUS__STAR_Static"
(Fn/methodType Double/TYPE Double/TYPE Double/TYPE)))
(def ^MethodHandle method
(.unreflect Fn/fnLookup (.getMethod (class +*-static-reified) "_PLUS__STAR_Static")))
13.650164 ns
(complete-bench (do (Fn/invoke method-double-double +*-static-reified 1.0 3.0)
#_(Fn/invoke method +*-static-reified 1 3 )))
(complete-bench (do (Fn/invoke method +*-static-reified 1.0 3.0)
#_(Fn/invoke method +*-static-reified 1 3 )))
All benchmarks use the lower quantile ( 2.5 % ) instead of considering outliers .
4.911254 ns
(complete-bench (do (+ 1.0 3.0)
(+ 1 3 )))
(complete-bench (do (Numeric/add 1.0 3.0)
(Numeric/add 1 3 )))
5.970614 ns
May currently have slightly worse performance since it is n't inlined , and is an instance instead of a static method
(let [^quantum.test.benchmarks.jvm._PLUS__STAR_StaticInterface
to get rid of var indirection , which ca n't be optimized away by the JVM because is marked as ` volatile `
(complete-bench (do (. +*-static-reified-direct _PLUS__STAR_Static 1.0 3.0)
(. +*-static-reified-direct _PLUS__STAR_Static 1 3 ))))
6.361026 ns
May currently have slightly worse performance since it is n't inlined , and is an instance instead of a static method
(complete-bench (do (+*-static 1.0 3.0)
(+*-static 1 3 )))
22.369795 ns ( 4.55x )
(complete-bench (do (argtypes-unknown 1.0 3.0)
(argtypes-unknown 1 3 )))
30.778042 ns ( 6.27x ) ( on first run is 23.467812 ns , 4.78x )
(complete-bench (do (Fn/dispatch2 dispatch-identity-map-mutable 1.0 3.0)
(Fn/dispatch2 dispatch-identity-map-mutable 1 3 )))
34.343497 ns
#_(complete-bench (do (Fn/dispatch2 dispatch-map-mutable 1.0 3.0)
(Fn/dispatch2 dispatch-map-mutable 1 3 )))
37.636059 ns ( 7.66x )
(complete-bench (do (case-hash-dispatch 1.0 3.0)
(case-hash-dispatch 1 3 )))
38.843166 ns
(complete-bench (do (case-string-dispatch 1.0 3.0)
(case-string-dispatch 1 3 )))
51.184897 ns ( 10.42x ) ( on first run is 33.707466 ns , 6.86x )
(complete-bench (do (+*-protocol-0 1.0 3.0)
(+*-protocol-0 1 3 )))
40.611242 ns
(complete-bench (do (dispatch-with-identity-map-mutable 1.0 3.0)
(dispatch-with-identity-map-mutable 1 3 )))
42.714549 ns
(complete-bench (do (dispatch-with-map-mutable 1.0 3.0)
(dispatch-with-map-mutable 1 3 )))
48.844710 ns
(complete-bench (do (dispatch 1.0 3.0)
(dispatch 1 3 )))
79.343540 ns
#_(complete-bench (do (dispatch-with-int->object-map-mutable 1.0 3.0)
(dispatch-with-int->object-map-mutable 1 3 )))
188.686935 ns
(complete-bench (.invokeWithArguments method (Array/newObjectArray +*-static-reified 1.0 3.0)))
212.066270 ns
(complete-bench (do (dispatch-with-map 1.0 3.0)
(dispatch-with-map 1 3 )))
(complete-bench
(Fn/invoke (.findVirtual Fn/fnLookup
(compile-time-class +*-static-boxed-reified)
"_PLUS__STAR_StaticBoxed"
(.unwrap (Fn/methodType Object Long Long)))
+*-static-boxed-reified 1 2))
#_"Resolved:
- Protocols may be 7.2x slower in this case but they're currently the only viable choice for multi-arg dispatch.
- Explore -std.org/jtc1/sc22/wg21/docs/papers/2007/n2216.pdf — perhaps a Clojure(Script)
implementation might yield the same speed benefits — i.e. *no statistical difference in performance
with direct dispatch*!
"
" Elapsed time : 365.916154 msecs " + , Add
" Elapsed time : 941.336378 msecs " Static
" Elapsed time : 20147.633612 msecs " Boxed math
" Elapsed time : 34638.789978 msecs " Dispatch , Dispatch Inlined
" Elapsed time : 46755.719601 msecs " Protocol
" Elapsed time : 68588.693153 msecs " Hash Dispatch
5.580126 ns
(let [v [1 2 3 4 5]]
(complete-bench (.get v 3)))
(let [v [1 2 3 4 5]]
(complete-bench (quantum.core.collections.core/get v 3)))
10.542661 ns
(let [v [1 2 3 4 5]]
(complete-bench (clojure.core/get v 3)))
(let [v [1 2 3 4 5]]
(complete-bench (quantum.core.collections.core/get-protocol v 3)))
(let [v (long-array [1 2 3 4 5])]
(complete-bench (clojure.core/aget v 3)))
(let [v (long-array [1 2 3 4 5])]
(complete-bench (quantum.core.data.Array/get v 3)))
8.691139 ns
(let [v (long-array [1 2 3 4 5])]
(complete-bench (quantum.core.collections.core/get v 3)))
(let [v (long-array [1 2 3 4 5])]
(complete-bench (quantum.core.collections.core/get-protocol v 3)))
(let [v (long-array [1 2 3 4 5])]
(complete-bench (clojure.core/get v 3)))
|
7fc65a58bfeb4ade356d7ad5153ee8c30553666e4a5ad04dd7c219b82e4facd1 | dpiponi/Moodler | HandleDraggingSelection.hs | module HandleDraggingSelection where
import Graphics.Gloss.Interface.IO.Game
import Control.Monad
import Control . Monad . Trans . Free
import Control.Lens hiding (setting)
import qualified Data.Set as S
import Sound.MoodlerLib.Quantise
import Sound.MoodlerLib.Symbols
import World
import WorldSupport
import ServerState
import UIElement
dragElement :: [UiId] -> Point -> [UiId] -> MoodlerM ()
dragElement top d sel = forM_ sel $ \s -> do
serverState . uiElements . ix s . ur . loc += d
elt <- getElementById "dragElement" s
case elt of
Container { _outside = cts } ->
-- If you drag a parent and its children then only the
-- parent needs to be expicitly dragged.
-- XXX use minimal parent func
dragElement top d (filter (not . flip elem top) $
S.toList cts)
_ -> return ()
handleDraggingSelection :: (Event -> MoodlerM Zero) -> Point ->
MoodlerM Zero
handleDraggingSelection handleDefault p0' =
getEvent >>= handleDraggingSelection' (quantise2 quantum p0')
where
doDrag :: Point -> Point -> MoodlerM ()
doDrag p0 p1 = do
sel <- use currentSelection
dragElement sel (p1-p0) sel
handleDraggingSelection' :: Point -> Event -> MoodlerM Zero
handleDraggingSelection' p0 (EventMotion p1') = do
let p1 = quantise2 quantum p1'
doDrag p0 p1
handleDraggingSelection handleDefault p1
handleDraggingSelection' p0
(EventKey (MouseButton LeftButton) Up _ p1') = do
let p1 = quantise2 quantum p1'
doDrag p0 p1
getEvent >>= handleDefault
handleDraggingSelection' a _ = handleDraggingSelection handleDefault a
| null | https://raw.githubusercontent.com/dpiponi/Moodler/a0c984c36abae52668d00f25eb3749e97e8936d3/Moodler/src/HandleDraggingSelection.hs | haskell | If you drag a parent and its children then only the
parent needs to be expicitly dragged.
XXX use minimal parent func | module HandleDraggingSelection where
import Graphics.Gloss.Interface.IO.Game
import Control.Monad
import Control . Monad . Trans . Free
import Control.Lens hiding (setting)
import qualified Data.Set as S
import Sound.MoodlerLib.Quantise
import Sound.MoodlerLib.Symbols
import World
import WorldSupport
import ServerState
import UIElement
dragElement :: [UiId] -> Point -> [UiId] -> MoodlerM ()
dragElement top d sel = forM_ sel $ \s -> do
serverState . uiElements . ix s . ur . loc += d
elt <- getElementById "dragElement" s
case elt of
Container { _outside = cts } ->
dragElement top d (filter (not . flip elem top) $
S.toList cts)
_ -> return ()
handleDraggingSelection :: (Event -> MoodlerM Zero) -> Point ->
MoodlerM Zero
handleDraggingSelection handleDefault p0' =
getEvent >>= handleDraggingSelection' (quantise2 quantum p0')
where
doDrag :: Point -> Point -> MoodlerM ()
doDrag p0 p1 = do
sel <- use currentSelection
dragElement sel (p1-p0) sel
handleDraggingSelection' :: Point -> Event -> MoodlerM Zero
handleDraggingSelection' p0 (EventMotion p1') = do
let p1 = quantise2 quantum p1'
doDrag p0 p1
handleDraggingSelection handleDefault p1
handleDraggingSelection' p0
(EventKey (MouseButton LeftButton) Up _ p1') = do
let p1 = quantise2 quantum p1'
doDrag p0 p1
getEvent >>= handleDefault
handleDraggingSelection' a _ = handleDraggingSelection handleDefault a
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.