_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
4e04e8da6b5ec00e3f873dcb33bcd4cc1fa1cdc1fe9505c0a8a21f387bf53823
susanemcg/pandoc-tufteLaTeX2GitBook
Helpers.hs
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} -- Utility functions for the test suite. module Tests.Helpers ( test , (=?>) , property , ToString(..) , ToPandoc(..) ) where import Text.Pandoc.Definition import Text.Pandoc.Builder (Inlines, Blocks, doc, plain) import Test.Framework import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck2 import Test.HUnit (assertBool) import Text.Pandoc.Shared (normalize, trimr) import Text.Pandoc.Options import Text.Pandoc.Writers.Native (writeNative) import qualified Test.QuickCheck.Property as QP import Data.Algorithm.Diff import qualified Data.Map as M test :: (ToString a, ToString b, ToString c) => (a -> b) -- ^ function to test -> String -- ^ name of test case -> (a, c) -- ^ (input, expected value) -> Test test fn name (input, expected) = testCase name $ assertBool msg (actual' == expected') where msg = nl ++ dashes "input" ++ nl ++ input' ++ nl ++ dashes "result" ++ nl ++ unlines (map vividize diff) ++ dashes "" nl = "\n" input' = toString input actual' = lines $ toString $ fn input expected' = lines $ toString expected diff = getDiff expected' actual' dashes "" = replicate 72 '-' dashes x = replicate (72 - length x - 5) '-' ++ " " ++ x ++ " ---" vividize :: Diff String -> String vividize (Both s _) = " " ++ s vividize (First s) = "- " ++ s vividize (Second s) = "+ " ++ s property :: QP.Testable a => TestName -> a -> Test property = testProperty infix 5 =?> (=?>) :: a -> b -> (a,b) x =?> y = (x, y) class ToString a where toString :: a -> String instance ToString Pandoc where toString d = writeNative def{ writerStandalone = s } $ toPandoc d where s = case d of (Pandoc (Meta m) _) | M.null m -> False | otherwise -> True instance ToString Blocks where toString = writeNative def . toPandoc instance ToString Inlines where toString = trimr . writeNative def . toPandoc instance ToString String where toString = id class ToPandoc a where toPandoc :: a -> Pandoc instance ToPandoc Pandoc where toPandoc = normalize instance ToPandoc Blocks where toPandoc = normalize . doc instance ToPandoc Inlines where toPandoc = normalize . doc . plain
null
https://raw.githubusercontent.com/susanemcg/pandoc-tufteLaTeX2GitBook/00c34b4299dd89c4e339e1cde006061918b559ab/pandoc-1.12.4.2/tests/Tests/Helpers.hs
haskell
# LANGUAGE TypeSynonymInstances, FlexibleInstances # Utility functions for the test suite. ^ function to test ^ name of test case ^ (input, expected value)
module Tests.Helpers ( test , (=?>) , property , ToString(..) , ToPandoc(..) ) where import Text.Pandoc.Definition import Text.Pandoc.Builder (Inlines, Blocks, doc, plain) import Test.Framework import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck2 import Test.HUnit (assertBool) import Text.Pandoc.Shared (normalize, trimr) import Text.Pandoc.Options import Text.Pandoc.Writers.Native (writeNative) import qualified Test.QuickCheck.Property as QP import Data.Algorithm.Diff import qualified Data.Map as M test :: (ToString a, ToString b, ToString c) -> Test test fn name (input, expected) = testCase name $ assertBool msg (actual' == expected') where msg = nl ++ dashes "input" ++ nl ++ input' ++ nl ++ dashes "result" ++ nl ++ unlines (map vividize diff) ++ dashes "" nl = "\n" input' = toString input actual' = lines $ toString $ fn input expected' = lines $ toString expected diff = getDiff expected' actual' dashes "" = replicate 72 '-' dashes x = replicate (72 - length x - 5) '-' ++ " " ++ x ++ " ---" vividize :: Diff String -> String vividize (Both s _) = " " ++ s vividize (First s) = "- " ++ s vividize (Second s) = "+ " ++ s property :: QP.Testable a => TestName -> a -> Test property = testProperty infix 5 =?> (=?>) :: a -> b -> (a,b) x =?> y = (x, y) class ToString a where toString :: a -> String instance ToString Pandoc where toString d = writeNative def{ writerStandalone = s } $ toPandoc d where s = case d of (Pandoc (Meta m) _) | M.null m -> False | otherwise -> True instance ToString Blocks where toString = writeNative def . toPandoc instance ToString Inlines where toString = trimr . writeNative def . toPandoc instance ToString String where toString = id class ToPandoc a where toPandoc :: a -> Pandoc instance ToPandoc Pandoc where toPandoc = normalize instance ToPandoc Blocks where toPandoc = normalize . doc instance ToPandoc Inlines where toPandoc = normalize . doc . plain
146ae74d667cad4e93b34307d9e2592eb2a32d5e115bab557560d95fe0a3c2bf
jtza8/interact
animation-sprite.lisp
; Use of this source code is governed by a BSD-style license that can be found in the license.txt file ; in the root directory of this project. (in-package :interact) (defclass animation-sprite (sprite) ((fps :initarg :fps :initform (error "must specify fps") :accessor fps) (sprite-vector :initarg :sprite-vector :initform (error "must specify sprite vector")) (watch :initform (make-instance 'watch)) (repeating :initform t :initarg :looping))) (defmethod initialize-instance :after ((sprite animation-sprite) &key (start t)) (with-slots (sprite-vector watch) sprite (check-type sprite-vector vector) (assert (> (length sprite-vector) 0)) (when start (start watch)))) (defmethod clone ((sprite animation-sprite) &rest init-args) (with-slots (height width fps sprite-vector repeating) sprite (apply #'make-instance 'animation-sprite (append init-args (list :height height :width width :fps fps :sprite-vector sprite-vector :looping repeating))))) (defmethod draw-sprite ((sprite animation-sprite) &key (x 0) (y 0) width height) (with-slots (fps sprite-vector watch repeating) sprite (let* ((frame-counter (truncate (* (lap watch :sec) fps))) (frame-count (length sprite-vector)) (frame-number (if repeating (rem frame-counter frame-count) (if (>= frame-counter frame-count) (progn (when (running-p watch) (stop watch)) (1- frame-count)) frame-counter)))) (draw-sprite (aref sprite-vector frame-number) :x x :y y :width width :height height)))) (defmethod free ((sprite animation-sprite)) (with-slots (sprite-vector) sprite (map nil #'free sprite-vector))) (macrolet ((messages-to-watch (&rest messages) `(progn ,@(loop for message in messages collect `(defmethod ,message ((sprite animation-sprite)) (with-slots (watch) sprite (,message watch))))))) (messages-to-watch start stop))
null
https://raw.githubusercontent.com/jtza8/interact/ea2121d7e900dac4fe2a085bd5f2783a640e71f8/src/animation-sprite.lisp
lisp
Use of this source code is governed by a BSD-style in the root directory of this project.
license that can be found in the license.txt file (in-package :interact) (defclass animation-sprite (sprite) ((fps :initarg :fps :initform (error "must specify fps") :accessor fps) (sprite-vector :initarg :sprite-vector :initform (error "must specify sprite vector")) (watch :initform (make-instance 'watch)) (repeating :initform t :initarg :looping))) (defmethod initialize-instance :after ((sprite animation-sprite) &key (start t)) (with-slots (sprite-vector watch) sprite (check-type sprite-vector vector) (assert (> (length sprite-vector) 0)) (when start (start watch)))) (defmethod clone ((sprite animation-sprite) &rest init-args) (with-slots (height width fps sprite-vector repeating) sprite (apply #'make-instance 'animation-sprite (append init-args (list :height height :width width :fps fps :sprite-vector sprite-vector :looping repeating))))) (defmethod draw-sprite ((sprite animation-sprite) &key (x 0) (y 0) width height) (with-slots (fps sprite-vector watch repeating) sprite (let* ((frame-counter (truncate (* (lap watch :sec) fps))) (frame-count (length sprite-vector)) (frame-number (if repeating (rem frame-counter frame-count) (if (>= frame-counter frame-count) (progn (when (running-p watch) (stop watch)) (1- frame-count)) frame-counter)))) (draw-sprite (aref sprite-vector frame-number) :x x :y y :width width :height height)))) (defmethod free ((sprite animation-sprite)) (with-slots (sprite-vector) sprite (map nil #'free sprite-vector))) (macrolet ((messages-to-watch (&rest messages) `(progn ,@(loop for message in messages collect `(defmethod ,message ((sprite animation-sprite)) (with-slots (watch) sprite (,message watch))))))) (messages-to-watch start stop))
04482fda06a3e0d1be29b16ed024721dde35d2f5bcd07ad06799d90f1470d7c7
logseq/logseq
header.cljs
(ns frontend.components.header (:require [cljs-bean.core :as bean] [frontend.components.export :as export] [frontend.components.page-menu :as page-menu] [frontend.components.plugins :as plugins] [frontend.components.server :as server] [frontend.components.right-sidebar :as sidebar] [frontend.components.svg :as svg] [frontend.config :as config] [frontend.context.i18n :refer [t]] [frontend.handler :as handler] [frontend.handler.file-sync :as file-sync-handler] [frontend.components.file-sync :as fs-sync] [frontend.handler.plugin :as plugin-handler] [frontend.handler.route :as route-handler] [frontend.handler.user :as user-handler] [frontend.handler.web.nfs :as nfs] [frontend.mobile.util :as mobile-util] [frontend.state :as state] [frontend.ui :as ui] [frontend.util :as util] [frontend.version :refer [version]] [reitit.frontend.easy :as rfe] [rum.core :as rum] [clojure.string :as string])) (rum/defc home-button < {:key-fn #(identity "home-button")} [] (ui/with-shortcut :go/home "left" [:button.button.icon.inline {:title "Home" :on-click #(do (when (mobile-util/native-iphone?) (state/set-left-sidebar-open! false)) (route-handler/redirect-to-home!))} (ui/icon "home" {:size ui/icon-size})])) (rum/defc login < rum/reactive < {:key-fn #(identity "login-button")} [] (let [_ (state/sub :auth/id-token) loading? (state/sub [:ui/loading? :login]) sync-enabled? (file-sync-handler/enable-sync?) logged? (user-handler/logged-in?)] (when-not (or config/publishing? logged? (not sync-enabled?)) [:a.button.text-sm.font-medium.block {:on-click #(js/window.open config/LOGIN-URL)} [:span (t :login)] (when loading? [:span.ml-2 (ui/loading "")])]))) (rum/defc left-menu-button < rum/reactive < {:key-fn #(identity "left-menu-toggle-button")} [{:keys [on-click]}] (ui/with-shortcut :ui/toggle-left-sidebar "bottom" [:button.#left-menu.cp__header-left-menu.button.icon {:title "Toggle left menu" :on-click on-click} (ui/icon "menu-2" {:size ui/icon-size})])) (def bug-report-url (let [ua (.-userAgent js/navigator) safe-ua (string/replace ua #"[^_/a-zA-Z0-9\.\(\)]+" " ") platform (str "App Version: " version "\n" "Git Revision: " config/REVISION "\n" "Platform: " safe-ua "\n" "Language: " (.-language js/navigator))] (str "?" "title=&" "template=bug_report.yaml&" "labels=from:in-app&" "platform=" (js/encodeURIComponent platform)))) (rum/defc dropdown-menu < rum/reactive < {:key-fn #(identity "repos-dropdown-menu")} [{:keys [current-repo t]}] (let [page-menu (page-menu/page-menu nil) page-menu-and-hr (when (seq page-menu) (concat page-menu [{:hr true}]))] (ui/dropdown-with-links (fn [{:keys [toggle-fn]}] [:button.button.icon.toolbar-dots-btn {:on-click toggle-fn :title "More"} (ui/icon "dots" {:size ui/icon-size})]) (->> [(when (state/enable-editing?) {:title (t :settings) :options {:on-click state/open-settings!} :icon (ui/icon "settings")}) (when config/lsp-enabled? {:title (t :plugins) :options {:on-click #(plugin-handler/goto-plugins-dashboard!)} :icon (ui/icon "apps")}) (when config/lsp-enabled? {:title (t :themes) :options {:on-click #(plugins/open-select-theme!)} :icon (ui/icon "palette")}) (when current-repo {:title (t :export-graph) :options {:on-click #(state/set-modal! export/export)} :icon (ui/icon "database-export")}) (when (and current-repo (state/enable-editing?)) {:title (t :import) :options {:href (rfe/href :import)} :icon (ui/icon "file-upload")}) {:title [:div.flex-row.flex.justify-between.items-center [:span (t :join-community)]] :options {:href "" :title (t :discourse-title) :target "_blank"} :icon (ui/icon "brand-discord")} {:title [:div.flex-row.flex.justify-between.items-center [:span (t :help/bug)]] :options {:href (rfe/href :bug-report)} :icon (ui/icon "bug")} (when (and (state/sub :auth/id-token) (user-handler/logged-in?)) {:title (str (t :logout) " (" (user-handler/email) ")") :options {:on-click #(user-handler/logout)} :icon (ui/icon "logout")})] (concat page-menu-and-hr) (remove nil?)) {}))) (rum/defc back-and-forward < {:key-fn #(identity "nav-history-buttons")} [] [:div.flex.flex-row (ui/with-shortcut :go/backward "bottom" [:button.it.navigation.nav-left.button.icon {:title "Go back" :on-click #(js/window.history.back)} (ui/icon "arrow-left" {:size ui/icon-size})]) (ui/with-shortcut :go/forward "bottom" [:button.it.navigation.nav-right.button.icon {:title "Go forward" :on-click #(js/window.history.forward)} (ui/icon "arrow-right" {:size ui/icon-size})])]) (rum/defc updater-tips-new-version [t] (let [[downloaded, set-downloaded] (rum/use-state nil) _ (rum/use-effect! (fn [] (when-let [channel (and (util/electron?) "auto-updater-downloaded")] (let [callback (fn [_ args] (js/console.debug "[new-version downloaded] args:" args) (let [args (bean/->clj args)] (set-downloaded args) (state/set-state! :electron/auto-updater-downloaded args)) nil)] (js/apis.addListener channel callback) #(js/apis.removeListener channel callback)))) [])] (when downloaded [:div.cp__header-tips [:p (t :updater/new-version-install) [:a.restart.ml-2 {:on-click #(handler/quit-and-install-new-version!)} (svg/reload 16) [:strong (t :updater/quit-and-install)]]]]))) (rum/defc ^:large-vars/cleanup-todo header < rum/reactive [{:keys [open-fn current-repo default-home new-block-mode]}] (let [repos (->> (state/sub [:me :repos]) (remove #(= (:url %) config/local-repo))) _ (state/sub [:user/info :UserGroups]) electron-mac? (and util/mac? (util/electron?)) show-open-folder? (and (nfs/supported?) (or (empty? repos) (nil? (state/sub :git/current-repo))) (not (mobile-util/native-platform?)) (not config/publishing?)) left-menu (left-menu-button {:on-click (fn [] (open-fn) (state/set-left-sidebar-open! (not (:ui/left-sidebar-open? @state/state))))}) custom-home-page? (and (state/custom-home-page?) (= (state/sub-default-home-page) (state/get-current-page))) sync-enabled? (file-sync-handler/enable-sync?)] [:div.cp__header.drag-region#head {:class (util/classnames [{:electron-mac electron-mac? :native-ios (mobile-util/native-ios?) :native-android (mobile-util/native-android?)}]) :on-double-click (fn [^js e] (when-let [target (.-target e)] (cond (and (util/electron?) (.. target -classList (contains "drag-region"))) (js/window.apis.toggleMaxOrMinActiveWindow) (mobile-util/native-platform?) (util/scroll-to-top true)))) :style {:fontSize 50}} [:div.l.flex.drag-region [left-menu (if (mobile-util/native-platform?) ;; back button for mobile (when-not (or (state/home?) custom-home-page? (state/whiteboard-dashboard?)) (ui/with-shortcut :go/backward "bottom" [:button.it.navigation.nav-left.button.icon.opacity-70 {:title "Go back" :on-click #(js/window.history.back)} (ui/icon "chevron-left" {:size 26})])) ;; search button for non-mobile (when current-repo (ui/with-shortcut :go/search "right" [:button.button.icon#search-button {:title "Search" :on-click #(do (when (or (mobile-util/native-android?) (mobile-util/native-iphone?)) (state/set-left-sidebar-open! false)) (state/pub-event! [:go/search]))} (ui/icon "search" {:size ui/icon-size})])))]] [:div.r.flex.drag-region (when (and current-repo (not (config/demo-graph? current-repo)) (user-handler/alpha-or-beta-user?)) (fs-sync/indicator)) (when (and (not= (state/get-current-route) :home) (not custom-home-page?)) (home-button)) (when sync-enabled? (login)) (when config/lsp-enabled? (plugins/hook-ui-items :toolbar)) (when (state/feature-http-server-enabled?) (server/server-indicator (state/sub :electron/server))) (when (util/electron?) (back-and-forward)) (when-not (mobile-util/native-platform?) (new-block-mode)) (when show-open-folder? [:a.text-sm.font-medium.button.icon.add-graph-btn.flex.items-center {:on-click #(route-handler/redirect! {:to :repo-add})} (ui/icon "folder-plus") (when-not config/mobile? [:span.ml-1 {:style {:margin-top (if electron-mac? 0 2)}} (t :on-boarding/add-graph)])]) (when config/publishing? [:a.text-sm.font-medium.button {:href (rfe/href :graph)} (t :graph)]) (dropdown-menu {:t t :current-repo current-repo :default-home default-home}) (when (not (state/sub :ui/sidebar-open?)) (sidebar/toggle)) (updater-tips-new-version t)]]))
null
https://raw.githubusercontent.com/logseq/logseq/c83c9733386705127f2fed740e6f9840bbb14157/src/main/frontend/components/header.cljs
clojure
back button for mobile search button for non-mobile
(ns frontend.components.header (:require [cljs-bean.core :as bean] [frontend.components.export :as export] [frontend.components.page-menu :as page-menu] [frontend.components.plugins :as plugins] [frontend.components.server :as server] [frontend.components.right-sidebar :as sidebar] [frontend.components.svg :as svg] [frontend.config :as config] [frontend.context.i18n :refer [t]] [frontend.handler :as handler] [frontend.handler.file-sync :as file-sync-handler] [frontend.components.file-sync :as fs-sync] [frontend.handler.plugin :as plugin-handler] [frontend.handler.route :as route-handler] [frontend.handler.user :as user-handler] [frontend.handler.web.nfs :as nfs] [frontend.mobile.util :as mobile-util] [frontend.state :as state] [frontend.ui :as ui] [frontend.util :as util] [frontend.version :refer [version]] [reitit.frontend.easy :as rfe] [rum.core :as rum] [clojure.string :as string])) (rum/defc home-button < {:key-fn #(identity "home-button")} [] (ui/with-shortcut :go/home "left" [:button.button.icon.inline {:title "Home" :on-click #(do (when (mobile-util/native-iphone?) (state/set-left-sidebar-open! false)) (route-handler/redirect-to-home!))} (ui/icon "home" {:size ui/icon-size})])) (rum/defc login < rum/reactive < {:key-fn #(identity "login-button")} [] (let [_ (state/sub :auth/id-token) loading? (state/sub [:ui/loading? :login]) sync-enabled? (file-sync-handler/enable-sync?) logged? (user-handler/logged-in?)] (when-not (or config/publishing? logged? (not sync-enabled?)) [:a.button.text-sm.font-medium.block {:on-click #(js/window.open config/LOGIN-URL)} [:span (t :login)] (when loading? [:span.ml-2 (ui/loading "")])]))) (rum/defc left-menu-button < rum/reactive < {:key-fn #(identity "left-menu-toggle-button")} [{:keys [on-click]}] (ui/with-shortcut :ui/toggle-left-sidebar "bottom" [:button.#left-menu.cp__header-left-menu.button.icon {:title "Toggle left menu" :on-click on-click} (ui/icon "menu-2" {:size ui/icon-size})])) (def bug-report-url (let [ua (.-userAgent js/navigator) safe-ua (string/replace ua #"[^_/a-zA-Z0-9\.\(\)]+" " ") platform (str "App Version: " version "\n" "Git Revision: " config/REVISION "\n" "Platform: " safe-ua "\n" "Language: " (.-language js/navigator))] (str "?" "title=&" "template=bug_report.yaml&" "labels=from:in-app&" "platform=" (js/encodeURIComponent platform)))) (rum/defc dropdown-menu < rum/reactive < {:key-fn #(identity "repos-dropdown-menu")} [{:keys [current-repo t]}] (let [page-menu (page-menu/page-menu nil) page-menu-and-hr (when (seq page-menu) (concat page-menu [{:hr true}]))] (ui/dropdown-with-links (fn [{:keys [toggle-fn]}] [:button.button.icon.toolbar-dots-btn {:on-click toggle-fn :title "More"} (ui/icon "dots" {:size ui/icon-size})]) (->> [(when (state/enable-editing?) {:title (t :settings) :options {:on-click state/open-settings!} :icon (ui/icon "settings")}) (when config/lsp-enabled? {:title (t :plugins) :options {:on-click #(plugin-handler/goto-plugins-dashboard!)} :icon (ui/icon "apps")}) (when config/lsp-enabled? {:title (t :themes) :options {:on-click #(plugins/open-select-theme!)} :icon (ui/icon "palette")}) (when current-repo {:title (t :export-graph) :options {:on-click #(state/set-modal! export/export)} :icon (ui/icon "database-export")}) (when (and current-repo (state/enable-editing?)) {:title (t :import) :options {:href (rfe/href :import)} :icon (ui/icon "file-upload")}) {:title [:div.flex-row.flex.justify-between.items-center [:span (t :join-community)]] :options {:href "" :title (t :discourse-title) :target "_blank"} :icon (ui/icon "brand-discord")} {:title [:div.flex-row.flex.justify-between.items-center [:span (t :help/bug)]] :options {:href (rfe/href :bug-report)} :icon (ui/icon "bug")} (when (and (state/sub :auth/id-token) (user-handler/logged-in?)) {:title (str (t :logout) " (" (user-handler/email) ")") :options {:on-click #(user-handler/logout)} :icon (ui/icon "logout")})] (concat page-menu-and-hr) (remove nil?)) {}))) (rum/defc back-and-forward < {:key-fn #(identity "nav-history-buttons")} [] [:div.flex.flex-row (ui/with-shortcut :go/backward "bottom" [:button.it.navigation.nav-left.button.icon {:title "Go back" :on-click #(js/window.history.back)} (ui/icon "arrow-left" {:size ui/icon-size})]) (ui/with-shortcut :go/forward "bottom" [:button.it.navigation.nav-right.button.icon {:title "Go forward" :on-click #(js/window.history.forward)} (ui/icon "arrow-right" {:size ui/icon-size})])]) (rum/defc updater-tips-new-version [t] (let [[downloaded, set-downloaded] (rum/use-state nil) _ (rum/use-effect! (fn [] (when-let [channel (and (util/electron?) "auto-updater-downloaded")] (let [callback (fn [_ args] (js/console.debug "[new-version downloaded] args:" args) (let [args (bean/->clj args)] (set-downloaded args) (state/set-state! :electron/auto-updater-downloaded args)) nil)] (js/apis.addListener channel callback) #(js/apis.removeListener channel callback)))) [])] (when downloaded [:div.cp__header-tips [:p (t :updater/new-version-install) [:a.restart.ml-2 {:on-click #(handler/quit-and-install-new-version!)} (svg/reload 16) [:strong (t :updater/quit-and-install)]]]]))) (rum/defc ^:large-vars/cleanup-todo header < rum/reactive [{:keys [open-fn current-repo default-home new-block-mode]}] (let [repos (->> (state/sub [:me :repos]) (remove #(= (:url %) config/local-repo))) _ (state/sub [:user/info :UserGroups]) electron-mac? (and util/mac? (util/electron?)) show-open-folder? (and (nfs/supported?) (or (empty? repos) (nil? (state/sub :git/current-repo))) (not (mobile-util/native-platform?)) (not config/publishing?)) left-menu (left-menu-button {:on-click (fn [] (open-fn) (state/set-left-sidebar-open! (not (:ui/left-sidebar-open? @state/state))))}) custom-home-page? (and (state/custom-home-page?) (= (state/sub-default-home-page) (state/get-current-page))) sync-enabled? (file-sync-handler/enable-sync?)] [:div.cp__header.drag-region#head {:class (util/classnames [{:electron-mac electron-mac? :native-ios (mobile-util/native-ios?) :native-android (mobile-util/native-android?)}]) :on-double-click (fn [^js e] (when-let [target (.-target e)] (cond (and (util/electron?) (.. target -classList (contains "drag-region"))) (js/window.apis.toggleMaxOrMinActiveWindow) (mobile-util/native-platform?) (util/scroll-to-top true)))) :style {:fontSize 50}} [:div.l.flex.drag-region [left-menu (if (mobile-util/native-platform?) (when-not (or (state/home?) custom-home-page? (state/whiteboard-dashboard?)) (ui/with-shortcut :go/backward "bottom" [:button.it.navigation.nav-left.button.icon.opacity-70 {:title "Go back" :on-click #(js/window.history.back)} (ui/icon "chevron-left" {:size 26})])) (when current-repo (ui/with-shortcut :go/search "right" [:button.button.icon#search-button {:title "Search" :on-click #(do (when (or (mobile-util/native-android?) (mobile-util/native-iphone?)) (state/set-left-sidebar-open! false)) (state/pub-event! [:go/search]))} (ui/icon "search" {:size ui/icon-size})])))]] [:div.r.flex.drag-region (when (and current-repo (not (config/demo-graph? current-repo)) (user-handler/alpha-or-beta-user?)) (fs-sync/indicator)) (when (and (not= (state/get-current-route) :home) (not custom-home-page?)) (home-button)) (when sync-enabled? (login)) (when config/lsp-enabled? (plugins/hook-ui-items :toolbar)) (when (state/feature-http-server-enabled?) (server/server-indicator (state/sub :electron/server))) (when (util/electron?) (back-and-forward)) (when-not (mobile-util/native-platform?) (new-block-mode)) (when show-open-folder? [:a.text-sm.font-medium.button.icon.add-graph-btn.flex.items-center {:on-click #(route-handler/redirect! {:to :repo-add})} (ui/icon "folder-plus") (when-not config/mobile? [:span.ml-1 {:style {:margin-top (if electron-mac? 0 2)}} (t :on-boarding/add-graph)])]) (when config/publishing? [:a.text-sm.font-medium.button {:href (rfe/href :graph)} (t :graph)]) (dropdown-menu {:t t :current-repo current-repo :default-home default-home}) (when (not (state/sub :ui/sidebar-open?)) (sidebar/toggle)) (updater-tips-new-version t)]]))
5b1ebf09e7f0037b5c504629d3f02283f669d056720b489206196e8fcc7e3619
lemmaandrew/CodingBatHaskell
stringMatch.hs
From Given 2 strings , a and b , return the number of the positions where they contain the same length 2 substring . So \"xxcaazz\ " and \"xxbaaz\ " yields 3 , since the \"xx\ " , \"aa\ " , and \"az\ " substrings appear in the same place in both strings . Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So \"xxcaazz\" and \"xxbaaz\" yields 3, since the \"xx\", \"aa\", and \"az\" substrings appear in the same place in both strings. -} import Test.Hspec ( hspec, describe, it, shouldBe ) stringMatch :: String -> String -> Int stringMatch a b = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "3" $ stringMatch "xxcaazz" "xxbaaz" `shouldBe` 3 it "2" $ stringMatch "abc" "abc" `shouldBe` 2 it "0" $ stringMatch "abc" "axc" `shouldBe` 0 it "1" $ stringMatch "hello" "he" `shouldBe` 1 it "1" $ stringMatch "he" "hello" `shouldBe` 1 it "0" $ stringMatch "h" "hello" `shouldBe` 0 it "0" $ stringMatch "" "hello" `shouldBe` 0 it "1" $ stringMatch "aabbccdd" "abbbxxd" `shouldBe` 1 it "3" $ stringMatch "aaxxaaxx" "iaxxai" `shouldBe` 3 it "3" $ stringMatch "iaxxai" "aaxxaaxx" `shouldBe` 3
null
https://raw.githubusercontent.com/lemmaandrew/CodingBatHaskell/d839118be02e1867504206657a0664fd79d04736/CodingBat/Warmup-2/stringMatch.hs
haskell
From Given 2 strings , a and b , return the number of the positions where they contain the same length 2 substring . So \"xxcaazz\ " and \"xxbaaz\ " yields 3 , since the \"xx\ " , \"aa\ " , and \"az\ " substrings appear in the same place in both strings . Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So \"xxcaazz\" and \"xxbaaz\" yields 3, since the \"xx\", \"aa\", and \"az\" substrings appear in the same place in both strings. -} import Test.Hspec ( hspec, describe, it, shouldBe ) stringMatch :: String -> String -> Int stringMatch a b = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "3" $ stringMatch "xxcaazz" "xxbaaz" `shouldBe` 3 it "2" $ stringMatch "abc" "abc" `shouldBe` 2 it "0" $ stringMatch "abc" "axc" `shouldBe` 0 it "1" $ stringMatch "hello" "he" `shouldBe` 1 it "1" $ stringMatch "he" "hello" `shouldBe` 1 it "0" $ stringMatch "h" "hello" `shouldBe` 0 it "0" $ stringMatch "" "hello" `shouldBe` 0 it "1" $ stringMatch "aabbccdd" "abbbxxd" `shouldBe` 1 it "3" $ stringMatch "aaxxaaxx" "iaxxai" `shouldBe` 3 it "3" $ stringMatch "iaxxai" "aaxxaaxx" `shouldBe` 3
3a2b17ed413cf6c960c835d143b49aa3a2125bc6a3b824cd0b73f1d55db57291
WormBase/wormbase_rest
overview.clj
(ns rest-api.classes.structure-data.widgets.overview (:require [datomic.api :as d] [rest-api.classes.generic-fields :as generic] [rest-api.db.main :refer [datomic-homology-conn]] [rest-api.formatters.object :as obj :refer [pack-obj]])) (defn sequence-field [s] {:data (when-let [protein (:structure-data/protein s)] (pack-obj protein)) :description "sequence of structure"}) We decided this data would only be provided to the UI through the (defn homology-data [s] {:data nil :description "Protein homologs for this structure"}) (defn status [s] {:data (cond (contains? s :structure-data/selected) "Selected" (contains? s :structure-data/cloned) "cloned" (contains? s :structure-data/expressed) "Expressed") :description (str "current status of the Structure_data:" (:structure-data/id s) " if not Live or Valid")}) (defn protein-homology [s] {:data (let [db (d/entity-db s) hdb (d/db datomic-homology-conn)] (some->> (d/q '[:find [?sid ...] :in $ $hdb ?sid :where [$hdb ?sd :structure-data/id ?sid] [$hdb ?h :homology/structure ?sd] [$hdb ?h :locatable/parent ?ph] [$hdb ?hp :protein/id ?hpid] [$ ?p :protein/id ?hpid]] db hdb (:structure-data/id s)) (map (fn [id] (let [protein (d/entity hdb id)] (keys protein)))))) :description "homology data re: this structure"}) (def widget {:name generic/name-field :sequence sequence-field :protein_homology protein-homology :status status ;:homology_data homology-data :remarks generic/remarks})
null
https://raw.githubusercontent.com/WormBase/wormbase_rest/e51026f35b87d96260b62ddb5458a81ee911bf3a/src/rest_api/classes/structure_data/widgets/overview.clj
clojure
:homology_data homology-data
(ns rest-api.classes.structure-data.widgets.overview (:require [datomic.api :as d] [rest-api.classes.generic-fields :as generic] [rest-api.db.main :refer [datomic-homology-conn]] [rest-api.formatters.object :as obj :refer [pack-obj]])) (defn sequence-field [s] {:data (when-let [protein (:structure-data/protein s)] (pack-obj protein)) :description "sequence of structure"}) We decided this data would only be provided to the UI through the (defn homology-data [s] {:data nil :description "Protein homologs for this structure"}) (defn status [s] {:data (cond (contains? s :structure-data/selected) "Selected" (contains? s :structure-data/cloned) "cloned" (contains? s :structure-data/expressed) "Expressed") :description (str "current status of the Structure_data:" (:structure-data/id s) " if not Live or Valid")}) (defn protein-homology [s] {:data (let [db (d/entity-db s) hdb (d/db datomic-homology-conn)] (some->> (d/q '[:find [?sid ...] :in $ $hdb ?sid :where [$hdb ?sd :structure-data/id ?sid] [$hdb ?h :homology/structure ?sd] [$hdb ?h :locatable/parent ?ph] [$hdb ?hp :protein/id ?hpid] [$ ?p :protein/id ?hpid]] db hdb (:structure-data/id s)) (map (fn [id] (let [protein (d/entity hdb id)] (keys protein)))))) :description "homology data re: this structure"}) (def widget {:name generic/name-field :sequence sequence-field :protein_homology protein-homology :status status :remarks generic/remarks})
93b5b1ebd7ec5f6108af96c929a35b1650362a29ed12483fcfde3ba5fbe3dbd4
tqtezos/stablecoin
StablecoinPath.hs
SPDX - FileCopyrightText : 2020 SPDX - License - Identifier : MIT | This module contains only the paths to the compiled LIGO contracts . -- Due to GHC stage restriction , they have to be in their own module in order to be used inside TemplateHaskell splices . module Lorentz.Contracts.StablecoinPath ( metadataRegistryContractPath , stablecoinFA1_2Path , stablecoinPath ) where -- | The path to the compiled stablecoin contract. stablecoinPath :: FilePath stablecoinPath = "./test/resources/stablecoin.tz" -- | The path to the compiled stablecoin FA1.2 contract. stablecoinFA1_2Path :: FilePath stablecoinFA1_2Path = "./test/resources/stablecoin.fa1.2.tz" -- | The path to the compiled metadata registry. metadataRegistryContractPath :: FilePath metadataRegistryContractPath = "./test/resources/metadata.tz"
null
https://raw.githubusercontent.com/tqtezos/stablecoin/e3e1d8694f27842b1a0ffe985f6d4a9d3e80b70f/haskell/src/Lorentz/Contracts/StablecoinPath.hs
haskell
| The path to the compiled stablecoin contract. | The path to the compiled stablecoin FA1.2 contract. | The path to the compiled metadata registry.
SPDX - FileCopyrightText : 2020 SPDX - License - Identifier : MIT | This module contains only the paths to the compiled LIGO contracts . Due to GHC stage restriction , they have to be in their own module in order to be used inside TemplateHaskell splices . module Lorentz.Contracts.StablecoinPath ( metadataRegistryContractPath , stablecoinFA1_2Path , stablecoinPath ) where stablecoinPath :: FilePath stablecoinPath = "./test/resources/stablecoin.tz" stablecoinFA1_2Path :: FilePath stablecoinFA1_2Path = "./test/resources/stablecoin.fa1.2.tz" metadataRegistryContractPath :: FilePath metadataRegistryContractPath = "./test/resources/metadata.tz"
ca53fa747e3af5be9035bc0aaed95fc79ec3850334721bb3b0fb332b4c59508b
tnelson/Forge
orderOfOpsExprs.rkt
#lang forge option run_sterling off option verbose 0 option problem_type temporal var sig Node { var edges : set Node, var fruit : set Node } test expect { tildeTighterThanPrimeSat : { always ~edges' = (~edges)' } is sat tildeTighterThanPrimeTheorem : { always ~edges' = (~edges)' } is theorem tranisitiveClosureTighterThanPrimeSat : { always ^edges' = (^edges)' } is sat tranisitiveClosureTighterThanPrimeTheorem : { always ^edges' = (^edges)' } is theorem reflexiveTranisitiveClosureTighterThanPrimeSat : { always *edges' = (*edges)' } is sat reflexiveTranisitiveClosureTighterThanPrimeTheorem : { always *edges' = (*edges)' } is theorem } test expect { primeTighterThanLeftJoinSat : { always Node.edges' = Node.(edges') } is sat primeTighterThanLeftJoinTheorem : { always Node.edges' = Node.(edges') } is theorem primeTighterThanRightJoinSat : { always edges'.Node = (edges').Node } is sat primeTighterThanRightJoinTheorem : { always edges'.Node = (edges').Node } is theorem } test expect { dotJoinTighterThanBoxJoinIsSat : { always Node.edges[fruit] = (Node.edges)[fruit] } is sat dotJoinTighterThanBoxJoinIsTheorem : { always Node.edges[fruit] = (Node.edges)[fruit] } is theorem } --The next tightest operators are <: and :> but we don't have those in Forge yet test expect { boxTighterThanArrowSat : { always (Node.fruit)->edges[Node] = (Node.fruit)->(edges[Node]) } is sat boxTighterThanArrowTheorem : { always (Node.fruit)->edges[Node] = (Node.fruit)->(edges[Node]) } is theorem } test expect { arrowTighterThanIntersectionSat : { always ( (Node->(Node.fruit) & (edges.Node)->Node) = ((Node->(Node.fruit)) & ((edges.Node)->Node)) ) } is sat arrowTighterThanIntersectionTheorem : { always ( (Node->(Node.fruit) & (edges.Node)->Node) = ((Node->(Node.fruit)) & ((edges.Node)->Node)) ) } is theorem } --The next tightest operator is ++ but we don't have it in Forge yet test expect { intersectionTighterThanCardinalitySat : { always #Node & Node.edges = #(Node & Node.edges) } is sat intersectionTighterThanCardinalityTheorem : { always #Node & Node.edges = #(Node & Node.edges) } is theorem } -- cardinality needs to be tighter than union, so -- #Node.fruit + #Node.edges should become #(Node.fruit) + #(Node.edges) -- however, since + is union, not addition, this will throw an error -- there currently is no way to test in forge surface if something raises an error -- so instead we will add a forge/core test to check this -- and to check oOps we will see that intersection is tighter than union test expect { intersectionTighterThanUnionSat : { always Node.edges & fruit.Node + edges.Node & Node.fruit = (Node.edges & fruit.Node) + (edges.Node & Node.fruit) } is sat intersectionTighterThanUnionTheorem : { always Node.edges & fruit.Node + edges.Node & Node.fruit = (Node.edges & fruit.Node) + (edges.Node & Node.fruit) } is theorem } test expect { unionTighterThanNoSat : { always ((no Node.edges + Node.fruit) iff (no (Node.edges + Node.fruit))) } is sat unionTighterThanNoTheorem : { always ((no Node.edges + Node.fruit) iff (no (Node.edges + Node.fruit))) } is theorem differenceTighterThanNoTheorem : { always ((no Node.edges - Node.fruit) iff (no (Node.edges - Node.fruit))) } is sat differenceTighterThanNoTheorem : { always ((no Node.edges - Node.fruit) iff (no (Node.edges - Node.fruit))) } is theorem unionTighterThanSomeTheorem : { always ((some Node.edges + Node.fruit) iff (some (Node.edges + Node.fruit))) } is sat unionTighterThanSomeTheorem : { always ((some Node.edges + Node.fruit) iff (some (Node.edges + Node.fruit))) } is theorem differenceTighterThanSomeTheorem : { always ((some Node.edges - Node.fruit) iff (some (Node.edges - Node.fruit))) } is sat differenceTighterThanSomeTheorem : { always ((some Node.edges - Node.fruit) iff (some (Node.edges - Node.fruit))) } is theorem unionTighterThanLoneTheorem : { always ((lone Node.edges + Node.fruit) iff (lone (Node.edges + Node.fruit))) } is sat unionTighterThanLoneTheorem : { always ((lone Node.edges + Node.fruit) iff (lone (Node.edges + Node.fruit))) } is theorem differenceTighterThanLoneTheorem : { always ((lone Node.edges - Node.fruit) iff (lone (Node.edges - Node.fruit))) } is sat differenceTighterThanLoneTheorem : { always ((lone Node.edges - Node.fruit) iff (lone (Node.edges - Node.fruit))) } is theorem unionTighterThanOneTheorem : { always ((one Node.edges + Node.fruit) iff (one (Node.edges + Node.fruit))) } is sat unionTighterThanOneTheorem : { always ((one Node.edges + Node.fruit) iff (one (Node.edges + Node.fruit))) } is theorem differenceTighterThanOneTheorem : { always ((one Node.edges - Node.fruit) iff (one (Node.edges - Node.fruit))) } is sat differenceTighterThanOneTheorem : { always ((one Node.edges - Node.fruit) iff (one (Node.edges - Node.fruit))) } is theorem } test expect { noTighterThanNegSat : { always ((! no Node) iff !(no Node)) } is sat noTighterThanNegTheorem : { always ((! no Node) iff !(no Node)) } is theorem noTighterThanNotSat : { always ((not no Node) iff not (no Node)) } is sat noTighterThanNotTheorem : { always ((not no Node) iff not (no Node)) } is theorem someTighterThanNegSat : { always ((! some Node) iff !(some Node)) } is sat someTighterThanNegTheorem : { always ((! some Node) iff !(some Node)) } is theorem someTighterThanNotSat : { always ((not some Node) iff not (some Node)) } is sat someTighterThanNotTheorem : { always ((not some Node) iff not (some Node)) } is theorem loneTighterThanNegSat : { always ((! lone Node) iff !(lone Node)) } is sat loneTighterThanNegTheorem : { always ((! lone Node) iff !(lone Node)) } is theorem loneTighterThanNotSat : { always ((not lone Node) iff not (lone Node)) } is sat loneTighterThanNotTheorem : { always ((not lone Node) iff not (lone Node)) } is theorem oneTighterThanNegSat : { always ((! one Node) iff !(one Node)) } is sat oneTighterThanNegTheorem : { always ((! one Node) iff !(one Node)) } is theorem oneTighterThanNotSat : { always ((not one Node) iff not (one Node)) } is sat oneTighterThanNotTheorem : { always ((not one Node) iff not (one Node)) } is theorem } test expect { negTighterThanInSat : { always ((Node.edges ! in fruit.Node) iff !(Node.edges in fruit.Node)) } is sat negTighterThanInTheorem : { always ((Node.edges ! in fruit.Node) iff !(Node.edges in fruit.Node)) } is theorem notTighterThanInSat : { always ((Node.edges not in fruit.Node) iff not (Node.edges in fruit.Node)) } is sat notTighterThanInTheorem : { always ((Node.edges not in fruit.Node) iff not (Node.edges in fruit.Node)) } is theorem negTighterThanEqSat : { always ((Node.edges != fruit.Node) iff !(Node.edges = fruit.Node)) } is sat negTighterThanEqTheorem : { always ((Node.edges != fruit.Node) iff !(Node.edges = fruit.Node)) } is theorem notTighterThanEqSat : { always ((Node.edges not = fruit.Node) iff not (Node.edges = fruit.Node)) } is sat notTighterThanEqTheorem : { always ((Node.edges not = fruit.Node) iff not (Node.edges = fruit.Node)) } is theorem negTighterThanIntEqSat : { always (all i1, i2 : Int | sum[i1] != sum[i2] iff !(sum[i1] = sum[i2])) } is sat negTighterThanIntEqTheorem : { always (all i1, i2 : Int | sum[i1] != sum[i2] iff !(sum[i1] = sum[i2])) } is theorem notTighterThanIntEqSat : { always (all i1, i2 : Int | sum[i1] not = sum[i2] iff not (sum[i1] = sum[i2])) } is sat notTighterThanIntEqTheorem : { always (all i1, i2 : Int | sum[i1] not = sum[i2] iff not (sum[i1] = sum[i2])) } is theorem negTighterThanLtSat : { always (all i1, i2 : Int | sum[i1] !< sum[i2] iff !(sum[i1] < sum[i2])) } is sat negTighterThanLtTheorem : { always (all i1, i2 : Int | sum[i1] !< sum[i2] iff !(sum[i1] < sum[i2])) } is theorem notTighterThanLtSat : { always (all i1, i2 : Int | sum[i1] not < sum[i2] iff not (sum[i1] < sum[i2])) } is sat notTighterThanLtTheorem : { always (all i1, i2 : Int | sum[i1] not < sum[i2] iff not (sum[i1] < sum[i2])) } is theorem negTighterThanGtSat : { always (all i1, i2 : Int | sum[i1] ! > sum[i2] iff !(sum[i1] > sum[i2])) } is sat negTighterThanGtTheorem : { always (all i1, i2 : Int | sum[i1] ! > sum[i2] iff !(sum[i1] > sum[i2])) } is theorem notTighterThanGtSat : { always (all i1, i2 : Int | sum[i1] not > sum[i2] iff not (sum[i1] > sum[i2])) } is sat notTighterThanGtTheorem : { always (all i1, i2 : Int | sum[i1] not > sum[i2] iff not (sum[i1] > sum[i2])) } is theorem negTighterThanGeqSat : { always (all i1, i2 : Int | sum[i1] ! >= sum[i2] iff !(sum[i1] >= sum[i2])) } is sat negTighterThanGeqTheorem : { always (all i1, i2 : Int | sum[i1] ! >= sum[i2] iff !(sum[i1] >= sum[i2])) } is theorem notTighterThanGeqSat : { always (all i1, i2 : Int | sum[i1] not >= sum[i2] iff not (sum[i1] >= sum[i2])) } is sat notTighterThanGeqTheorem : { always (all i1, i2 : Int | sum[i1] not >= sum[i2] iff not (sum[i1] >= sum[i2])) } is theorem negTighterThanLeqSat : { always (all i1, i2 : Int | sum[i1] ! <= sum[i2] iff !(sum[i1] <= sum[i2])) } is sat negTighterThanLeqTheorem : { always (all i1, i2 : Int | sum[i1] ! <= sum[i2] iff !(sum[i1] <= sum[i2])) } is theorem notTighterThanLeqSat : { always (all i1, i2 : Int | sum[i1] not <= sum[i2] iff not (sum[i1] <= sum[i2])) } is sat notTighterThanLeqTheorem : { always (all i1, i2 : Int | sum[i1] not <= sum[i2] iff not (sum[i1] <= sum[i2])) } is theorem }
null
https://raw.githubusercontent.com/tnelson/Forge/a7187ef110f46493c1d45011035b05646b9ccd22/forge/tests/forge/expressions/orderOfOpsExprs.rkt
racket
#lang forge option run_sterling off option verbose 0 option problem_type temporal var sig Node { var edges : set Node, var fruit : set Node } test expect { tildeTighterThanPrimeSat : { always ~edges' = (~edges)' } is sat tildeTighterThanPrimeTheorem : { always ~edges' = (~edges)' } is theorem tranisitiveClosureTighterThanPrimeSat : { always ^edges' = (^edges)' } is sat tranisitiveClosureTighterThanPrimeTheorem : { always ^edges' = (^edges)' } is theorem reflexiveTranisitiveClosureTighterThanPrimeSat : { always *edges' = (*edges)' } is sat reflexiveTranisitiveClosureTighterThanPrimeTheorem : { always *edges' = (*edges)' } is theorem } test expect { primeTighterThanLeftJoinSat : { always Node.edges' = Node.(edges') } is sat primeTighterThanLeftJoinTheorem : { always Node.edges' = Node.(edges') } is theorem primeTighterThanRightJoinSat : { always edges'.Node = (edges').Node } is sat primeTighterThanRightJoinTheorem : { always edges'.Node = (edges').Node } is theorem } test expect { dotJoinTighterThanBoxJoinIsSat : { always Node.edges[fruit] = (Node.edges)[fruit] } is sat dotJoinTighterThanBoxJoinIsTheorem : { always Node.edges[fruit] = (Node.edges)[fruit] } is theorem } --The next tightest operators are <: and :> but we don't have those in Forge yet test expect { boxTighterThanArrowSat : { always (Node.fruit)->edges[Node] = (Node.fruit)->(edges[Node]) } is sat boxTighterThanArrowTheorem : { always (Node.fruit)->edges[Node] = (Node.fruit)->(edges[Node]) } is theorem } test expect { arrowTighterThanIntersectionSat : { always ( (Node->(Node.fruit) & (edges.Node)->Node) = ((Node->(Node.fruit)) & ((edges.Node)->Node)) ) } is sat arrowTighterThanIntersectionTheorem : { always ( (Node->(Node.fruit) & (edges.Node)->Node) = ((Node->(Node.fruit)) & ((edges.Node)->Node)) ) } is theorem } --The next tightest operator is ++ but we don't have it in Forge yet test expect { intersectionTighterThanCardinalitySat : { always #Node & Node.edges = #(Node & Node.edges) } is sat intersectionTighterThanCardinalityTheorem : { always #Node & Node.edges = #(Node & Node.edges) } is theorem } -- cardinality needs to be tighter than union, so -- #Node.fruit + #Node.edges should become #(Node.fruit) + #(Node.edges) -- however, since + is union, not addition, this will throw an error -- there currently is no way to test in forge surface if something raises an error -- so instead we will add a forge/core test to check this -- and to check oOps we will see that intersection is tighter than union test expect { intersectionTighterThanUnionSat : { always Node.edges & fruit.Node + edges.Node & Node.fruit = (Node.edges & fruit.Node) + (edges.Node & Node.fruit) } is sat intersectionTighterThanUnionTheorem : { always Node.edges & fruit.Node + edges.Node & Node.fruit = (Node.edges & fruit.Node) + (edges.Node & Node.fruit) } is theorem } test expect { unionTighterThanNoSat : { always ((no Node.edges + Node.fruit) iff (no (Node.edges + Node.fruit))) } is sat unionTighterThanNoTheorem : { always ((no Node.edges + Node.fruit) iff (no (Node.edges + Node.fruit))) } is theorem differenceTighterThanNoTheorem : { always ((no Node.edges - Node.fruit) iff (no (Node.edges - Node.fruit))) } is sat differenceTighterThanNoTheorem : { always ((no Node.edges - Node.fruit) iff (no (Node.edges - Node.fruit))) } is theorem unionTighterThanSomeTheorem : { always ((some Node.edges + Node.fruit) iff (some (Node.edges + Node.fruit))) } is sat unionTighterThanSomeTheorem : { always ((some Node.edges + Node.fruit) iff (some (Node.edges + Node.fruit))) } is theorem differenceTighterThanSomeTheorem : { always ((some Node.edges - Node.fruit) iff (some (Node.edges - Node.fruit))) } is sat differenceTighterThanSomeTheorem : { always ((some Node.edges - Node.fruit) iff (some (Node.edges - Node.fruit))) } is theorem unionTighterThanLoneTheorem : { always ((lone Node.edges + Node.fruit) iff (lone (Node.edges + Node.fruit))) } is sat unionTighterThanLoneTheorem : { always ((lone Node.edges + Node.fruit) iff (lone (Node.edges + Node.fruit))) } is theorem differenceTighterThanLoneTheorem : { always ((lone Node.edges - Node.fruit) iff (lone (Node.edges - Node.fruit))) } is sat differenceTighterThanLoneTheorem : { always ((lone Node.edges - Node.fruit) iff (lone (Node.edges - Node.fruit))) } is theorem unionTighterThanOneTheorem : { always ((one Node.edges + Node.fruit) iff (one (Node.edges + Node.fruit))) } is sat unionTighterThanOneTheorem : { always ((one Node.edges + Node.fruit) iff (one (Node.edges + Node.fruit))) } is theorem differenceTighterThanOneTheorem : { always ((one Node.edges - Node.fruit) iff (one (Node.edges - Node.fruit))) } is sat differenceTighterThanOneTheorem : { always ((one Node.edges - Node.fruit) iff (one (Node.edges - Node.fruit))) } is theorem } test expect { noTighterThanNegSat : { always ((! no Node) iff !(no Node)) } is sat noTighterThanNegTheorem : { always ((! no Node) iff !(no Node)) } is theorem noTighterThanNotSat : { always ((not no Node) iff not (no Node)) } is sat noTighterThanNotTheorem : { always ((not no Node) iff not (no Node)) } is theorem someTighterThanNegSat : { always ((! some Node) iff !(some Node)) } is sat someTighterThanNegTheorem : { always ((! some Node) iff !(some Node)) } is theorem someTighterThanNotSat : { always ((not some Node) iff not (some Node)) } is sat someTighterThanNotTheorem : { always ((not some Node) iff not (some Node)) } is theorem loneTighterThanNegSat : { always ((! lone Node) iff !(lone Node)) } is sat loneTighterThanNegTheorem : { always ((! lone Node) iff !(lone Node)) } is theorem loneTighterThanNotSat : { always ((not lone Node) iff not (lone Node)) } is sat loneTighterThanNotTheorem : { always ((not lone Node) iff not (lone Node)) } is theorem oneTighterThanNegSat : { always ((! one Node) iff !(one Node)) } is sat oneTighterThanNegTheorem : { always ((! one Node) iff !(one Node)) } is theorem oneTighterThanNotSat : { always ((not one Node) iff not (one Node)) } is sat oneTighterThanNotTheorem : { always ((not one Node) iff not (one Node)) } is theorem } test expect { negTighterThanInSat : { always ((Node.edges ! in fruit.Node) iff !(Node.edges in fruit.Node)) } is sat negTighterThanInTheorem : { always ((Node.edges ! in fruit.Node) iff !(Node.edges in fruit.Node)) } is theorem notTighterThanInSat : { always ((Node.edges not in fruit.Node) iff not (Node.edges in fruit.Node)) } is sat notTighterThanInTheorem : { always ((Node.edges not in fruit.Node) iff not (Node.edges in fruit.Node)) } is theorem negTighterThanEqSat : { always ((Node.edges != fruit.Node) iff !(Node.edges = fruit.Node)) } is sat negTighterThanEqTheorem : { always ((Node.edges != fruit.Node) iff !(Node.edges = fruit.Node)) } is theorem notTighterThanEqSat : { always ((Node.edges not = fruit.Node) iff not (Node.edges = fruit.Node)) } is sat notTighterThanEqTheorem : { always ((Node.edges not = fruit.Node) iff not (Node.edges = fruit.Node)) } is theorem negTighterThanIntEqSat : { always (all i1, i2 : Int | sum[i1] != sum[i2] iff !(sum[i1] = sum[i2])) } is sat negTighterThanIntEqTheorem : { always (all i1, i2 : Int | sum[i1] != sum[i2] iff !(sum[i1] = sum[i2])) } is theorem notTighterThanIntEqSat : { always (all i1, i2 : Int | sum[i1] not = sum[i2] iff not (sum[i1] = sum[i2])) } is sat notTighterThanIntEqTheorem : { always (all i1, i2 : Int | sum[i1] not = sum[i2] iff not (sum[i1] = sum[i2])) } is theorem negTighterThanLtSat : { always (all i1, i2 : Int | sum[i1] !< sum[i2] iff !(sum[i1] < sum[i2])) } is sat negTighterThanLtTheorem : { always (all i1, i2 : Int | sum[i1] !< sum[i2] iff !(sum[i1] < sum[i2])) } is theorem notTighterThanLtSat : { always (all i1, i2 : Int | sum[i1] not < sum[i2] iff not (sum[i1] < sum[i2])) } is sat notTighterThanLtTheorem : { always (all i1, i2 : Int | sum[i1] not < sum[i2] iff not (sum[i1] < sum[i2])) } is theorem negTighterThanGtSat : { always (all i1, i2 : Int | sum[i1] ! > sum[i2] iff !(sum[i1] > sum[i2])) } is sat negTighterThanGtTheorem : { always (all i1, i2 : Int | sum[i1] ! > sum[i2] iff !(sum[i1] > sum[i2])) } is theorem notTighterThanGtSat : { always (all i1, i2 : Int | sum[i1] not > sum[i2] iff not (sum[i1] > sum[i2])) } is sat notTighterThanGtTheorem : { always (all i1, i2 : Int | sum[i1] not > sum[i2] iff not (sum[i1] > sum[i2])) } is theorem negTighterThanGeqSat : { always (all i1, i2 : Int | sum[i1] ! >= sum[i2] iff !(sum[i1] >= sum[i2])) } is sat negTighterThanGeqTheorem : { always (all i1, i2 : Int | sum[i1] ! >= sum[i2] iff !(sum[i1] >= sum[i2])) } is theorem notTighterThanGeqSat : { always (all i1, i2 : Int | sum[i1] not >= sum[i2] iff not (sum[i1] >= sum[i2])) } is sat notTighterThanGeqTheorem : { always (all i1, i2 : Int | sum[i1] not >= sum[i2] iff not (sum[i1] >= sum[i2])) } is theorem negTighterThanLeqSat : { always (all i1, i2 : Int | sum[i1] ! <= sum[i2] iff !(sum[i1] <= sum[i2])) } is sat negTighterThanLeqTheorem : { always (all i1, i2 : Int | sum[i1] ! <= sum[i2] iff !(sum[i1] <= sum[i2])) } is theorem notTighterThanLeqSat : { always (all i1, i2 : Int | sum[i1] not <= sum[i2] iff not (sum[i1] <= sum[i2])) } is sat notTighterThanLeqTheorem : { always (all i1, i2 : Int | sum[i1] not <= sum[i2] iff not (sum[i1] <= sum[i2])) } is theorem }
941ec67081d0d2d00b7906fe12236f0e3b48e1630b650e50189cbecf06f94cbf
fission-codes/fission
Environment.hs
module Fission.CLI.App.Environment ( create , read , readFrom , absPath , relPath , ignoreDefault , module Fission.CLI.App.Environment.Types ) where import qualified Data.Yaml as YAML import RIO.Directory import RIO.FilePath import qualified RIO.Text as Text import Fission.Prelude import Fission.Error.NotFound.Types import Fission.URL.Types import Fission.CLI.App.Environment.Types import qualified Fission.CLI.YAML as YAML create :: ( MonadIO m , MonadLogger m ) => URL -> FilePath -> m () create appURL buildDir = do path <- absPath YAML.writeFile path Env {ipfsIgnored = [], ..} read :: ( MonadIO m , MonadLogger m , MonadRaise m , m `Raises` YAML.ParseException , m `Raises` NotFound FilePath ) => m Env read = YAML.readFile =<< absPath readFrom :: ( MonadIO m , MonadRaise m , MonadLogger m , m `Raises` YAML.ParseException , m `Raises` NotFound FilePath ) => FilePath -> m Env readFrom appPath = YAML.readFile $ appPath </> relPath absPath :: MonadIO m => m FilePath absPath = do pwd <- getCurrentDirectory return $ pwd </> relPath relPath :: FilePath relPath = "fission.yaml" ignoreDefault :: [Text] ignoreDefault = [ Text.pack relPath , ".env" , ".DS_Store" ]
null
https://raw.githubusercontent.com/fission-codes/fission/11d14b729ccebfd69499a534445fb072ac3433a3/fission-cli/library/Fission/CLI/App/Environment.hs
haskell
module Fission.CLI.App.Environment ( create , read , readFrom , absPath , relPath , ignoreDefault , module Fission.CLI.App.Environment.Types ) where import qualified Data.Yaml as YAML import RIO.Directory import RIO.FilePath import qualified RIO.Text as Text import Fission.Prelude import Fission.Error.NotFound.Types import Fission.URL.Types import Fission.CLI.App.Environment.Types import qualified Fission.CLI.YAML as YAML create :: ( MonadIO m , MonadLogger m ) => URL -> FilePath -> m () create appURL buildDir = do path <- absPath YAML.writeFile path Env {ipfsIgnored = [], ..} read :: ( MonadIO m , MonadLogger m , MonadRaise m , m `Raises` YAML.ParseException , m `Raises` NotFound FilePath ) => m Env read = YAML.readFile =<< absPath readFrom :: ( MonadIO m , MonadRaise m , MonadLogger m , m `Raises` YAML.ParseException , m `Raises` NotFound FilePath ) => FilePath -> m Env readFrom appPath = YAML.readFile $ appPath </> relPath absPath :: MonadIO m => m FilePath absPath = do pwd <- getCurrentDirectory return $ pwd </> relPath relPath :: FilePath relPath = "fission.yaml" ignoreDefault :: [Text] ignoreDefault = [ Text.pack relPath , ".env" , ".DS_Store" ]
ad982e9ce1b56bac5118b7157268d0e29e027f95371e708441aa9572c0ec195f
pkamenarsky/synchron
SVG.hs
# LANGUAGE FlexibleContexts # # LANGUAGE DeriveFunctor # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PartialTypeSignatures # # LANGUAGE TupleSections # module Syn.SVG where import Control.Monad (void) import Control.Monad.Free import Data.List (intersperse) import Data.Maybe (fromMaybe) import Data.Text (Text) import qualified Data.Map as M import qualified Data.Text as T import Graphics.Svg hiding (aR) import Syn (DbgSyn (..), DbgBinOp (..), Syn (..), SynF (..), Event (..), EventId (..), EventValue (..)) import qualified Syn import Debug.Trace data BinOp = GAnd | GOr deriving (Eq, Show) data GSyn = GDone | GAwait Syn.EventId | GEmit Syn.EventId | GForever | GBin BinOp GSyn GSyn deriving (Eq, Show) data TSyn w = TDone w | TBlocked w | TForever w | TAwait w Syn.EventId (TSyn w) | TEmit w Syn.EventId (TSyn w) | TJoin (TSyn w) | TBin w BinOp (TSyn w) (TSyn w) (TSyn w) deriving (Eq, Show, Functor) wrapG :: GSyn -> TSyn () wrapG GDone = TDone () wrapG (GAwait e) = TAwait () e (TDone ()) wrapG (GEmit e) = TEmit () e (TDone ()) wrapG GForever = TForever () wrapG (GBin op p q) = TBin () op (wrapG p) (wrapG q) (TDone ()) toTSyn' :: DbgSyn -> TSyn () toTSyn' DbgDone = TDone () toTSyn' DbgBlocked = TBlocked () toTSyn' (DbgAwait e next) = TAwait () e (toTSyn' next) toTSyn' (DbgEmit e next) = TEmit () e (toTSyn' next) toTSyn' (DbgJoin next) = TJoin (toTSyn' next) toTSyn' DbgForever = TForever () toTSyn' (DbgBin op p q next) = TBin () (toTOp op) (toTSyn' (p DbgBlocked)) (toTSyn' (q DbgBlocked)) (toTSyn' next) where toTOp DbgAnd = GAnd toTOp DbgOr = GOr r c x = take x (repeat c) ss = r ' ' fst3 (a, b, c) = a color :: Int -> String -> String color c s = "\ESC[" <> show (31 + (c `mod` 7)) <> "m" <> s <> "\ESC[m" evColor :: EventId -> String -> String evColor (Internal (_, c)) = color c evColor (External (_, c)) = color c evColor' :: EventId -> Int evColor' (Internal (_, c)) = c evColor' (External (_, c)) = c type W = Int type H = Int data Pictogram = PictAwait Int | PictEmit Int | PictDone | PictForever instance Show Pictogram where show (PictAwait c) = color c "○" show (PictEmit c) = color c "▲" show PictDone = "◆" show PictForever = "∞" data G = L W H Pictogram | B BinOp Bool W H G G | E W H deriving Show gw :: G -> W gw (L w _ _) = w gw (E w _) = w gw (B _ _ w _ _ _) = w gh :: G -> H gh (L _ h _) = h gh (E _ h) = h gh (B _ _ _ h _ _) = h roww = 2 drawG :: G -> [String] drawG (L w h c) = r (ss w) (h - 1) <> [show c <> ss (w - 1)] drawG (E w h) = r (ss w) h drawG (B op draw w h p q) = (if draw then header' else []) <> ls -- zipWith (<>) (drawG p) (drawG q) where ls = [ fromMaybe (ss (gw p)) l <> fromMaybe (ss (gw q)) r | (l, r) <- zipPadF (drawG p) (drawG q) ] top GAnd = "∧" top GOr = "∨" header = [ top op <> ss (w - 1), r '—' (w - 1) <> [' '] ] header' = [ top op <> [' '] <> r '—' (w - 3) <> [' '] ] drawGs :: [G] -> [String] drawGs = concatMap drawG pprintG :: [G] -> IO () pprintG = void . traverse putStrLn . drawGs labelWidth :: W -> TSyn () -> (TSyn W, W) -- returned W >= passed W labelWidth parw (TDone _) = (TDone parw, parw) labelWidth parw (TBlocked _) = (TBlocked parw, parw) labelWidth parw (TForever _) = (TForever parw, parw) labelWidth parw (TAwait _ e next) = (TAwait w e p, w) where (p, w) = labelWidth parw next labelWidth parw (TEmit _ e next) = (TEmit w e p, w) where (p, w) = labelWidth parw next labelWidth parw (TBin _ op p q d) = (TBin dw op p' q' d', dw) where (p', pw) = labelWidth roww p (q', qw) = labelWidth roww q (d', dw) = labelWidth (max (pw + qw) parw) d labelWidth parw (TJoin p) = (TJoin p', w) where (p', w) = labelWidth parw p toG :: Monoid v => Syn v a -> [G] toG p = go l where t = toTSyn' (toDbgSyn p DbgDone) l = (,True) <$> fst (labelWidth roww t) go g = case showG g of (g', Just n) -> g':go n (g', _) -> [g'] testG (g:gs) = all ((== gw g) . gw) (g:gs) showG :: TSyn (W, Bool) -> (G, Maybe (TSyn (W, Bool))) showG (TDone (w, _)) = (L w 1 PictDone, Nothing) -- showG (TDone (w, _)) = (L w 1 "D", Nothing) showG (TBlocked (w, _)) = (E w 1, Nothing) showG (TForever (w, _)) = (L w 1 PictForever, Nothing) -- showG (TAwait (w, _) e next) = (L w 1 ("A"), Just next) showG (TAwait (w, _) e next) = (L w 1 (PictAwait (evColor' e)), Just next) showG ( TEmit ( w , _ ) e next ) = ( L w 1 ( " E " ) , Just next ) showG (TEmit (w, _) e next) = (L w 1 (PictEmit (evColor' e)), Just next) showG (TJoin next) = showG next showG (TBin (w, draw) op p q d) = case (pg, qg) of (E _ _, E _ _) -> showG d otherwise -> (pq, Just (TBin (w, False) op (fromMaybe (TBlocked (gw pg, False)) p') (fromMaybe (TBlocked (gw qg, False)) q') d)) where (pg, p') = showG p (qg, q') = showG q adjustH :: Int -> G -> G adjustH h (L w _ c) = L w h c -- only adjust height if no header drawn adjustH h (B op False bw _ p q) = B op False bw h (adjustH h p) (adjustH h q) adjustH _ b = b mh = max (gh pg) (gh qg) pq = B op draw w (mh + if draw then 1 else 0) (adjustH mh pg) (adjustH mh qg) showTSyn :: TSyn () -> ([[String]], Int) showTSyn (TDone _) = ([["◆"]], 1) showTSyn (TBlocked _) = ([], 1) showTSyn (TForever _) = ([["∞"]], 1) showTSyn (TJoin next) = (t, w) -- ([["v" <> ss (w - 1)]] <> t, w) where (t, w) = showTSyn next showTSyn (TAwait _ e next) = ([[evColor e "○" <> ss (w - 1)]] <> t, w) where (t, w) = showTSyn next showTSyn (TEmit _ e next) = ([[evColor e "▲" <> ss (w - 1)]] <> t, w) where (t, w) = showTSyn next showTSyn (TBin _ op p q d) = ( header <> go pg (fmap (fmap (fmap (padto qw ' '))) qg) <> dt , pw + qw + 1 ) where (pt, pw) = showTSyn p (qt, qw') = showTSyn q (dt, dw) = showTSyn d qw = max qw' dw padto x r s = take (x - length s) (repeat r) <> s (pg, qg) = unzip (zipPadB pt qt) top GAnd = "∧" top GOr = "∨" header' = [ [ top op <> " " <> r '—' (pw + qw + 1 - 2) ] ] header = [ [ top op <> ss (pw + qw + 1 - 1) , r '—' (pw + qw + 1) ] ] go :: [Maybe [String]] -> [Maybe [String]] -> [[String]] -- go a b -- | trace (show (a, b)) False = undefined go [] _ = [] go _ [] = [] go (Just [pt]:ps) (Just [qt]:qs) = [[pt <> " " <> qt]] <> go ps qs go (Just [pt]:ps) (Nothing:qs) = [[pt <> " " <> ss qw]] <> go ps qs go (Nothing:ps) (Just [qt]:qs) = [[ss pw <> " " <> qt]] <> go ps qs go (Just pt:ps) x@(Just [qt]:qs) = [map (<> (" " <> ss qw)) pt] <> go ps x go (Just pt:ps) x@(Nothing:qs) = [map (<> (" " <> ss qw)) pt] <> go ps x go x@(Just [pt]:ps) (Just qt:qs) = [map ((" " <> ss pw) <>) qt] <> go x qs go x@(Nothing:ps) (Just qt:qs) = [map ((" " <> ss pw) <>) qt] <> go x qs go (Just pt:ps) (Just qt:qs) = [ls] <> go ps qs where ls = [ case t of (Just a, Just b) -> a <> " " <> b (Just a, Nothing) -> a <> " " <> ss qw (Nothing, Just b) -> ss pw <> " " <> b | t <- zipPadF pt qt ] zipLines :: [[String]] -> [[String]] -> [(Maybe [String], Maybe [String])] zipLines ([a]:as) ([b]:bs) = (Just [a], Just [b]):zipLines as bs zipLines ([a]:as) (b:bs) = (Nothing, Just b):zipLines ([a]:as) bs zipLines (a:as) ([b]:bs) = (Just a, Nothing):zipLines as ([b]:bs) toDbgSyn :: Monoid v => Syn v a -> (DbgSyn -> DbgSyn) toDbgSyn = go mempty 0 id where go m eid dbg p = if M.size m' == 0 then dbg . dbg' else go m' eid' (dbg . dbg') p' where (eid', p', dbg', _, m', ios, u) = Syn.stepOnce' m 0 eid p Syn.E toGSyn :: Monoid v => Syn v a -> [GSyn] toGSyn = go mempty 0 [] where convert :: Syn v a -> GSyn convert (Syn (Pure _)) = GDone convert (Syn (Free Forever)) = GForever convert (Syn (Free (MapView _ p _))) = convert p convert (Syn (Free (Await (Event _ e) _))) = GAwait e convert (Syn (Free (Emit (EventValue (Event _ e) _) _))) = GEmit e convert (Syn (Free (Or p q _))) = GBin GOr (convert p) (convert q) convert (Syn (Free (And p q _))) = GBin GAnd (convert p) (convert q) go m eid gp p = if M.size m' == 0 then convert p':gp else go m' eid' (convert p':gp) p' where (eid', p', _, _, m', ios, u) = Syn.stepOnce' m 0 eid p Syn.E zipPadB :: [a] -> [b] -> [(Maybe a, Maybe b)] zipPadB as bs = zip (map Just as <> take (max 0 (length bs - length as)) (repeat Nothing)) (map Just bs <> take (max 0 (length as - length bs)) (repeat Nothing)) zipPadF :: [a] -> [b] -> [(Maybe a, Maybe b)] zipPadF as bs = zip (take (max 0 (length bs - length as)) (repeat Nothing) <> map Just as) (take (max 0 (length as - length bs)) (repeat Nothing) <> map Just bs) pprintProgram p = void $ traverse putStrLn (showProgram' ((reverse $ toGSyn p))) pprintProgram2 p = void $ traverse putStrLn (concat $ fst $ showTSyn (toTSyn' (toDbgSyn p DbgDone))) pprintProgram3 p = fst $ labelWidth roww $ toTSyn' (toDbgSyn p DbgDone) pprintProgram4 :: Monoid v => Syn v a -> IO () pprintProgram4 = pprintG . toG showTrail :: GSyn -> [String] showTrail = fst3 . go where go :: GSyn -> ([String], Int, Int) go (GEmit e) = ([evColor e "▲"], 1, 0) go (GAwait e) = ([evColor e "○"], 1, 0) go GDone = (["◆"], 1, 0) go GForever = (["∞"], 1, 0) go (GBin op p q) = ( header <> subheader <> lines , pw + qw + 1 , length header + length subheader ) where top GAnd = "∧" top GOr = "∨" header' = [ top op <> " " <> r '—' (pw + qw + 1 - 2) ] header = [ top op <> ss (pw + qw + 1 - 1) , r '—' (pw + qw + 1) ] subheader = [ mconcat [ case ph of Nothing -> ss pw Just t -> t , " " , case qh of Nothing -> ss qw Just t -> t ] | (ph, qh) <- zipPadF (take ph pt) (take qh qt) ] lines = [ mconcat [ case ph of Nothing -> ss pw Just t -> t , " " , case qh of Nothing -> ss qw Just t -> t ] | (ph, qh) <- zipPadF (drop ph pt) (drop qh qt) ] (pt, pw, ph) = go p (qt, qw, qh) = go q showProgram :: [GSyn] -> [String] showProgram = concat . go [] where go u [] = [] go u (p:ps) = t':go t ps where t = showTrail p t' = strip u t strip [] bs = bs strip (a:as) (b:bs) | a == b = strip as bs | otherwise = (b:bs) showProgram' :: [GSyn] -> [String] showProgram' = concat . intersperse [""] . map showTrail -------------------------------------------------------------------------------- p4 : : ( ) _ -- p4 = Syn.local $ \e -> Syn.local $ \f -> do -- a@((_, _), _, (_, _)) <- Syn.andd ( Syn.andd ( Syn.await e , Syn.emit f " F " ) , Syn.orr [ Syn.await f > > Syn.orr [ Syn.forever , Syn.await e ] , Syn.forever ] , Syn.andd ( pure " _ " : : ( ) String , Syn.await f > > Syn.emit e " E " ) -- ) -- pure a -- void $ traverse putStrLn (concat $ fst $ showTSyn (toTSyn (reverse $ toGSyn p6))) p6 = Syn.local $ \e - > Syn.local $ \f - > Syn.local $ \g - > do -- a@((_, _), (_, _, _), (_, _, _), (_, _)) <- Syn.andd ( Syn.andd ( Syn.await e , Syn.emit f " F " > > ( Syn.andd ( Syn.await , Syn.await ) : : ( ) ( _ , _ ) ) > > Syn.emit e " E " ) , ( Syn.await f , Syn.await g , Syn.await e ) , ( Syn.await e , Syn.await , Syn.await f ) , ( pure " _ " : : ( ) String , Syn.await f > > Syn.emit g " G " ) -- ) -- pure a -- p6_2 = Syn.local $ \e - > Syn.local $ \f - > Syn.local $ \g - > do -- a@((_, _), (_, _, _), (_, _, _), (_, _)) <- Syn.andd ( Syn.andd ( Syn.await e , Syn.emit f " F " > > Syn.await > > Syn.emit e " E " ) , ( Syn.await f , Syn.await g , Syn.await e ) , ( Syn.await e , Syn.await , Syn.await f ) , ( pure " _ " : : ( ) String , Syn.await f > > Syn.emit g " G " ) -- ) -- pure a -- p7 : : ( ) _ -- p7 = Syn.local $ \e -> Syn.local $ \f -> do -- (_, _) <- Syn.andd ( go 0 0 e f -- , do Syn.emit f 1 Syn.emit f 2 Syn.emit f 3 Syn.emit f 6 Syn.emit f 8 -- Syn.emit e (Right ()) -- ) -- pure () -- where -- go :: Int -> Int -> Syn.Event Syn.Internal (Either Int ()) -> Syn.Event Syn.Internal Int -> Syn () Int -- go x y e f = do -- a <- Syn.orr [ Left <$> Syn.await e, Right <$> Syn.await f ] -- case a of -- Left (Left x') -> go (x + x') y e f -- Right y' -> go x (y + y') e f -- _ -> pure (x + y) svg :: Element svg = g_ [] (text_ [] "YO") p :: Element p = path_ [ D_ <<- (mA 10 80 <> qA 52.5 10 95 80 <> tA 180 80 <> z) , Fill_ <<- "#333333" ] aR :: RealFloat a => a -> a -> a -> Int -> Int -> a -> a -> Text aR rx ry xrot largeFlag sweepFlag x y = T.concat [ "a ", toText rx, ",", toText ry, " ", toText xrot, " ", T.pack (show largeFlag) , " ", T.pack (show sweepFlag), " ", toText x, " ", toText y, " "] palette = [ "#e6194b", "#3cb44b", "#ffe119", "#4363d8", "#f58231", "#911eb4", "#46f0f0", "#f032e6", "#bcf60c", "#fabebe", "#008080", "#e6beff", "#9a6324", "#fffac8", "#800000", "#aaffc3", "#808000", "#ffd8b1", "#000075", "#808080", "#ffffff", "#000000" ] paletteColor x = palette !! (x `mod` length palette) trail' :: Pictogram -> Text -> Double -> Double -> Double -> Double -> Double -> Element trail' c color x y width height r = mconcat [ path_ [ D_ <<- (mA x y <> vR height <> aR (width / 2) (width /2) 0 1 0 width 0 <> vR (-height) <> z) , Fill_ <<- "#000" ] , case c of PictAwait c -> circle_ [ Cx_ <<- t (x + (width / 2)) , Cy_ <<- t (y + height) , R_ <<- t (r / 1.1) -- , Stroke_ <<- paletteColor c , Stroke_width _ < < - " 2px " -- , Fill_ <<- "transparent" , Fill_ <<- paletteColor c , Class_ <<- "circle" ] PictDone -> path_ [ D_ <<- (mA (x + width / 2) (y + height - r) <> lR r r <> lR (-r) r <> lR (-r) (-r) <> z) , Fill_ <<- "#fff" ] PictEmit c -> path_ [ D_ <<- (mA (x + width / 2 - r) (y + height - r) <> lR r (r * 1.8) <> lR r (-r * 1.8) <> z) , Fill_ <<- paletteColor c ] otherwise -> path_ [] ] where t = T.pack . show trail :: Text -> Double -> Double -> Double -> Double -> Double -> Element trail color x y width height r = mconcat [ path_ [ D_ <<- (mA x y <> vR height <> aR (width / 2) (width /2) 0 1 0 width 0 <> vR (-height) <> z) , Fill_ <<- color ] , mconcat [ circle_ [ Cx_ <<- t (x + (width / 2)) , Cy_ <<- t (y + height) , R_ <<- t r , Fill_ <<- "#ddd" , Class_ <<- "circle" ] ] ] where t = T.pack . show generateSVG style t = mconcat $ intersperse "\n" [ "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" , "<svg version=\"1.1\" xmlns=\"\" xmlns:xlink=\"\" x=\"0px\" y=\"0px\" viewBox=\"0 0 960 960\">" , "<defs>" , "<style type=\"text/css\"><![CDATA[" , style , "]]></style>" , "</defs>" , show t , "</svg>" ] gridw = 16 gridh = 30 gridx = 50 gridy = 50 tox x = gridx + fromIntegral x * gridw toy y = gridy + fromIntegral y * gridh tow w = fromIntegral w * gridw toh h = fromIntegral h * gridh gridTrail :: Pictogram -> Int -> Int -> Int -> Element gridTrail t x y h = trail' t "#333" (tox x) (toy y) (tow 1) (toh h) (gridw / 4) svgG :: Int -> Int -> G -> Element svgG x y (L _ h c) = gridTrail c x y h svgG x y (E _ _) = mempty svgG x y (B op draw w h p q) = mconcat [ svgG x (y + h - gh p) p , svgG (x + gw p) (y + h - gh q) q , if draw then path_ [ D _ < < - ( mA ( tox x ) ( toy ( y + 1 ) - ( gridh / 3 ) ) < > hR ( tow ( w - 1 ) ) ) [ D_ <<- (mA (tox x) (toy (y + 1) - (gridh / 3) - 2) <> lR tm 0 <> lR tx (-ty) <> lR tx ty <> lR tm 0) , Stroke_width_ <<- "3px" , Stroke_ <<- "#000" , Fill_ <<- "transparent" ] else mempty ] where tw = tow (w - 1) tx = 6 ty = case op of GAnd -> 6 GOr -> (-6) tm = tw / 2 - tx svgGs :: H -> [G] -> Element svgGs _ [] = mempty svgGs h (g:gs) = svgGs (h + h') gs <> svgG 0 h g where h' = gh g makeSvg :: Monoid v => Syn v a -> IO () makeSvg p = writeFile "out.svg" (generateSVG "" (svgGs 0 $ toG p)) -- main :: IO () -- main = do -- style <- readFile "style.css" -- writeFile "out.svg" (generateSVG style trails)
null
https://raw.githubusercontent.com/pkamenarsky/synchron/8fa21f586b974da830c202b58a46a652176a6933/src/Syn/SVG.hs
haskell
# LANGUAGE OverloadedStrings # zipWith (<>) (drawG p) (drawG q) returned W >= passed W showG (TDone (w, _)) = (L w 1 "D", Nothing) showG (TAwait (w, _) e next) = (L w 1 ("A"), Just next) only adjust height if no header drawn ([["v" <> ss (w - 1)]] <> t, w) go a b | trace (show (a, b)) False = undefined ------------------------------------------------------------------------------ p4 = Syn.local $ \e -> Syn.local $ \f -> do a@((_, _), _, (_, _)) <- Syn.andd ) pure a void $ traverse putStrLn (concat $ fst $ showTSyn (toTSyn (reverse $ toGSyn p6))) a@((_, _), (_, _, _), (_, _, _), (_, _)) <- Syn.andd ) pure a a@((_, _), (_, _, _), (_, _, _), (_, _)) <- Syn.andd ) pure a p7 = Syn.local $ \e -> Syn.local $ \f -> do (_, _) <- Syn.andd , do Syn.emit e (Right ()) ) pure () where go :: Int -> Int -> Syn.Event Syn.Internal (Either Int ()) -> Syn.Event Syn.Internal Int -> Syn () Int go x y e f = do a <- Syn.orr [ Left <$> Syn.await e, Right <$> Syn.await f ] case a of Left (Left x') -> go (x + x') y e f Right y' -> go x (y + y') e f _ -> pure (x + y) , Stroke_ <<- paletteColor c , Fill_ <<- "transparent" main :: IO () main = do style <- readFile "style.css" writeFile "out.svg" (generateSVG style trails)
# LANGUAGE FlexibleContexts # # LANGUAGE DeriveFunctor # # LANGUAGE PartialTypeSignatures # # LANGUAGE TupleSections # module Syn.SVG where import Control.Monad (void) import Control.Monad.Free import Data.List (intersperse) import Data.Maybe (fromMaybe) import Data.Text (Text) import qualified Data.Map as M import qualified Data.Text as T import Graphics.Svg hiding (aR) import Syn (DbgSyn (..), DbgBinOp (..), Syn (..), SynF (..), Event (..), EventId (..), EventValue (..)) import qualified Syn import Debug.Trace data BinOp = GAnd | GOr deriving (Eq, Show) data GSyn = GDone | GAwait Syn.EventId | GEmit Syn.EventId | GForever | GBin BinOp GSyn GSyn deriving (Eq, Show) data TSyn w = TDone w | TBlocked w | TForever w | TAwait w Syn.EventId (TSyn w) | TEmit w Syn.EventId (TSyn w) | TJoin (TSyn w) | TBin w BinOp (TSyn w) (TSyn w) (TSyn w) deriving (Eq, Show, Functor) wrapG :: GSyn -> TSyn () wrapG GDone = TDone () wrapG (GAwait e) = TAwait () e (TDone ()) wrapG (GEmit e) = TEmit () e (TDone ()) wrapG GForever = TForever () wrapG (GBin op p q) = TBin () op (wrapG p) (wrapG q) (TDone ()) toTSyn' :: DbgSyn -> TSyn () toTSyn' DbgDone = TDone () toTSyn' DbgBlocked = TBlocked () toTSyn' (DbgAwait e next) = TAwait () e (toTSyn' next) toTSyn' (DbgEmit e next) = TEmit () e (toTSyn' next) toTSyn' (DbgJoin next) = TJoin (toTSyn' next) toTSyn' DbgForever = TForever () toTSyn' (DbgBin op p q next) = TBin () (toTOp op) (toTSyn' (p DbgBlocked)) (toTSyn' (q DbgBlocked)) (toTSyn' next) where toTOp DbgAnd = GAnd toTOp DbgOr = GOr r c x = take x (repeat c) ss = r ' ' fst3 (a, b, c) = a color :: Int -> String -> String color c s = "\ESC[" <> show (31 + (c `mod` 7)) <> "m" <> s <> "\ESC[m" evColor :: EventId -> String -> String evColor (Internal (_, c)) = color c evColor (External (_, c)) = color c evColor' :: EventId -> Int evColor' (Internal (_, c)) = c evColor' (External (_, c)) = c type W = Int type H = Int data Pictogram = PictAwait Int | PictEmit Int | PictDone | PictForever instance Show Pictogram where show (PictAwait c) = color c "○" show (PictEmit c) = color c "▲" show PictDone = "◆" show PictForever = "∞" data G = L W H Pictogram | B BinOp Bool W H G G | E W H deriving Show gw :: G -> W gw (L w _ _) = w gw (E w _) = w gw (B _ _ w _ _ _) = w gh :: G -> H gh (L _ h _) = h gh (E _ h) = h gh (B _ _ _ h _ _) = h roww = 2 drawG :: G -> [String] drawG (L w h c) = r (ss w) (h - 1) <> [show c <> ss (w - 1)] drawG (E w h) = r (ss w) h where ls = [ fromMaybe (ss (gw p)) l <> fromMaybe (ss (gw q)) r | (l, r) <- zipPadF (drawG p) (drawG q) ] top GAnd = "∧" top GOr = "∨" header = [ top op <> ss (w - 1), r '—' (w - 1) <> [' '] ] header' = [ top op <> [' '] <> r '—' (w - 3) <> [' '] ] drawGs :: [G] -> [String] drawGs = concatMap drawG pprintG :: [G] -> IO () pprintG = void . traverse putStrLn . drawGs labelWidth parw (TDone _) = (TDone parw, parw) labelWidth parw (TBlocked _) = (TBlocked parw, parw) labelWidth parw (TForever _) = (TForever parw, parw) labelWidth parw (TAwait _ e next) = (TAwait w e p, w) where (p, w) = labelWidth parw next labelWidth parw (TEmit _ e next) = (TEmit w e p, w) where (p, w) = labelWidth parw next labelWidth parw (TBin _ op p q d) = (TBin dw op p' q' d', dw) where (p', pw) = labelWidth roww p (q', qw) = labelWidth roww q (d', dw) = labelWidth (max (pw + qw) parw) d labelWidth parw (TJoin p) = (TJoin p', w) where (p', w) = labelWidth parw p toG :: Monoid v => Syn v a -> [G] toG p = go l where t = toTSyn' (toDbgSyn p DbgDone) l = (,True) <$> fst (labelWidth roww t) go g = case showG g of (g', Just n) -> g':go n (g', _) -> [g'] testG (g:gs) = all ((== gw g) . gw) (g:gs) showG :: TSyn (W, Bool) -> (G, Maybe (TSyn (W, Bool))) showG (TDone (w, _)) = (L w 1 PictDone, Nothing) showG (TBlocked (w, _)) = (E w 1, Nothing) showG (TForever (w, _)) = (L w 1 PictForever, Nothing) showG (TAwait (w, _) e next) = (L w 1 (PictAwait (evColor' e)), Just next) showG ( TEmit ( w , _ ) e next ) = ( L w 1 ( " E " ) , Just next ) showG (TEmit (w, _) e next) = (L w 1 (PictEmit (evColor' e)), Just next) showG (TJoin next) = showG next showG (TBin (w, draw) op p q d) = case (pg, qg) of (E _ _, E _ _) -> showG d otherwise -> (pq, Just (TBin (w, False) op (fromMaybe (TBlocked (gw pg, False)) p') (fromMaybe (TBlocked (gw qg, False)) q') d)) where (pg, p') = showG p (qg, q') = showG q adjustH :: Int -> G -> G adjustH h (L w _ c) = L w h c adjustH h (B op False bw _ p q) = B op False bw h (adjustH h p) (adjustH h q) adjustH _ b = b mh = max (gh pg) (gh qg) pq = B op draw w (mh + if draw then 1 else 0) (adjustH mh pg) (adjustH mh qg) showTSyn :: TSyn () -> ([[String]], Int) showTSyn (TDone _) = ([["◆"]], 1) showTSyn (TBlocked _) = ([], 1) showTSyn (TForever _) = ([["∞"]], 1) where (t, w) = showTSyn next showTSyn (TAwait _ e next) = ([[evColor e "○" <> ss (w - 1)]] <> t, w) where (t, w) = showTSyn next showTSyn (TEmit _ e next) = ([[evColor e "▲" <> ss (w - 1)]] <> t, w) where (t, w) = showTSyn next showTSyn (TBin _ op p q d) = ( header <> go pg (fmap (fmap (fmap (padto qw ' '))) qg) <> dt , pw + qw + 1 ) where (pt, pw) = showTSyn p (qt, qw') = showTSyn q (dt, dw) = showTSyn d qw = max qw' dw padto x r s = take (x - length s) (repeat r) <> s (pg, qg) = unzip (zipPadB pt qt) top GAnd = "∧" top GOr = "∨" header' = [ [ top op <> " " <> r '—' (pw + qw + 1 - 2) ] ] header = [ [ top op <> ss (pw + qw + 1 - 1) , r '—' (pw + qw + 1) ] ] go :: [Maybe [String]] -> [Maybe [String]] -> [[String]] go [] _ = [] go _ [] = [] go (Just [pt]:ps) (Just [qt]:qs) = [[pt <> " " <> qt]] <> go ps qs go (Just [pt]:ps) (Nothing:qs) = [[pt <> " " <> ss qw]] <> go ps qs go (Nothing:ps) (Just [qt]:qs) = [[ss pw <> " " <> qt]] <> go ps qs go (Just pt:ps) x@(Just [qt]:qs) = [map (<> (" " <> ss qw)) pt] <> go ps x go (Just pt:ps) x@(Nothing:qs) = [map (<> (" " <> ss qw)) pt] <> go ps x go x@(Just [pt]:ps) (Just qt:qs) = [map ((" " <> ss pw) <>) qt] <> go x qs go x@(Nothing:ps) (Just qt:qs) = [map ((" " <> ss pw) <>) qt] <> go x qs go (Just pt:ps) (Just qt:qs) = [ls] <> go ps qs where ls = [ case t of (Just a, Just b) -> a <> " " <> b (Just a, Nothing) -> a <> " " <> ss qw (Nothing, Just b) -> ss pw <> " " <> b | t <- zipPadF pt qt ] zipLines :: [[String]] -> [[String]] -> [(Maybe [String], Maybe [String])] zipLines ([a]:as) ([b]:bs) = (Just [a], Just [b]):zipLines as bs zipLines ([a]:as) (b:bs) = (Nothing, Just b):zipLines ([a]:as) bs zipLines (a:as) ([b]:bs) = (Just a, Nothing):zipLines as ([b]:bs) toDbgSyn :: Monoid v => Syn v a -> (DbgSyn -> DbgSyn) toDbgSyn = go mempty 0 id where go m eid dbg p = if M.size m' == 0 then dbg . dbg' else go m' eid' (dbg . dbg') p' where (eid', p', dbg', _, m', ios, u) = Syn.stepOnce' m 0 eid p Syn.E toGSyn :: Monoid v => Syn v a -> [GSyn] toGSyn = go mempty 0 [] where convert :: Syn v a -> GSyn convert (Syn (Pure _)) = GDone convert (Syn (Free Forever)) = GForever convert (Syn (Free (MapView _ p _))) = convert p convert (Syn (Free (Await (Event _ e) _))) = GAwait e convert (Syn (Free (Emit (EventValue (Event _ e) _) _))) = GEmit e convert (Syn (Free (Or p q _))) = GBin GOr (convert p) (convert q) convert (Syn (Free (And p q _))) = GBin GAnd (convert p) (convert q) go m eid gp p = if M.size m' == 0 then convert p':gp else go m' eid' (convert p':gp) p' where (eid', p', _, _, m', ios, u) = Syn.stepOnce' m 0 eid p Syn.E zipPadB :: [a] -> [b] -> [(Maybe a, Maybe b)] zipPadB as bs = zip (map Just as <> take (max 0 (length bs - length as)) (repeat Nothing)) (map Just bs <> take (max 0 (length as - length bs)) (repeat Nothing)) zipPadF :: [a] -> [b] -> [(Maybe a, Maybe b)] zipPadF as bs = zip (take (max 0 (length bs - length as)) (repeat Nothing) <> map Just as) (take (max 0 (length as - length bs)) (repeat Nothing) <> map Just bs) pprintProgram p = void $ traverse putStrLn (showProgram' ((reverse $ toGSyn p))) pprintProgram2 p = void $ traverse putStrLn (concat $ fst $ showTSyn (toTSyn' (toDbgSyn p DbgDone))) pprintProgram3 p = fst $ labelWidth roww $ toTSyn' (toDbgSyn p DbgDone) pprintProgram4 :: Monoid v => Syn v a -> IO () pprintProgram4 = pprintG . toG showTrail :: GSyn -> [String] showTrail = fst3 . go where go :: GSyn -> ([String], Int, Int) go (GEmit e) = ([evColor e "▲"], 1, 0) go (GAwait e) = ([evColor e "○"], 1, 0) go GDone = (["◆"], 1, 0) go GForever = (["∞"], 1, 0) go (GBin op p q) = ( header <> subheader <> lines , pw + qw + 1 , length header + length subheader ) where top GAnd = "∧" top GOr = "∨" header' = [ top op <> " " <> r '—' (pw + qw + 1 - 2) ] header = [ top op <> ss (pw + qw + 1 - 1) , r '—' (pw + qw + 1) ] subheader = [ mconcat [ case ph of Nothing -> ss pw Just t -> t , " " , case qh of Nothing -> ss qw Just t -> t ] | (ph, qh) <- zipPadF (take ph pt) (take qh qt) ] lines = [ mconcat [ case ph of Nothing -> ss pw Just t -> t , " " , case qh of Nothing -> ss qw Just t -> t ] | (ph, qh) <- zipPadF (drop ph pt) (drop qh qt) ] (pt, pw, ph) = go p (qt, qw, qh) = go q showProgram :: [GSyn] -> [String] showProgram = concat . go [] where go u [] = [] go u (p:ps) = t':go t ps where t = showTrail p t' = strip u t strip [] bs = bs strip (a:as) (b:bs) | a == b = strip as bs | otherwise = (b:bs) showProgram' :: [GSyn] -> [String] showProgram' = concat . intersperse [""] . map showTrail p4 : : ( ) _ ( Syn.andd ( Syn.await e , Syn.emit f " F " ) , Syn.orr [ Syn.await f > > Syn.orr [ Syn.forever , Syn.await e ] , Syn.forever ] , Syn.andd ( pure " _ " : : ( ) String , Syn.await f > > Syn.emit e " E " ) p6 = Syn.local $ \e - > Syn.local $ \f - > Syn.local $ \g - > do ( Syn.andd ( Syn.await e , Syn.emit f " F " > > ( Syn.andd ( Syn.await , Syn.await ) : : ( ) ( _ , _ ) ) > > Syn.emit e " E " ) , ( Syn.await f , Syn.await g , Syn.await e ) , ( Syn.await e , Syn.await , Syn.await f ) , ( pure " _ " : : ( ) String , Syn.await f > > Syn.emit g " G " ) p6_2 = Syn.local $ \e - > Syn.local $ \f - > Syn.local $ \g - > do ( Syn.andd ( Syn.await e , Syn.emit f " F " > > Syn.await > > Syn.emit e " E " ) , ( Syn.await f , Syn.await g , Syn.await e ) , ( Syn.await e , Syn.await , Syn.await f ) , ( pure " _ " : : ( ) String , Syn.await f > > Syn.emit g " G " ) p7 : : ( ) _ ( go 0 0 e f Syn.emit f 1 Syn.emit f 2 Syn.emit f 3 Syn.emit f 6 Syn.emit f 8 svg :: Element svg = g_ [] (text_ [] "YO") p :: Element p = path_ [ D_ <<- (mA 10 80 <> qA 52.5 10 95 80 <> tA 180 80 <> z) , Fill_ <<- "#333333" ] aR :: RealFloat a => a -> a -> a -> Int -> Int -> a -> a -> Text aR rx ry xrot largeFlag sweepFlag x y = T.concat [ "a ", toText rx, ",", toText ry, " ", toText xrot, " ", T.pack (show largeFlag) , " ", T.pack (show sweepFlag), " ", toText x, " ", toText y, " "] palette = [ "#e6194b", "#3cb44b", "#ffe119", "#4363d8", "#f58231", "#911eb4", "#46f0f0", "#f032e6", "#bcf60c", "#fabebe", "#008080", "#e6beff", "#9a6324", "#fffac8", "#800000", "#aaffc3", "#808000", "#ffd8b1", "#000075", "#808080", "#ffffff", "#000000" ] paletteColor x = palette !! (x `mod` length palette) trail' :: Pictogram -> Text -> Double -> Double -> Double -> Double -> Double -> Element trail' c color x y width height r = mconcat [ path_ [ D_ <<- (mA x y <> vR height <> aR (width / 2) (width /2) 0 1 0 width 0 <> vR (-height) <> z) , Fill_ <<- "#000" ] , case c of PictAwait c -> circle_ [ Cx_ <<- t (x + (width / 2)) , Cy_ <<- t (y + height) , R_ <<- t (r / 1.1) , Stroke_width _ < < - " 2px " , Fill_ <<- paletteColor c , Class_ <<- "circle" ] PictDone -> path_ [ D_ <<- (mA (x + width / 2) (y + height - r) <> lR r r <> lR (-r) r <> lR (-r) (-r) <> z) , Fill_ <<- "#fff" ] PictEmit c -> path_ [ D_ <<- (mA (x + width / 2 - r) (y + height - r) <> lR r (r * 1.8) <> lR r (-r * 1.8) <> z) , Fill_ <<- paletteColor c ] otherwise -> path_ [] ] where t = T.pack . show trail :: Text -> Double -> Double -> Double -> Double -> Double -> Element trail color x y width height r = mconcat [ path_ [ D_ <<- (mA x y <> vR height <> aR (width / 2) (width /2) 0 1 0 width 0 <> vR (-height) <> z) , Fill_ <<- color ] , mconcat [ circle_ [ Cx_ <<- t (x + (width / 2)) , Cy_ <<- t (y + height) , R_ <<- t r , Fill_ <<- "#ddd" , Class_ <<- "circle" ] ] ] where t = T.pack . show generateSVG style t = mconcat $ intersperse "\n" [ "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" , "<svg version=\"1.1\" xmlns=\"\" xmlns:xlink=\"\" x=\"0px\" y=\"0px\" viewBox=\"0 0 960 960\">" , "<defs>" , "<style type=\"text/css\"><![CDATA[" , style , "]]></style>" , "</defs>" , show t , "</svg>" ] gridw = 16 gridh = 30 gridx = 50 gridy = 50 tox x = gridx + fromIntegral x * gridw toy y = gridy + fromIntegral y * gridh tow w = fromIntegral w * gridw toh h = fromIntegral h * gridh gridTrail :: Pictogram -> Int -> Int -> Int -> Element gridTrail t x y h = trail' t "#333" (tox x) (toy y) (tow 1) (toh h) (gridw / 4) svgG :: Int -> Int -> G -> Element svgG x y (L _ h c) = gridTrail c x y h svgG x y (E _ _) = mempty svgG x y (B op draw w h p q) = mconcat [ svgG x (y + h - gh p) p , svgG (x + gw p) (y + h - gh q) q , if draw then path_ [ D _ < < - ( mA ( tox x ) ( toy ( y + 1 ) - ( gridh / 3 ) ) < > hR ( tow ( w - 1 ) ) ) [ D_ <<- (mA (tox x) (toy (y + 1) - (gridh / 3) - 2) <> lR tm 0 <> lR tx (-ty) <> lR tx ty <> lR tm 0) , Stroke_width_ <<- "3px" , Stroke_ <<- "#000" , Fill_ <<- "transparent" ] else mempty ] where tw = tow (w - 1) tx = 6 ty = case op of GAnd -> 6 GOr -> (-6) tm = tw / 2 - tx svgGs :: H -> [G] -> Element svgGs _ [] = mempty svgGs h (g:gs) = svgGs (h + h') gs <> svgG 0 h g where h' = gh g makeSvg :: Monoid v => Syn v a -> IO () makeSvg p = writeFile "out.svg" (generateSVG "" (svgGs 0 $ toG p))
a7a47db9f758934314961f74e547c3b3f0d31100f4f499ee95710ddaf1540098
levand/quiescent
project.clj
(defproject quiescent.examples.composite-components "0.1.0" :plugins [[lein-cljsbuild "1.1.2"]] :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.7.228"] [quiescent/quiescent "0.3.0"] [cljsjs/react-bootstrap "0.28.1-0" :exclusions [[cljsjs/react]]]] :clean-targets ^{:protect false} [:target-path :compile-path "resources/public/gen"] :cljsbuild {:builds {:dev {:source-paths ["src"] :compiler {:output-dir "resources/public/gen/dev" :output-to "resources/public/gen/dev/main.js" :optimizations :none :source-map true}} :prod {:source-paths ["src"] :compiler {:output-to "resources/public/gen/main.js" :optimizations :advanced :pretty-print false}}}})
null
https://raw.githubusercontent.com/levand/quiescent/2063ebcaffb2c62e48a177c894a10f9066b7f2cc/examples/composite-components/project.clj
clojure
(defproject quiescent.examples.composite-components "0.1.0" :plugins [[lein-cljsbuild "1.1.2"]] :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/clojurescript "1.7.228"] [quiescent/quiescent "0.3.0"] [cljsjs/react-bootstrap "0.28.1-0" :exclusions [[cljsjs/react]]]] :clean-targets ^{:protect false} [:target-path :compile-path "resources/public/gen"] :cljsbuild {:builds {:dev {:source-paths ["src"] :compiler {:output-dir "resources/public/gen/dev" :output-to "resources/public/gen/dev/main.js" :optimizations :none :source-map true}} :prod {:source-paths ["src"] :compiler {:output-to "resources/public/gen/main.js" :optimizations :advanced :pretty-print false}}}})
27a8c56b86afa303391194bd2979262365224ed2880d2ddc1f5c509dcee7e44f
wireapp/wire-server
One2One.hs
-- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- 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 </>. module Galley.Types.Conversations.One2One (one2OneConvId) where import Control.Error (atMay) import qualified Crypto.Hash as Crypto import Data.Bits import Data.ByteArray (convert) import qualified Data.ByteString as B import Data.ByteString.Conversion import qualified Data.ByteString.Lazy as L import Data.Id import Data.Qualified import Data.UUID (UUID) import qualified Data.UUID as UUID import qualified Data.UUID.Tagged as U import Imports | The hash function used to obtain the 1 - 1 conversation ID for a pair of users . -- /Note/ : the hash function must always return byte strings of length > 16 . hash :: ByteString -> ByteString hash = convert . Crypto.hash @ByteString @Crypto.SHA256 | A randomly - generated UUID to use as a namespace for the UUIDv5 of 1 - 1 -- conversation IDs namespace :: UUID namespace = UUID.fromWords 0x9a51edb8 0x060c0d9a 0x0c2950a8 0x5d152982 compareDomains :: Ord a => Qualified a -> Qualified a -> Ordering compareDomains (Qualified a1 dom1) (Qualified a2 dom2) = compare (dom1, a1) (dom2, a2) quidToByteString :: Qualified UserId -> ByteString quidToByteString (Qualified uid domain) = toByteString' uid <> toByteString' domain | This function returns the 1 - 1 conversation for a given pair of users . -- Let A , B denote the ( not necessarily distinct ) backends of the two users , -- with the domain of A less or equal than the domain of B in the lexicographic ordering of their ascii encodings . Given users a@A and b@B , the UUID and owning domain of the unique 1 - 1 conversation between a and b shall be a -- deterministic function of the input data, plus some fixed parameters, as -- described below. -- -- __Parameters__ -- -- * A (collision-resistant) hash function h with N bits of output, where N s a multiple of 8 strictly larger than 128 ; this is set to SHA256 . -- * A "namespace" UUID n. -- -- __Algorithm__ -- First , in the special case where A and B are the same backend , assume that the UUID of a is lower than that of b. If that is not the case , swap a -- and b in the following. This is necessary to ensure that the function we -- describe below is symmetric in its arguments. Let c be the bytestring obtained as the concatenation of the following 5 -- components: -- * the 16 bytes of the namespace n * the 16 bytes of the UUID of a -- * the ascii encoding of the domain of A * the 16 bytes of the UUID of b -- * the ascii encoding of the domain of B, -- and let x = ) be its hashed value . The UUID of the 1 - 1 conversation between a and b is obtained by converting the first 128 bits of x to a UUID V5 . Note that our use of V5 here is not strictly compliant with RFC 4122 , since we are using a custom hash and not necessarily . -- The owning domain for the conversation is set to be A if bit 128 of x ( i.e. the most significant bit of the octet at index 16 ) is 0 , and B otherwise . -- This is well-defined, because we assumed the number of bits of x to be strictly larger than 128 . one2OneConvId :: Qualified UserId -> Qualified UserId -> Qualified ConvId one2OneConvId a b = case compareDomains a b of GT -> one2OneConvId b a _ -> let c = mconcat [ L.toStrict (UUID.toByteString namespace), quidToByteString a, quidToByteString b ] x = hash c result = U.toUUID . U.mk @U.V5 . fromMaybe UUID.nil -- fromByteString only returns 'Nothing' when the input is not exactly 16 bytes long , here this should not be a case since ' hash ' is supposed to return atleast 16 bytes and we use ' B.take -- 16' to truncate it . UUID.fromByteString . L.fromStrict . B.take 16 $ x domain | fromMaybe 0 (atMay (B.unpack x) 16) .&. 0x80 == 0 = qDomain a | otherwise = qDomain b in Qualified (Id result) domain
null
https://raw.githubusercontent.com/wireapp/wire-server/e03f7219210019ae5be50739f594dc667e669168/libs/galley-types/src/Galley/Types/Conversations/One2One.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under 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. with this program. If not, see </>. conversation IDs with the domain of A less or equal than the domain of B in the lexicographic deterministic function of the input data, plus some fixed parameters, as described below. __Parameters__ * A (collision-resistant) hash function h with N bits of output, where N * A "namespace" UUID n. __Algorithm__ and b in the following. This is necessary to ensure that the function we describe below is symmetric in its arguments. components: * the ascii encoding of the domain of A * the ascii encoding of the domain of B, This is well-defined, because we assumed the number of bits of x to be fromByteString only returns 'Nothing' when the input is not 16' to truncate it
Copyright ( C ) 2022 Wire Swiss GmbH < > 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 You should have received a copy of the GNU Affero General Public License along module Galley.Types.Conversations.One2One (one2OneConvId) where import Control.Error (atMay) import qualified Crypto.Hash as Crypto import Data.Bits import Data.ByteArray (convert) import qualified Data.ByteString as B import Data.ByteString.Conversion import qualified Data.ByteString.Lazy as L import Data.Id import Data.Qualified import Data.UUID (UUID) import qualified Data.UUID as UUID import qualified Data.UUID.Tagged as U import Imports | The hash function used to obtain the 1 - 1 conversation ID for a pair of users . /Note/ : the hash function must always return byte strings of length > 16 . hash :: ByteString -> ByteString hash = convert . Crypto.hash @ByteString @Crypto.SHA256 | A randomly - generated UUID to use as a namespace for the UUIDv5 of 1 - 1 namespace :: UUID namespace = UUID.fromWords 0x9a51edb8 0x060c0d9a 0x0c2950a8 0x5d152982 compareDomains :: Ord a => Qualified a -> Qualified a -> Ordering compareDomains (Qualified a1 dom1) (Qualified a2 dom2) = compare (dom1, a1) (dom2, a2) quidToByteString :: Qualified UserId -> ByteString quidToByteString (Qualified uid domain) = toByteString' uid <> toByteString' domain | This function returns the 1 - 1 conversation for a given pair of users . Let A , B denote the ( not necessarily distinct ) backends of the two users , ordering of their ascii encodings . Given users a@A and b@B , the UUID and owning domain of the unique 1 - 1 conversation between a and b shall be a s a multiple of 8 strictly larger than 128 ; this is set to SHA256 . First , in the special case where A and B are the same backend , assume that the UUID of a is lower than that of b. If that is not the case , swap a Let c be the bytestring obtained as the concatenation of the following 5 * the 16 bytes of the namespace n * the 16 bytes of the UUID of a * the 16 bytes of the UUID of b and let x = ) be its hashed value . The UUID of the 1 - 1 conversation between a and b is obtained by converting the first 128 bits of x to a UUID V5 . Note that our use of V5 here is not strictly compliant with RFC 4122 , since we are using a custom hash and not necessarily . The owning domain for the conversation is set to be A if bit 128 of x ( i.e. the most significant bit of the octet at index 16 ) is 0 , and B otherwise . strictly larger than 128 . one2OneConvId :: Qualified UserId -> Qualified UserId -> Qualified ConvId one2OneConvId a b = case compareDomains a b of GT -> one2OneConvId b a _ -> let c = mconcat [ L.toStrict (UUID.toByteString namespace), quidToByteString a, quidToByteString b ] x = hash c result = U.toUUID . U.mk @U.V5 . fromMaybe UUID.nil exactly 16 bytes long , here this should not be a case since ' hash ' is supposed to return atleast 16 bytes and we use ' B.take . UUID.fromByteString . L.fromStrict . B.take 16 $ x domain | fromMaybe 0 (atMay (B.unpack x) 16) .&. 0x80 == 0 = qDomain a | otherwise = qDomain b in Qualified (Id result) domain
352b45438ca3c5e4b86e3cfcb46a7d0ac45b4edc09825b589bcb3a32430f3fe0
skanev/playground
13.scm
SICP exercise 3.13 ; ; Consider the following make-cycle procedure, which uses the last-pair procedure defined in exercise 3.12 : ; ; (define (make-cycle x) ; (set-cdr! (last-pair x) x) ; x) ; ; Draw a box-and-pointer diagram that shows the structure z created by ; ; (define z (make-cycle (list 'a 'b 'c))) ; ; What happens if we try to compute (last-pair z)? ; Here's the diagram: ; ; +----------------------------------+ ; | | ; +---+---+ +---+---+ +---+---+ | ; z --> | . | . -----| . | . -----| . | . ---+ ; +-|-+---+ +-|-+---+ +-|-+---+ ; | | | ; +---+ +---+ +---+ ; | a | | b | | c | ; +---+ +---+ +---+ ; ; If we try to compute (last-pair z), it will end up in an infinite recursion, ; because there is no pair with a cdr that is null.
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/03/13.scm
scheme
Consider the following make-cycle procedure, which uses the last-pair (define (make-cycle x) (set-cdr! (last-pair x) x) x) Draw a box-and-pointer diagram that shows the structure z created by (define z (make-cycle (list 'a 'b 'c))) What happens if we try to compute (last-pair z)? Here's the diagram: +----------------------------------+ | | +---+---+ +---+---+ +---+---+ | z --> | . | . -----| . | . -----| . | . ---+ +-|-+---+ +-|-+---+ +-|-+---+ | | | +---+ +---+ +---+ | a | | b | | c | +---+ +---+ +---+ If we try to compute (last-pair z), it will end up in an infinite recursion, because there is no pair with a cdr that is null.
SICP exercise 3.13 procedure defined in exercise 3.12 :
f8b416e07db11d87eda0c28b83e2026c75625f6d1274aed7c0bf43b7f6399610
portkey-cloud/aws-clj-sdk
mturk_requester.clj
(ns portkey.aws.mturk-requester (:require [portkey.aws])) (def endpoints '{"sandbox" {:credential-scope {:service "mturk-requester", :region "sandbox"}, :ssl-common-name "mturk-requester-sandbox.us-east-1.amazonaws.com", :endpoint "-requester-sandbox.us-east-1.amazonaws.com", :signature-version :v4}, "us-east-1" {:credential-scope {:service "mturk-requester", :region "us-east-1"}, :ssl-common-name "mturk-requester.us-east-1.amazonaws.com", :endpoint "-requester.us-east-1.amazonaws.com", :signature-version :v4}}) (comment TODO support "json")
null
https://raw.githubusercontent.com/portkey-cloud/aws-clj-sdk/10623a5c86bd56c8b312f56b76ae5ff52c26a945/src/portkey/aws/mturk_requester.clj
clojure
(ns portkey.aws.mturk-requester (:require [portkey.aws])) (def endpoints '{"sandbox" {:credential-scope {:service "mturk-requester", :region "sandbox"}, :ssl-common-name "mturk-requester-sandbox.us-east-1.amazonaws.com", :endpoint "-requester-sandbox.us-east-1.amazonaws.com", :signature-version :v4}, "us-east-1" {:credential-scope {:service "mturk-requester", :region "us-east-1"}, :ssl-common-name "mturk-requester.us-east-1.amazonaws.com", :endpoint "-requester.us-east-1.amazonaws.com", :signature-version :v4}}) (comment TODO support "json")
048ee6f24bb31fd67b586200ca48db4b2f9357b0f3f83a81409b99f948270237
racket/typed-racket
fx-filter.rkt
#lang typed/racket ;; test filters on fx primitives that tell us that if the function ;; returns at all, its arguments were fixnums ;; currently only works if the fx operation is used in test position, ;; due to the way filters are used. this should be improved in the ;; future (require racket/fixnum) (: f : Integer -> Fixnum) (define (f x) (if (fx+ x 4) x x)) (: g : Integer -> Fixnum) (define (g x) (if (fxnot x) x x))
null
https://raw.githubusercontent.com/racket/typed-racket/0236151e3b95d6d39276353cb5005197843e16e4/typed-racket-test/succeed/fx-filter.rkt
racket
test filters on fx primitives that tell us that if the function returns at all, its arguments were fixnums currently only works if the fx operation is used in test position, due to the way filters are used. this should be improved in the future
#lang typed/racket (require racket/fixnum) (: f : Integer -> Fixnum) (define (f x) (if (fx+ x 4) x x)) (: g : Integer -> Fixnum) (define (g x) (if (fxnot x) x x))
066474322d3ed9a67c556f6e1a127220ecde6bbb0dfdaa46b7f8c8097d4401f4
lmj/lfarm
cognate.lisp
Copyright ( c ) 2013 , . All rights reserved . ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials provided ;;; with the distribution. ;;; ;;; * Neither the name of the project nor the names of its ;;; contributors may be used to endorse or promote products derived ;;; from this software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , ;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (defpackage #:lfarm-client.cognate (:documentation "Promises and futures.") (:use #:cl #:lfarm-common #:lfarm-client.kernel #:lfarm-client.promise) (:export #:plet #:pmap #:pmapcar #:pmap-into #:preduce #:preduce-partial #:pmap-reduce) (:import-from #:lfarm-client.kernel #:maybe-convert-task #:maybe-convert-task-form)) (in-package #:lfarm-client.cognate) ;;;; plet (defun pairp (form) (and (consp form) (eql (length form) 2))) (defun parse-bindings (bindings) (let* ((pairs (remove-if-not #'pairp bindings)) (non-pairs (remove-if #'pairp bindings)) (syms (loop for (name nil) in pairs collect (gensym (symbol-name name))))) (values pairs non-pairs syms))) (defmacro plet (bindings &body body) "The syntax of `plet' matches that of `let'. plet ({var-no-init | (var [init-form])}*) form* For each (var init-form) pair, a future is created which executes `init-form'. Inside `body', `var' is a symbol macro which expands to a `force' form for the corresponding future. Each `var-no-init' is bound to nil and each `var' without `init-form' is bound to nil (no future is created)." (multiple-value-bind (pairs non-pairs syms) (parse-bindings bindings) `(symbol-macrolet ,(loop for sym in syms for (name nil) in pairs collect `(,name (force ,sym))) (let (,@(loop for sym in syms for (nil form) in pairs collect `(,sym (future ,form))) ,@non-pairs) ,@body)))) ;;;; subdivide (defun find-num-parts (size parts-hint) (multiple-value-bind (quo rem) (floor size parts-hint) (values (if (zerop quo) rem parts-hint) quo rem))) (defmacro with-parts (seq-size parts-hint &body body) (with-gensyms (quo rem index num-parts part-offset part-size) `(multiple-value-bind (,num-parts ,quo ,rem) (find-num-parts ,seq-size ,parts-hint) (let ((,index 0) (,part-offset 0) (,part-size 0)) (flet ((next-part () (when (< ,index ,num-parts) (unless (zerop ,index) (incf ,part-offset ,part-size)) (setf ,part-size (if (< ,index ,rem) (1+ ,quo) ,quo)) (incf ,index))) (part-size () ,part-size) (part-offset () ,part-offset) (num-parts () ,num-parts)) (declare (inline part-size part-offset num-parts) (ignorable #'part-size #'part-offset #'num-parts)) ,@body))))) (defun zip/vector (seqs) (apply #'map 'vector #'list seqs)) (defun find-min-length (seqs) (reduce #'min seqs :key #'length)) (defun get-parts-hint (parts-hint) (cond (parts-hint (check-type parts-hint (integer 1 #.most-positive-fixnum)) parts-hint) (t (kernel-worker-count)))) (defmacro pop-plist (list) `(loop while (keywordp (car ,list)) collect (pop ,list) collect (pop ,list))) (defun %parse-options (args) (destructuring-bind (&key size parts) (pop-plist args) (values args size parts))) (defun parse-options (args) (multiple-value-bind (seqs size parts) (%parse-options args) (unless seqs (error "Input sequence(s) for parallelization not found.")) (unless size (setf size (find-min-length seqs))) (setf parts (get-parts-hint parts)) (values seqs size parts))) (defmacro with-parsed-options ((args size parts) &body body) `(multiple-value-bind (,args ,size ,parts) (parse-options ,args) ,@body)) (defun subdivide-array (array size parts-hint) Create copies , in contradistinction to lparallel . Otherwise we ;; send unnecessary data over the wire. A serialized displaced ;; vector includes its displaced-to vector. (with-parts size parts-hint (map-into (make-array (num-parts)) (lambda () (next-part) (replace (make-array (part-size) :element-type (array-element-type array)) array :start2 (part-offset)))))) (defun subdivide-list (list size parts-hint) Create copies , in contradistinction to lparallel . Otherwise we ;; send unnecessary data over the wire. (with-parts size parts-hint (loop with p = list while (next-part) collect (loop repeat (part-size) collect (car p) do (setf p (cdr p)))))) (defun make-parts (result size parts-hint) (etypecase result (list (subdivide-list result size parts-hint)) (vector (subdivide-array result size parts-hint)))) (defun make-input-parts (sequences size parts-hint) "Subdivide and interleave sequences for parallel mapping." (zip/vector (mapcar (lambda (seq) (make-parts seq size parts-hint)) sequences))) ;;;; task util (defun receive-indexed (channel count) (loop with result = (make-array count) repeat count do (destructuring-bind (index . data) (receive-result channel) (setf (aref result index) data)) finally (return result))) (defun task->fn-form (task) (etypecase task (symbol `',task) (cons task))) (defmacro funcall-task (task &rest args) (with-gensyms (channel) `(let ((,channel (make-channel))) (submit-task ,channel ,task ,@args) (receive-result ,channel)))) ;;;; pmap (defwith with-max-fill-pointer (seq) (if (and (vectorp seq) (array-has-fill-pointer-p seq)) (let ((prev-fill-pointer (fill-pointer seq))) (unwind-protect/safe :prepare (setf (fill-pointer seq) (array-total-size seq)) :main (call-body) :cleanup (setf (fill-pointer seq) prev-fill-pointer))) (call-body))) (defun mapping-task (subresult-type task) `(lambda (subseqs part-index part-size) (cons part-index (apply #'map-into (make-sequence ',subresult-type part-size) ,(task->fn-form task) subseqs)))) (defun subresult-type (result-seq) (let ((element-type (etypecase result-seq (list t) (vector (array-element-type result-seq))))) `(simple-array ,element-type (*)))) (defun pmap-into/submit (channel result-seq task sequences size parts-hint) (let* ((task (maybe-convert-task task)) (mapping-task (mapping-task (subresult-type result-seq) task)) (input-parts (make-input-parts sequences size parts-hint))) (with-parts size parts-hint (loop for subseqs across input-parts for part-index from 0 while (next-part) do (submit-task channel mapping-task subseqs part-index (part-size)))))) (defun pmap-into/receive (channel result-seq size parts-hint) (with-parts size parts-hint (let ((result-parts (receive-indexed channel (num-parts)))) (with-max-fill-pointer (result-seq) (loop for index from 0 while (next-part) do (replace result-seq (aref result-parts index) :start1 (part-offset) :end1 (+ (part-offset) (part-size)))))))) (defun pmap-into/parsed (result-seq task sequences size parts-hint) (let ((channel (make-channel))) (pmap-into/submit channel result-seq task sequences size parts-hint) (pmap-into/receive channel result-seq size parts-hint)) result-seq) (defun pmap/parsed (result-type function sequences size parts-hint) ;; do nothing for (pmap nil ...) (when result-type (pmap-into/parsed (make-sequence result-type size) function sequences size parts-hint))) (defun pmap/unparsed (result-type function sequences) (with-parsed-options (sequences size parts-hint) (pmap/parsed result-type function sequences size parts-hint))) (defun pmap/fn (result-type task first-sequence &rest more-sequences) (pmap/unparsed result-type task (cons first-sequence more-sequences))) (defmacro pmap (result-type task first-sequence &rest more-sequences &environment env) "Parallel version of `map'. Keyword arguments `parts' and `size' are also accepted. The `parts' option divides each sequence into `parts' number of parts. Default is (kernel-worker-count). The `size' option limits the number of elements mapped to `size'. When given, no `length' calls are made on the sequence(s) passed. Warning: `size' must be less than or equal to the length of the smallest sequence passed. It is unspecified what happens when that condition is not met." `(pmap/fn ,result-type ,(maybe-convert-task-form task env) ,first-sequence ,@more-sequences)) (defun pmapcar/fn (task first-sequence &rest more-sequences) (apply #'pmap/fn 'list task (cons first-sequence more-sequences))) (defmacro pmapcar (task first-sequence &rest more-sequences &environment env) "Parallel version of `mapcar'. Keyword arguments `parts' and `size' are also accepted (see `pmap'). Unlike `mapcar', `pmapcar' also accepts vectors." `(pmap/fn 'list ,(maybe-convert-task-form task env) ,first-sequence ,@more-sequences)) (defun pmap-into-thunk-form (task) (with-gensyms (x) (etypecase task (cons (destructuring-bind (head lambda-list &rest body) task (assert (eq head 'lambda)) `(lambda (,x ,@lambda-list) (declare (ignore ,x)) ,@body)))))) (defun pmap-into/unparsed (result-seq task args) (let ((task (maybe-convert-task task))) (multiple-value-bind (seqs size parts-hint) (%parse-options args) (let* ((has-fill-p (and (arrayp result-seq) (array-has-fill-pointer-p result-seq))) (parts-hint (get-parts-hint parts-hint)) (size (or size (let ((limit (if has-fill-p (array-total-size result-seq) (length result-seq)))) (if seqs (min limit (find-min-length seqs)) limit))))) (prog1 (if seqs (pmap-into/parsed result-seq task seqs size parts-hint) (pmap-into/parsed result-seq (pmap-into-thunk-form task) (list result-seq) size parts-hint)) (when has-fill-p (setf (fill-pointer result-seq) size))))))) (defun pmap-into/fn (result-sequence task &rest sequences) (typecase result-sequence ((or array list) (pmap-into/unparsed result-sequence task sequences)) (t (apply #'map-into result-sequence task sequences))) result-sequence) (defmacro pmap-into (result-sequence task &rest sequences &environment env) "Parallel version of `map-into'. Keyword arguments `parts' and `size' are also accepted (see `pmap')." `(pmap-into/fn ,result-sequence ,(maybe-convert-task-form task env) ,@sequences)) ;;;; preduce (defun reducing-task (task keyword-args) (let ((keyword-args (copy-list keyword-args))) (when-let (key (getf keyword-args :key)) (setf (getf keyword-args :key) (task->fn-form key))) `(lambda (sequence start end result-index) (cons result-index (reduce ,(task->fn-form task) sequence :start start :end end ,@keyword-args))))) (defun preduce-partial/vector (task sequence start size parts &rest keyword-args) (let ((reducing-task (reducing-task task keyword-args)) (channel (make-channel))) (with-parts size parts (loop for result-index from 0 while (next-part) do (submit-task channel reducing-task sequence (+ start (part-offset)) (+ start (part-offset) (part-size)) result-index)) (receive-indexed channel (num-parts))))) (defun preduce-partial/list (task sequence start size parts &rest keyword-args) (let ((reducing-task (reducing-task task keyword-args)) (channel (make-channel))) (with-parts size parts (loop with subseq = (nthcdr start sequence) for result-index from 0 while (next-part) do (submit-task channel reducing-task subseq 0 (part-size) result-index) (setf subseq (nthcdr (part-size) subseq))) (receive-indexed channel (num-parts))))) (defun %preduce-partial (task sequence start size parts &rest keyword-args) (etypecase sequence (vector (apply #'preduce-partial/vector task sequence start size parts keyword-args)) (list (apply #'preduce-partial/list task sequence start size parts keyword-args)))) (defun reduce/remote (task results) (funcall-task `(lambda (results) (reduce ,(task->fn-form task) results)) results)) (defun preduce/common (task sequence subsize &key key from-end (start 0) end (initial-value nil initial-value-given-p) parts recurse partial) (declare (ignore end)) (let ((task (maybe-convert-task task))) (cond ((zerop subsize) (when partial (error "PREDUCE-PARTIAL given zero-length sequence")) (if initial-value-given-p initial-value (funcall-task task))) (t (let* ((parts-hint (get-parts-hint parts)) (results (apply #'%preduce-partial task sequence start subsize parts-hint :key key :from-end from-end (when initial-value-given-p (list :initial-value initial-value))))) (if partial results (let ((new-size (length results))) (if (and recurse (>= new-size 4)) (apply #'preduce/common task results new-size :from-end from-end :parts (min parts-hint (floor new-size 2)) :recurse recurse (when initial-value-given-p (list :initial-value initial-value))) (reduce/remote task results))))))))) (defun subsize (seq size start end) (let ((result (- (or end size) start))) (when (or (minusp result) (> result size)) (error "Bad interval for sequence operation on ~a: start=~a end=~a" seq start end)) result)) (defun preduce/fn (task sequence &rest args &key key from-end (start 0) end initial-value parts recurse) (declare (ignore key from-end initial-value parts recurse)) (etypecase sequence ((or vector list) (apply #'preduce/common task sequence (subsize sequence (length sequence) start end) args)))) (defun maybe-convert-key-form (keyword-args env) (let ((keyword-args (copy-list keyword-args))) (when-let (key (getf keyword-args :key)) (setf (getf keyword-args :key) (maybe-convert-task-form key env))) keyword-args)) (defmacro preduce (task sequence &rest args &key key from-end (start 0) end initial-value parts recurse &environment env) "Parallel version of `reduce'. `preduce' subdivides the input sequence into `parts' number of parts and, in parallel, calls `reduce' on each part. The partial results are then reduced again, either by `reduce' (the default) or, if `recurse' is non-nil, by `preduce'. `parts' defaults to (kernel-worker-count). `key' is thrown out while reducing the partial results. It applies to the first pass only. `start' and `end' have the same meaning as in `reduce'. `from-end' means \"from the end of each part\". `initial-value' means \"initial value of each part\"." (declare (ignore key from-end start end initial-value parts recurse)) `(preduce/fn ,(maybe-convert-task-form task env) ,sequence ,@(maybe-convert-key-form args env))) (defun preduce-partial/fn (task sequence &rest args &key key from-end (start 0) end initial-value parts) (declare (ignore key from-end initial-value parts)) (apply #'preduce/common task sequence (subsize sequence (length sequence) start end) :partial t args)) (defmacro preduce-partial (task sequence &rest args &key key from-end (start 0) end initial-value parts &environment env) "Like `preduce' but only does a single reducing pass. The length of `sequence' must not be zero. Returns the partial results as a vector." (declare (ignore key from-end start end initial-value parts)) `(preduce-partial/fn ,(maybe-convert-task-form task env) ,sequence ,@(maybe-convert-key-form args env))) (defmacro pmap-reduce (map-function reduce-function sequence &rest args &key start end initial-value parts recurse) "Equivalent to (preduce reduce-function sequence :key map-function ...)." (declare (ignore start end initial-value parts recurse)) `(preduce ,reduce-function ,sequence :key ,map-function ,@args))
null
https://raw.githubusercontent.com/lmj/lfarm/f7ba49f1ec01fb99a7aeb8f18e245a44411c361b/lfarm-client/cognate.lisp
lisp
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT LOSS OF USE , DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. plet subdivide send unnecessary data over the wire. A serialized displaced vector includes its displaced-to vector. send unnecessary data over the wire. task util pmap do nothing for (pmap nil ...) preduce
Copyright ( c ) 2013 , . All rights reserved . " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT (defpackage #:lfarm-client.cognate (:documentation "Promises and futures.") (:use #:cl #:lfarm-common #:lfarm-client.kernel #:lfarm-client.promise) (:export #:plet #:pmap #:pmapcar #:pmap-into #:preduce #:preduce-partial #:pmap-reduce) (:import-from #:lfarm-client.kernel #:maybe-convert-task #:maybe-convert-task-form)) (in-package #:lfarm-client.cognate) (defun pairp (form) (and (consp form) (eql (length form) 2))) (defun parse-bindings (bindings) (let* ((pairs (remove-if-not #'pairp bindings)) (non-pairs (remove-if #'pairp bindings)) (syms (loop for (name nil) in pairs collect (gensym (symbol-name name))))) (values pairs non-pairs syms))) (defmacro plet (bindings &body body) "The syntax of `plet' matches that of `let'. plet ({var-no-init | (var [init-form])}*) form* For each (var init-form) pair, a future is created which executes `init-form'. Inside `body', `var' is a symbol macro which expands to a `force' form for the corresponding future. Each `var-no-init' is bound to nil and each `var' without `init-form' is bound to nil (no future is created)." (multiple-value-bind (pairs non-pairs syms) (parse-bindings bindings) `(symbol-macrolet ,(loop for sym in syms for (name nil) in pairs collect `(,name (force ,sym))) (let (,@(loop for sym in syms for (nil form) in pairs collect `(,sym (future ,form))) ,@non-pairs) ,@body)))) (defun find-num-parts (size parts-hint) (multiple-value-bind (quo rem) (floor size parts-hint) (values (if (zerop quo) rem parts-hint) quo rem))) (defmacro with-parts (seq-size parts-hint &body body) (with-gensyms (quo rem index num-parts part-offset part-size) `(multiple-value-bind (,num-parts ,quo ,rem) (find-num-parts ,seq-size ,parts-hint) (let ((,index 0) (,part-offset 0) (,part-size 0)) (flet ((next-part () (when (< ,index ,num-parts) (unless (zerop ,index) (incf ,part-offset ,part-size)) (setf ,part-size (if (< ,index ,rem) (1+ ,quo) ,quo)) (incf ,index))) (part-size () ,part-size) (part-offset () ,part-offset) (num-parts () ,num-parts)) (declare (inline part-size part-offset num-parts) (ignorable #'part-size #'part-offset #'num-parts)) ,@body))))) (defun zip/vector (seqs) (apply #'map 'vector #'list seqs)) (defun find-min-length (seqs) (reduce #'min seqs :key #'length)) (defun get-parts-hint (parts-hint) (cond (parts-hint (check-type parts-hint (integer 1 #.most-positive-fixnum)) parts-hint) (t (kernel-worker-count)))) (defmacro pop-plist (list) `(loop while (keywordp (car ,list)) collect (pop ,list) collect (pop ,list))) (defun %parse-options (args) (destructuring-bind (&key size parts) (pop-plist args) (values args size parts))) (defun parse-options (args) (multiple-value-bind (seqs size parts) (%parse-options args) (unless seqs (error "Input sequence(s) for parallelization not found.")) (unless size (setf size (find-min-length seqs))) (setf parts (get-parts-hint parts)) (values seqs size parts))) (defmacro with-parsed-options ((args size parts) &body body) `(multiple-value-bind (,args ,size ,parts) (parse-options ,args) ,@body)) (defun subdivide-array (array size parts-hint) Create copies , in contradistinction to lparallel . Otherwise we (with-parts size parts-hint (map-into (make-array (num-parts)) (lambda () (next-part) (replace (make-array (part-size) :element-type (array-element-type array)) array :start2 (part-offset)))))) (defun subdivide-list (list size parts-hint) Create copies , in contradistinction to lparallel . Otherwise we (with-parts size parts-hint (loop with p = list while (next-part) collect (loop repeat (part-size) collect (car p) do (setf p (cdr p)))))) (defun make-parts (result size parts-hint) (etypecase result (list (subdivide-list result size parts-hint)) (vector (subdivide-array result size parts-hint)))) (defun make-input-parts (sequences size parts-hint) "Subdivide and interleave sequences for parallel mapping." (zip/vector (mapcar (lambda (seq) (make-parts seq size parts-hint)) sequences))) (defun receive-indexed (channel count) (loop with result = (make-array count) repeat count do (destructuring-bind (index . data) (receive-result channel) (setf (aref result index) data)) finally (return result))) (defun task->fn-form (task) (etypecase task (symbol `',task) (cons task))) (defmacro funcall-task (task &rest args) (with-gensyms (channel) `(let ((,channel (make-channel))) (submit-task ,channel ,task ,@args) (receive-result ,channel)))) (defwith with-max-fill-pointer (seq) (if (and (vectorp seq) (array-has-fill-pointer-p seq)) (let ((prev-fill-pointer (fill-pointer seq))) (unwind-protect/safe :prepare (setf (fill-pointer seq) (array-total-size seq)) :main (call-body) :cleanup (setf (fill-pointer seq) prev-fill-pointer))) (call-body))) (defun mapping-task (subresult-type task) `(lambda (subseqs part-index part-size) (cons part-index (apply #'map-into (make-sequence ',subresult-type part-size) ,(task->fn-form task) subseqs)))) (defun subresult-type (result-seq) (let ((element-type (etypecase result-seq (list t) (vector (array-element-type result-seq))))) `(simple-array ,element-type (*)))) (defun pmap-into/submit (channel result-seq task sequences size parts-hint) (let* ((task (maybe-convert-task task)) (mapping-task (mapping-task (subresult-type result-seq) task)) (input-parts (make-input-parts sequences size parts-hint))) (with-parts size parts-hint (loop for subseqs across input-parts for part-index from 0 while (next-part) do (submit-task channel mapping-task subseqs part-index (part-size)))))) (defun pmap-into/receive (channel result-seq size parts-hint) (with-parts size parts-hint (let ((result-parts (receive-indexed channel (num-parts)))) (with-max-fill-pointer (result-seq) (loop for index from 0 while (next-part) do (replace result-seq (aref result-parts index) :start1 (part-offset) :end1 (+ (part-offset) (part-size)))))))) (defun pmap-into/parsed (result-seq task sequences size parts-hint) (let ((channel (make-channel))) (pmap-into/submit channel result-seq task sequences size parts-hint) (pmap-into/receive channel result-seq size parts-hint)) result-seq) (defun pmap/parsed (result-type function sequences size parts-hint) (when result-type (pmap-into/parsed (make-sequence result-type size) function sequences size parts-hint))) (defun pmap/unparsed (result-type function sequences) (with-parsed-options (sequences size parts-hint) (pmap/parsed result-type function sequences size parts-hint))) (defun pmap/fn (result-type task first-sequence &rest more-sequences) (pmap/unparsed result-type task (cons first-sequence more-sequences))) (defmacro pmap (result-type task first-sequence &rest more-sequences &environment env) "Parallel version of `map'. Keyword arguments `parts' and `size' are also accepted. The `parts' option divides each sequence into `parts' number of parts. Default is (kernel-worker-count). The `size' option limits the number of elements mapped to `size'. When given, no `length' calls are made on the sequence(s) passed. Warning: `size' must be less than or equal to the length of the smallest sequence passed. It is unspecified what happens when that condition is not met." `(pmap/fn ,result-type ,(maybe-convert-task-form task env) ,first-sequence ,@more-sequences)) (defun pmapcar/fn (task first-sequence &rest more-sequences) (apply #'pmap/fn 'list task (cons first-sequence more-sequences))) (defmacro pmapcar (task first-sequence &rest more-sequences &environment env) "Parallel version of `mapcar'. Keyword arguments `parts' and `size' are also accepted (see `pmap'). Unlike `mapcar', `pmapcar' also accepts vectors." `(pmap/fn 'list ,(maybe-convert-task-form task env) ,first-sequence ,@more-sequences)) (defun pmap-into-thunk-form (task) (with-gensyms (x) (etypecase task (cons (destructuring-bind (head lambda-list &rest body) task (assert (eq head 'lambda)) `(lambda (,x ,@lambda-list) (declare (ignore ,x)) ,@body)))))) (defun pmap-into/unparsed (result-seq task args) (let ((task (maybe-convert-task task))) (multiple-value-bind (seqs size parts-hint) (%parse-options args) (let* ((has-fill-p (and (arrayp result-seq) (array-has-fill-pointer-p result-seq))) (parts-hint (get-parts-hint parts-hint)) (size (or size (let ((limit (if has-fill-p (array-total-size result-seq) (length result-seq)))) (if seqs (min limit (find-min-length seqs)) limit))))) (prog1 (if seqs (pmap-into/parsed result-seq task seqs size parts-hint) (pmap-into/parsed result-seq (pmap-into-thunk-form task) (list result-seq) size parts-hint)) (when has-fill-p (setf (fill-pointer result-seq) size))))))) (defun pmap-into/fn (result-sequence task &rest sequences) (typecase result-sequence ((or array list) (pmap-into/unparsed result-sequence task sequences)) (t (apply #'map-into result-sequence task sequences))) result-sequence) (defmacro pmap-into (result-sequence task &rest sequences &environment env) "Parallel version of `map-into'. Keyword arguments `parts' and `size' are also accepted (see `pmap')." `(pmap-into/fn ,result-sequence ,(maybe-convert-task-form task env) ,@sequences)) (defun reducing-task (task keyword-args) (let ((keyword-args (copy-list keyword-args))) (when-let (key (getf keyword-args :key)) (setf (getf keyword-args :key) (task->fn-form key))) `(lambda (sequence start end result-index) (cons result-index (reduce ,(task->fn-form task) sequence :start start :end end ,@keyword-args))))) (defun preduce-partial/vector (task sequence start size parts &rest keyword-args) (let ((reducing-task (reducing-task task keyword-args)) (channel (make-channel))) (with-parts size parts (loop for result-index from 0 while (next-part) do (submit-task channel reducing-task sequence (+ start (part-offset)) (+ start (part-offset) (part-size)) result-index)) (receive-indexed channel (num-parts))))) (defun preduce-partial/list (task sequence start size parts &rest keyword-args) (let ((reducing-task (reducing-task task keyword-args)) (channel (make-channel))) (with-parts size parts (loop with subseq = (nthcdr start sequence) for result-index from 0 while (next-part) do (submit-task channel reducing-task subseq 0 (part-size) result-index) (setf subseq (nthcdr (part-size) subseq))) (receive-indexed channel (num-parts))))) (defun %preduce-partial (task sequence start size parts &rest keyword-args) (etypecase sequence (vector (apply #'preduce-partial/vector task sequence start size parts keyword-args)) (list (apply #'preduce-partial/list task sequence start size parts keyword-args)))) (defun reduce/remote (task results) (funcall-task `(lambda (results) (reduce ,(task->fn-form task) results)) results)) (defun preduce/common (task sequence subsize &key key from-end (start 0) end (initial-value nil initial-value-given-p) parts recurse partial) (declare (ignore end)) (let ((task (maybe-convert-task task))) (cond ((zerop subsize) (when partial (error "PREDUCE-PARTIAL given zero-length sequence")) (if initial-value-given-p initial-value (funcall-task task))) (t (let* ((parts-hint (get-parts-hint parts)) (results (apply #'%preduce-partial task sequence start subsize parts-hint :key key :from-end from-end (when initial-value-given-p (list :initial-value initial-value))))) (if partial results (let ((new-size (length results))) (if (and recurse (>= new-size 4)) (apply #'preduce/common task results new-size :from-end from-end :parts (min parts-hint (floor new-size 2)) :recurse recurse (when initial-value-given-p (list :initial-value initial-value))) (reduce/remote task results))))))))) (defun subsize (seq size start end) (let ((result (- (or end size) start))) (when (or (minusp result) (> result size)) (error "Bad interval for sequence operation on ~a: start=~a end=~a" seq start end)) result)) (defun preduce/fn (task sequence &rest args &key key from-end (start 0) end initial-value parts recurse) (declare (ignore key from-end initial-value parts recurse)) (etypecase sequence ((or vector list) (apply #'preduce/common task sequence (subsize sequence (length sequence) start end) args)))) (defun maybe-convert-key-form (keyword-args env) (let ((keyword-args (copy-list keyword-args))) (when-let (key (getf keyword-args :key)) (setf (getf keyword-args :key) (maybe-convert-task-form key env))) keyword-args)) (defmacro preduce (task sequence &rest args &key key from-end (start 0) end initial-value parts recurse &environment env) "Parallel version of `reduce'. `preduce' subdivides the input sequence into `parts' number of parts and, in parallel, calls `reduce' on each part. The partial results are then reduced again, either by `reduce' (the default) or, if `recurse' is non-nil, by `preduce'. `parts' defaults to (kernel-worker-count). `key' is thrown out while reducing the partial results. It applies to the first pass only. `start' and `end' have the same meaning as in `reduce'. `from-end' means \"from the end of each part\". `initial-value' means \"initial value of each part\"." (declare (ignore key from-end start end initial-value parts recurse)) `(preduce/fn ,(maybe-convert-task-form task env) ,sequence ,@(maybe-convert-key-form args env))) (defun preduce-partial/fn (task sequence &rest args &key key from-end (start 0) end initial-value parts) (declare (ignore key from-end initial-value parts)) (apply #'preduce/common task sequence (subsize sequence (length sequence) start end) :partial t args)) (defmacro preduce-partial (task sequence &rest args &key key from-end (start 0) end initial-value parts &environment env) "Like `preduce' but only does a single reducing pass. The length of `sequence' must not be zero. Returns the partial results as a vector." (declare (ignore key from-end start end initial-value parts)) `(preduce-partial/fn ,(maybe-convert-task-form task env) ,sequence ,@(maybe-convert-key-form args env))) (defmacro pmap-reduce (map-function reduce-function sequence &rest args &key start end initial-value parts recurse) "Equivalent to (preduce reduce-function sequence :key map-function ...)." (declare (ignore start end initial-value parts recurse)) `(preduce ,reduce-function ,sequence :key ,map-function ,@args))
478036578b62b95b610c5e229c93e3c249a348025692670297071e0b9467cbb8
qfpl/reflex-workshop
Item.hs
| Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation License : : Stability : experimental Portability : non - portable Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecursiveDo # {-# LANGUAGE GADTs #-} module Exercises.Todo.Item where import Control.Monad import Data.Bool import Data.Monoid import Control.Lens import Data.Text (Text) import qualified Data.Text as Text import Data.Map (Map) import qualified Data.Map as Map import Reflex.Dom.Core import Common.Todo todoItem :: MonadWidget t m => TodoItem -> m (Event t ()) todoItem ti = do pure never todoItemExercise :: MonadWidget t m => TodoItem -> m () todoItemExercise ti = pure ()
null
https://raw.githubusercontent.com/qfpl/reflex-workshop/244ef13fb4b2e884f455eccc50072e98d1668c9e/src/Exercises/Todo/Item.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE GADTs #
| Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation License : : Stability : experimental Portability : non - portable Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} # LANGUAGE RecursiveDo # module Exercises.Todo.Item where import Control.Monad import Data.Bool import Data.Monoid import Control.Lens import Data.Text (Text) import qualified Data.Text as Text import Data.Map (Map) import qualified Data.Map as Map import Reflex.Dom.Core import Common.Todo todoItem :: MonadWidget t m => TodoItem -> m (Event t ()) todoItem ti = do pure never todoItemExercise :: MonadWidget t m => TodoItem -> m () todoItemExercise ti = pure ()
468eda7e1ed4321a481ac4e467dc2363314064557507861bd48bc23dbd20cfde
CryptoKami/cryptokami-core
Util.hs
# LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE DataKinds #-} -- | Some utility functions necessary to implement block processing logic. module Pos.Block.Logic.Util ( -- * Common/Utils lcaWithMainChain , calcChainQuality , calcChainQualityM , calcOverallChainQuality , calcChainQualityFixedTime ) where import Universum import Control.Lens (_Wrapped) import Data.List (findIndex) import Data.List.NonEmpty ((<|)) import qualified Data.List.NonEmpty as NE import Formatting (int, sformat, (%)) import System.Wlog (WithLogger) import Pos.Block.Slog.Context (slogGetLastSlots) import Pos.Block.Slog.Types (HasSlogGState) import Pos.Core (BlockCount, FlatSlotId, HeaderHash, Timestamp (..), difficultyL, fixedTimeCQ, flattenSlotId, headerHash, prevBlockL) import Pos.Core.Block (BlockHeader) import Pos.Core.Configuration (HasConfiguration, blkSecurityParam) import qualified Pos.DB.BlockIndex as DB import Pos.DB.Class (MonadBlockDBRead) import Pos.Exception (reportFatalError) import Pos.GState.BlockExtra (isBlockInMainChain) import Pos.Slotting (MonadSlots (..), getCurrentSlotFlat, slotFromTimestamp) import Pos.Util (_neHead) import Pos.Util.Chrono (NE, OldestFirst (..)) - Usually in this method oldest header is LCA , so it can be optimized -- by traversing from older to newer. -- | Find LCA of headers list and main chain, including oldest header 's parent hash . Iterates from newest to oldest until meets -- first header that's in main chain. O(n). lcaWithMainChain :: (HasConfiguration, MonadBlockDBRead m) => OldestFirst NE BlockHeader -> m (Maybe HeaderHash) lcaWithMainChain headers = lcaProceed Nothing $ oldestParent <| fmap headerHash (getOldestFirst headers) where oldestParent :: HeaderHash oldestParent = headers ^. _Wrapped . _neHead . prevBlockL lcaProceed prevValue (h :| others) = do inMain <- isBlockInMainChain h case (others, inMain) of (_, False) -> pure prevValue ([], True) -> pure $ Just h (x:xs, True) -> lcaProceed (Just h) (x :| xs) -- | Calculate chain quality using slot of the block which has depth = -- 'blocksCount' and another slot after that one for which we -- want to know chain quality. -- -- See documentation of 'chainQualityThreshold' to see why this -- function returns any 'Fractional'. calcChainQuality :: Fractional res => BlockCount -> FlatSlotId -> FlatSlotId -> Maybe res calcChainQuality blockCount deepSlot newSlot | deepSlot == newSlot = Nothing | otherwise = Just $ realToFrac blockCount / realToFrac (newSlot - deepSlot) -- | Version of 'calcChainQuality' which takes last blocks' slots from -- the monadic context. It computes chain quality for last -- 'blkSecurityParam' blocks. calcChainQualityM :: ( MonadReader ctx m , HasSlogGState ctx , MonadIO m , MonadThrow m , WithLogger m , Fractional res , HasConfiguration ) => FlatSlotId -> m (Maybe res) calcChainQualityM newSlot = do OldestFirst lastSlots <- slogGetLastSlots let len = length lastSlots case nonEmpty lastSlots of Nothing -> return Nothing Just slotsNE | len > fromIntegral blkSecurityParam -> reportFatalError $ sformat ("number of last slots is greater than 'k': "%int) len | otherwise -> return (calcChainQuality (fromIntegral len) (NE.head slotsNE) newSlot) | Calculate overall chain quality , number of main blocks -- divided by number of slots so far. Returns 'Nothing' if current -- slot is unknown. calcOverallChainQuality :: forall ctx m res. (Fractional res, MonadSlots ctx m, MonadBlockDBRead m, HasConfiguration) => m (Maybe res) calcOverallChainQuality = getCurrentSlotFlat >>= \case Nothing -> pure Nothing Just curFlatSlot -> calcOverallChainQualityDo curFlatSlot <$> DB.getTipHeader where calcOverallChainQualityDo curFlatSlot tipHeader | curFlatSlot == 0 = Nothing | otherwise = calcChainQuality (fromIntegral $ tipHeader ^. difficultyL) 0 curFlatSlot -- | Calculate chain quality for approximately 'fixedTimeCQ'. Works -- only if the following conditions are met: -- 1 . At least ' fixedTimeCQ ' passed since system start . 2 . Block with depth ' blkSecurityParam ' was created more than ' fixedTimeCQ ' ago . You should configure constants properly . For k = 2160 ' fixedTimeCQ ' can be even 12h . We want 1h , so it 's not -- restrictive at all. 3 . We are able to determine which slot started ' fixedTimeCQ ' ago . calcChainQualityFixedTime :: forall ctx m res. (Fractional res, MonadSlots ctx m, HasConfiguration, HasSlogGState ctx) => m (Maybe res) calcChainQualityFixedTime = do Timestamp curTime <- currentTimeSlotting let olderTime = Timestamp (curTime - fixedTimeCQ) (,) <$> slotFromTimestamp olderTime <*> getCurrentSlotFlat >>= \case (Just (flattenSlotId -> olderSlotId), Just currentSlotId) -> calcChainQualityFixedTimeDo olderSlotId currentSlotId <$> slogGetLastSlots _ -> return Nothing where -- 'lastSlots' contains slots of last 'k' blocks. -- We need to return 'Just' if we know now many blocks were created since -- 'olderSlotId'. -- We know it if there is a slot which is ≤ than 'olderSlotId' in -- 'lastSlots'. calcChainQualityFixedTimeDo :: FlatSlotId -> FlatSlotId -> OldestFirst [] FlatSlotId -> Maybe res calcChainQualityFixedTimeDo olderSlotId currentSlotId (OldestFirst lastSlots) = case findIndex (>= olderSlotId) lastSlots of Just firstNew | firstNew > 0 || head lastSlots == Just olderSlotId -> let blockCount = fromIntegral (length lastSlots - firstNew) in calcChainQuality blockCount olderSlotId currentSlotId -- All slots are less than 'olderSlotId', something is bad. _ -> Nothing
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/block/src/Pos/Block/Logic/Util.hs
haskell
# LANGUAGE DataKinds # | Some utility functions necessary to implement block processing logic. * Common/Utils by traversing from older to newer. | Find LCA of headers list and main chain, including oldest first header that's in main chain. O(n). | Calculate chain quality using slot of the block which has depth = 'blocksCount' and another slot after that one for which we want to know chain quality. See documentation of 'chainQualityThreshold' to see why this function returns any 'Fractional'. | Version of 'calcChainQuality' which takes last blocks' slots from the monadic context. It computes chain quality for last 'blkSecurityParam' blocks. divided by number of slots so far. Returns 'Nothing' if current slot is unknown. | Calculate chain quality for approximately 'fixedTimeCQ'. Works only if the following conditions are met: restrictive at all. 'lastSlots' contains slots of last 'k' blocks. We need to return 'Just' if we know now many blocks were created since 'olderSlotId'. We know it if there is a slot which is ≤ than 'olderSlotId' in 'lastSlots'. All slots are less than 'olderSlotId', something is bad.
# LANGUAGE AllowAmbiguousTypes # module Pos.Block.Logic.Util ( lcaWithMainChain , calcChainQuality , calcChainQualityM , calcOverallChainQuality , calcChainQualityFixedTime ) where import Universum import Control.Lens (_Wrapped) import Data.List (findIndex) import Data.List.NonEmpty ((<|)) import qualified Data.List.NonEmpty as NE import Formatting (int, sformat, (%)) import System.Wlog (WithLogger) import Pos.Block.Slog.Context (slogGetLastSlots) import Pos.Block.Slog.Types (HasSlogGState) import Pos.Core (BlockCount, FlatSlotId, HeaderHash, Timestamp (..), difficultyL, fixedTimeCQ, flattenSlotId, headerHash, prevBlockL) import Pos.Core.Block (BlockHeader) import Pos.Core.Configuration (HasConfiguration, blkSecurityParam) import qualified Pos.DB.BlockIndex as DB import Pos.DB.Class (MonadBlockDBRead) import Pos.Exception (reportFatalError) import Pos.GState.BlockExtra (isBlockInMainChain) import Pos.Slotting (MonadSlots (..), getCurrentSlotFlat, slotFromTimestamp) import Pos.Util (_neHead) import Pos.Util.Chrono (NE, OldestFirst (..)) - Usually in this method oldest header is LCA , so it can be optimized header 's parent hash . Iterates from newest to oldest until meets lcaWithMainChain :: (HasConfiguration, MonadBlockDBRead m) => OldestFirst NE BlockHeader -> m (Maybe HeaderHash) lcaWithMainChain headers = lcaProceed Nothing $ oldestParent <| fmap headerHash (getOldestFirst headers) where oldestParent :: HeaderHash oldestParent = headers ^. _Wrapped . _neHead . prevBlockL lcaProceed prevValue (h :| others) = do inMain <- isBlockInMainChain h case (others, inMain) of (_, False) -> pure prevValue ([], True) -> pure $ Just h (x:xs, True) -> lcaProceed (Just h) (x :| xs) calcChainQuality :: Fractional res => BlockCount -> FlatSlotId -> FlatSlotId -> Maybe res calcChainQuality blockCount deepSlot newSlot | deepSlot == newSlot = Nothing | otherwise = Just $ realToFrac blockCount / realToFrac (newSlot - deepSlot) calcChainQualityM :: ( MonadReader ctx m , HasSlogGState ctx , MonadIO m , MonadThrow m , WithLogger m , Fractional res , HasConfiguration ) => FlatSlotId -> m (Maybe res) calcChainQualityM newSlot = do OldestFirst lastSlots <- slogGetLastSlots let len = length lastSlots case nonEmpty lastSlots of Nothing -> return Nothing Just slotsNE | len > fromIntegral blkSecurityParam -> reportFatalError $ sformat ("number of last slots is greater than 'k': "%int) len | otherwise -> return (calcChainQuality (fromIntegral len) (NE.head slotsNE) newSlot) | Calculate overall chain quality , number of main blocks calcOverallChainQuality :: forall ctx m res. (Fractional res, MonadSlots ctx m, MonadBlockDBRead m, HasConfiguration) => m (Maybe res) calcOverallChainQuality = getCurrentSlotFlat >>= \case Nothing -> pure Nothing Just curFlatSlot -> calcOverallChainQualityDo curFlatSlot <$> DB.getTipHeader where calcOverallChainQualityDo curFlatSlot tipHeader | curFlatSlot == 0 = Nothing | otherwise = calcChainQuality (fromIntegral $ tipHeader ^. difficultyL) 0 curFlatSlot 1 . At least ' fixedTimeCQ ' passed since system start . 2 . Block with depth ' blkSecurityParam ' was created more than ' fixedTimeCQ ' ago . You should configure constants properly . For k = 2160 ' fixedTimeCQ ' can be even 12h . We want 1h , so it 's not 3 . We are able to determine which slot started ' fixedTimeCQ ' ago . calcChainQualityFixedTime :: forall ctx m res. (Fractional res, MonadSlots ctx m, HasConfiguration, HasSlogGState ctx) => m (Maybe res) calcChainQualityFixedTime = do Timestamp curTime <- currentTimeSlotting let olderTime = Timestamp (curTime - fixedTimeCQ) (,) <$> slotFromTimestamp olderTime <*> getCurrentSlotFlat >>= \case (Just (flattenSlotId -> olderSlotId), Just currentSlotId) -> calcChainQualityFixedTimeDo olderSlotId currentSlotId <$> slogGetLastSlots _ -> return Nothing where calcChainQualityFixedTimeDo :: FlatSlotId -> FlatSlotId -> OldestFirst [] FlatSlotId -> Maybe res calcChainQualityFixedTimeDo olderSlotId currentSlotId (OldestFirst lastSlots) = case findIndex (>= olderSlotId) lastSlots of Just firstNew | firstNew > 0 || head lastSlots == Just olderSlotId -> let blockCount = fromIntegral (length lastSlots - firstNew) in calcChainQuality blockCount olderSlotId currentSlotId _ -> Nothing
0aceb0ca4fde62b14a80350feb26bf8fe9efb68b46d22f49ebdeb024e43ff0b7
kmi/irs
old.lisp
Mode : Lisp ; Package : Author : The Open University (in-package "OCML") (in-ontology uk-location-ontology) (def-class uk-village (village)) (def-class uk-city (city)) (def-class uk-town (town)) (def-class english-city (uk-city)) (def-class scotish-city (uk-city)) (def-class welsh-city (uk-city)) (def-class irish-city (uk-city)) (def-instance London english-city) (def-instance Andover english-city) (def-instance Axminster english-city) (def-instance Banbury english-city) (def-instance Barnsley english-city) (def-instance Basingstoke english-city) (def-instance Bath english-city) (def-instance Bedford english-city) (def-instance Berwick_upon_Tweed english-city) (def-instance Birmingham english-city) (def-instance Bishops_Stortford english-city) (def-instance Blackburn english-city) (def-instance Blackpool english-city) (def-instance Bolton english-city) (def-instance Bournemouth english-city) (def-instance Bradford english-city) (def-instance Brighton english-city) (def-instance Bristol english-city) (def-instance Burnley english-city) (def-instance Bury_St_Edmonds english-city) (def-instance Cambridge english-city) (def-instance Carlisle english-city) (def-instance Chelmsford english-city) (def-instance Cheltenham english-city) (def-instance Chester english-city) (def-instance Chichester english-city) (def-instance Colchester english-city) (def-instance Coventry english-city) (def-instance Crawley english-city) (def-instance Croydon english-city) (def-instance Darlington english-city) (def-instance Dartford english-city) (def-instance Derby english-city) (def-instance Doncaster english-city) (def-instance Douglas_IoM english-city) (def-instance Dover english-city) (def-instance Enfield english-city) (def-instance Epsom english-city) (def-instance Exeter english-city) (def-instance Gloucester english-city) (def-instance Grantham english-city) (def-instance Guildford english-city) (def-instance Halifax english-city) (def-instance Harrogate english-city) (def-instance Hastings english-city) (def-instance Hawes english-city) (def-instance Hereford english-city) (def-instance High_Wycombe english-city) (def-instance Huddersfield english-city) (def-instance Hull english-city) (def-instance Ipswich english-city) (def-instance Kendal english-city) (def-instance Kings_Lynn english-city) (def-instance Lancaster english-city) (def-instance Leeds english-city) (def-instance Leicester english-city) (def-instance Lincoln english-city) (def-instance Liverpool english-city) (def-instance London english-city) (def-instance Lowestoft english-city) (def-instance Ludlow english-city) (def-instance Luton english-city) (def-instance Maidstone english-city) (def-instance Manchester english-city) (def-instance Middlesbrough english-city) (def-instance Milton_Keynes english-city) (def-instance Newcastle english-city) (def-instance Newmarket english-city) (def-instance Newport english-city) (def-instance Northampton english-city) (def-instance Norwich english-city) (def-instance Nottingham english-city) (def-instance Okehampton english-city) (def-instance Oxford english-city) (def-instance Penzance english-city) (def-instance Peterborough english-city) (def-instance Plymouth english-city) (def-instance Portsmouth english-city) (def-instance Preston english-city) (def-instance Reading english-city) (def-instance Rochdale english-city) (def-instance Rugby english-city) (def-instance Salisbury english-city) (def-instance Scunthorpe english-city) (def-instance Sheffield english-city) (def-instance Shrewsbury english-city) (def-instance Skegness english-city) (def-instance Slough english-city) (def-instance Southampton english-city) (def-instance Southend_on_Sea english-city) (def-instance Staines english-city) (def-instance Stanhope english-city) (def-instance St_Helier english-city) (def-instance St_Marys english-city) (def-instance Stoke_on_Trent english-city) (def-instance Stratford_upon_Avon english-city) (def-instance Sunderland english-city) (def-instance Swindon english-city) (def-instance Taunton english-city) (def-instance Thirsk english-city) (def-instance Torquay english-city) (def-instance Tunbridge_Wells english-city) (def-instance Warminster english-city) (def-instance Warrington english-city) (def-instance Warwick english-city) (def-instance Watford english-city) (def-instance Western_Super_Mare english-city) (def-instance Weymouth english-city) (def-instance Whitby english-city) (def-instance Winchester english-city) (def-instance Wolverhampton english-city) (def-instance Worcester english-city) (def-instance Yeovil english-city) (def-instance York english-city) (def-instance Edinburgh scotish-city) (def-instance Aberdeen scotish-city) (def-instance Aviemore scotish-city) (def-instance Ayr scotish-city) (def-instance Bathgate scotish-city) (def-instance Braemar scotish-city) (def-instance Campbeltown scotish-city) (def-instance Cumbernauld scotish-city) (def-instance Dornoch scotish-city) (def-instance Dumfries scotish-city) (def-instance Dunbar scotish-city) (def-instance Dundee scotish-city) (def-instance Edinburgh scotish-city) (def-instance Elgin scotish-city) (def-instance Falkirk scotish-city) (def-instance Fort_Augutus scotish-city) (def-instance Fort_William scotish-city) (def-instance Fraserburgh scotish-city) (def-instance Galashiels scotish-city) (def-instance Glasgow scotish-city) (def-instance Gleneagles scotish-city) (def-instance Hawick scotish-city) (def-instance Huntly scotish-city) (def-instance Inverness scotish-city) (def-instance Kelso scotish-city) (def-instance Killin scotish-city) (def-instance Kilmarnock scotish-city) (def-instance Kings_House scotish-city) (def-instance Kirkcaldy scotish-city) (def-instance Kirkcudbright scotish-city) (def-instance Kirkwall scotish-city) (def-instance Lanark scotish-city) (def-instance Lerwick scotish-city) (def-instance Lochboisedale scotish-city) (def-instance Montrose scotish-city) (def-instance Motherwell scotish-city) (def-instance Oban scotish-city) (def-instance Paisley scotish-city) (def-instance Peebles scotish-city) (def-instance Perth scotish-city) (def-instance Peterhead scotish-city) (def-instance Pitlochry scotish-city) (def-instance Port_Askaig scotish-city) (def-instance Portree scotish-city) (def-instance Sanquar scotish-city) (def-instance St_Andrews scotish-city) (def-instance Stirling scotish-city) (def-instance Stranraer scotish-city) (def-instance Stornoway scotish-city) (def-instance Tiree scotish-city) (def-instance Tobermory scotish-city) (def-instance Ullapool scotish-city) (def-instance Cardiff welsh-city) (def-instance Aberystwyth welsh-city) (def-instance Bangor welsh-city) (def-instance Brecon welsh-city) (def-instance Bridgend welsh-city) (def-instance Cardigan welsh-city) (def-instance Carmarthen welsh-city) (def-instance Cardiff welsh-city) (def-instance Colwyn-bay welsh-city) (def-instance Holyhead welsh-city) (def-instance Llandrindod_Wells welsh-city) (def-instance Merthye_Tydfil welsh-city) (def-instance Milford_Haven welsh-city) (def-instance Portmadoc welsh-city) (def-instance Swansea welsh-city) (def-instance Welshpool welsh-city) (def-instance WrexhamN welsh-city) (def-instance Armagh irish-city) (def-instance Ballymena irish-city) (def-instance Belfast irish-city) (def-instance Coleraine irish-city) (def-instance Enniskillen irish-city) (def-instance Larne irish-city) (def-instance Londonderry irish-city) (def-instance Newry irish-city) (def-instance Omagh irish-city)
null
https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/domains/uk-location-ontology/old.lisp
lisp
Package :
Author : The Open University (in-package "OCML") (in-ontology uk-location-ontology) (def-class uk-village (village)) (def-class uk-city (city)) (def-class uk-town (town)) (def-class english-city (uk-city)) (def-class scotish-city (uk-city)) (def-class welsh-city (uk-city)) (def-class irish-city (uk-city)) (def-instance London english-city) (def-instance Andover english-city) (def-instance Axminster english-city) (def-instance Banbury english-city) (def-instance Barnsley english-city) (def-instance Basingstoke english-city) (def-instance Bath english-city) (def-instance Bedford english-city) (def-instance Berwick_upon_Tweed english-city) (def-instance Birmingham english-city) (def-instance Bishops_Stortford english-city) (def-instance Blackburn english-city) (def-instance Blackpool english-city) (def-instance Bolton english-city) (def-instance Bournemouth english-city) (def-instance Bradford english-city) (def-instance Brighton english-city) (def-instance Bristol english-city) (def-instance Burnley english-city) (def-instance Bury_St_Edmonds english-city) (def-instance Cambridge english-city) (def-instance Carlisle english-city) (def-instance Chelmsford english-city) (def-instance Cheltenham english-city) (def-instance Chester english-city) (def-instance Chichester english-city) (def-instance Colchester english-city) (def-instance Coventry english-city) (def-instance Crawley english-city) (def-instance Croydon english-city) (def-instance Darlington english-city) (def-instance Dartford english-city) (def-instance Derby english-city) (def-instance Doncaster english-city) (def-instance Douglas_IoM english-city) (def-instance Dover english-city) (def-instance Enfield english-city) (def-instance Epsom english-city) (def-instance Exeter english-city) (def-instance Gloucester english-city) (def-instance Grantham english-city) (def-instance Guildford english-city) (def-instance Halifax english-city) (def-instance Harrogate english-city) (def-instance Hastings english-city) (def-instance Hawes english-city) (def-instance Hereford english-city) (def-instance High_Wycombe english-city) (def-instance Huddersfield english-city) (def-instance Hull english-city) (def-instance Ipswich english-city) (def-instance Kendal english-city) (def-instance Kings_Lynn english-city) (def-instance Lancaster english-city) (def-instance Leeds english-city) (def-instance Leicester english-city) (def-instance Lincoln english-city) (def-instance Liverpool english-city) (def-instance London english-city) (def-instance Lowestoft english-city) (def-instance Ludlow english-city) (def-instance Luton english-city) (def-instance Maidstone english-city) (def-instance Manchester english-city) (def-instance Middlesbrough english-city) (def-instance Milton_Keynes english-city) (def-instance Newcastle english-city) (def-instance Newmarket english-city) (def-instance Newport english-city) (def-instance Northampton english-city) (def-instance Norwich english-city) (def-instance Nottingham english-city) (def-instance Okehampton english-city) (def-instance Oxford english-city) (def-instance Penzance english-city) (def-instance Peterborough english-city) (def-instance Plymouth english-city) (def-instance Portsmouth english-city) (def-instance Preston english-city) (def-instance Reading english-city) (def-instance Rochdale english-city) (def-instance Rugby english-city) (def-instance Salisbury english-city) (def-instance Scunthorpe english-city) (def-instance Sheffield english-city) (def-instance Shrewsbury english-city) (def-instance Skegness english-city) (def-instance Slough english-city) (def-instance Southampton english-city) (def-instance Southend_on_Sea english-city) (def-instance Staines english-city) (def-instance Stanhope english-city) (def-instance St_Helier english-city) (def-instance St_Marys english-city) (def-instance Stoke_on_Trent english-city) (def-instance Stratford_upon_Avon english-city) (def-instance Sunderland english-city) (def-instance Swindon english-city) (def-instance Taunton english-city) (def-instance Thirsk english-city) (def-instance Torquay english-city) (def-instance Tunbridge_Wells english-city) (def-instance Warminster english-city) (def-instance Warrington english-city) (def-instance Warwick english-city) (def-instance Watford english-city) (def-instance Western_Super_Mare english-city) (def-instance Weymouth english-city) (def-instance Whitby english-city) (def-instance Winchester english-city) (def-instance Wolverhampton english-city) (def-instance Worcester english-city) (def-instance Yeovil english-city) (def-instance York english-city) (def-instance Edinburgh scotish-city) (def-instance Aberdeen scotish-city) (def-instance Aviemore scotish-city) (def-instance Ayr scotish-city) (def-instance Bathgate scotish-city) (def-instance Braemar scotish-city) (def-instance Campbeltown scotish-city) (def-instance Cumbernauld scotish-city) (def-instance Dornoch scotish-city) (def-instance Dumfries scotish-city) (def-instance Dunbar scotish-city) (def-instance Dundee scotish-city) (def-instance Edinburgh scotish-city) (def-instance Elgin scotish-city) (def-instance Falkirk scotish-city) (def-instance Fort_Augutus scotish-city) (def-instance Fort_William scotish-city) (def-instance Fraserburgh scotish-city) (def-instance Galashiels scotish-city) (def-instance Glasgow scotish-city) (def-instance Gleneagles scotish-city) (def-instance Hawick scotish-city) (def-instance Huntly scotish-city) (def-instance Inverness scotish-city) (def-instance Kelso scotish-city) (def-instance Killin scotish-city) (def-instance Kilmarnock scotish-city) (def-instance Kings_House scotish-city) (def-instance Kirkcaldy scotish-city) (def-instance Kirkcudbright scotish-city) (def-instance Kirkwall scotish-city) (def-instance Lanark scotish-city) (def-instance Lerwick scotish-city) (def-instance Lochboisedale scotish-city) (def-instance Montrose scotish-city) (def-instance Motherwell scotish-city) (def-instance Oban scotish-city) (def-instance Paisley scotish-city) (def-instance Peebles scotish-city) (def-instance Perth scotish-city) (def-instance Peterhead scotish-city) (def-instance Pitlochry scotish-city) (def-instance Port_Askaig scotish-city) (def-instance Portree scotish-city) (def-instance Sanquar scotish-city) (def-instance St_Andrews scotish-city) (def-instance Stirling scotish-city) (def-instance Stranraer scotish-city) (def-instance Stornoway scotish-city) (def-instance Tiree scotish-city) (def-instance Tobermory scotish-city) (def-instance Ullapool scotish-city) (def-instance Cardiff welsh-city) (def-instance Aberystwyth welsh-city) (def-instance Bangor welsh-city) (def-instance Brecon welsh-city) (def-instance Bridgend welsh-city) (def-instance Cardigan welsh-city) (def-instance Carmarthen welsh-city) (def-instance Cardiff welsh-city) (def-instance Colwyn-bay welsh-city) (def-instance Holyhead welsh-city) (def-instance Llandrindod_Wells welsh-city) (def-instance Merthye_Tydfil welsh-city) (def-instance Milford_Haven welsh-city) (def-instance Portmadoc welsh-city) (def-instance Swansea welsh-city) (def-instance Welshpool welsh-city) (def-instance WrexhamN welsh-city) (def-instance Armagh irish-city) (def-instance Ballymena irish-city) (def-instance Belfast irish-city) (def-instance Coleraine irish-city) (def-instance Enniskillen irish-city) (def-instance Larne irish-city) (def-instance Londonderry irish-city) (def-instance Newry irish-city) (def-instance Omagh irish-city)
b8322c0d4046a0c70e84fd57889939557cb737c0e931e6055b62c584970c5bd3
nshepperd/funn
RNNChar.hs
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # {-# LANGUAGE GADTs #-} # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # {-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-} # OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver # {-# OPTIONS_GHC -fconstraint-solver-iterations=20 #-} module AI.Funn.Models.RNNChar (Model, ModelPars, ParsWrapped, buildModel, initialize, readPars, storePars) where import qualified Codec.CBOR.Decoding as C import qualified Codec.CBOR.Read as C import qualified Codec.CBOR.Write as C import qualified Codec.Serialise.Class as C import Control.Monad.IO.Class import qualified Data.ByteString.Lazy as BL import Data.Constraint import Data.Proxy import Data.Random import Data.Type.Equality import Data.Vector (Vector) import qualified Data.Vector.Generic as V import GHC.TypeLits import Unsafe.Coerce import AI.Funn.Common import AI.Funn.Diff.Diff (Diff(..), Derivable(..), (>>>)) import qualified AI.Funn.Diff.Diff as Diff import AI.Funn.Flat.Blob (Blob, blob, getBlob) import qualified AI.Funn.Flat.Blob as Blob import AI.Funn.Flat.ParBox import AI.Funn.Network.Flat import AI.Funn.Network.LSTM import AI.Funn.Network.Mixing import AI.Funn.Network.Network import qualified AI.Funn.Network.Network as Network import AI.Funn.Network.RNN import AI.Funn.SGD import AI.Funn.Space import AI.Funn.TypeLits type StepState size = (Blob size, Blob size) stepNetwork :: (Monad m, KnownNat size) => Proxy size -> Network m (StepState size, Blob 256) (StepState size, Blob 256) stepNetwork Proxy = assocR ( n , 4n ) ( n , n ) >>> second dupLayer >>> assocL >>> second (amixLayer (Proxy @ 5)) allNetwork :: (Monad m, KnownNat size) => Proxy size -> Network m (StepState size, Vector (Blob 256)) (Vector (Blob 256)) allNetwork size = scanlLayer (stepNetwork size) >>> sndNetwork evalNetwork :: (Monad m, KnownNat size) => Proxy size -> Network m (StepState size, (Vector (Blob 256), Vector Int)) Double evalNetwork size = assocL >>> first (allNetwork size) >>> zipLayer >>> mapLayer softmaxCost >>> vsumLayer openNetwork :: forall m n a b. KnownNat n => Network m a b -> Maybe (Diff m (Blob n, a) b, RVar (Blob n)) openNetwork (Network p diff initial) = case sameNat p (Proxy @ n) of Just Refl -> Just (diff, initial) Nothing -> Nothing type family Pars (size :: Nat) :: Nat parDict :: KnownNat size => Proxy size -> Dict (KnownNat (Pars size)) parDict size = case stepNetwork @IO size of Network (Proxy :: Proxy ps) _ _ -> unsafeCoerce (Dict :: Dict (KnownNat ps)) data Model m size where Model :: KnownNat (Pars size) => { modelStep :: Diff m (Blob (Pars size), (StepState size, Blob 256)) (StepState size, Blob 256), modelRun :: Diff m ((Blob (Pars size), StepState size), Vector (Blob 256)) (Vector (Blob 256)), modelEval :: Diff m ((Blob (Pars size), StepState size), (Vector (Blob 256), Vector Int)) Double } -> Model m size buildModel :: (Monad m, KnownNat size) => Proxy size -> Model m size buildModel size = case parDict size of Dict -> let Just (diff_step, _) = openNetwork (stepNetwork size) Just (diff_run, _) = openNetwork (allNetwork size) Just (diff_eval, _) = openNetwork (evalNetwork size) in (Model diff_step (Diff.assocR >>> diff_run) (Diff.assocR >>> diff_eval)) data ModelPars size where ModelPars :: KnownNat (Pars size) => Blob (Pars size) -> StepState size -> ModelPars size sampleIO :: MonadIO m => RVar a -> m a sampleIO v = liftIO (runRVar v StdRandom) initialize :: KnownNat size => Proxy size -> IO (ModelPars size) initialize size = case parDict size of Dict -> case openNetwork (stepNetwork @IO size) of Just (_, initrvar) -> do p <- sampleIO initrvar s0 <- Blob.generate (pure 0) s1 <- Blob.generate (pure 0) return (ModelPars p (s0, s1)) data ParsWrapped = forall size. KnownNat size => ParsWrapped (ModelPars size) instance C.Serialise ParsWrapped where encode (ParsWrapped (ModelPars p s0 :: ModelPars size)) = C.encode (natVal (Proxy @ size), p, s0) decode = do 3 <- C.decodeListLen size <- C.decodeInteger withNat size $ \(proxy :: Proxy size) -> do case parDict proxy of Dict -> do p <- C.decode s0 <- C.decode return (ParsWrapped (ModelPars p s0 :: ModelPars size)) storePars :: forall size. KnownNat size => FilePath -> ModelPars size -> IO () storePars fname m = BL.writeFile fname (encodeToByteString (ParsWrapped m)) readPars :: FilePath -> IO ParsWrapped readPars fname = decodeOrError <$> BL.readFile fname
null
https://raw.githubusercontent.com/nshepperd/funn/23138fc44cfda90afd49927c39b122ed78945293/AI/Funn/Models/RNNChar.hs
haskell
# LANGUAGE GADTs # # OPTIONS_GHC -fplugin GHC.TypeLits.Normalise # # OPTIONS_GHC -fconstraint-solver-iterations=20 #
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE PolyKinds # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver # module AI.Funn.Models.RNNChar (Model, ModelPars, ParsWrapped, buildModel, initialize, readPars, storePars) where import qualified Codec.CBOR.Decoding as C import qualified Codec.CBOR.Read as C import qualified Codec.CBOR.Write as C import qualified Codec.Serialise.Class as C import Control.Monad.IO.Class import qualified Data.ByteString.Lazy as BL import Data.Constraint import Data.Proxy import Data.Random import Data.Type.Equality import Data.Vector (Vector) import qualified Data.Vector.Generic as V import GHC.TypeLits import Unsafe.Coerce import AI.Funn.Common import AI.Funn.Diff.Diff (Diff(..), Derivable(..), (>>>)) import qualified AI.Funn.Diff.Diff as Diff import AI.Funn.Flat.Blob (Blob, blob, getBlob) import qualified AI.Funn.Flat.Blob as Blob import AI.Funn.Flat.ParBox import AI.Funn.Network.Flat import AI.Funn.Network.LSTM import AI.Funn.Network.Mixing import AI.Funn.Network.Network import qualified AI.Funn.Network.Network as Network import AI.Funn.Network.RNN import AI.Funn.SGD import AI.Funn.Space import AI.Funn.TypeLits type StepState size = (Blob size, Blob size) stepNetwork :: (Monad m, KnownNat size) => Proxy size -> Network m (StepState size, Blob 256) (StepState size, Blob 256) stepNetwork Proxy = assocR ( n , 4n ) ( n , n ) >>> second dupLayer >>> assocL >>> second (amixLayer (Proxy @ 5)) allNetwork :: (Monad m, KnownNat size) => Proxy size -> Network m (StepState size, Vector (Blob 256)) (Vector (Blob 256)) allNetwork size = scanlLayer (stepNetwork size) >>> sndNetwork evalNetwork :: (Monad m, KnownNat size) => Proxy size -> Network m (StepState size, (Vector (Blob 256), Vector Int)) Double evalNetwork size = assocL >>> first (allNetwork size) >>> zipLayer >>> mapLayer softmaxCost >>> vsumLayer openNetwork :: forall m n a b. KnownNat n => Network m a b -> Maybe (Diff m (Blob n, a) b, RVar (Blob n)) openNetwork (Network p diff initial) = case sameNat p (Proxy @ n) of Just Refl -> Just (diff, initial) Nothing -> Nothing type family Pars (size :: Nat) :: Nat parDict :: KnownNat size => Proxy size -> Dict (KnownNat (Pars size)) parDict size = case stepNetwork @IO size of Network (Proxy :: Proxy ps) _ _ -> unsafeCoerce (Dict :: Dict (KnownNat ps)) data Model m size where Model :: KnownNat (Pars size) => { modelStep :: Diff m (Blob (Pars size), (StepState size, Blob 256)) (StepState size, Blob 256), modelRun :: Diff m ((Blob (Pars size), StepState size), Vector (Blob 256)) (Vector (Blob 256)), modelEval :: Diff m ((Blob (Pars size), StepState size), (Vector (Blob 256), Vector Int)) Double } -> Model m size buildModel :: (Monad m, KnownNat size) => Proxy size -> Model m size buildModel size = case parDict size of Dict -> let Just (diff_step, _) = openNetwork (stepNetwork size) Just (diff_run, _) = openNetwork (allNetwork size) Just (diff_eval, _) = openNetwork (evalNetwork size) in (Model diff_step (Diff.assocR >>> diff_run) (Diff.assocR >>> diff_eval)) data ModelPars size where ModelPars :: KnownNat (Pars size) => Blob (Pars size) -> StepState size -> ModelPars size sampleIO :: MonadIO m => RVar a -> m a sampleIO v = liftIO (runRVar v StdRandom) initialize :: KnownNat size => Proxy size -> IO (ModelPars size) initialize size = case parDict size of Dict -> case openNetwork (stepNetwork @IO size) of Just (_, initrvar) -> do p <- sampleIO initrvar s0 <- Blob.generate (pure 0) s1 <- Blob.generate (pure 0) return (ModelPars p (s0, s1)) data ParsWrapped = forall size. KnownNat size => ParsWrapped (ModelPars size) instance C.Serialise ParsWrapped where encode (ParsWrapped (ModelPars p s0 :: ModelPars size)) = C.encode (natVal (Proxy @ size), p, s0) decode = do 3 <- C.decodeListLen size <- C.decodeInteger withNat size $ \(proxy :: Proxy size) -> do case parDict proxy of Dict -> do p <- C.decode s0 <- C.decode return (ParsWrapped (ModelPars p s0 :: ModelPars size)) storePars :: forall size. KnownNat size => FilePath -> ModelPars size -> IO () storePars fname m = BL.writeFile fname (encodeToByteString (ParsWrapped m)) readPars :: FilePath -> IO ParsWrapped readPars fname = decodeOrError <$> BL.readFile fname
968cd40a08a57f288b7a4016e696918ade47b179e0d6eba50cb0e03baaa2ea2e
project-oak/hafnium-verification
utils.mli
* Copyright ( c ) 2014 - present , Facebook , Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) val open_in : string -> in_channel val open_out : string -> out_channel val string_starts_with : string -> string -> bool val string_ends_with : string -> string -> bool val string_split : char -> string -> string list val string_join : char -> string list -> string val list_starts_with : 'a list -> 'a list -> bool val list_ends_with : 'a list -> 'a list -> bool val make_cached : ('a -> 'b) -> 'a -> 'b val line_stream_of_channel : in_channel -> string Stream.t val stream_concat : 'a Stream.t Stream.t -> 'a Stream.t val stream_append : 'a Stream.t -> 'a Stream.t -> 'a Stream.t val stream_map : ('a -> 'b) -> 'a Stream.t -> 'b Stream.t val stream_filter : ('a -> bool) -> 'a Stream.t -> 'a Stream.t val stream_fold : ('a -> 'b -> 'b) -> 'b -> 'a Stream.t -> 'b val stream_to_list : 'a Stream.t -> 'a list val assert_true : string -> bool -> unit val assert_false : string -> bool -> unit val assert_equal : string -> 'a -> 'a -> unit module DisjointSet : sig type 'a t val create : unit -> 'a t val find : 'a t -> 'a -> 'a val union : 'a t -> 'a -> 'a -> unit val iter : 'a t -> ('a -> 'a -> unit) -> unit end val fix_arg_spec : (Arg.key * Arg.spec * Arg.doc) list -> Arg.usage_msg -> (Arg.key * Arg.spec * Arg.doc) list
null
https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/facebook-clang-plugins/clang-ocaml/utils.mli
ocaml
* Copyright ( c ) 2014 - present , Facebook , Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) val open_in : string -> in_channel val open_out : string -> out_channel val string_starts_with : string -> string -> bool val string_ends_with : string -> string -> bool val string_split : char -> string -> string list val string_join : char -> string list -> string val list_starts_with : 'a list -> 'a list -> bool val list_ends_with : 'a list -> 'a list -> bool val make_cached : ('a -> 'b) -> 'a -> 'b val line_stream_of_channel : in_channel -> string Stream.t val stream_concat : 'a Stream.t Stream.t -> 'a Stream.t val stream_append : 'a Stream.t -> 'a Stream.t -> 'a Stream.t val stream_map : ('a -> 'b) -> 'a Stream.t -> 'b Stream.t val stream_filter : ('a -> bool) -> 'a Stream.t -> 'a Stream.t val stream_fold : ('a -> 'b -> 'b) -> 'b -> 'a Stream.t -> 'b val stream_to_list : 'a Stream.t -> 'a list val assert_true : string -> bool -> unit val assert_false : string -> bool -> unit val assert_equal : string -> 'a -> 'a -> unit module DisjointSet : sig type 'a t val create : unit -> 'a t val find : 'a t -> 'a -> 'a val union : 'a t -> 'a -> 'a -> unit val iter : 'a t -> ('a -> 'a -> unit) -> unit end val fix_arg_spec : (Arg.key * Arg.spec * Arg.doc) list -> Arg.usage_msg -> (Arg.key * Arg.spec * Arg.doc) list
43c597cac1b22ea86a35f4d3d34b6cd0123dff3ddfcc10d21c7860771933a11b
tweag/asterius
ado-optimal.hs
{-# LANGUAGE ScopedTypeVariables, ExistentialQuantification, ApplicativeDo #-} {-# OPTIONS_GHC -foptimal-applicative-do #-} module Main where import Control.Applicative import Text.PrettyPrint as PP (a:b:c:d:e:f:g:h:_) = map (\c -> doc [c]) ['a'..] -- This one requires -foptimal-applicative-do to find the best solution -- ((a; b) | (c; d)); e test1 :: M () test1 = do x1 <- a x2 <- const b x1 x3 <- c x4 <- const d x3 x5 <- const e (x1,x4) return (const () x5) -- (a | c); (b | d); e test2 :: M () test2 = do x1 <- a x3 <- c x2 <- const b x1 x4 <- const d x3 x5 <- const e (x1,x4) return (const () x5) main = mapM_ run [ test1 , test2 ] -- Testing code, prints out the structure of a monad/applicative expression newtype M a = M (Bool -> (Maybe Doc, a)) maybeParen True d = parens d maybeParen _ d = d run :: M a -> IO () run (M m) = print d where (Just d,_) = m False instance Functor M where fmap f m = m >>= return . f instance Applicative M where pure a = M $ \_ -> (Nothing, a) M f <*> M a = M $ \p -> let (Just d1, f') = f True (Just d2, a') = a True in (Just (maybeParen p (d1 <+> char '|' <+> d2)), f' a') instance Monad M where return = pure M m >>= k = M $ \p -> let (d1, a) = m True (d2, b) = case k a of M f -> f True in case (d1,d2) of (Nothing,Nothing) -> (Nothing, b) (Just d, Nothing) -> (Just d, b) (Nothing, Just d) -> (Just d, b) (Just d1, Just d2) -> (Just (maybeParen p (d1 PP.<> semi <+> d2)), b) doc :: String -> M () doc d = M $ \_ -> (Just (text d), ())
null
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/ado/ado-optimal.hs
haskell
# LANGUAGE ScopedTypeVariables, ExistentialQuantification, ApplicativeDo # # OPTIONS_GHC -foptimal-applicative-do # This one requires -foptimal-applicative-do to find the best solution ((a; b) | (c; d)); e (a | c); (b | d); e Testing code, prints out the structure of a monad/applicative expression
module Main where import Control.Applicative import Text.PrettyPrint as PP (a:b:c:d:e:f:g:h:_) = map (\c -> doc [c]) ['a'..] test1 :: M () test1 = do x1 <- a x2 <- const b x1 x3 <- c x4 <- const d x3 x5 <- const e (x1,x4) return (const () x5) test2 :: M () test2 = do x1 <- a x3 <- c x2 <- const b x1 x4 <- const d x3 x5 <- const e (x1,x4) return (const () x5) main = mapM_ run [ test1 , test2 ] newtype M a = M (Bool -> (Maybe Doc, a)) maybeParen True d = parens d maybeParen _ d = d run :: M a -> IO () run (M m) = print d where (Just d,_) = m False instance Functor M where fmap f m = m >>= return . f instance Applicative M where pure a = M $ \_ -> (Nothing, a) M f <*> M a = M $ \p -> let (Just d1, f') = f True (Just d2, a') = a True in (Just (maybeParen p (d1 <+> char '|' <+> d2)), f' a') instance Monad M where return = pure M m >>= k = M $ \p -> let (d1, a) = m True (d2, b) = case k a of M f -> f True in case (d1,d2) of (Nothing,Nothing) -> (Nothing, b) (Just d, Nothing) -> (Just d, b) (Nothing, Just d) -> (Just d, b) (Just d1, Just d2) -> (Just (maybeParen p (d1 PP.<> semi <+> d2)), b) doc :: String -> M () doc d = M $ \_ -> (Just (text d), ())
067866228076385dac8ceac23ec6d9cb759afa9d65543529c6b90fbd8136b51a
penrose/geometric-queries
main.hs
# LANGUAGE OverloadedStrings , DeriveGeneric # module Main where import qualified Data.Text as T import qualified Data.ByteString.Lazy.Char8 as B import qualified Control.Monad.IO.Class as IO import GHC.Generics import Data.Aeson import Web.Scotty as S import PointsAndLines import Polygons import Gradients import Debug.Trace data Output = Output { oType :: String, value :: String } deriving (Show, Generic) instance ToJSON Output where toEncoding = genericToEncoding defaultOptions data Request = Request { func :: String, args :: [[[Double]]] } deriving (Show, Generic, Read) instance FromJSON Request main :: IO () main = scotty 9202 $ do get "/" $ do IO.liftIO $ putStrLn "on home page..." setHeader "Content-Type" "text/html" file "index.html" post "/url" $ do IO.liftIO $ putStrLn "eval request..." obj <- S.jsonData :: ActionM Request IO.liftIO $ putStrLn $ show obj setHeader "Content-Type" "application/json" S.json $ Output { oType = "success", value=eval (func obj) (args obj) } get "/:file" $ do dir <- T.unpack <$> param "file" IO.liftIO $ putStrLn $ "get request: " ++ dir file dir eval :: String -> [[[Double]]] -> String eval func args = case func of first 3 : used for detect onclick "dist" -> show $ dist (parsePt (args!!0)) (parsePt (args!!1)) "outsidedness" -> show $ outsidedness (parsePoly (args!!0)) (parsePt (args!!1)) "shortestDistPS" -> show $ shortestDistPS (parsePt (args!!0)) (parseSeg (args!!1)) -- below: query functions to test "closestPointPS" -> strPt $ closestPointPS (parsePt (args!!0)) (parseSeg (args!!1)) "intersectionSS" -> strMaybePt $ intersectionSS (parseSeg (args!!0)) (parseSeg (args!!1)) "shortestSegmentSS" -> strSeg $ shortestSegmentSS (parseSeg (args!!0)) (parseSeg (args!!1)) "closestPointGP" -> strPt $ closestPointGP (parsePoly (args!!0)) (parsePt (args!!1)) "segIsInside" -> strBool $ segIsInside (parsePoly (args!!0)) (parseSeg (args!!1)) "shortestSegmentGS" -> strSeg $ shortestSegmentGS (parsePoly (args!!0)) (parseSeg (args!!1)) "shortestSegmentGG" -> strSeg $ shortestSegmentGG (parsePoly (args!!0)) (parsePoly (args!!1)) "maxUDistSegGS" -> strSeg $ maxUDistSegGS (parsePoly (args!!0)) (parseSeg (args!!1)) "maxUDistSegGG" -> strSeg $ maxUDistSegGG (parsePoly (args!!0)) (parsePoly (args!!1)) "minSignedDistSegGG" -> strSeg $ minSignedDistSegGG (parsePoly (args!!0)) (parsePoly (args!!1)) "maxSignedDistSegGG" -> strSeg $ maxSignedDistSegGG (parsePoly (args!!0)) (parsePoly (args!!1)) "containB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++(show d)++"]") $ containB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "containedB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++ (show d)++"]") $ containedB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "containAB" -> (\(a,b,c,d,e) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c) ++ "," ++ (show d) ++","++ (strPoly e) ++"]") $ containAB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "containedAB" -> (\(a,b,c,d,e) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c) ++ "," ++ (show d) ++","++ (strPoly e) ++"]") $ containedAB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "disjB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++ (show d)++"]") $ disjB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "disjAB" -> (\(a,b,c,d,e) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c) ++ "," ++ (show d) ++","++ (strPoly e) ++"]") $ disjAB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "inTangB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++ (show d) ++ "]") $ inTangB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "outTangB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++ (show d) ++ "]") $ outTangB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "bdixB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++ (show d) ++ "]") $ bdixB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "bdixAB" -> (\(a,b,c,d,e) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c) ++ "," ++ (show d) ++","++ (strPoly e) ++"]") $ bdixAB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) -- below: for test in js "maxUDistGG" -> show $ maxUDistGG (parsePoly (args!!0)) (parsePoly (args!!1)) "maxUDistGGtest" -> show $ maxUDistGGtest (parsePoly (args!!0)) (parsePoly (args!!1)) "maxUDistGGtestSeg" -> strSeg $ maxUDistGGtestSeg (parsePoly (args!!0)) (parsePoly (args!!1)) "maxUDistSegGSaprx" -> strSeg $ maxUDistSegGSaprx (parsePoly (args!!0)) (parseSeg (args!!1)) parseNum :: [[Double]] -> Double parseNum arg = arg!!0!!0 parsePt :: [[Double]] -> Point parsePt arg = (arg!!0!!0, arg!!0!!1) parseSeg :: [[Double]] -> LineSeg parseSeg arg = let p1 = (arg!!0!!0, arg!!0!!1) p2 = (arg!!1!!0, arg!!1!!1) in (p1, p2) parsePoly :: [[Double]] -> Polygon parsePoly arg = map (\(a:b:_)->(a,b)) arg parseList :: [[Double]] -> [Double] parseList arg = arg!!0 strBool :: Bool -> String strBool b = if b then "true" else "false" strPt :: Point -> String strPt (x, y) = "[" ++ (show x) ++ "," ++ (show y) ++ "]" strSeg :: LineSeg -> String strSeg (p1, p2) = "[" ++ (strPt p1) ++ "," ++ (strPt p2) ++ "]" strPoly :: Polygon -> String strPoly poly = let res = foldl (\a b->a++","++(strPt b)) (strPt $ poly!!0) (tail poly) in "[" ++ res ++ "]" strMaybePt :: Maybe Point -> String strMaybePt mp = case mp of Nothing ->"{Just: false}" Just p -> "{\"Just\": true, \"value\": " ++ (strPt p) ++ "}"
null
https://raw.githubusercontent.com/penrose/geometric-queries/79676192b2740e7bed39535611db8949b7846e14/main.hs
haskell
below: query functions to test below: for test in js
# LANGUAGE OverloadedStrings , DeriveGeneric # module Main where import qualified Data.Text as T import qualified Data.ByteString.Lazy.Char8 as B import qualified Control.Monad.IO.Class as IO import GHC.Generics import Data.Aeson import Web.Scotty as S import PointsAndLines import Polygons import Gradients import Debug.Trace data Output = Output { oType :: String, value :: String } deriving (Show, Generic) instance ToJSON Output where toEncoding = genericToEncoding defaultOptions data Request = Request { func :: String, args :: [[[Double]]] } deriving (Show, Generic, Read) instance FromJSON Request main :: IO () main = scotty 9202 $ do get "/" $ do IO.liftIO $ putStrLn "on home page..." setHeader "Content-Type" "text/html" file "index.html" post "/url" $ do IO.liftIO $ putStrLn "eval request..." obj <- S.jsonData :: ActionM Request IO.liftIO $ putStrLn $ show obj setHeader "Content-Type" "application/json" S.json $ Output { oType = "success", value=eval (func obj) (args obj) } get "/:file" $ do dir <- T.unpack <$> param "file" IO.liftIO $ putStrLn $ "get request: " ++ dir file dir eval :: String -> [[[Double]]] -> String eval func args = case func of first 3 : used for detect onclick "dist" -> show $ dist (parsePt (args!!0)) (parsePt (args!!1)) "outsidedness" -> show $ outsidedness (parsePoly (args!!0)) (parsePt (args!!1)) "shortestDistPS" -> show $ shortestDistPS (parsePt (args!!0)) (parseSeg (args!!1)) "closestPointPS" -> strPt $ closestPointPS (parsePt (args!!0)) (parseSeg (args!!1)) "intersectionSS" -> strMaybePt $ intersectionSS (parseSeg (args!!0)) (parseSeg (args!!1)) "shortestSegmentSS" -> strSeg $ shortestSegmentSS (parseSeg (args!!0)) (parseSeg (args!!1)) "closestPointGP" -> strPt $ closestPointGP (parsePoly (args!!0)) (parsePt (args!!1)) "segIsInside" -> strBool $ segIsInside (parsePoly (args!!0)) (parseSeg (args!!1)) "shortestSegmentGS" -> strSeg $ shortestSegmentGS (parsePoly (args!!0)) (parseSeg (args!!1)) "shortestSegmentGG" -> strSeg $ shortestSegmentGG (parsePoly (args!!0)) (parsePoly (args!!1)) "maxUDistSegGS" -> strSeg $ maxUDistSegGS (parsePoly (args!!0)) (parseSeg (args!!1)) "maxUDistSegGG" -> strSeg $ maxUDistSegGG (parsePoly (args!!0)) (parsePoly (args!!1)) "minSignedDistSegGG" -> strSeg $ minSignedDistSegGG (parsePoly (args!!0)) (parsePoly (args!!1)) "maxSignedDistSegGG" -> strSeg $ maxSignedDistSegGG (parsePoly (args!!0)) (parsePoly (args!!1)) "containB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++(show d)++"]") $ containB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "containedB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++ (show d)++"]") $ containedB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "containAB" -> (\(a,b,c,d,e) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c) ++ "," ++ (show d) ++","++ (strPoly e) ++"]") $ containAB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "containedAB" -> (\(a,b,c,d,e) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c) ++ "," ++ (show d) ++","++ (strPoly e) ++"]") $ containedAB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "disjB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++ (show d)++"]") $ disjB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "disjAB" -> (\(a,b,c,d,e) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c) ++ "," ++ (show d) ++","++ (strPoly e) ++"]") $ disjAB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "inTangB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++ (show d) ++ "]") $ inTangB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "outTangB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++ (show d) ++ "]") $ outTangB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "bdixB" -> (\(a,b,c,d) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c)++"," ++ (show d) ++ "]") $ bdixB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "bdixAB" -> (\(a,b,c,d,e) -> "[" ++ (strPoly a) ++ "," ++ (show b) ++ "," ++ (show c) ++ "," ++ (show d) ++","++ (strPoly e) ++"]") $ bdixAB (parsePoly(args!!0)) (parsePoly(args!!1)) (parseList(args!!2)) (parseList(args!!3)) "maxUDistGG" -> show $ maxUDistGG (parsePoly (args!!0)) (parsePoly (args!!1)) "maxUDistGGtest" -> show $ maxUDistGGtest (parsePoly (args!!0)) (parsePoly (args!!1)) "maxUDistGGtestSeg" -> strSeg $ maxUDistGGtestSeg (parsePoly (args!!0)) (parsePoly (args!!1)) "maxUDistSegGSaprx" -> strSeg $ maxUDistSegGSaprx (parsePoly (args!!0)) (parseSeg (args!!1)) parseNum :: [[Double]] -> Double parseNum arg = arg!!0!!0 parsePt :: [[Double]] -> Point parsePt arg = (arg!!0!!0, arg!!0!!1) parseSeg :: [[Double]] -> LineSeg parseSeg arg = let p1 = (arg!!0!!0, arg!!0!!1) p2 = (arg!!1!!0, arg!!1!!1) in (p1, p2) parsePoly :: [[Double]] -> Polygon parsePoly arg = map (\(a:b:_)->(a,b)) arg parseList :: [[Double]] -> [Double] parseList arg = arg!!0 strBool :: Bool -> String strBool b = if b then "true" else "false" strPt :: Point -> String strPt (x, y) = "[" ++ (show x) ++ "," ++ (show y) ++ "]" strSeg :: LineSeg -> String strSeg (p1, p2) = "[" ++ (strPt p1) ++ "," ++ (strPt p2) ++ "]" strPoly :: Polygon -> String strPoly poly = let res = foldl (\a b->a++","++(strPt b)) (strPt $ poly!!0) (tail poly) in "[" ++ res ++ "]" strMaybePt :: Maybe Point -> String strMaybePt mp = case mp of Nothing ->"{Just: false}" Just p -> "{\"Just\": true, \"value\": " ++ (strPt p) ++ "}"
9cd37b5b88d3b04ec8e6c515264598c550f0d1d286afcdfaf00ac97b4cb5340b
DogLooksGood/holdem
handler.clj
(ns poker.web.handler (:require [hiccup.core :as html] [ring.util.response :as resp] [hiccup.page :as page] [hiccup.util :as html-util] [ring.middleware.anti-forgery] [poker.account :as account] [poker.lobby :as lobby] [poker.game :as game] [poker.chat :as chat] [poker.ladder :as ladder] [clojure.tools.logging :as log] [clojure.core.async :as a] [poker.system.web-pub :refer [pub-bus]] [poker.web.ws :as ws] [clojure.java.io :as io] [clojure.string :as str])) (defn format-ex [ex] {:error (ex-message ex), :data (ex-data ex)}) (def index-hydration-template (str/trim-newline (slurp (io/resource "index-ssr.html")))) (defn game-index-page [_req] {:status 200, ;; This page should not be cached. :headers {"Cache-control" "no-cache"} :body (let [csrf-token (force ring.middleware.anti-forgery/*anti-forgery-token*)] (html/html [:html [:head [:title "Holdem"] [:meta {:name "viewport", :content "width=device-width, initial-scale=1.0"}] [:meta {:charset "UTF-8"}] (page/include-css "css/app.css")] [:body [:div#sente-csrf-token {:data-csrf-token csrf-token}] [:div#ssr-enabled] [:div#app (html-util/as-str index-hydration-template)] (page/include-js "js/app.js")]]))}) (defn signup [{:keys [params session]}] (try (let [{:player/keys [token id]} (account/signup! params)] (-> (resp/response {:player/token token, :player/id id}) ;; Old session contains CSRF token (assoc :session (assoc session :uid id)))) (catch Exception ex (resp/response (format-ex ex))))) (defn auth [{:keys [params session]}] (try (let [{:player/keys [token id]} (account/auth-player-by-token! (:token params))] (-> (resp/response {:player/token token, :player/id id}) (assoc :session (assoc session :uid id)))) (catch Exception ex (resp/response (format-ex ex))))) (defn alive [req] (log/debugf "alive, session: %s" (prn-str (:session req))) {:status 200, :body "ok"}) (defmethod ws/handle-event :test/test [_ctx event] (log/debugf "test event: %s" (prn-str event))) (defmethod ws/handle-event :lobby/create-game [_ctx {:keys [?data ?reply-fn]}] (try (log/debugf "player create game, ?data: %s" ?data) (let [token (:player/token ?data) {:player/keys [id avatar]} (account/auth-player-by-token! token) ret (lobby/create-game! (assoc ?data :player/id id :player/props {:player/avatar avatar}))] (a/>!! pub-bus [:lobby-output/updated]) (?reply-fn ret)) (catch Exception ex (?reply-fn (format-ex ex))))) (defmethod ws/handle-event :lobby/list-games [_ctx {:keys [?reply-fn]}] (let [ret (lobby/list-games {})] (?reply-fn ret))) (defmethod ws/handle-event :lobby/list-players [_ctx {:keys [?reply-fn]}] (let [ret (ws/list-all-uids)] (?reply-fn ret))) (defmethod ws/handle-event :ladder/list-leaderboard [_ctx {:keys [?reply-fn]}] (let [ret (ladder/list-leaderboard)] (?reply-fn ret))) (defmethod ws/handle-event :lobby/list-joined-games [_ctx {:keys [?reply-fn ?data]}] (let [ret (lobby/list-joined-games ?data)] (?reply-fn ret))) (defmethod ws/handle-event :lobby/join-game [_ctx {:keys [?data ?reply-fn]}] (try (log/debugf "player join game: %s" ?data) (let [token (:player/token ?data) {:player/keys [id avatar]} (account/auth-player-by-token! token) ret (lobby/join-game! (assoc ?data :player/id id :player/props {:player/avatar avatar}))] (a/>!! pub-bus [:lobby-output/updated]) (?reply-fn ret)) (catch Exception ex (?reply-fn (format-ex ex))))) ;; Leave game or websocket disconnect FIXME return correct status code . (defmethod ws/handle-event :lobby/leave-game [_ctx {:keys [?data ?reply-fn]}] (try (log/debugf "player leave game: %s" ?data) (let [token (:player/token ?data) player-id (:player/id (account/auth-player-by-token! token)) ret (lobby/leave-game! (assoc ?data :player/id player-id))] (a/>!! pub-bus [:lobby-output/updated]) (?reply-fn ret)) (catch Exception ex (?reply-fn (format-ex ex))))) (defmethod ws/handle-event :chsk/uidport-open [_ctx {:keys [uid]}] (log/debugf "player connected: %s" uid) (a/>!! pub-bus [:lobby-output/updated])) (defmethod ws/handle-event :chsk/uidport-close [_ctx {:keys [?data uid]}] (try (log/debugf "player leave game due to websocket disconnect: %s" ?data) (lobby/leave-all-games! {:player/id uid}) (a/>!! pub-bus [:lobby-output/updated]) (catch Exception ex (log/error ex)))) (defmethod ws/handle-event :game/call [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "player %s call: %s" (:player/name uid) ?data) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-call {:player-id uid}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/bet [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s bet: %s" (:player/name uid) ?data) (let [{:keys [bet game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-bet {:player-id uid, :bet bet}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/check [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s check: %s" (:player/name uid) ?data) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-check {:player-id uid}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/fold [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s fold: %s" (:player/name uid) ?data) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-fold {:player-id uid}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/join-bet [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s join-bet: %s" (:player/name uid) ?data) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-join-bet {:player-id uid}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/musk [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s musk: %s" (:player/name uid) ?data) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-musk {:player-id uid}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/raise [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s raise: %s" (:player/name uid) ?data) (let [{:keys [raise game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-raise {:player-id uid, :raise raise}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/request-deal-times [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s request deal times: %s" (:player/name uid) ?data) (let [{:keys [deal-times game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-request-deal-times {:player-id uid, :deal-times deal-times}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/buyin [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s buyin" (:player/name uid)) (let [{:keys [seat game-id]} ?data game (game/get-game game-id) stack 20000] (?reply-fn (game/send-game-event game [:game-event/player-buyin {:player-id uid, :seat seat, :stack-add stack}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/get-current-state [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s get current state" (:player/name uid)) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-get-current-state {:player-id uid}]))) (catch Exception ex (log/errorf ex "Handle event error")))) (defmethod ws/handle-event :message/new-message [_ctx {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s send message" (:player/name uid)) (let [{:keys [game-id content]} ?data params {:message/game-id game-id, :message/content content, :message/sender uid}] (?reply-fn (chat/broadcast-new-message! params))) (catch Exception ex (log/errorf ex "Handle event error"))))
null
https://raw.githubusercontent.com/DogLooksGood/holdem/76791c1b51eda0f439778f1018753af95583773f/src/clj/poker/web/handler.clj
clojure
This page should not be cached. Old session contains CSRF token Leave game or websocket disconnect
(ns poker.web.handler (:require [hiccup.core :as html] [ring.util.response :as resp] [hiccup.page :as page] [hiccup.util :as html-util] [ring.middleware.anti-forgery] [poker.account :as account] [poker.lobby :as lobby] [poker.game :as game] [poker.chat :as chat] [poker.ladder :as ladder] [clojure.tools.logging :as log] [clojure.core.async :as a] [poker.system.web-pub :refer [pub-bus]] [poker.web.ws :as ws] [clojure.java.io :as io] [clojure.string :as str])) (defn format-ex [ex] {:error (ex-message ex), :data (ex-data ex)}) (def index-hydration-template (str/trim-newline (slurp (io/resource "index-ssr.html")))) (defn game-index-page [_req] {:status 200, :headers {"Cache-control" "no-cache"} :body (let [csrf-token (force ring.middleware.anti-forgery/*anti-forgery-token*)] (html/html [:html [:head [:title "Holdem"] [:meta {:name "viewport", :content "width=device-width, initial-scale=1.0"}] [:meta {:charset "UTF-8"}] (page/include-css "css/app.css")] [:body [:div#sente-csrf-token {:data-csrf-token csrf-token}] [:div#ssr-enabled] [:div#app (html-util/as-str index-hydration-template)] (page/include-js "js/app.js")]]))}) (defn signup [{:keys [params session]}] (try (let [{:player/keys [token id]} (account/signup! params)] (-> (resp/response {:player/token token, :player/id id}) (assoc :session (assoc session :uid id)))) (catch Exception ex (resp/response (format-ex ex))))) (defn auth [{:keys [params session]}] (try (let [{:player/keys [token id]} (account/auth-player-by-token! (:token params))] (-> (resp/response {:player/token token, :player/id id}) (assoc :session (assoc session :uid id)))) (catch Exception ex (resp/response (format-ex ex))))) (defn alive [req] (log/debugf "alive, session: %s" (prn-str (:session req))) {:status 200, :body "ok"}) (defmethod ws/handle-event :test/test [_ctx event] (log/debugf "test event: %s" (prn-str event))) (defmethod ws/handle-event :lobby/create-game [_ctx {:keys [?data ?reply-fn]}] (try (log/debugf "player create game, ?data: %s" ?data) (let [token (:player/token ?data) {:player/keys [id avatar]} (account/auth-player-by-token! token) ret (lobby/create-game! (assoc ?data :player/id id :player/props {:player/avatar avatar}))] (a/>!! pub-bus [:lobby-output/updated]) (?reply-fn ret)) (catch Exception ex (?reply-fn (format-ex ex))))) (defmethod ws/handle-event :lobby/list-games [_ctx {:keys [?reply-fn]}] (let [ret (lobby/list-games {})] (?reply-fn ret))) (defmethod ws/handle-event :lobby/list-players [_ctx {:keys [?reply-fn]}] (let [ret (ws/list-all-uids)] (?reply-fn ret))) (defmethod ws/handle-event :ladder/list-leaderboard [_ctx {:keys [?reply-fn]}] (let [ret (ladder/list-leaderboard)] (?reply-fn ret))) (defmethod ws/handle-event :lobby/list-joined-games [_ctx {:keys [?reply-fn ?data]}] (let [ret (lobby/list-joined-games ?data)] (?reply-fn ret))) (defmethod ws/handle-event :lobby/join-game [_ctx {:keys [?data ?reply-fn]}] (try (log/debugf "player join game: %s" ?data) (let [token (:player/token ?data) {:player/keys [id avatar]} (account/auth-player-by-token! token) ret (lobby/join-game! (assoc ?data :player/id id :player/props {:player/avatar avatar}))] (a/>!! pub-bus [:lobby-output/updated]) (?reply-fn ret)) (catch Exception ex (?reply-fn (format-ex ex))))) FIXME return correct status code . (defmethod ws/handle-event :lobby/leave-game [_ctx {:keys [?data ?reply-fn]}] (try (log/debugf "player leave game: %s" ?data) (let [token (:player/token ?data) player-id (:player/id (account/auth-player-by-token! token)) ret (lobby/leave-game! (assoc ?data :player/id player-id))] (a/>!! pub-bus [:lobby-output/updated]) (?reply-fn ret)) (catch Exception ex (?reply-fn (format-ex ex))))) (defmethod ws/handle-event :chsk/uidport-open [_ctx {:keys [uid]}] (log/debugf "player connected: %s" uid) (a/>!! pub-bus [:lobby-output/updated])) (defmethod ws/handle-event :chsk/uidport-close [_ctx {:keys [?data uid]}] (try (log/debugf "player leave game due to websocket disconnect: %s" ?data) (lobby/leave-all-games! {:player/id uid}) (a/>!! pub-bus [:lobby-output/updated]) (catch Exception ex (log/error ex)))) (defmethod ws/handle-event :game/call [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "player %s call: %s" (:player/name uid) ?data) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-call {:player-id uid}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/bet [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s bet: %s" (:player/name uid) ?data) (let [{:keys [bet game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-bet {:player-id uid, :bet bet}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/check [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s check: %s" (:player/name uid) ?data) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-check {:player-id uid}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/fold [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s fold: %s" (:player/name uid) ?data) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-fold {:player-id uid}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/join-bet [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s join-bet: %s" (:player/name uid) ?data) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-join-bet {:player-id uid}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/musk [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s musk: %s" (:player/name uid) ?data) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-musk {:player-id uid}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/raise [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s raise: %s" (:player/name uid) ?data) (let [{:keys [raise game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-raise {:player-id uid, :raise raise}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/request-deal-times [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s request deal times: %s" (:player/name uid) ?data) (let [{:keys [deal-times game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-request-deal-times {:player-id uid, :deal-times deal-times}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/buyin [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s buyin" (:player/name uid)) (let [{:keys [seat game-id]} ?data game (game/get-game game-id) stack 20000] (?reply-fn (game/send-game-event game [:game-event/player-buyin {:player-id uid, :seat seat, :stack-add stack}]))) (catch Exception ex (log/warnf ex "Handle event error")))) (defmethod ws/handle-event :game/get-current-state [_cxt {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s get current state" (:player/name uid)) (let [{:keys [game-id]} ?data game (game/get-game game-id)] (?reply-fn (game/send-game-event game [:game-event/player-get-current-state {:player-id uid}]))) (catch Exception ex (log/errorf ex "Handle event error")))) (defmethod ws/handle-event :message/new-message [_ctx {:keys [?data uid ?reply-fn]}] (try (log/debugf "Player %s send message" (:player/name uid)) (let [{:keys [game-id content]} ?data params {:message/game-id game-id, :message/content content, :message/sender uid}] (?reply-fn (chat/broadcast-new-message! params))) (catch Exception ex (log/errorf ex "Handle event error"))))
47728053fa8af28d45bdc208aba74c3ef6a0820a0e5efa9d578992dae003f60b
SamB/coq
inductive.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (*i $Id$ i*) (*i*) open Names open Univ open Term open Declarations open Environ (*i*) (*s Extracting an inductive type from a construction *) (* [find_m*type env sigma c] coerce [c] to an recursive type (I args). [find_rectype], [find_inductive] and [find_coinductive] respectively accepts any recursive type, only an inductive type and only a coinductive type. They raise [Not_found] if not convertible to a recursive type. *) val find_rectype : env -> types -> inductive * constr list val find_inductive : env -> types -> inductive * constr list val find_coinductive : env -> types -> inductive * constr list type mind_specif = mutual_inductive_body * one_inductive_body (*s Fetching information in the environment about an inductive type. Raises [Not_found] if the inductive type is not found. *) val lookup_mind_specif : env -> inductive -> mind_specif (*s Functions to build standard types related to inductive *) val ind_subst : mutual_inductive -> mutual_inductive_body -> constr list val type_of_inductive : env -> mind_specif -> types val elim_sorts : mind_specif -> sorts_family list (* Return type as quoted by the user *) val type_of_constructor : constructor -> mind_specif -> types (* Return constructor types in normal form *) val arities_of_constructors : inductive -> mind_specif -> types array (* Transforms inductive specification into types (in nf) *) val arities_of_specif : mutual_inductive -> mind_specif -> types array [ type_case_branches env ( I , args ) ( p : A ) c ] computes useful types about the following Cases expression : < p > Cases ( c : : ( I args ) ) of b1 .. bn end It computes the type of every branch ( pattern variables are introduced by products ) , the type for the whole expression , and the universe constraints generated . about the following Cases expression: <p>Cases (c :: (I args)) of b1..bn end It computes the type of every branch (pattern variables are introduced by products), the type for the whole expression, and the universe constraints generated. *) val type_case_branches : env -> inductive * constr list -> unsafe_judgment -> constr -> types array * types * constraints (* Return the arity of an inductive type *) val mind_arity : one_inductive_body -> Sign.rel_context * sorts_family val inductive_sort_family : one_inductive_body -> sorts_family (* Check a [case_info] actually correspond to a Case expression on the given inductive type. *) val check_case_info : env -> inductive -> case_info -> unit s Guard conditions for fix and cofix - points . val check_fix : env -> fixpoint -> unit val check_cofix : env -> cofixpoint -> unit (*s Support for sort-polymorphic inductive types *) val type_of_inductive_knowing_parameters : env -> one_inductive_body -> types array -> types val max_inductive_sort : sorts array -> universe val instantiate_universes : env -> Sign.rel_context -> polymorphic_arity -> types array -> Sign.rel_context * sorts (***************************************************************) (* Debug *) type size = Large | Strict type subterm_spec = Subterm of (size * wf_paths) | Dead_code | Not_subterm type guard_env = { env : env; (* dB of last fixpoint *) rel_min : int; (* inductive of recarg of each fixpoint *) inds : inductive array; (* the recarg information of inductive family *) recvec : wf_paths array; (* dB of variables denoting subterms *) genv : subterm_spec list; } val subterm_specif : guard_env -> constr -> subterm_spec val case_branches_specif : guard_env -> subterm_spec -> inductive -> constr array -> (guard_env * constr) array
null
https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/kernel/inductive.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** i $Id$ i i i s Extracting an inductive type from a construction [find_m*type env sigma c] coerce [c] to an recursive type (I args). [find_rectype], [find_inductive] and [find_coinductive] respectively accepts any recursive type, only an inductive type and only a coinductive type. They raise [Not_found] if not convertible to a recursive type. s Fetching information in the environment about an inductive type. Raises [Not_found] if the inductive type is not found. s Functions to build standard types related to inductive Return type as quoted by the user Return constructor types in normal form Transforms inductive specification into types (in nf) Return the arity of an inductive type Check a [case_info] actually correspond to a Case expression on the given inductive type. s Support for sort-polymorphic inductive types ************************************************************* Debug dB of last fixpoint inductive of recarg of each fixpoint the recarg information of inductive family dB of variables denoting subterms
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Names open Univ open Term open Declarations open Environ val find_rectype : env -> types -> inductive * constr list val find_inductive : env -> types -> inductive * constr list val find_coinductive : env -> types -> inductive * constr list type mind_specif = mutual_inductive_body * one_inductive_body val lookup_mind_specif : env -> inductive -> mind_specif val ind_subst : mutual_inductive -> mutual_inductive_body -> constr list val type_of_inductive : env -> mind_specif -> types val elim_sorts : mind_specif -> sorts_family list val type_of_constructor : constructor -> mind_specif -> types val arities_of_constructors : inductive -> mind_specif -> types array val arities_of_specif : mutual_inductive -> mind_specif -> types array [ type_case_branches env ( I , args ) ( p : A ) c ] computes useful types about the following Cases expression : < p > Cases ( c : : ( I args ) ) of b1 .. bn end It computes the type of every branch ( pattern variables are introduced by products ) , the type for the whole expression , and the universe constraints generated . about the following Cases expression: <p>Cases (c :: (I args)) of b1..bn end It computes the type of every branch (pattern variables are introduced by products), the type for the whole expression, and the universe constraints generated. *) val type_case_branches : env -> inductive * constr list -> unsafe_judgment -> constr -> types array * types * constraints val mind_arity : one_inductive_body -> Sign.rel_context * sorts_family val inductive_sort_family : one_inductive_body -> sorts_family val check_case_info : env -> inductive -> case_info -> unit s Guard conditions for fix and cofix - points . val check_fix : env -> fixpoint -> unit val check_cofix : env -> cofixpoint -> unit val type_of_inductive_knowing_parameters : env -> one_inductive_body -> types array -> types val max_inductive_sort : sorts array -> universe val instantiate_universes : env -> Sign.rel_context -> polymorphic_arity -> types array -> Sign.rel_context * sorts type size = Large | Strict type subterm_spec = Subterm of (size * wf_paths) | Dead_code | Not_subterm type guard_env = { env : env; rel_min : int; inds : inductive array; recvec : wf_paths array; genv : subterm_spec list; } val subterm_specif : guard_env -> constr -> subterm_spec val case_branches_specif : guard_env -> subterm_spec -> inductive -> constr array -> (guard_env * constr) array
18c93cd66e6c7ff1efb8f9040a4d6237a7fbd35e149b81bc0bd9a04d296a113d
AccelerateHS/accelerate-examples
Main.hs
module Main where import Config import FFT import HighPass import Prelude as P import Data.Label import System.Exit import System.Environment import System.FilePath import Data.Array.Accelerate as A import Data.Array.Accelerate.IO.Codec.BMP as A import Data.Array.Accelerate.Examples.Internal as A -- Main routine ---------------------------------------------------------------- main :: IO () main = do beginMonitoring (conf, opts, rest) <- parseArgs options defaults header footer (fileIn, fileOut) <- case rest of (i:o:_) -> return (i,o) _ -> withArgs ["--help"] $ parseArgs options defaults header footer >> exitSuccess -- Read in the image file img <- either (error . show) id `fmap` A.readImageFromBMP fileIn -- Set up the operations let (file,bmp) = splitExtension fileOut fileMag = file P.++ "-mag" <.> bmp filePhase = file P.++ "-phase" <.> bmp fileHP = file P.++ "-hp" <.> bmp cutoff = get configCutoff conf clip = get configClip conf backend = get optBackend opts -- Write out the images to file -- highpass = run backend $ highpassFFT cutoff (use img) (mag, phase) = run backend $ imageFFT clip (use img) writeImageToBMP fileHP highpass writeImageToBMP fileMag mag writeImageToBMP filePhase phase runBenchmarks opts (P.drop 2 rest) [ bench "highpass" $ whnf (run1 backend (highpassFFT cutoff)) img , bench "fft" $ whnf (run1 backend (imageFFT clip)) img ]
null
https://raw.githubusercontent.com/AccelerateHS/accelerate-examples/a973ee423b5eadda6ef2e2504d2383f625e49821/examples/fft/src-acc/Main.hs
haskell
Main routine ---------------------------------------------------------------- Read in the image file Set up the operations Write out the images to file
module Main where import Config import FFT import HighPass import Prelude as P import Data.Label import System.Exit import System.Environment import System.FilePath import Data.Array.Accelerate as A import Data.Array.Accelerate.IO.Codec.BMP as A import Data.Array.Accelerate.Examples.Internal as A main :: IO () main = do beginMonitoring (conf, opts, rest) <- parseArgs options defaults header footer (fileIn, fileOut) <- case rest of (i:o:_) -> return (i,o) _ -> withArgs ["--help"] $ parseArgs options defaults header footer >> exitSuccess img <- either (error . show) id `fmap` A.readImageFromBMP fileIn let (file,bmp) = splitExtension fileOut fileMag = file P.++ "-mag" <.> bmp filePhase = file P.++ "-phase" <.> bmp fileHP = file P.++ "-hp" <.> bmp cutoff = get configCutoff conf clip = get configClip conf backend = get optBackend opts highpass = run backend $ highpassFFT cutoff (use img) (mag, phase) = run backend $ imageFFT clip (use img) writeImageToBMP fileHP highpass writeImageToBMP fileMag mag writeImageToBMP filePhase phase runBenchmarks opts (P.drop 2 rest) [ bench "highpass" $ whnf (run1 backend (highpassFFT cutoff)) img , bench "fft" $ whnf (run1 backend (imageFFT clip)) img ]
b549dceb6fdad27ab477fe3daa53ed7c49b1e692cae8c6bd5e84592a9dc06800
pepe/two-in-shadows
routes.cljs
(ns two-in-shadows.server.routes "Routes for the server" (:require ["koa-router" :as Router] ["koa-body" :as body] [two-in-shadows.utils :as utils] [two-in-shadows.server.events :as events])) (defn ^:private greeting "Renders document with greeting" [ctx next] (utils/set-body ctx {:message (utils/greeting "Welcome to Shadows") :date (utils/current-date)}) (next)) (defn ^:private ping "Returns pong document with pong message" [ctx next] (utils/set-raw-body ctx #js{:message "pong"}) (next)) (defn ^:private list-colls "Returns list of collections" [store] (fn [ctx next] (utils/set-body ctx (events/get-all store)) (next))) (defn ^:private list-all "Returns list of items" [store] (fn [ctx next] (let [{collection :collection} (utils/get-params ctx)] (utils/set-body ctx (events/get-all store collection))) (next))) (defn ^:private add-one "Add item to store" [store] (fn [ctx next] (let [{collection :collection} (utils/get-params ctx)] (events/add-one store collection (utils/get-body ctx))) (utils/set-body ctx {:message "added"}) (next))) (defn ^:private remove-one "Remove item from store" [store] (fn [ctx next] (let [{collection :collection} (utils/get-params ctx)] (events/remove-one store collection (utils/get-body ctx))) (utils/set-body ctx {:message "removed"}) (next))) (def ^:private router "Application router" (let [router (Router.) store (events/init-store)] (doto router (.get "/collections" (list-colls store)) (.get "/storage/:collection" (list-all store)) (.delete "/storage/:collection" (body #js{:strict false}) (remove-one store)) (.post "/storage/:collection" (body) (add-one store)) (.get "/ping" ping) (.get "/greeting" greeting)))) (def allowed-methods "All allowed methods" (.allowedMethods router)) (def all "All routes" (.routes router))
null
https://raw.githubusercontent.com/pepe/two-in-shadows/b49a484cf1cc1a9a2e0a5ffb358acfe0f56d895c/src/two_in_shadows/server/routes.cljs
clojure
(ns two-in-shadows.server.routes "Routes for the server" (:require ["koa-router" :as Router] ["koa-body" :as body] [two-in-shadows.utils :as utils] [two-in-shadows.server.events :as events])) (defn ^:private greeting "Renders document with greeting" [ctx next] (utils/set-body ctx {:message (utils/greeting "Welcome to Shadows") :date (utils/current-date)}) (next)) (defn ^:private ping "Returns pong document with pong message" [ctx next] (utils/set-raw-body ctx #js{:message "pong"}) (next)) (defn ^:private list-colls "Returns list of collections" [store] (fn [ctx next] (utils/set-body ctx (events/get-all store)) (next))) (defn ^:private list-all "Returns list of items" [store] (fn [ctx next] (let [{collection :collection} (utils/get-params ctx)] (utils/set-body ctx (events/get-all store collection))) (next))) (defn ^:private add-one "Add item to store" [store] (fn [ctx next] (let [{collection :collection} (utils/get-params ctx)] (events/add-one store collection (utils/get-body ctx))) (utils/set-body ctx {:message "added"}) (next))) (defn ^:private remove-one "Remove item from store" [store] (fn [ctx next] (let [{collection :collection} (utils/get-params ctx)] (events/remove-one store collection (utils/get-body ctx))) (utils/set-body ctx {:message "removed"}) (next))) (def ^:private router "Application router" (let [router (Router.) store (events/init-store)] (doto router (.get "/collections" (list-colls store)) (.get "/storage/:collection" (list-all store)) (.delete "/storage/:collection" (body #js{:strict false}) (remove-one store)) (.post "/storage/:collection" (body) (add-one store)) (.get "/ping" ping) (.get "/greeting" greeting)))) (def allowed-methods "All allowed methods" (.allowedMethods router)) (def all "All routes" (.routes router))
6c42964bf72607d4a9024d89a2f365a32677c385596c1f0174d7a95b5b6869a0
duo-lang/duo-lang
TypeAutomata.hs
module Pretty.TypeAutomata ( typeAutToDot ) where import Data.Graph.Inductive.Graph import Data.GraphViz.Attributes.Complete (Attribute(Style), StyleName(Dashed,Dotted), StyleItem(SItem)) import Data.GraphViz import Data.Maybe (catMaybes) import Data.Set qualified as S import Data.Map qualified as M import Data.Text.Lazy (pack) import Prettyprinter import Pretty.Pretty (ppPrintString, PrettyAnn(..), intercalateX) import Pretty.Common import Pretty.Types (pipeSym) import TypeAutomata.Definition import Syntax.CST.Types (PrdCns(..)) import Syntax.RST.Types (Polarity(..)) --------------------------------------------------------------------------------- -- Prettyprinting of Type Automata --------------------------------------------------------------------------------- instance PrettyAnn XtorLabel where prettyAnn lbl = prettyAnn lbl.labelName <> prettyArity lbl.labelArity instance PrettyAnn PrimitiveType where prettyAnn I64 = "I64" prettyAnn F64 = "F64" prettyAnn PChar = "Char" prettyAnn PString = "String" instance PrettyAnn NodeLabel where prettyAnn (MkPrimitiveNodeLabel _ tp) = prettyAnn tp prettyAnn (MkNodeLabel _ maybeDat maybeCodat tns refDat refCodat knd) = intercalateX ";" (catMaybes [printDat <$> maybeDat , printCodat <$> maybeCodat , printNominal tns , printRefDat refDat , printRefCodat refCodat , Just $ prettyAnn knd]) where printDat dat = mempty <+> cat (punctuate " , " (prettyAnn <$> S.toList dat)) <+> mempty printCodat codat = mempty <+> cat (punctuate " , " (prettyAnn <$> S.toList codat)) <+> mempty printNominal tnSet = case S.toList tnSet of [] -> Nothing tns -> Just (intercalateX ";" ((\(tn, _) -> prettyAnn tn) <$> tns)) printRefDat refDat = case M.toList refDat of [] -> Nothing refTns -> Just $ intercalateX "; " $ (\(key, content) -> angles $ mempty <+> prettyAnn key <+> pipeSym <+> printDat content <+> mempty) <$> refTns printRefCodat refCodat = case M.toList refCodat of [] -> Nothing refTns -> Just $ intercalateX "; " $ (\(key, content) -> braces $ mempty <+> prettyAnn key <+> pipeSym <+> printCodat content <+> mempty) <$> refTns instance PrettyAnn (EdgeLabel a) where prettyAnn (EdgeSymbol _ xt Prd i) = prettyAnn xt <> parens (pretty i) prettyAnn (EdgeSymbol _ xt Cns i) = prettyAnn xt <> brackets (pretty i) prettyAnn (EpsilonEdge _) = "e" prettyAnn (RefineEdge tn) = prettyAnn tn prettyAnn (TypeArgEdge tn v i) = "TypeArg" <> parens (prettyAnn tn <> " , " <> prettyAnn v <> " , " <> pretty i) typeAutToDot :: Bool -> TypeAut' (EdgeLabel a) f pol -> DotGraph Node typeAutToDot showId aut = let grWithFlow = insEdges [(i,j,EpsilonEdge (error "Never forced")) | (i,j) <- aut.ta_core.ta_flowEdges] aut.ta_core.ta_gr in graphToDot (typeAutParams showId) grWithFlow typeAutParams :: Bool -> GraphvizParams Node NodeLabel (EdgeLabel a) () NodeLabel typeAutParams showId = defaultParams { fmtNode = \(n,nl) -> [ style filled , fillColor $ case getPolarityNL nl of {Pos -> White; Neg -> Gray} , textLabel (pack ((if showId then show n <> ": " else "") <> ppPrintString (nl :: NodeLabel)))] , fmtEdge = \(_,_,elM) -> case elM of el@EdgeSymbol {} -> regularEdgeStyle el (EpsilonEdge _) -> flowEdgeStyle RefineEdge tn -> refEdgeStyle tn el@TypeArgEdge {} -> typeArgEdgeStyle el } where flowEdgeStyle = [arrowTo dotArrow, Style [SItem Dashed []]] regularEdgeStyle el = [textLabel $ pack (ppPrintString el)] refEdgeStyle tn = [arrowTo vee, Style [SItem Dotted []], textLabel $ pack $ ppPrintString tn] typeArgEdgeStyle el = [textLabel $ pack (ppPrintString el)]
null
https://raw.githubusercontent.com/duo-lang/duo-lang/320625ac68446c9b8fb50f4b2181c97a95ff1b8f/src/Pretty/TypeAutomata.hs
haskell
------------------------------------------------------------------------------- Prettyprinting of Type Automata -------------------------------------------------------------------------------
module Pretty.TypeAutomata ( typeAutToDot ) where import Data.Graph.Inductive.Graph import Data.GraphViz.Attributes.Complete (Attribute(Style), StyleName(Dashed,Dotted), StyleItem(SItem)) import Data.GraphViz import Data.Maybe (catMaybes) import Data.Set qualified as S import Data.Map qualified as M import Data.Text.Lazy (pack) import Prettyprinter import Pretty.Pretty (ppPrintString, PrettyAnn(..), intercalateX) import Pretty.Common import Pretty.Types (pipeSym) import TypeAutomata.Definition import Syntax.CST.Types (PrdCns(..)) import Syntax.RST.Types (Polarity(..)) instance PrettyAnn XtorLabel where prettyAnn lbl = prettyAnn lbl.labelName <> prettyArity lbl.labelArity instance PrettyAnn PrimitiveType where prettyAnn I64 = "I64" prettyAnn F64 = "F64" prettyAnn PChar = "Char" prettyAnn PString = "String" instance PrettyAnn NodeLabel where prettyAnn (MkPrimitiveNodeLabel _ tp) = prettyAnn tp prettyAnn (MkNodeLabel _ maybeDat maybeCodat tns refDat refCodat knd) = intercalateX ";" (catMaybes [printDat <$> maybeDat , printCodat <$> maybeCodat , printNominal tns , printRefDat refDat , printRefCodat refCodat , Just $ prettyAnn knd]) where printDat dat = mempty <+> cat (punctuate " , " (prettyAnn <$> S.toList dat)) <+> mempty printCodat codat = mempty <+> cat (punctuate " , " (prettyAnn <$> S.toList codat)) <+> mempty printNominal tnSet = case S.toList tnSet of [] -> Nothing tns -> Just (intercalateX ";" ((\(tn, _) -> prettyAnn tn) <$> tns)) printRefDat refDat = case M.toList refDat of [] -> Nothing refTns -> Just $ intercalateX "; " $ (\(key, content) -> angles $ mempty <+> prettyAnn key <+> pipeSym <+> printDat content <+> mempty) <$> refTns printRefCodat refCodat = case M.toList refCodat of [] -> Nothing refTns -> Just $ intercalateX "; " $ (\(key, content) -> braces $ mempty <+> prettyAnn key <+> pipeSym <+> printCodat content <+> mempty) <$> refTns instance PrettyAnn (EdgeLabel a) where prettyAnn (EdgeSymbol _ xt Prd i) = prettyAnn xt <> parens (pretty i) prettyAnn (EdgeSymbol _ xt Cns i) = prettyAnn xt <> brackets (pretty i) prettyAnn (EpsilonEdge _) = "e" prettyAnn (RefineEdge tn) = prettyAnn tn prettyAnn (TypeArgEdge tn v i) = "TypeArg" <> parens (prettyAnn tn <> " , " <> prettyAnn v <> " , " <> pretty i) typeAutToDot :: Bool -> TypeAut' (EdgeLabel a) f pol -> DotGraph Node typeAutToDot showId aut = let grWithFlow = insEdges [(i,j,EpsilonEdge (error "Never forced")) | (i,j) <- aut.ta_core.ta_flowEdges] aut.ta_core.ta_gr in graphToDot (typeAutParams showId) grWithFlow typeAutParams :: Bool -> GraphvizParams Node NodeLabel (EdgeLabel a) () NodeLabel typeAutParams showId = defaultParams { fmtNode = \(n,nl) -> [ style filled , fillColor $ case getPolarityNL nl of {Pos -> White; Neg -> Gray} , textLabel (pack ((if showId then show n <> ": " else "") <> ppPrintString (nl :: NodeLabel)))] , fmtEdge = \(_,_,elM) -> case elM of el@EdgeSymbol {} -> regularEdgeStyle el (EpsilonEdge _) -> flowEdgeStyle RefineEdge tn -> refEdgeStyle tn el@TypeArgEdge {} -> typeArgEdgeStyle el } where flowEdgeStyle = [arrowTo dotArrow, Style [SItem Dashed []]] regularEdgeStyle el = [textLabel $ pack (ppPrintString el)] refEdgeStyle tn = [arrowTo vee, Style [SItem Dotted []], textLabel $ pack $ ppPrintString tn] typeArgEdgeStyle el = [textLabel $ pack (ppPrintString el)]
28b666cd9d9b57e084e59bb90c1990d9fe18a54461c01ba406652220febcd30f
ocaml/ocaml
pr6416.ml
(* TEST flags="-no-alias-deps -w +40" * expect *) module M = struct type t = A module M : sig val f : t -> unit end = struct type t = B let f B = () end end;; [%%expect{| Lines 5-8, characters 8-5: 5 | ........struct 6 | type t = B 7 | let f B = () 8 | end Error: Signature mismatch: Modules do not match: sig type t = B val f : t -> unit end is not included in sig val f : t -> unit end Values do not match: val f : t -> unit is not included in val f : t/2 -> unit The type t -> unit is not compatible with the type t/2 -> unit Type t is not compatible with type t/2 Line 6, characters 4-14: Definition of type t Line 2, characters 2-12: Definition of type t/2 |}] module N = struct type t= A module M: sig type u = A of t end = struct type t = B type u = A of t end end;; [%%expect{| Line 4, characters 2-39: 4 | struct type t = B type u = A of t end ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: Signature mismatch: Modules do not match: sig type t = B type u = A of t end is not included in sig type u = A of t end Type declarations do not match: type u = A of t is not included in type u = A of t/2 Constructors do not match: A of t is not the same as: A of t The type t is not equal to the type t/2 Line 4, characters 9-19: Definition of type t Line 2, characters 2-11: Definition of type t/2 |}] module K = struct module type s module M: sig module A:functor(X:s) -> sig end end = struct module type s module A(X:s) =struct end end end;; [%%expect{| Lines 4-7, characters 4-7: 4 | ....struct 5 | module type s 6 | module A(X:s) =struct end 7 | end Error: Signature mismatch: Modules do not match: sig module type s module A : functor (X : s) -> sig end end is not included in sig module A : functor (X : s) -> sig end end In module A: Modules do not match: functor (X : s) -> ... is not included in functor (X : s/2) -> ... Module types do not match: s does not include s/2 Line 5, characters 6-19: Definition of module type s Line 2, characters 2-15: Definition of module type s/2 |}] module L = struct module T = struct type t end module M: sig type t = A of T.t end = struct module T = struct type t end type t = A of T.t end end;; [%%expect {| Lines 4-7, characters 4-7: 4 | ....struct 5 | module T = struct type t end 6 | type t = A of T.t 7 | end Error: Signature mismatch: Modules do not match: sig module T : sig type t end type t = A of T.t end is not included in sig type t = A of T.t end Type declarations do not match: type t = A of T.t is not included in type t = A of T/2.t Constructors do not match: A of T.t is not the same as: A of T.t The type T.t is not equal to the type T/2.t Line 5, characters 6-34: Definition of module T Line 2, characters 2-30: Definition of module T/2 |}] module O = struct module type s type t = A module M: sig val f: (module s) -> t -> t end = struct module type s type t = B let f (module X:s) A = B end end;; [%%expect{| Line 5, characters 2-62: 5 | struct module type s type t = B let f (module X:s) A = B end ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: Signature mismatch: Modules do not match: sig module type s type t = B val f : (module s) -> t/2 -> t end is not included in sig val f : (module s) -> t -> t end Values do not match: val f : (module s) -> t/2 -> t is not included in val f : (module s/2) -> t/2 -> t/2 The type (module s) -> t/2 -> t is not compatible with the type (module s/2) -> t/2 -> t/2 Type (module s) is not compatible with type (module s/2) Line 5, characters 23-33: Definition of type t Line 3, characters 2-12: Definition of type t/2 Line 5, characters 9-22: Definition of module type s Line 2, characters 2-15: Definition of module type s/2 |}] module P = struct module type a type a = A module M : sig val f: a -> (module a) -> a end = struct type a = B let f A _ = B end end;; [%%expect{| Line 5, characters 5-41: 5 | = struct type a = B let f A _ = B end ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: Signature mismatch: Modules do not match: sig type a = B val f : a/2 -> 'a -> a end is not included in sig val f : a -> (module a) -> a end Values do not match: val f : a/2 -> 'a -> a is not included in val f : a/2 -> (module a) -> a/2 The type a/2 -> (module a) -> a is not compatible with the type a/2 -> (module a) -> a/2 Type a is not compatible with type a/2 Line 5, characters 12-22: Definition of type a Line 3, characters 2-12: Definition of type a/2 |}] module Q = struct class a = object method m = () end module M: sig class b: a end = struct class a = object method c = let module X = struct type t end in () end class b = a end end;; [%%expect{| Lines 4-7, characters 2-5: 4 | ..struct 5 | class a = object method c = let module X = struct type t end in () end 6 | class b = a 7 | end Error: Signature mismatch: Modules do not match: sig class a : object method c : unit end class b : a end is not included in sig class b : a end Class declarations do not match: class b : a does not match class b : a/2 The public method c cannot be hidden The first class type has no method m Line 5, characters 4-74: Definition of class type a Line 2, characters 2-36: Definition of class type a/2 |}] module R = struct class type a = object method m: unit end module M: sig class type b= a end = struct class type a = object end class type b = a end end;; [%%expect{| Lines 4-7, characters 2-5: 4 | ..struct 5 | class type a = object end 6 | class type b = a 7 | end Error: Signature mismatch: Modules do not match: sig class type a = object end class type b = a end is not included in sig class type b = a end Class type declarations do not match: class type b = a does not match class type b = a/2 The first class type has no method m Line 5, characters 4-29: Definition of class type a Line 2, characters 2-42: Definition of class type a/2 |}] module S = struct class a= object end class b = a end;; [%%expect{| module S : sig class a : object end class b : a end |}] module X: sig type t class type a = object method m:t end module K: sig type t class type c = object method m: t end end end = struct type t class type a = object method m:t end module K = struct type t class type c = object inherit a end end end;; [%%expect{| Lines 8-15, characters 6-3: 8 | ......struct 9 | type t 10 | class type a = object method m:t end 11 | module K = struct 12 | type t 13 | class type c = object inherit a end 14 | end 15 | end.. Error: Signature mismatch: Modules do not match: sig type t class type a = object method m : t end module K : sig type t class type c = object method m : t/2 end end end is not included in sig type t class type a = object method m : t end module K : sig type t class type c = object method m : t end end end In module K: Modules do not match: sig type t = K.t class type c = object method m : t/2 end end is not included in sig type t class type c = object method m : t end end In module K: Class type declarations do not match: class type c = object method m : t/2 end does not match class type c = object method m : t end The method m has type t/2 but is expected to have type t Type t/2 is not equal to type t = K.t Line 12, characters 4-10: Definition of type t Line 9, characters 2-8: Definition of type t/2 |}] ;; module rec M: sig type t type a = M.t end = struct type t module M = struct type t end type a = M.t end;; [%%expect{| Line 2, characters 0-59: 2 | struct type t module M = struct type t end type a = M.t end;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: Signature mismatch: Modules do not match: sig type t = M.t module M : sig type t = M.M.t end type a = M.t end is not included in sig type t type a = M.t end Type declarations do not match: type a = M.t is not included in type a = M/2.t The type M.t = M/2.M.t is not equal to the type M/2.t Line 2, characters 14-42: Definition of module M File "_none_", line 1: Definition of module M/2 |}] (** Multiple redefinition of t *) type t = A;; type t = B;; type t = C;; type t = D;; module M: sig val f: t -> t -> t -> t end = struct let f A B C = D end;; [%%expect {| type t = A type t = B type t = C type t = D Lines 5-7, characters 44-3: 5 | ............................................struct 6 | let f A B C = D 7 | end.. Error: Signature mismatch: Modules do not match: sig val f : t/4 -> t/3 -> t/2 -> t end is not included in sig val f : t -> t -> t -> t end Values do not match: val f : t/4 -> t/3 -> t/2 -> t is not included in val f : t -> t -> t -> t The type t/4 -> t/3 -> t/2 -> t is not compatible with the type t -> t -> t -> t Type t/4 is not compatible with type t Line 4, characters 0-10: Definition of type t Line 3, characters 0-10: Definition of type t/2 Line 2, characters 0-10: Definition of type t/3 Line 1, characters 0-10: Definition of type t/4 |}] (** Check interaction with no-alias-deps *) module Foo = struct type info = { doc : unit } type t = { info : info } end let add_extra_info arg = arg.Foo.info.doc [%%expect {| module Foo : sig type info = { doc : unit; } type t = { info : info; } end Line 5, characters 38-41: 5 | let add_extra_info arg = arg.Foo.info.doc ^^^ Warning 40 [name-out-of-scope]: doc was selected from type Foo.info. It is not visible in the current scope, and will not be selected if the type becomes unknown. val add_extra_info : Foo.t -> unit = <fun> |}] (** Check type-directed disambiguation *) module Bar = struct type info = { doc : unit } end;; module Foo = struct type t = { info : Bar.info } end;; module Bar = struct end;; let add_extra_info arg = arg.Foo.info.doc [%%expect{| module Bar : sig type info = { doc : unit; } end module Foo : sig type t = { info : Bar.info; } end module Bar : sig end Line 8, characters 38-41: 8 | let add_extra_info arg = arg.Foo.info.doc ^^^ Warning 40 [name-out-of-scope]: doc was selected from type Bar/2.info. It is not visible in the current scope, and will not be selected if the type becomes unknown. val add_extra_info : Foo.t -> unit = <fun> |}]
null
https://raw.githubusercontent.com/ocaml/ocaml/d71ea3d089ae3c338b8b6e2fb7beb08908076c7a/testsuite/tests/typing-misc/pr6416.ml
ocaml
TEST flags="-no-alias-deps -w +40" * expect * Multiple redefinition of t * Check interaction with no-alias-deps * Check type-directed disambiguation
module M = struct type t = A module M : sig val f : t -> unit end = struct type t = B let f B = () end end;; [%%expect{| Lines 5-8, characters 8-5: 5 | ........struct 6 | type t = B 7 | let f B = () 8 | end Error: Signature mismatch: Modules do not match: sig type t = B val f : t -> unit end is not included in sig val f : t -> unit end Values do not match: val f : t -> unit is not included in val f : t/2 -> unit The type t -> unit is not compatible with the type t/2 -> unit Type t is not compatible with type t/2 Line 6, characters 4-14: Definition of type t Line 2, characters 2-12: Definition of type t/2 |}] module N = struct type t= A module M: sig type u = A of t end = struct type t = B type u = A of t end end;; [%%expect{| Line 4, characters 2-39: 4 | struct type t = B type u = A of t end ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: Signature mismatch: Modules do not match: sig type t = B type u = A of t end is not included in sig type u = A of t end Type declarations do not match: type u = A of t is not included in type u = A of t/2 Constructors do not match: A of t is not the same as: A of t The type t is not equal to the type t/2 Line 4, characters 9-19: Definition of type t Line 2, characters 2-11: Definition of type t/2 |}] module K = struct module type s module M: sig module A:functor(X:s) -> sig end end = struct module type s module A(X:s) =struct end end end;; [%%expect{| Lines 4-7, characters 4-7: 4 | ....struct 5 | module type s 6 | module A(X:s) =struct end 7 | end Error: Signature mismatch: Modules do not match: sig module type s module A : functor (X : s) -> sig end end is not included in sig module A : functor (X : s) -> sig end end In module A: Modules do not match: functor (X : s) -> ... is not included in functor (X : s/2) -> ... Module types do not match: s does not include s/2 Line 5, characters 6-19: Definition of module type s Line 2, characters 2-15: Definition of module type s/2 |}] module L = struct module T = struct type t end module M: sig type t = A of T.t end = struct module T = struct type t end type t = A of T.t end end;; [%%expect {| Lines 4-7, characters 4-7: 4 | ....struct 5 | module T = struct type t end 6 | type t = A of T.t 7 | end Error: Signature mismatch: Modules do not match: sig module T : sig type t end type t = A of T.t end is not included in sig type t = A of T.t end Type declarations do not match: type t = A of T.t is not included in type t = A of T/2.t Constructors do not match: A of T.t is not the same as: A of T.t The type T.t is not equal to the type T/2.t Line 5, characters 6-34: Definition of module T Line 2, characters 2-30: Definition of module T/2 |}] module O = struct module type s type t = A module M: sig val f: (module s) -> t -> t end = struct module type s type t = B let f (module X:s) A = B end end;; [%%expect{| Line 5, characters 2-62: 5 | struct module type s type t = B let f (module X:s) A = B end ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: Signature mismatch: Modules do not match: sig module type s type t = B val f : (module s) -> t/2 -> t end is not included in sig val f : (module s) -> t -> t end Values do not match: val f : (module s) -> t/2 -> t is not included in val f : (module s/2) -> t/2 -> t/2 The type (module s) -> t/2 -> t is not compatible with the type (module s/2) -> t/2 -> t/2 Type (module s) is not compatible with type (module s/2) Line 5, characters 23-33: Definition of type t Line 3, characters 2-12: Definition of type t/2 Line 5, characters 9-22: Definition of module type s Line 2, characters 2-15: Definition of module type s/2 |}] module P = struct module type a type a = A module M : sig val f: a -> (module a) -> a end = struct type a = B let f A _ = B end end;; [%%expect{| Line 5, characters 5-41: 5 | = struct type a = B let f A _ = B end ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: Signature mismatch: Modules do not match: sig type a = B val f : a/2 -> 'a -> a end is not included in sig val f : a -> (module a) -> a end Values do not match: val f : a/2 -> 'a -> a is not included in val f : a/2 -> (module a) -> a/2 The type a/2 -> (module a) -> a is not compatible with the type a/2 -> (module a) -> a/2 Type a is not compatible with type a/2 Line 5, characters 12-22: Definition of type a Line 3, characters 2-12: Definition of type a/2 |}] module Q = struct class a = object method m = () end module M: sig class b: a end = struct class a = object method c = let module X = struct type t end in () end class b = a end end;; [%%expect{| Lines 4-7, characters 2-5: 4 | ..struct 5 | class a = object method c = let module X = struct type t end in () end 6 | class b = a 7 | end Error: Signature mismatch: Modules do not match: sig class a : object method c : unit end class b : a end is not included in sig class b : a end Class declarations do not match: class b : a does not match class b : a/2 The public method c cannot be hidden The first class type has no method m Line 5, characters 4-74: Definition of class type a Line 2, characters 2-36: Definition of class type a/2 |}] module R = struct class type a = object method m: unit end module M: sig class type b= a end = struct class type a = object end class type b = a end end;; [%%expect{| Lines 4-7, characters 2-5: 4 | ..struct 5 | class type a = object end 6 | class type b = a 7 | end Error: Signature mismatch: Modules do not match: sig class type a = object end class type b = a end is not included in sig class type b = a end Class type declarations do not match: class type b = a does not match class type b = a/2 The first class type has no method m Line 5, characters 4-29: Definition of class type a Line 2, characters 2-42: Definition of class type a/2 |}] module S = struct class a= object end class b = a end;; [%%expect{| module S : sig class a : object end class b : a end |}] module X: sig type t class type a = object method m:t end module K: sig type t class type c = object method m: t end end end = struct type t class type a = object method m:t end module K = struct type t class type c = object inherit a end end end;; [%%expect{| Lines 8-15, characters 6-3: 8 | ......struct 9 | type t 10 | class type a = object method m:t end 11 | module K = struct 12 | type t 13 | class type c = object inherit a end 14 | end 15 | end.. Error: Signature mismatch: Modules do not match: sig type t class type a = object method m : t end module K : sig type t class type c = object method m : t/2 end end end is not included in sig type t class type a = object method m : t end module K : sig type t class type c = object method m : t end end end In module K: Modules do not match: sig type t = K.t class type c = object method m : t/2 end end is not included in sig type t class type c = object method m : t end end In module K: Class type declarations do not match: class type c = object method m : t/2 end does not match class type c = object method m : t end The method m has type t/2 but is expected to have type t Type t/2 is not equal to type t = K.t Line 12, characters 4-10: Definition of type t Line 9, characters 2-8: Definition of type t/2 |}] ;; module rec M: sig type t type a = M.t end = struct type t module M = struct type t end type a = M.t end;; [%%expect{| Line 2, characters 0-59: 2 | struct type t module M = struct type t end type a = M.t end;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Error: Signature mismatch: Modules do not match: sig type t = M.t module M : sig type t = M.M.t end type a = M.t end is not included in sig type t type a = M.t end Type declarations do not match: type a = M.t is not included in type a = M/2.t The type M.t = M/2.M.t is not equal to the type M/2.t Line 2, characters 14-42: Definition of module M File "_none_", line 1: Definition of module M/2 |}] type t = A;; type t = B;; type t = C;; type t = D;; module M: sig val f: t -> t -> t -> t end = struct let f A B C = D end;; [%%expect {| type t = A type t = B type t = C type t = D Lines 5-7, characters 44-3: 5 | ............................................struct 6 | let f A B C = D 7 | end.. Error: Signature mismatch: Modules do not match: sig val f : t/4 -> t/3 -> t/2 -> t end is not included in sig val f : t -> t -> t -> t end Values do not match: val f : t/4 -> t/3 -> t/2 -> t is not included in val f : t -> t -> t -> t The type t/4 -> t/3 -> t/2 -> t is not compatible with the type t -> t -> t -> t Type t/4 is not compatible with type t Line 4, characters 0-10: Definition of type t Line 3, characters 0-10: Definition of type t/2 Line 2, characters 0-10: Definition of type t/3 Line 1, characters 0-10: Definition of type t/4 |}] module Foo = struct type info = { doc : unit } type t = { info : info } end let add_extra_info arg = arg.Foo.info.doc [%%expect {| module Foo : sig type info = { doc : unit; } type t = { info : info; } end Line 5, characters 38-41: 5 | let add_extra_info arg = arg.Foo.info.doc ^^^ Warning 40 [name-out-of-scope]: doc was selected from type Foo.info. It is not visible in the current scope, and will not be selected if the type becomes unknown. val add_extra_info : Foo.t -> unit = <fun> |}] module Bar = struct type info = { doc : unit } end;; module Foo = struct type t = { info : Bar.info } end;; module Bar = struct end;; let add_extra_info arg = arg.Foo.info.doc [%%expect{| module Bar : sig type info = { doc : unit; } end module Foo : sig type t = { info : Bar.info; } end module Bar : sig end Line 8, characters 38-41: 8 | let add_extra_info arg = arg.Foo.info.doc ^^^ Warning 40 [name-out-of-scope]: doc was selected from type Bar/2.info. It is not visible in the current scope, and will not be selected if the type becomes unknown. val add_extra_info : Foo.t -> unit = <fun> |}]
970a34bbfe56d66075a48c0587862573210dd60e617a361c734fe3231ba39f7f
softwarelanguageslab/maf
R5RS_various_letrec-begin-4.scm
; Changes: * removed : 0 * added : 0 * swaps : 1 ; * negated predicates: 0 ; * swapped branches: 0 * calls to i d fun : 1 (letrec ((h (lambda () (<change> () ((lambda (x) x) ())))) (i 1) (res (begin (<change> (h) i) (<change> i (h))))) res)
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_various_letrec-begin-4.scm
scheme
Changes: * negated predicates: 0 * swapped branches: 0
* removed : 0 * added : 0 * swaps : 1 * calls to i d fun : 1 (letrec ((h (lambda () (<change> () ((lambda (x) x) ())))) (i 1) (res (begin (<change> (h) i) (<change> i (h))))) res)
4233d20043316ff93fb74c1a035bd9cb180b11e11576085e2d87f66c68d79c58
tweag/asterius
T11607.hs
# LANGUAGE ApplicativeDo # # LANGUAGE GeneralizedNewtypeDeriving # newtype MaybeA a = MaybeA (Maybe a) deriving (Show, Functor, Applicative) main :: IO () main = print $ do x <- MaybeA $ Just 42 pure x
null
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/ado/T11607.hs
haskell
# LANGUAGE ApplicativeDo # # LANGUAGE GeneralizedNewtypeDeriving # newtype MaybeA a = MaybeA (Maybe a) deriving (Show, Functor, Applicative) main :: IO () main = print $ do x <- MaybeA $ Just 42 pure x
9407b40a8c531ebd1f2bb373458c345e5cb42ca2b56b55d425f2eee9e23ebd34
gordonpace/contractLarva
Parsing.hs
Copyright 2017 and -- Licensed under the Apache License , Version 2.0 ( the " License " ) ; -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- -2.0 -- -- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. module DEA.Parsing ( module Parseable, module DEA.DEA ) where import Data.List import Control.Monad hiding (guard) import Text.Parsec hiding (State, label) import Text.Parsec.String import Parseable import Solidity import DEA.DEA -- ------------------------------------ readComment :: Parser () readComment = try (string "//" *> manyTill anyChar (eof <|> (newline *> return ())) *> return ()) <|> (string "/*" *> manyTill anyChar (string "*/") *> return ()) whitespace :: Parser () whitespace = void $ many ((space *> return ()) <|> readComment) endOfWord :: Parser () endOfWord = eof <|> notFollowedBy (alphaNum <|> char '_') readIdentifier :: Parser String readIdentifier = (:) <$> (letter <|> char '_') <*> many (alphaNum <|> char '_') <* endOfWord readKeyword :: String -> Parser String readKeyword word = string word <* endOfWord readAnyKeyword :: Parser String readAnyKeyword = many letter <* endOfWord commaSep1 :: Parser a -> Parser [a] commaSep1 p = do x <- p <* whitespace xs <- many (char ',' *> whitespace *> p <* whitespace) return (x:xs) instance Parseable Specification where display = intercalate "\n" . map display . contractSpecifications parser = whitespace *> (Specification <$> (many parser <* whitespace)) <* eof instance Parseable ContractSpecification where display monitor = unlines $ [ "monitor " ++ display (contractName monitor) ++ " {" , "declarations {" ] ++ map display (declarations monitor) ++ [ "}" , "initialisation ", display (initialisation monitor) , "reparation ", display (reparation monitor) , "satisfaction ", display (satisfaction monitor) ] ++ map display (deas monitor) ++ ["}"] where indentLineList = map (" "++) indentLines line = concat [ if (c=='\n') then "\n " else [c] | c <- line ] parser = do _contractName <- readKeyword "monitor" *> whitespace *> parser <* whitespace <* char '{' <* whitespace _declarations <- (try ( readKeyword "declarations" *> whitespace *> char '{' *> whitespace *> many (parser <* whitespace) <* char '}' ) <|> return []) <* whitespace _initialisation <- (try (readKeyword "initialisation" *> whitespace *> parser) <|> return (Block [])) <* whitespace _reparation <- (try (readKeyword "reparation" *> whitespace *> parser) <|> return (Block [])) <* whitespace _satisfaction <- (try (readKeyword "satisfaction" *> whitespace *> parser) <|> return (Block [])) <* whitespace _deas <- many (parser <* whitespace) _ <- char '}' return $ ContractSpecification { contractName = _contractName, declarations = _declarations, initialisation = _initialisation, satisfaction = _satisfaction, reparation = _reparation, deas = _deas } instance Parseable DEA where parser = do _deaName <- readKeyword "DEA" *> whitespace *> readIdentifier <* whitespace <* char '{' <* whitespace (_allStates, _initialStates, _badStates, _acceptanceStates) <- readStates <* whitespace _transitions <- readKeyword "transitions" *> whitespace *> char '{' *> whitespace *> many (parser <* whitespace) <* char '}' <* whitespace _ <- char '}' <* whitespace return DEA { deaName = _deaName, allStates = _allStates, initialStates = _initialStates, transitions = _transitions, badStates = _badStates, acceptanceStates = _acceptanceStates } where readStates = processStates <$> ( readKeyword "states" *> whitespace *> char '{' *> whitespace *> many ( do s <- parser <* whitespace t <- ((char ':' *> whitespace *> readStateTag) <|> return "") <* whitespace <* char ';' <* whitespace return (s,t) ) <* char '}' ) where processStates :: [(State, String)] -> ([State],[State], [State], [State]) processStates stateList = (allStates, initialStates, badStates, acceptanceStates) where allStates = map fst stateList initialStates = [ s | (s,"initial") <- stateList ] badStates = [ s | (s,"bad") <- stateList ] acceptanceStates = [ s | (s,"accept") <- stateList ] display dea = unlines $ [ "DEA "++deaName dea ++" {" , " states {" ] ++ [ " " ++ display state ++ describe state ++ ";" | state <- allStates dea ] ++ [ " }" , " transitions {" ] ++ [ " " ++ display t++";" | t <- transitions dea ] ++ [ " }" , "}" ] where describe state | null keywords = "" | otherwise = ": "++intercalate ", " keywords where keywords = ["initial" | state == initialState dea]++ ["bad" | state `elem` badStates dea]++ ["accept" | state `elem` acceptanceStates dea] instance Parseable State where parser = State <$> readAnyKeyword display = unState readStateTag :: Parser String readStateTag = choice $ map readKeyword ["initial", "bad", "accept"] instance Parseable Transition where parser = do _src <- parser <* whitespace _label <- string "-[" *> whitespace *> parser <* whitespace <* string "]->" <* whitespace _dst <- parser <* whitespace <* char ';' return Transition { src = _src, dst = _dst, label = _label } display transition = display (src transition)++" -["++display (label transition)++"]-> "++display (dst transition) instance Parseable GCL where parser = do _event <- parser <* whitespace _guard <- ( try (Just <$> (char '|' *> whitespace *> parser)) <|> try (const Nothing <$> char '|') <|> return Nothing ) <* whitespace _action <- ( try (Just <$> (string "~>" *> whitespace *> parser)) <|> try (const Nothing <$> string "~>") <|> return Nothing ) return GCL { event = _event, guard = _guard, action = _action } display rule = concat $ [ display (event rule) ] ++ [ " | (" ++display c++")" | Just c <- [guard rule] ] ++ [ " ~> {"++lineDisplay a++"}" | Just a <- [action rule]] instance Parseable Event where parser = try (UponEntry <$> (readKeyword "before" *> whitespace *> char '(' *> whitespace *> parser <* whitespace <* char ')')) <|> try (UponExit <$> (readKeyword "after" *> whitespace *> char '(' *> whitespace *> parser <* whitespace <* char ')')) <|> try ((readKeyword "beforetransfer" <* whitespace *> return BeforeTransfer)) <|> try ((readKeyword "aftertransfer" <* whitespace *> return AfterTransfer)) <|> try ((readKeyword "beforeselfdestruct" <* whitespace *> return BeforeSelfDestruct)) <|> try ((readKeyword "afterselfdestruct" <* whitespace *> return AfterSelfDestruct)) <|> (VariableAssignment <$> (parser <* whitespace <* char '@' <* whitespace <* char '(' <* whitespace) <*> (try (Just <$> parser <* whitespace <* char ')') <|> return Nothing) ) display (UponEntry fn) = "before("++display fn++")" display (UponExit fn) = "after("++display fn++")" display (BeforeTransfer) = "beforetransfer" display (AfterTransfer) = "aftertransfer" display (BeforeSelfDestruct) = "beforeselfdestruct" display (AfterSelfDestruct) = "afterselfdestruct" display (VariableAssignment vn e) = display vn ++maybe "" (\e -> "@("++display e++")") e instance Parseable FunctionCall where parser = do fn <- parser <* whitespace maybe_el <- parser return (FunctionCall { functionName = fn, parametersPassed = maybe_el }) display fc = display (functionName fc) ++ maybe "" display (parametersPassed fc)
null
https://raw.githubusercontent.com/gordonpace/contractLarva/5a2febd1c9ba4763b30def3a96bb07f2fef8a9dc/src/DEA/Parsing.hs
haskell
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------
Copyright 2017 and Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , module DEA.Parsing ( module Parseable, module DEA.DEA ) where import Data.List import Control.Monad hiding (guard) import Text.Parsec hiding (State, label) import Text.Parsec.String import Parseable import Solidity import DEA.DEA readComment :: Parser () readComment = try (string "//" *> manyTill anyChar (eof <|> (newline *> return ())) *> return ()) <|> (string "/*" *> manyTill anyChar (string "*/") *> return ()) whitespace :: Parser () whitespace = void $ many ((space *> return ()) <|> readComment) endOfWord :: Parser () endOfWord = eof <|> notFollowedBy (alphaNum <|> char '_') readIdentifier :: Parser String readIdentifier = (:) <$> (letter <|> char '_') <*> many (alphaNum <|> char '_') <* endOfWord readKeyword :: String -> Parser String readKeyword word = string word <* endOfWord readAnyKeyword :: Parser String readAnyKeyword = many letter <* endOfWord commaSep1 :: Parser a -> Parser [a] commaSep1 p = do x <- p <* whitespace xs <- many (char ',' *> whitespace *> p <* whitespace) return (x:xs) instance Parseable Specification where display = intercalate "\n" . map display . contractSpecifications parser = whitespace *> (Specification <$> (many parser <* whitespace)) <* eof instance Parseable ContractSpecification where display monitor = unlines $ [ "monitor " ++ display (contractName monitor) ++ " {" , "declarations {" ] ++ map display (declarations monitor) ++ [ "}" , "initialisation ", display (initialisation monitor) , "reparation ", display (reparation monitor) , "satisfaction ", display (satisfaction monitor) ] ++ map display (deas monitor) ++ ["}"] where indentLineList = map (" "++) indentLines line = concat [ if (c=='\n') then "\n " else [c] | c <- line ] parser = do _contractName <- readKeyword "monitor" *> whitespace *> parser <* whitespace <* char '{' <* whitespace _declarations <- (try ( readKeyword "declarations" *> whitespace *> char '{' *> whitespace *> many (parser <* whitespace) <* char '}' ) <|> return []) <* whitespace _initialisation <- (try (readKeyword "initialisation" *> whitespace *> parser) <|> return (Block [])) <* whitespace _reparation <- (try (readKeyword "reparation" *> whitespace *> parser) <|> return (Block [])) <* whitespace _satisfaction <- (try (readKeyword "satisfaction" *> whitespace *> parser) <|> return (Block [])) <* whitespace _deas <- many (parser <* whitespace) _ <- char '}' return $ ContractSpecification { contractName = _contractName, declarations = _declarations, initialisation = _initialisation, satisfaction = _satisfaction, reparation = _reparation, deas = _deas } instance Parseable DEA where parser = do _deaName <- readKeyword "DEA" *> whitespace *> readIdentifier <* whitespace <* char '{' <* whitespace (_allStates, _initialStates, _badStates, _acceptanceStates) <- readStates <* whitespace _transitions <- readKeyword "transitions" *> whitespace *> char '{' *> whitespace *> many (parser <* whitespace) <* char '}' <* whitespace _ <- char '}' <* whitespace return DEA { deaName = _deaName, allStates = _allStates, initialStates = _initialStates, transitions = _transitions, badStates = _badStates, acceptanceStates = _acceptanceStates } where readStates = processStates <$> ( readKeyword "states" *> whitespace *> char '{' *> whitespace *> many ( do s <- parser <* whitespace t <- ((char ':' *> whitespace *> readStateTag) <|> return "") <* whitespace <* char ';' <* whitespace return (s,t) ) <* char '}' ) where processStates :: [(State, String)] -> ([State],[State], [State], [State]) processStates stateList = (allStates, initialStates, badStates, acceptanceStates) where allStates = map fst stateList initialStates = [ s | (s,"initial") <- stateList ] badStates = [ s | (s,"bad") <- stateList ] acceptanceStates = [ s | (s,"accept") <- stateList ] display dea = unlines $ [ "DEA "++deaName dea ++" {" , " states {" ] ++ [ " " ++ display state ++ describe state ++ ";" | state <- allStates dea ] ++ [ " }" , " transitions {" ] ++ [ " " ++ display t++";" | t <- transitions dea ] ++ [ " }" , "}" ] where describe state | null keywords = "" | otherwise = ": "++intercalate ", " keywords where keywords = ["initial" | state == initialState dea]++ ["bad" | state `elem` badStates dea]++ ["accept" | state `elem` acceptanceStates dea] instance Parseable State where parser = State <$> readAnyKeyword display = unState readStateTag :: Parser String readStateTag = choice $ map readKeyword ["initial", "bad", "accept"] instance Parseable Transition where parser = do _src <- parser <* whitespace _label <- string "-[" *> whitespace *> parser <* whitespace <* string "]->" <* whitespace _dst <- parser <* whitespace <* char ';' return Transition { src = _src, dst = _dst, label = _label } display transition = display (src transition)++" -["++display (label transition)++"]-> "++display (dst transition) instance Parseable GCL where parser = do _event <- parser <* whitespace _guard <- ( try (Just <$> (char '|' *> whitespace *> parser)) <|> try (const Nothing <$> char '|') <|> return Nothing ) <* whitespace _action <- ( try (Just <$> (string "~>" *> whitespace *> parser)) <|> try (const Nothing <$> string "~>") <|> return Nothing ) return GCL { event = _event, guard = _guard, action = _action } display rule = concat $ [ display (event rule) ] ++ [ " | (" ++display c++")" | Just c <- [guard rule] ] ++ [ " ~> {"++lineDisplay a++"}" | Just a <- [action rule]] instance Parseable Event where parser = try (UponEntry <$> (readKeyword "before" *> whitespace *> char '(' *> whitespace *> parser <* whitespace <* char ')')) <|> try (UponExit <$> (readKeyword "after" *> whitespace *> char '(' *> whitespace *> parser <* whitespace <* char ')')) <|> try ((readKeyword "beforetransfer" <* whitespace *> return BeforeTransfer)) <|> try ((readKeyword "aftertransfer" <* whitespace *> return AfterTransfer)) <|> try ((readKeyword "beforeselfdestruct" <* whitespace *> return BeforeSelfDestruct)) <|> try ((readKeyword "afterselfdestruct" <* whitespace *> return AfterSelfDestruct)) <|> (VariableAssignment <$> (parser <* whitespace <* char '@' <* whitespace <* char '(' <* whitespace) <*> (try (Just <$> parser <* whitespace <* char ')') <|> return Nothing) ) display (UponEntry fn) = "before("++display fn++")" display (UponExit fn) = "after("++display fn++")" display (BeforeTransfer) = "beforetransfer" display (AfterTransfer) = "aftertransfer" display (BeforeSelfDestruct) = "beforeselfdestruct" display (AfterSelfDestruct) = "afterselfdestruct" display (VariableAssignment vn e) = display vn ++maybe "" (\e -> "@("++display e++")") e instance Parseable FunctionCall where parser = do fn <- parser <* whitespace maybe_el <- parser return (FunctionCall { functionName = fn, parametersPassed = maybe_el }) display fc = display (functionName fc) ++ maybe "" display (parametersPassed fc)
649e8e062f20083e5698218e840088a09c7f567439ed818694ced6780d8ea519
themetaschemer/malt
A-scalar-ops.rkt
#lang racket (require (only-in "../tensors.rkt" ext1-ρ ext2-ρ)) (require "../autodiff.rkt") (define +-0-0 (prim2 + (λ (a b z) (values z z)))) (define --0-0 (prim2 - (λ (a b z) (values z (- z))))) (define *-0-0 (prim2 * (λ (a b z) (values (* b z) (* a z))))) (define /-0-0 (prim2 / (λ (a b z) (values (* z (/ 1 b)) (* z (/ (- a) (* b b))))))) (define expt-0-0 (prim2 expt (λ (a b z) (values (* z (* b (expt a (- b 1)))) (* z (* (expt a b) (log a))))))) (define exp-0 (prim1 exp (λ (a z) (* z (exp a))))) (define log-0 (prim1 log (λ (a z) (* z (/ 1 a))))) (define sqrt-0 (prim1 sqrt (λ (x z) (/ z (* 2 (sqrt x)))))) (define abs-0-ρ (λ (x) (cond ((< x 0) (* -1 x)) (else x)))) (define abs-0-∇ (λ (x z) (cond ((< x 0) (- z)) (else z)))) (define abs-0 (prim1 abs-0-ρ abs-0-∇)) (define rectify-0-ρ (λ (s) (cond ((< s 0.0) 0.0) (else s)))) (define rectify-0-∇ (λ (s z) (cond ((< s 0.0) 0.0) (else z)))) (define rectify-shape (λ (s) s)) (define rectify-0 (prim1 rectify-0-ρ rectify-0-∇ rectify-shape)) ;;------------------------------------ ;; differentiable extended functions. ;;------------------------------------ (define d* (ext2 *-0-0 0 0)) (define d+ (ext2 +-0-0 0 0)) (define d- (ext2 --0-0 0 0)) (define d/ (ext2 /-0-0 0 0)) (define d-expt (ext2 expt-0-0 0 0)) (define d-exp (ext1 exp-0 0)) (define d-log (ext1 log-0 0)) (define d-abs (ext1 abs-0 0)) (define d-rectify (ext1 rectify-0 0)) (define d-sqrt (ext1 sqrt-0 0)) (define d-sqr (λ (x) (d* x x))) ;;------------------------------------ ;; non-differentiable extended functions. ;;------------------------------------ (define *-ρ (ext2-ρ * 0 0)) (define +-ρ (ext2-ρ + 0 0)) (define --ρ (ext2-ρ - 0 0)) (define /-ρ (ext2-ρ / 0 0)) (define expt-ρ (ext2-ρ expt 0 0)) (define exp-ρ (ext1-ρ exp 0)) (define log-ρ (ext1-ρ log 0)) (define abs-ρ (ext1-ρ abs-0-ρ 0)) (define rectify-ρ (ext1-ρ rectify-0-ρ 0)) (define sqrt-ρ (λ (a) (expt-ρ a 1/2))) (define sqr-ρ (λ (x) (*-ρ x x))) (include "test/test-A-scalar-ops.rkt") (provide +-0-0 --0-0 *-0-0 /-0-0 expt-0-0 exp-0 log-0 abs-0 rectify-0 sqrt-0 d+ d- d* d/ d-expt d-exp d-log d-abs d-rectify d-sqrt d-sqr +-ρ --ρ *-ρ /-ρ expt-ρ exp-ρ log-ρ abs-ρ rectify-ρ sqrt-ρ sqr-ρ)
null
https://raw.githubusercontent.com/themetaschemer/malt/c5adcf5022677cf109e96f93b574d6f107f367bb/flat-tensors/ext-ops/A-scalar-ops.rkt
racket
------------------------------------ differentiable extended functions. ------------------------------------ ------------------------------------ non-differentiable extended functions. ------------------------------------
#lang racket (require (only-in "../tensors.rkt" ext1-ρ ext2-ρ)) (require "../autodiff.rkt") (define +-0-0 (prim2 + (λ (a b z) (values z z)))) (define --0-0 (prim2 - (λ (a b z) (values z (- z))))) (define *-0-0 (prim2 * (λ (a b z) (values (* b z) (* a z))))) (define /-0-0 (prim2 / (λ (a b z) (values (* z (/ 1 b)) (* z (/ (- a) (* b b))))))) (define expt-0-0 (prim2 expt (λ (a b z) (values (* z (* b (expt a (- b 1)))) (* z (* (expt a b) (log a))))))) (define exp-0 (prim1 exp (λ (a z) (* z (exp a))))) (define log-0 (prim1 log (λ (a z) (* z (/ 1 a))))) (define sqrt-0 (prim1 sqrt (λ (x z) (/ z (* 2 (sqrt x)))))) (define abs-0-ρ (λ (x) (cond ((< x 0) (* -1 x)) (else x)))) (define abs-0-∇ (λ (x z) (cond ((< x 0) (- z)) (else z)))) (define abs-0 (prim1 abs-0-ρ abs-0-∇)) (define rectify-0-ρ (λ (s) (cond ((< s 0.0) 0.0) (else s)))) (define rectify-0-∇ (λ (s z) (cond ((< s 0.0) 0.0) (else z)))) (define rectify-shape (λ (s) s)) (define rectify-0 (prim1 rectify-0-ρ rectify-0-∇ rectify-shape)) (define d* (ext2 *-0-0 0 0)) (define d+ (ext2 +-0-0 0 0)) (define d- (ext2 --0-0 0 0)) (define d/ (ext2 /-0-0 0 0)) (define d-expt (ext2 expt-0-0 0 0)) (define d-exp (ext1 exp-0 0)) (define d-log (ext1 log-0 0)) (define d-abs (ext1 abs-0 0)) (define d-rectify (ext1 rectify-0 0)) (define d-sqrt (ext1 sqrt-0 0)) (define d-sqr (λ (x) (d* x x))) (define *-ρ (ext2-ρ * 0 0)) (define +-ρ (ext2-ρ + 0 0)) (define --ρ (ext2-ρ - 0 0)) (define /-ρ (ext2-ρ / 0 0)) (define expt-ρ (ext2-ρ expt 0 0)) (define exp-ρ (ext1-ρ exp 0)) (define log-ρ (ext1-ρ log 0)) (define abs-ρ (ext1-ρ abs-0-ρ 0)) (define rectify-ρ (ext1-ρ rectify-0-ρ 0)) (define sqrt-ρ (λ (a) (expt-ρ a 1/2))) (define sqr-ρ (λ (x) (*-ρ x x))) (include "test/test-A-scalar-ops.rkt") (provide +-0-0 --0-0 *-0-0 /-0-0 expt-0-0 exp-0 log-0 abs-0 rectify-0 sqrt-0 d+ d- d* d/ d-expt d-exp d-log d-abs d-rectify d-sqrt d-sqr +-ρ --ρ *-ρ /-ρ expt-ρ exp-ρ log-ρ abs-ρ rectify-ρ sqrt-ρ sqr-ρ)
759a2c50f207d8d395e8c3c29aeaa7436782e3e545be6a349f0b4bd1c8b59be5
mneedham/ranking-algorithms
glicko.clj
(ns ranking-algorithms.glicko (:require [clojure.math.numeric-tower :as math])) (defn as-glicko-opposition [{ goals-for :for goals-against :against ranking :points rd :rd}] {:opponent-ranking ranking :opponent-ranking-rd rd :score (cond (> goals-for goals-against) 1 (< goals-for goals-against) 0 :else 0.5)}) (defn initial-rankings [teams] (apply array-map (mapcat (fn [x] [x {:points 1500.00 :rd 350.00}]) teams))) (defn tidy [team] (if (= "Rànger's" team) "Rangers" team)) (def q (/ (java.lang.Math/log 10) 400)) (defn g [rd] (/ 1 (java.lang.Math/sqrt (+ 1 (/ (* 3 (math/expt q 2) (math/expt rd 2)) (math/expt ( . Math PI) 2)))))) (defn e [rating opponent-rating opponent-rd] (/ 1 (+ 1 (math/expt 10 (/ (* (- (g opponent-rd)) (- rating opponent-rating)) 400))))) (defn process-opponent [total opponent] (let [{:keys [g e]} opponent] (+ total (* (math/expt g 2) e (- 1 e))))) (defn d2 [opponents] (/ 1 (* (math/expt q 2) (reduce process-opponent 0 opponents)))) (defn update-ranking [ranking-delta opponent] (let [{:keys [ranking opponent-ranking opponent-ranking-rd score]} opponent] (+ ranking-delta (* (g opponent-ranking-rd) (- score (e ranking opponent-ranking opponent-ranking-rd)))))) (defn g-and-e [ranking {o-rd :opponent-ranking-rd o-ranking :opponent-ranking}] {:g (g o-rd) :e (e ranking o-ranking o-rd)}) (defn ranking-after-round [{ ranking :ranking rd :ranking-rd opponents :opponents}] (+ ranking (* (/ q (+ (/ 1 (math/expt rd 2)) (/ 1 (d2 (map (partial g-and-e ranking) opponents))))) (reduce update-ranking 0 (map #(assoc-in % [:ranking] ranking) opponents))))) (defn rd-after-round [{ ranking :ranking rd :ranking-rd opponents :opponents}] (java.lang.Math/sqrt (/ 1 (+ (/ 1 (math/expt rd 2)) (/ 1 (d2 (map (partial g-and-e ranking) opponents))))))) (defn c [rd t] (java.lang.Math/sqrt (/ (- (math/expt 350 2) (math/expt rd 2)) t))) (defn updated-rd [old-rd c t] (min (java.lang.Math/sqrt (+ (math/expt old-rd 2) (* (math/expt c 2) t))) 350.00)) (defn process-match [ts match] (let [{:keys [home away home_score away_score]} match] (-> ts (update-in [home :points] #(ranking-after-round {:ranking % :ranking-rd (:rd (get ts home)) :opponent-ranking (:points (get ts away)) :opponent-ranking-td (:rd (get ts away))})))))
null
https://raw.githubusercontent.com/mneedham/ranking-algorithms/30d300170f60f24663c3d377ce68565427a42cb4/src/ranking_algorithms/glicko.clj
clojure
(ns ranking-algorithms.glicko (:require [clojure.math.numeric-tower :as math])) (defn as-glicko-opposition [{ goals-for :for goals-against :against ranking :points rd :rd}] {:opponent-ranking ranking :opponent-ranking-rd rd :score (cond (> goals-for goals-against) 1 (< goals-for goals-against) 0 :else 0.5)}) (defn initial-rankings [teams] (apply array-map (mapcat (fn [x] [x {:points 1500.00 :rd 350.00}]) teams))) (defn tidy [team] (if (= "Rànger's" team) "Rangers" team)) (def q (/ (java.lang.Math/log 10) 400)) (defn g [rd] (/ 1 (java.lang.Math/sqrt (+ 1 (/ (* 3 (math/expt q 2) (math/expt rd 2)) (math/expt ( . Math PI) 2)))))) (defn e [rating opponent-rating opponent-rd] (/ 1 (+ 1 (math/expt 10 (/ (* (- (g opponent-rd)) (- rating opponent-rating)) 400))))) (defn process-opponent [total opponent] (let [{:keys [g e]} opponent] (+ total (* (math/expt g 2) e (- 1 e))))) (defn d2 [opponents] (/ 1 (* (math/expt q 2) (reduce process-opponent 0 opponents)))) (defn update-ranking [ranking-delta opponent] (let [{:keys [ranking opponent-ranking opponent-ranking-rd score]} opponent] (+ ranking-delta (* (g opponent-ranking-rd) (- score (e ranking opponent-ranking opponent-ranking-rd)))))) (defn g-and-e [ranking {o-rd :opponent-ranking-rd o-ranking :opponent-ranking}] {:g (g o-rd) :e (e ranking o-ranking o-rd)}) (defn ranking-after-round [{ ranking :ranking rd :ranking-rd opponents :opponents}] (+ ranking (* (/ q (+ (/ 1 (math/expt rd 2)) (/ 1 (d2 (map (partial g-and-e ranking) opponents))))) (reduce update-ranking 0 (map #(assoc-in % [:ranking] ranking) opponents))))) (defn rd-after-round [{ ranking :ranking rd :ranking-rd opponents :opponents}] (java.lang.Math/sqrt (/ 1 (+ (/ 1 (math/expt rd 2)) (/ 1 (d2 (map (partial g-and-e ranking) opponents))))))) (defn c [rd t] (java.lang.Math/sqrt (/ (- (math/expt 350 2) (math/expt rd 2)) t))) (defn updated-rd [old-rd c t] (min (java.lang.Math/sqrt (+ (math/expt old-rd 2) (* (math/expt c 2) t))) 350.00)) (defn process-match [ts match] (let [{:keys [home away home_score away_score]} match] (-> ts (update-in [home :points] #(ranking-after-round {:ranking % :ranking-rd (:rd (get ts home)) :opponent-ranking (:points (get ts away)) :opponent-ranking-td (:rd (get ts away))})))))
77ae72889e963a4c8768cae6e287e46b529fc9e93ad7563902569b2bb5fa3994
korya/efuns
bytegen.mli
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ I d : bytegen.mli , v 1.1 2000/05/22 08:54:53 (* Generation of bytecode from lambda terms *) open Lambda open Instruct val compile_implementation: string -> lambda -> instruction list val compile_phrase: lambda -> instruction list * instruction list
null
https://raw.githubusercontent.com/korya/efuns/78b21d9dff45b7eec764c63132c7a564f5367c30/ocamlsrc/compat/2.04/include/bytegen.mli
ocaml
********************************************************************* Objective Caml ********************************************************************* Generation of bytecode from lambda terms
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ I d : bytegen.mli , v 1.1 2000/05/22 08:54:53 open Lambda open Instruct val compile_implementation: string -> lambda -> instruction list val compile_phrase: lambda -> instruction list * instruction list
f48abd3ac5c3cb57c2d9e3da5d66aa025deaf5484244090cf4a95d4430406440
simingwang/emqx-plugin-kafkav5
dtls_connection.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2013 - 2022 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% -module(dtls_connection). %%---------------------------------------------------------------------- %% Purpose: DTLS-1-DTLS-1.2 FSM (* = optional) %%---------------------------------------------------------------------- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% For UDP transport the following flights are used as retransmission units %% in case of package loss. Flight timers are handled in state entry functions. %% %% Client Server %% ------ ------ %% ClientHello -------- > Flight 1 %% %% <------- HelloVerifyRequest Flight 2 %% ClientHello -------- > Flight 3 %% ServerHello \ %% Certificate* \ %% ServerKeyExchange* Flight 4 CertificateRequest * / %% <-------- ServerHelloDone / %% %% Certificate* \ ClientKeyExchange \ CertificateVerify * Flight 5 [ ChangeCipherSpec ] / %% Finished --------> / %% %% [ChangeCipherSpec] \ Flight 6 %% <-------- Finished / %% Message Flights for Full Handshake %% %% %% ------ ------ %% ClientHello -------- > Abbrev Flight 1 %% ServerHello \ part 1 [ ChangeCipherSpec ] Abbrev Flight 2 < -------- Finished / part 2 %% [ ChangeCipherSpec ] \ Abbrev Flight 3 %% Finished --------> / %% %% Message Flights for Abbbriviated Handshake %%---------------------------------------------------------------------- %% Start FSM ---> CONFIG_ERROR %% Send error to user %% | and shutdown %% | %% V %% INITIAL_HELLO %% %% | Send/ Recv Flight 1 %% | %% | %% USER_HELLO | %% <- Possibly let user provide V %% options after looking at hello ex -> HELLO | Send Recv Flight 2 to Flight 4 or | Flight 1 to Abbrev Flight 2 part 1 %% | %% New session | Resumed session WAIT_OCSP_STAPELING < ---------------------------------- > ABBRIVIATED %% %% <- Possibly Receive -- | | OCSP Stapel ------ > | Send/ Recv Flight 5 | %% | | V | Send / Recv Abbrev Flight part 2 | to Flight 3 CIPHER | %% | | | Send/ Recv Flight 6 | %% | | %% V V %% ---------------------------------------------------- %% | %% | %% V %% CONNECTION %% | %% V %% GO BACK TO HELLO %%---------------------------------------------------------------------- Internal application API -behaviour(gen_statem). -include_lib("public_key/include/public_key.hrl"). -include_lib("kernel/include/logger.hrl"). -include("dtls_connection.hrl"). -include("dtls_handshake.hrl"). -include("ssl_alert.hrl"). -include("dtls_record.hrl"). -include("ssl_cipher.hrl"). -include("ssl_api.hrl"). -include("ssl_internal.hrl"). -include("ssl_srp.hrl"). Internal application API %% Setup -export([init/1]). -export([renegotiate/2]). -export([alert_or_reset_connection/3]). %% Code re-use from dtls_gen_connection. %% gen_statem state functions -export([initial_hello/3, config_error/3, downgrade/3, hello/3, user_hello/3, wait_ocsp_stapling/3, certify/3, cipher/3, abbreviated/3, connection/3]). %% gen_statem callbacks -export([callback_mode/0, terminate/3, code_change/4, format_status/2]). %%==================================================================== Internal application API %%==================================================================== %%==================================================================== %% Setup %%==================================================================== init([Role, Host, Port, Socket, Options, User, CbInfo]) -> process_flag(trap_exit, true), State0 = #state{protocol_specific = Map} = initial_state(Role, Host, Port, Socket, Options, User, CbInfo), try State = ssl_gen_statem:ssl_config(State0#state.ssl_options, Role, State0), gen_statem:enter_loop(?MODULE, [], initial_hello, State) catch throw:Error -> EState = State0#state{protocol_specific = Map#{error => Error}}, gen_statem:enter_loop(?MODULE, [], config_error, EState) end. %%==================================================================== %% Handshake %%==================================================================== renegotiate(#state{static_env = #static_env{role = client}} = State0, Actions) -> %% Handle same way as if server requested %% the renegotiation State = dtls_gen_connection:reinit_handshake_data(State0), {next_state, connection, State, [{next_event, internal, #hello_request{}} | Actions]}; renegotiate(#state{static_env = #static_env{role = server}} = State0, Actions) -> HelloRequest = ssl_handshake:hello_request(), State1 = prepare_flight(State0), {State, MoreActions} = dtls_gen_connection:send_handshake(HelloRequest, State1), dtls_gen_connection:next_event(hello, no_record, State, Actions ++ MoreActions). %%-------------------------------------------------------------------- State functions %%-------------------------------------------------------------------- %%-------------------------------------------------------------------- -spec initial_hello(gen_statem:event_type(), {start, timeout()} | term(), #state{}) -> gen_statem:state_function_result(). %%-------------------------------------------------------------------- initial_hello(enter, _, State) -> {keep_state, State}; initial_hello({call, From}, {start, Timeout}, #state{static_env = #static_env{host = Host, port = Port, role = client, socket = {_, Socket}, transport_cb = Transport, session_cache = Cache, session_cache_cb = CacheCb}, protocol_specific = PS, handshake_env = #handshake_env{renegotiation = {Renegotiation, _}}, connection_env = #connection_env{cert_key_pairs = CertKeyPairs} = CEnv, ssl_options = #{versions := Versions} = SslOpts, session = Session0, connection_states = ConnectionStates0 } = State0) -> Packages = maps:get(active_n, PS), dtls_socket:setopts(Transport, Socket, [{active,Packages}]), Session = ssl_session:client_select_session({Host, Port, SslOpts}, Cache, CacheCb, Session0, CertKeyPairs), Hello = dtls_handshake:client_hello(Host, Port, ConnectionStates0, SslOpts, Session#session.session_id, Renegotiation), MaxFragEnum = maps:get(max_frag_enum, Hello#client_hello.extensions, undefined), ConnectionStates1 = ssl_record:set_max_fragment_length(MaxFragEnum, ConnectionStates0), Version = Hello#client_hello.client_version, HelloVersion = dtls_record:hello_version(Version, Versions), State1 = prepare_flight(State0#state{connection_env = CEnv#connection_env{negotiated_version = Version}, connection_states = ConnectionStates1}), {State2, Actions} = dtls_gen_connection:send_handshake(Hello, State1#state{connection_env = CEnv#connection_env{negotiated_version = HelloVersion}}), RequestedVersion session = Session, start_or_recv_from = From, protocol_specific = PS#{active_n_toggle := false} }, dtls_gen_connection:next_event(hello, no_record, State, [{{timeout, handshake}, Timeout, close} | Actions]); initial_hello({call, _} = Type, Event, #state{static_env = #static_env{role = server}, protocol_specific = PS0} = State) -> PS = PS0#{current_cookie_secret => dtls_v1:cookie_secret(), previous_cookie_secret => <<>>}, Result = ssl_gen_statem:?FUNCTION_NAME(Type, Event, State#state{protocol_specific = PS}), erlang:send_after(dtls_v1:cookie_timeout(), self(), new_cookie_secret), Result; initial_hello(Type, Event, State) -> ssl_gen_statem:?FUNCTION_NAME(Type, Event, State). %%-------------------------------------------------------------------- -spec config_error(gen_statem:event_type(), {start, timeout()} | term(), #state{}) -> gen_statem:state_function_result(). %%-------------------------------------------------------------------- config_error(enter, _, State) -> {keep_state, State}; config_error(Type, Event, State) -> ssl_gen_statem:?FUNCTION_NAME(Type, Event, State). %%-------------------------------------------------------------------- -spec hello(gen_statem:event_type(), #hello_request{} | #client_hello{} | #server_hello{} | term(), #state{}) -> gen_statem:state_function_result(). %%-------------------------------------------------------------------- hello(enter, _, #state{static_env = #static_env{role = server}} = State) -> {keep_state, State}; hello(enter, _, #state{static_env = #static_env{role = client}} = State0) -> {State, Actions} = handle_flight_timer(State0), {keep_state, State, Actions}; hello(internal, #client_hello{cookie = <<>>, client_version = Version} = Hello, #state{static_env = #static_env{role = server, transport_cb = Transport, socket = Socket}, handshake_env = HsEnv, connection_env = CEnv, protocol_specific = #{current_cookie_secret := Secret}} = State0) -> try tls_dtls_connection:handle_sni_extension(State0, Hello) of #state{} = State1 -> {ok, {IP, Port}} = dtls_socket:peername(Transport, Socket), Cookie = dtls_handshake:cookie(Secret, IP, Port, Hello), FROM RFC 6347 regarding HelloVerifyRequest message : The server_version field has the same syntax as in TLS . However , in %% order to avoid the requirement to do version negotiation in the initial handshake , DTLS 1.2 server implementations SHOULD use DTLS version 1.0 regardless of the version of TLS that is expected to be %% negotiated. VerifyRequest = dtls_handshake:hello_verify_request(Cookie, ?HELLO_VERIFY_REQUEST_VERSION), State2 = prepare_flight(State1#state{connection_env = CEnv#connection_env{negotiated_version = Version}}), {State, Actions} = dtls_gen_connection:send_handshake(VerifyRequest, State2), dtls_gen_connection:next_event(?FUNCTION_NAME, no_record, State#state{handshake_env = HsEnv#handshake_env{ tls_handshake_history = ssl_handshake:init_handshake_history()}}, Actions) catch throw:#alert{} = Alert -> alert_or_reset_connection(Alert, ?FUNCTION_NAME, State0) end; hello(internal, #hello_verify_request{cookie = Cookie}, #state{static_env = #static_env{role = client, host = Host, port = Port}, handshake_env = #handshake_env{renegotiation = {Renegotiation, _}, ocsp_stapling_state = OcspState0} = HsEnv, connection_env = CEnv, ssl_options = #{ocsp_stapling := OcspStaplingOpt, ocsp_nonce := OcspNonceOpt} = SslOpts, session = #session{session_id = Id}, connection_states = ConnectionStates0, protocol_specific = PS } = State0) -> OcspNonce = tls_handshake:ocsp_nonce(OcspNonceOpt, OcspStaplingOpt), Hello = dtls_handshake:client_hello(Host, Port, Cookie, ConnectionStates0, SslOpts, Id, Renegotiation, OcspNonce), Version = Hello#client_hello.client_version, State1 = prepare_flight(State0#state{handshake_env = HsEnv#handshake_env{tls_handshake_history = ssl_handshake:init_handshake_history(), ocsp_stapling_state = OcspState0#{ocsp_nonce => OcspNonce}}}), {State2, Actions} = dtls_gen_connection:send_handshake(Hello, State1), RequestedVersion protocol_specific = PS#{current_cookie_secret => Cookie} }, dtls_gen_connection:next_event(?FUNCTION_NAME, no_record, State, Actions); hello(internal, #client_hello{extensions = Extensions} = Hello, #state{ssl_options = #{handshake := hello}, handshake_env = HsEnv, start_or_recv_from = From} = State0) -> try tls_dtls_connection:handle_sni_extension(State0, Hello) of #state{} = State -> {next_state, user_hello, State#state{start_or_recv_from = undefined, handshake_env = HsEnv#handshake_env{hello = Hello}}, [{reply, From, {ok, Extensions}}]} catch throw:#alert{} = Alert -> alert_or_reset_connection(Alert, ?FUNCTION_NAME, State0) end; hello(internal, #client_hello{cookie = Cookie} = Hello, #state{static_env = #static_env{role = server, transport_cb = Transport, socket = Socket}, protocol_specific = #{current_cookie_secret := Secret, previous_cookie_secret := PSecret} } = State) -> {ok, {IP, Port}} = dtls_socket:peername(Transport, Socket), case dtls_handshake:cookie(Secret, IP, Port, Hello) of Cookie -> handle_client_hello(Hello, State); _ -> case dtls_handshake:cookie(PSecret, IP, Port, Hello) of Cookie -> handle_client_hello(Hello, State); _ -> Handle bad cookie as new cookie request RFC 6347 4.1.2 hello(internal, Hello#client_hello{cookie = <<>>}, State) end end; hello(internal, #server_hello{extensions = Extensions} = Hello, #state{ssl_options = #{ handshake := hello}, handshake_env = HsEnv, start_or_recv_from = From} = State) -> {next_state, user_hello, State#state{start_or_recv_from = undefined, handshake_env = HsEnv#handshake_env{ hello = Hello}}, [{reply, From, {ok, Extensions}}]}; hello(internal, #server_hello{} = Hello, #state{ static_env = #static_env{role = client}, handshake_env = #handshake_env{ renegotiation = {Renegotiation, _}, ocsp_stapling_state = OcspState0} = HsEnv, connection_states = ConnectionStates0, session = #session{session_id = OldId}, ssl_options = SslOptions} = State) -> try {Version, NewId, ConnectionStates, ProtoExt, Protocol, OcspState} = dtls_handshake:hello(Hello, SslOptions, ConnectionStates0, Renegotiation, OldId), tls_dtls_connection:handle_session(Hello, Version, NewId, ConnectionStates, ProtoExt, Protocol, State#state{handshake_env = HsEnv#handshake_env{ ocsp_stapling_state = maps:merge(OcspState0,OcspState)}}) catch throw:#alert{} = Alert -> ssl_gen_statem:handle_own_alert(Alert, ?FUNCTION_NAME, State) end; hello(internal, {handshake, {#client_hello{cookie = <<>>} = Handshake, _}}, State) -> %% Initial hello should not be in handshake history {next_state, ?FUNCTION_NAME, State, [{next_event, internal, Handshake}]}; hello(internal, {handshake, {#hello_verify_request{} = Handshake, _}}, State) -> %% hello_verify should not be in handshake history {next_state, ?FUNCTION_NAME, State, [{next_event, internal, Handshake}]}; hello(internal, #change_cipher_spec{type = <<1>>}, State0) -> {State1, Actions0} = dtls_gen_connection:send_handshake_flight(State0, retransmit_epoch(?FUNCTION_NAME, State0)), {next_state, ?FUNCTION_NAME, State, Actions} = dtls_gen_connection:next_event(?FUNCTION_NAME, no_record, State1, Actions0), %% This will reset the retransmission timer by repeating the enter state event {repeat_state, State, Actions}; hello(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); hello(state_timeout, Event, State) -> handle_state_timeout(Event, ?FUNCTION_NAME, State); hello(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). user_hello(enter, _, State) -> {keep_state, State}; user_hello(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). %%-------------------------------------------------------------------- -spec abbreviated(gen_statem:event_type(), term(), #state{}) -> gen_statem:state_function_result(). %%-------------------------------------------------------------------- abbreviated(enter, _, State0) -> {State, Actions} = handle_flight_timer(State0), {keep_state, State, Actions}; abbreviated(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); abbreviated(internal = Type, #change_cipher_spec{type = <<1>>} = Event, #state{connection_states = ConnectionStates0} = State) -> ConnectionStates1 = dtls_record:save_current_connection_state(ConnectionStates0, read), ConnectionStates = dtls_record:next_epoch(ConnectionStates1, read), gen_handshake(?FUNCTION_NAME, Type, Event, State#state{connection_states = ConnectionStates}); abbreviated(internal = Type, #finished{} = Event, #state{connection_states = ConnectionStates, protocol_specific = PS} = State) -> gen_handshake(?FUNCTION_NAME, Type, Event, prepare_flight(State#state{connection_states = ConnectionStates, protocol_specific = PS#{flight_state => connection}})); abbreviated(state_timeout, Event, State) -> handle_state_timeout(Event, ?FUNCTION_NAME, State); abbreviated(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). %%-------------------------------------------------------------------- -spec wait_ocsp_stapling(gen_statem:event_type(), term(), #state{}) -> gen_statem:state_function_result(). %%-------------------------------------------------------------------- wait_ocsp_stapling(enter, _Event, State0) -> {State, Actions} = handle_flight_timer(State0), {keep_state, State, Actions}; wait_ocsp_stapling(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); wait_ocsp_stapling(state_timeout, Event, State) -> handle_state_timeout(Event, ?FUNCTION_NAME, State); wait_ocsp_stapling(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). %%-------------------------------------------------------------------- -spec certify(gen_statem:event_type(), term(), #state{}) -> gen_statem:state_function_result(). %%-------------------------------------------------------------------- certify(enter, _, State0) -> {State, Actions} = handle_flight_timer(State0), {keep_state, State, Actions}; certify(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); certify(internal = Type, #server_hello_done{} = Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, prepare_flight(State)); certify(internal, #change_cipher_spec{type = <<1>>}, State0) -> {State1, Actions0} = dtls_gen_connection:send_handshake_flight(State0, retransmit_epoch(?FUNCTION_NAME, State0)), {next_state, ?FUNCTION_NAME, State, Actions} = dtls_gen_connection:next_event(?FUNCTION_NAME, no_record, State1, Actions0), %% This will reset the retransmission timer by repeating the enter state event {repeat_state, State, Actions}; certify(state_timeout, Event, State) -> handle_state_timeout(Event, ?FUNCTION_NAME, State); certify(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). %%-------------------------------------------------------------------- -spec cipher(gen_statem:event_type(), term(), #state{}) -> gen_statem:state_function_result(). %%-------------------------------------------------------------------- cipher(enter, _, State0) -> {State, Actions} = handle_flight_timer(State0), {keep_state, State, Actions}; cipher(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); cipher(internal = Type, #change_cipher_spec{type = <<1>>} = Event, #state{connection_states = ConnectionStates0} = State) -> ConnectionStates1 = dtls_record:save_current_connection_state(ConnectionStates0, read), ConnectionStates = dtls_record:next_epoch(ConnectionStates1, read), gen_handshake(?FUNCTION_NAME, Type, Event, State#state{connection_states = ConnectionStates}); cipher(internal = Type, #finished{} = Event, #state{connection_states = ConnectionStates, protocol_specific = PS} = State) -> gen_handshake(?FUNCTION_NAME, Type, Event, prepare_flight(State#state{connection_states = ConnectionStates, protocol_specific = PS#{flight_state => connection}})); cipher(state_timeout, Event, State) -> handle_state_timeout(Event, ?FUNCTION_NAME, State); cipher(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). %%-------------------------------------------------------------------- -spec connection(gen_statem:event_type(), #hello_request{} | #client_hello{}| term(), #state{}) -> gen_statem:state_function_result(). %%-------------------------------------------------------------------- connection(enter, _, #state{connection_states = Cs0} = State0) -> State = case maps:is_key(previous_cs, Cs0) of false -> State0; true -> Cs = maps:remove(previous_cs, Cs0), State0#state{connection_states = Cs} end, {keep_state, State}; connection(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); connection(internal, #hello_request{}, #state{static_env = #static_env{host = Host, port = Port, data_tag = DataTag, session_cache = Cache, session_cache_cb = CacheCb }, handshake_env = #handshake_env{renegotiation = {Renegotiation, _}}, connection_env = #connection_env{cert_key_pairs = CertKeyPairs} = CEnv, session = Session0, ssl_options = #{versions := Versions} = SslOpts, connection_states = ConnectionStates0, protocol_specific = PS } = State0) -> #{current_cookie_secret := Cookie} = PS, Session = ssl_session:client_select_session({Host, Port, SslOpts}, Cache, CacheCb, Session0, CertKeyPairs), Hello = dtls_handshake:client_hello(Host, Port, Cookie, ConnectionStates0, SslOpts, Session#session.session_id, Renegotiation, undefined), Version = Hello#client_hello.client_version, HelloVersion = dtls_record:hello_version(Version, Versions), State1 = prepare_flight(State0), {State2, Actions} = dtls_gen_connection:send_handshake(Hello, State1#state{connection_env = CEnv#connection_env{negotiated_version = HelloVersion}}), State = State2#state{protocol_specific = PS#{flight_state => dtls_gen_connection:initial_flight_state(DataTag)}, session = Session}, dtls_gen_connection:next_event(hello, no_record, State, Actions); connection(internal, #client_hello{} = Hello, #state{static_env = #static_env{role = server}, handshake_env = #handshake_env{allow_renegotiate = true} = HsEnv} = State) -> %% Mitigate Computational DoS attack %% %% -ssl-dos/ Rather than disabling client %% initiated renegotiation we will disallow many client initiated %% renegotiations immediately after each other. erlang:send_after(?WAIT_TO_ALLOW_RENEGOTIATION, self(), allow_renegotiate), {next_state, hello, State#state{handshake_env = HsEnv#handshake_env{renegotiation = {true, peer}, allow_renegotiate = false}}, [{next_event, internal, Hello}]}; connection(internal, #client_hello{}, #state{static_env = #static_env{role = server, protocol_cb = Connection}, handshake_env = #handshake_env{allow_renegotiate = false}} = State0) -> Alert = ?ALERT_REC(?WARNING, ?NO_RENEGOTIATION), State1 = dtls_gen_connection:send_alert(Alert, State0), {Record, State} = ssl_gen_statem:prepare_connection(State1, Connection), dtls_gen_connection:next_event(?FUNCTION_NAME, Record, State); connection(internal, new_connection, #state{ssl_options=SSLOptions, handshake_env=HsEnv, connection_states = OldCs} = State) -> case maps:get(previous_cs, OldCs, undefined) of undefined -> BeastMitigation = maps:get(beast_mitigation, SSLOptions, disabled), ConnectionStates0 = dtls_record:init_connection_states(server, BeastMitigation), ConnectionStates = ConnectionStates0#{previous_cs => OldCs}, {next_state, hello, State#state{handshake_env = HsEnv#handshake_env{renegotiation = {false, first}}, connection_states = ConnectionStates}}; _ -> %% Someone spamming new_connection, just drop them {keep_state, State} end; connection({call, From}, {application_data, Data}, State) -> try send_application_data(Data, From, ?FUNCTION_NAME, State) catch throw:Error -> ssl_gen_statem:hibernate_after(?FUNCTION_NAME, State, [{reply, From, Error}]) end; connection({call, From}, {downgrade, Pid}, #state{connection_env = CEnv, static_env = #static_env{transport_cb = Transport, socket = {_Server, Socket} = DTLSSocket}} = State) -> %% For testing purposes, downgrades without noticing the server dtls_socket:setopts(Transport, Socket, [{active, false}, {packet, 0}, {mode, binary}]), Transport:controlling_process(Socket, Pid), {stop_and_reply, {shutdown, normal}, {reply, From, {ok, DTLSSocket}}, State#state{connection_env = CEnv#connection_env{socket_terminated = true}}}; connection(Type, Event, State) -> try tls_dtls_connection:?FUNCTION_NAME(Type, Event, State) catch throw:#alert{}=Alert -> ssl_gen_statem:handle_own_alert(Alert, ?FUNCTION_NAME, State) end. TODO does this make sense for DTLS ? %%-------------------------------------------------------------------- -spec downgrade(gen_statem:event_type(), term(), #state{}) -> gen_statem:state_function_result(). %%-------------------------------------------------------------------- downgrade(enter, _, State) -> {keep_state, State}; downgrade(Type, Event, State) -> try tls_dtls_connection:?FUNCTION_NAME(Type, Event, State) catch throw:#alert{}=Alert -> ssl_gen_statem:handle_own_alert(Alert, ?FUNCTION_NAME, State) end. %%-------------------------------------------------------------------- %% gen_statem callbacks %%-------------------------------------------------------------------- callback_mode() -> [state_functions, state_enter]. terminate(Reason, StateName, State) -> ssl_gen_statem:terminate(Reason, StateName, State). code_change(_OldVsn, StateName, State, _Extra) -> {ok, StateName, State}. format_status(Type, Data) -> ssl_gen_statem:format_status(Type, Data). %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- initial_state(Role, Host, Port, Socket, {#{client_renegotiation := ClientRenegotiation} = SSLOptions, SocketOptions, Trackers}, User, {CbModule, DataTag, CloseTag, ErrorTag, PassiveTag}) -> BeastMitigation = maps:get(beast_mitigation, SSLOptions, disabled), ConnectionStates = dtls_record:init_connection_states(Role, BeastMitigation), #{session_cb := SessionCacheCb} = ssl_config:pre_1_3_session_opts(Role), InternalActiveN = ssl_config:get_internal_active_n(), Monitor = erlang:monitor(process, User), InitStatEnv = #static_env{ role = Role, transport_cb = CbModule, protocol_cb = dtls_gen_connection, data_tag = DataTag, close_tag = CloseTag, error_tag = ErrorTag, passive_tag = PassiveTag, host = Host, port = Port, socket = Socket, session_cache_cb = SessionCacheCb, trackers = Trackers }, #state{static_env = InitStatEnv, handshake_env = #handshake_env{ tls_handshake_history = ssl_handshake:init_handshake_history(), renegotiation = {false, first}, allow_renegotiate = ClientRenegotiation }, connection_env = #connection_env{user_application = {Monitor, User}}, socket_options = SocketOptions, %% We do not want to save the password in the state so that %% could be written in the clear into error logs. ssl_options = SSLOptions#{password => undefined}, session = #session{is_resumable = false}, connection_states = ConnectionStates, protocol_buffers = #protocol_buffers{}, user_data_buffer = {[],0,[]}, start_or_recv_from = undefined, flight_buffer = dtls_gen_connection:new_flight(), protocol_specific = #{active_n => InternalActiveN, active_n_toggle => true, flight_state => dtls_gen_connection:initial_flight_state(DataTag), ignored_alerts => 0, max_ignored_alerts => 10 } }. handle_client_hello(#client_hello{client_version = ClientVersion} = Hello, State0) -> try #state{connection_states = ConnectionStates0, static_env = #static_env{trackers = Trackers}, handshake_env = #handshake_env{kex_algorithm = KeyExAlg, renegotiation = {Renegotiation, _}, negotiated_protocol = CurrentProtocol} = HsEnv, connection_env = #connection_env{cert_key_pairs = CertKeyPairs} = CEnv, session = Session0, ssl_options = SslOpts} = tls_dtls_connection:handle_sni_extension(State0, Hello), SessionTracker = proplists:get_value(session_id_tracker, Trackers), {Version, {Type, Session}, ConnectionStates, Protocol0, ServerHelloExt, HashSign} = dtls_handshake:hello(Hello, SslOpts, {SessionTracker, Session0, ConnectionStates0, CertKeyPairs, KeyExAlg}, Renegotiation), Protocol = case Protocol0 of undefined -> CurrentProtocol; _ -> Protocol0 end, State = prepare_flight(State0#state{connection_states = ConnectionStates, connection_env = CEnv#connection_env{negotiated_version = Version}, handshake_env = HsEnv#handshake_env{ hashsign_algorithm = HashSign, client_hello_version = ClientVersion, negotiated_protocol = Protocol}, session = Session}), {next_state, hello, State, [{next_event, internal, {common_client_hello, Type, ServerHelloExt}}]} catch #alert{} = Alert -> alert_or_reset_connection(Alert, hello, State0) end. handle_state_timeout(flight_retransmission_timeout, StateName, #state{protocol_specific = #{flight_state := {retransmit, _NextTimeout}}} = State0) -> {State1, Actions0} = dtls_gen_connection:send_handshake_flight(State0, retransmit_epoch(StateName, State0)), {next_state, StateName, State, Actions} = dtls_gen_connection:next_event(StateName, no_record, State1, Actions0), %% This will reset the retransmission timer by repeating the enter state event {repeat_state, State, Actions}. alert_or_reset_connection(Alert, StateName, #state{connection_states = Cs} = State) -> case maps:get(previous_cs, Cs, undefined) of undefined -> ssl_gen_statem:handle_own_alert(Alert, StateName, State); PreviousConn -> %% There exists an old connection and the new one failed, %% reset to the old working one. %% The next alert will be sent HsEnv0 = State#state.handshake_env, HsEnv = HsEnv0#handshake_env{renegotiation = undefined}, NewState = State#state{connection_states = PreviousConn, handshake_env = HsEnv }, {next_state, connection, NewState} end. gen_handshake(StateName, Type, Event, State) -> try tls_dtls_connection:StateName(Type, Event, State) catch throw:#alert{}=Alert -> alert_or_reset_connection(Alert, StateName, State); error:_ -> Alert = ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE, malformed_handshake_data), alert_or_reset_connection(Alert, StateName, State) end. gen_info(Event, connection = StateName, State) -> try dtls_gen_connection:handle_info(Event, StateName, State) catch error:_ -> Alert = ?ALERT_REC(?FATAL, ?INTERNAL_ERROR, malformed_data), alert_or_reset_connection(Alert, StateName, State) end; gen_info(Event, StateName, State) -> try dtls_gen_connection:handle_info(Event, StateName, State) catch error:_ -> Alert = ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE,malformed_handshake_data), alert_or_reset_connection(Alert, StateName, State) end. prepare_flight(#state{flight_buffer = Flight, connection_states = ConnectionStates0, protocol_buffers = #protocol_buffers{} = Buffers} = State) -> ConnectionStates = dtls_record:save_current_connection_state(ConnectionStates0, write), State#state{flight_buffer = next_flight(Flight), connection_states = ConnectionStates, protocol_buffers = Buffers#protocol_buffers{ dtls_handshake_next_fragments = [], dtls_handshake_later_fragments = []}}. next_flight(Flight) -> Flight#{handshakes => [], change_cipher_spec => undefined, handshakes_after_change_cipher_spec => []}. handle_flight_timer(#state{static_env = #static_env{data_tag = udp}, protocol_specific = #{flight_state := {retransmit, Timeout}}} = State) -> start_retransmision_timer(Timeout, State); handle_flight_timer(#state{static_env = #static_env{data_tag = udp}, protocol_specific = #{flight_state := connection}} = State) -> {State, []}; handle_flight_timer(#state{protocol_specific = #{flight_state := reliable}} = State) -> No retransmision needed i.e DTLS over SCTP {State, []}. start_retransmision_timer(Timeout, #state{protocol_specific = PS} = State) -> {State#state{protocol_specific = PS#{flight_state => {retransmit, new_timeout(Timeout)}}}, [{state_timeout, Timeout, flight_retransmission_timeout}]}. new_timeout(N) when N =< 30000 -> N * 2; new_timeout(_) -> 60000. retransmit_epoch(_StateName, #state{connection_states = ConnectionStates}) -> #{epoch := Epoch} = ssl_record:current_connection_state(ConnectionStates, write), Epoch. send_application_data(Data, From, _StateName, #state{static_env = #static_env{socket = Socket, transport_cb = Transport}, connection_env = #connection_env{negotiated_version = Version}, handshake_env = HsEnv, connection_states = ConnectionStates0, ssl_options = #{renegotiate_at := RenegotiateAt, log_level := LogLevel}} = State0) -> case time_to_renegotiate(Data, ConnectionStates0, RenegotiateAt) of true -> renegotiate(State0#state{handshake_env = HsEnv#handshake_env{renegotiation = {true, internal}}}, [{next_event, {call, From}, {application_data, Data}}]); false -> {Msgs, ConnectionStates} = dtls_record:encode_data(Data, Version, ConnectionStates0), State = State0#state{connection_states = ConnectionStates}, case send_msgs(Transport, Socket, Msgs) of ok -> ssl_logger:debug(LogLevel, outbound, 'record', Msgs), ssl_gen_statem:hibernate_after(connection, State, [{reply, From, ok}]); Result -> ssl_gen_statem:hibernate_after(connection, State, [{reply, From, Result}]) end end. send_msgs(Transport, Socket, [Msg|Msgs]) -> case dtls_gen_connection:send(Transport, Socket, Msg) of ok -> send_msgs(Transport, Socket, Msgs); Error -> Error end; send_msgs(_, _, []) -> ok. time_to_renegotiate(_Data, #{current_write := #{sequence_number := Num}}, RenegotiateAt) -> %% We could do test: %% is_time_to_renegotiate((erlang:byte_size(_Data) div ? MAX_PLAIN_TEXT_LENGTH ) + 1 , RenegotiateAt ) , but we chose to %% have a some what lower renegotiateAt and a much cheaper test is_time_to_renegotiate(Num, RenegotiateAt). is_time_to_renegotiate(N, M) when N < M-> false; is_time_to_renegotiate(_,_) -> true.
null
https://raw.githubusercontent.com/simingwang/emqx-plugin-kafkav5/bbf919e56dbc8fd2d4c1c541084532f844a11cbc/_build/default/rel/emqx_plugin_kafka/lib/ssl-10.7/src/dtls_connection.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% ---------------------------------------------------------------------- Purpose: DTLS-1-DTLS-1.2 FSM (* = optional) ---------------------------------------------------------------------- in case of package loss. Flight timers are handled in state entry functions. Client Server ------ ------ <------- HelloVerifyRequest Flight 2 Certificate* \ ServerKeyExchange* Flight 4 <-------- ServerHelloDone / Certificate* \ Finished --------> / [ChangeCipherSpec] \ Flight 6 <-------- Finished / ------ ------ Finished --------> / ---------------------------------------------------------------------- Start FSM ---> CONFIG_ERROR Send error to user | and shutdown | V INITIAL_HELLO | Send/ Recv Flight 1 | | USER_HELLO | <- Possibly let user provide V options after looking at hello ex -> HELLO | New session | Resumed session <- Possibly Receive -- | | | | | | | | V V ---------------------------------------------------- | | V CONNECTION | V GO BACK TO HELLO ---------------------------------------------------------------------- Setup Code re-use from dtls_gen_connection. gen_statem state functions gen_statem callbacks ==================================================================== ==================================================================== ==================================================================== Setup ==================================================================== ==================================================================== Handshake ==================================================================== Handle same way as if server requested the renegotiation -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- order to avoid the requirement to do version negotiation in the negotiated. Initial hello should not be in handshake history hello_verify should not be in handshake history This will reset the retransmission timer by repeating the enter state event -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- This will reset the retransmission timer by repeating the enter state event -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- Mitigate Computational DoS attack -ssl-dos/ Rather than disabling client initiated renegotiation we will disallow many client initiated renegotiations immediately after each other. Someone spamming new_connection, just drop them For testing purposes, downgrades without noticing the server -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- gen_statem callbacks -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- We do not want to save the password in the state so that could be written in the clear into error logs. This will reset the retransmission timer by repeating the enter state event There exists an old connection and the new one failed, reset to the old working one. The next alert will be sent We could do test: is_time_to_renegotiate((erlang:byte_size(_Data) div have a some what lower renegotiateAt and a much cheaper test
Copyright Ericsson AB 2013 - 2022 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(dtls_connection). For UDP transport the following flights are used as retransmission units ClientHello -------- > Flight 1 ClientHello -------- > Flight 3 ServerHello \ CertificateRequest * / ClientKeyExchange \ CertificateVerify * Flight 5 [ ChangeCipherSpec ] / Message Flights for Full Handshake ClientHello -------- > Abbrev Flight 1 ServerHello \ part 1 [ ChangeCipherSpec ] Abbrev Flight 2 < -------- Finished / part 2 [ ChangeCipherSpec ] \ Abbrev Flight 3 Message Flights for Abbbriviated Handshake | Send Recv Flight 2 to Flight 4 or | Flight 1 to Abbrev Flight 2 part 1 WAIT_OCSP_STAPELING < ---------------------------------- > ABBRIVIATED OCSP Stapel ------ > | Send/ Recv Flight 5 | V | Send / Recv Abbrev Flight part 2 | to Flight 3 CIPHER | | Send/ Recv Flight 6 | Internal application API -behaviour(gen_statem). -include_lib("public_key/include/public_key.hrl"). -include_lib("kernel/include/logger.hrl"). -include("dtls_connection.hrl"). -include("dtls_handshake.hrl"). -include("ssl_alert.hrl"). -include("dtls_record.hrl"). -include("ssl_cipher.hrl"). -include("ssl_api.hrl"). -include("ssl_internal.hrl"). -include("ssl_srp.hrl"). Internal application API -export([init/1]). -export([renegotiate/2]). -export([initial_hello/3, config_error/3, downgrade/3, hello/3, user_hello/3, wait_ocsp_stapling/3, certify/3, cipher/3, abbreviated/3, connection/3]). -export([callback_mode/0, terminate/3, code_change/4, format_status/2]). Internal application API init([Role, Host, Port, Socket, Options, User, CbInfo]) -> process_flag(trap_exit, true), State0 = #state{protocol_specific = Map} = initial_state(Role, Host, Port, Socket, Options, User, CbInfo), try State = ssl_gen_statem:ssl_config(State0#state.ssl_options, Role, State0), gen_statem:enter_loop(?MODULE, [], initial_hello, State) catch throw:Error -> EState = State0#state{protocol_specific = Map#{error => Error}}, gen_statem:enter_loop(?MODULE, [], config_error, EState) end. renegotiate(#state{static_env = #static_env{role = client}} = State0, Actions) -> State = dtls_gen_connection:reinit_handshake_data(State0), {next_state, connection, State, [{next_event, internal, #hello_request{}} | Actions]}; renegotiate(#state{static_env = #static_env{role = server}} = State0, Actions) -> HelloRequest = ssl_handshake:hello_request(), State1 = prepare_flight(State0), {State, MoreActions} = dtls_gen_connection:send_handshake(HelloRequest, State1), dtls_gen_connection:next_event(hello, no_record, State, Actions ++ MoreActions). State functions -spec initial_hello(gen_statem:event_type(), {start, timeout()} | term(), #state{}) -> gen_statem:state_function_result(). initial_hello(enter, _, State) -> {keep_state, State}; initial_hello({call, From}, {start, Timeout}, #state{static_env = #static_env{host = Host, port = Port, role = client, socket = {_, Socket}, transport_cb = Transport, session_cache = Cache, session_cache_cb = CacheCb}, protocol_specific = PS, handshake_env = #handshake_env{renegotiation = {Renegotiation, _}}, connection_env = #connection_env{cert_key_pairs = CertKeyPairs} = CEnv, ssl_options = #{versions := Versions} = SslOpts, session = Session0, connection_states = ConnectionStates0 } = State0) -> Packages = maps:get(active_n, PS), dtls_socket:setopts(Transport, Socket, [{active,Packages}]), Session = ssl_session:client_select_session({Host, Port, SslOpts}, Cache, CacheCb, Session0, CertKeyPairs), Hello = dtls_handshake:client_hello(Host, Port, ConnectionStates0, SslOpts, Session#session.session_id, Renegotiation), MaxFragEnum = maps:get(max_frag_enum, Hello#client_hello.extensions, undefined), ConnectionStates1 = ssl_record:set_max_fragment_length(MaxFragEnum, ConnectionStates0), Version = Hello#client_hello.client_version, HelloVersion = dtls_record:hello_version(Version, Versions), State1 = prepare_flight(State0#state{connection_env = CEnv#connection_env{negotiated_version = Version}, connection_states = ConnectionStates1}), {State2, Actions} = dtls_gen_connection:send_handshake(Hello, State1#state{connection_env = CEnv#connection_env{negotiated_version = HelloVersion}}), RequestedVersion session = Session, start_or_recv_from = From, protocol_specific = PS#{active_n_toggle := false} }, dtls_gen_connection:next_event(hello, no_record, State, [{{timeout, handshake}, Timeout, close} | Actions]); initial_hello({call, _} = Type, Event, #state{static_env = #static_env{role = server}, protocol_specific = PS0} = State) -> PS = PS0#{current_cookie_secret => dtls_v1:cookie_secret(), previous_cookie_secret => <<>>}, Result = ssl_gen_statem:?FUNCTION_NAME(Type, Event, State#state{protocol_specific = PS}), erlang:send_after(dtls_v1:cookie_timeout(), self(), new_cookie_secret), Result; initial_hello(Type, Event, State) -> ssl_gen_statem:?FUNCTION_NAME(Type, Event, State). -spec config_error(gen_statem:event_type(), {start, timeout()} | term(), #state{}) -> gen_statem:state_function_result(). config_error(enter, _, State) -> {keep_state, State}; config_error(Type, Event, State) -> ssl_gen_statem:?FUNCTION_NAME(Type, Event, State). -spec hello(gen_statem:event_type(), #hello_request{} | #client_hello{} | #server_hello{} | term(), #state{}) -> gen_statem:state_function_result(). hello(enter, _, #state{static_env = #static_env{role = server}} = State) -> {keep_state, State}; hello(enter, _, #state{static_env = #static_env{role = client}} = State0) -> {State, Actions} = handle_flight_timer(State0), {keep_state, State, Actions}; hello(internal, #client_hello{cookie = <<>>, client_version = Version} = Hello, #state{static_env = #static_env{role = server, transport_cb = Transport, socket = Socket}, handshake_env = HsEnv, connection_env = CEnv, protocol_specific = #{current_cookie_secret := Secret}} = State0) -> try tls_dtls_connection:handle_sni_extension(State0, Hello) of #state{} = State1 -> {ok, {IP, Port}} = dtls_socket:peername(Transport, Socket), Cookie = dtls_handshake:cookie(Secret, IP, Port, Hello), FROM RFC 6347 regarding HelloVerifyRequest message : The server_version field has the same syntax as in TLS . However , in initial handshake , DTLS 1.2 server implementations SHOULD use DTLS version 1.0 regardless of the version of TLS that is expected to be VerifyRequest = dtls_handshake:hello_verify_request(Cookie, ?HELLO_VERIFY_REQUEST_VERSION), State2 = prepare_flight(State1#state{connection_env = CEnv#connection_env{negotiated_version = Version}}), {State, Actions} = dtls_gen_connection:send_handshake(VerifyRequest, State2), dtls_gen_connection:next_event(?FUNCTION_NAME, no_record, State#state{handshake_env = HsEnv#handshake_env{ tls_handshake_history = ssl_handshake:init_handshake_history()}}, Actions) catch throw:#alert{} = Alert -> alert_or_reset_connection(Alert, ?FUNCTION_NAME, State0) end; hello(internal, #hello_verify_request{cookie = Cookie}, #state{static_env = #static_env{role = client, host = Host, port = Port}, handshake_env = #handshake_env{renegotiation = {Renegotiation, _}, ocsp_stapling_state = OcspState0} = HsEnv, connection_env = CEnv, ssl_options = #{ocsp_stapling := OcspStaplingOpt, ocsp_nonce := OcspNonceOpt} = SslOpts, session = #session{session_id = Id}, connection_states = ConnectionStates0, protocol_specific = PS } = State0) -> OcspNonce = tls_handshake:ocsp_nonce(OcspNonceOpt, OcspStaplingOpt), Hello = dtls_handshake:client_hello(Host, Port, Cookie, ConnectionStates0, SslOpts, Id, Renegotiation, OcspNonce), Version = Hello#client_hello.client_version, State1 = prepare_flight(State0#state{handshake_env = HsEnv#handshake_env{tls_handshake_history = ssl_handshake:init_handshake_history(), ocsp_stapling_state = OcspState0#{ocsp_nonce => OcspNonce}}}), {State2, Actions} = dtls_gen_connection:send_handshake(Hello, State1), RequestedVersion protocol_specific = PS#{current_cookie_secret => Cookie} }, dtls_gen_connection:next_event(?FUNCTION_NAME, no_record, State, Actions); hello(internal, #client_hello{extensions = Extensions} = Hello, #state{ssl_options = #{handshake := hello}, handshake_env = HsEnv, start_or_recv_from = From} = State0) -> try tls_dtls_connection:handle_sni_extension(State0, Hello) of #state{} = State -> {next_state, user_hello, State#state{start_or_recv_from = undefined, handshake_env = HsEnv#handshake_env{hello = Hello}}, [{reply, From, {ok, Extensions}}]} catch throw:#alert{} = Alert -> alert_or_reset_connection(Alert, ?FUNCTION_NAME, State0) end; hello(internal, #client_hello{cookie = Cookie} = Hello, #state{static_env = #static_env{role = server, transport_cb = Transport, socket = Socket}, protocol_specific = #{current_cookie_secret := Secret, previous_cookie_secret := PSecret} } = State) -> {ok, {IP, Port}} = dtls_socket:peername(Transport, Socket), case dtls_handshake:cookie(Secret, IP, Port, Hello) of Cookie -> handle_client_hello(Hello, State); _ -> case dtls_handshake:cookie(PSecret, IP, Port, Hello) of Cookie -> handle_client_hello(Hello, State); _ -> Handle bad cookie as new cookie request RFC 6347 4.1.2 hello(internal, Hello#client_hello{cookie = <<>>}, State) end end; hello(internal, #server_hello{extensions = Extensions} = Hello, #state{ssl_options = #{ handshake := hello}, handshake_env = HsEnv, start_or_recv_from = From} = State) -> {next_state, user_hello, State#state{start_or_recv_from = undefined, handshake_env = HsEnv#handshake_env{ hello = Hello}}, [{reply, From, {ok, Extensions}}]}; hello(internal, #server_hello{} = Hello, #state{ static_env = #static_env{role = client}, handshake_env = #handshake_env{ renegotiation = {Renegotiation, _}, ocsp_stapling_state = OcspState0} = HsEnv, connection_states = ConnectionStates0, session = #session{session_id = OldId}, ssl_options = SslOptions} = State) -> try {Version, NewId, ConnectionStates, ProtoExt, Protocol, OcspState} = dtls_handshake:hello(Hello, SslOptions, ConnectionStates0, Renegotiation, OldId), tls_dtls_connection:handle_session(Hello, Version, NewId, ConnectionStates, ProtoExt, Protocol, State#state{handshake_env = HsEnv#handshake_env{ ocsp_stapling_state = maps:merge(OcspState0,OcspState)}}) catch throw:#alert{} = Alert -> ssl_gen_statem:handle_own_alert(Alert, ?FUNCTION_NAME, State) end; hello(internal, {handshake, {#client_hello{cookie = <<>>} = Handshake, _}}, State) -> {next_state, ?FUNCTION_NAME, State, [{next_event, internal, Handshake}]}; hello(internal, {handshake, {#hello_verify_request{} = Handshake, _}}, State) -> {next_state, ?FUNCTION_NAME, State, [{next_event, internal, Handshake}]}; hello(internal, #change_cipher_spec{type = <<1>>}, State0) -> {State1, Actions0} = dtls_gen_connection:send_handshake_flight(State0, retransmit_epoch(?FUNCTION_NAME, State0)), {next_state, ?FUNCTION_NAME, State, Actions} = dtls_gen_connection:next_event(?FUNCTION_NAME, no_record, State1, Actions0), {repeat_state, State, Actions}; hello(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); hello(state_timeout, Event, State) -> handle_state_timeout(Event, ?FUNCTION_NAME, State); hello(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). user_hello(enter, _, State) -> {keep_state, State}; user_hello(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). -spec abbreviated(gen_statem:event_type(), term(), #state{}) -> gen_statem:state_function_result(). abbreviated(enter, _, State0) -> {State, Actions} = handle_flight_timer(State0), {keep_state, State, Actions}; abbreviated(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); abbreviated(internal = Type, #change_cipher_spec{type = <<1>>} = Event, #state{connection_states = ConnectionStates0} = State) -> ConnectionStates1 = dtls_record:save_current_connection_state(ConnectionStates0, read), ConnectionStates = dtls_record:next_epoch(ConnectionStates1, read), gen_handshake(?FUNCTION_NAME, Type, Event, State#state{connection_states = ConnectionStates}); abbreviated(internal = Type, #finished{} = Event, #state{connection_states = ConnectionStates, protocol_specific = PS} = State) -> gen_handshake(?FUNCTION_NAME, Type, Event, prepare_flight(State#state{connection_states = ConnectionStates, protocol_specific = PS#{flight_state => connection}})); abbreviated(state_timeout, Event, State) -> handle_state_timeout(Event, ?FUNCTION_NAME, State); abbreviated(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). -spec wait_ocsp_stapling(gen_statem:event_type(), term(), #state{}) -> gen_statem:state_function_result(). wait_ocsp_stapling(enter, _Event, State0) -> {State, Actions} = handle_flight_timer(State0), {keep_state, State, Actions}; wait_ocsp_stapling(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); wait_ocsp_stapling(state_timeout, Event, State) -> handle_state_timeout(Event, ?FUNCTION_NAME, State); wait_ocsp_stapling(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). -spec certify(gen_statem:event_type(), term(), #state{}) -> gen_statem:state_function_result(). certify(enter, _, State0) -> {State, Actions} = handle_flight_timer(State0), {keep_state, State, Actions}; certify(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); certify(internal = Type, #server_hello_done{} = Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, prepare_flight(State)); certify(internal, #change_cipher_spec{type = <<1>>}, State0) -> {State1, Actions0} = dtls_gen_connection:send_handshake_flight(State0, retransmit_epoch(?FUNCTION_NAME, State0)), {next_state, ?FUNCTION_NAME, State, Actions} = dtls_gen_connection:next_event(?FUNCTION_NAME, no_record, State1, Actions0), {repeat_state, State, Actions}; certify(state_timeout, Event, State) -> handle_state_timeout(Event, ?FUNCTION_NAME, State); certify(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). -spec cipher(gen_statem:event_type(), term(), #state{}) -> gen_statem:state_function_result(). cipher(enter, _, State0) -> {State, Actions} = handle_flight_timer(State0), {keep_state, State, Actions}; cipher(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); cipher(internal = Type, #change_cipher_spec{type = <<1>>} = Event, #state{connection_states = ConnectionStates0} = State) -> ConnectionStates1 = dtls_record:save_current_connection_state(ConnectionStates0, read), ConnectionStates = dtls_record:next_epoch(ConnectionStates1, read), gen_handshake(?FUNCTION_NAME, Type, Event, State#state{connection_states = ConnectionStates}); cipher(internal = Type, #finished{} = Event, #state{connection_states = ConnectionStates, protocol_specific = PS} = State) -> gen_handshake(?FUNCTION_NAME, Type, Event, prepare_flight(State#state{connection_states = ConnectionStates, protocol_specific = PS#{flight_state => connection}})); cipher(state_timeout, Event, State) -> handle_state_timeout(Event, ?FUNCTION_NAME, State); cipher(Type, Event, State) -> gen_handshake(?FUNCTION_NAME, Type, Event, State). -spec connection(gen_statem:event_type(), #hello_request{} | #client_hello{}| term(), #state{}) -> gen_statem:state_function_result(). connection(enter, _, #state{connection_states = Cs0} = State0) -> State = case maps:is_key(previous_cs, Cs0) of false -> State0; true -> Cs = maps:remove(previous_cs, Cs0), State0#state{connection_states = Cs} end, {keep_state, State}; connection(info, Event, State) -> gen_info(Event, ?FUNCTION_NAME, State); connection(internal, #hello_request{}, #state{static_env = #static_env{host = Host, port = Port, data_tag = DataTag, session_cache = Cache, session_cache_cb = CacheCb }, handshake_env = #handshake_env{renegotiation = {Renegotiation, _}}, connection_env = #connection_env{cert_key_pairs = CertKeyPairs} = CEnv, session = Session0, ssl_options = #{versions := Versions} = SslOpts, connection_states = ConnectionStates0, protocol_specific = PS } = State0) -> #{current_cookie_secret := Cookie} = PS, Session = ssl_session:client_select_session({Host, Port, SslOpts}, Cache, CacheCb, Session0, CertKeyPairs), Hello = dtls_handshake:client_hello(Host, Port, Cookie, ConnectionStates0, SslOpts, Session#session.session_id, Renegotiation, undefined), Version = Hello#client_hello.client_version, HelloVersion = dtls_record:hello_version(Version, Versions), State1 = prepare_flight(State0), {State2, Actions} = dtls_gen_connection:send_handshake(Hello, State1#state{connection_env = CEnv#connection_env{negotiated_version = HelloVersion}}), State = State2#state{protocol_specific = PS#{flight_state => dtls_gen_connection:initial_flight_state(DataTag)}, session = Session}, dtls_gen_connection:next_event(hello, no_record, State, Actions); connection(internal, #client_hello{} = Hello, #state{static_env = #static_env{role = server}, handshake_env = #handshake_env{allow_renegotiate = true} = HsEnv} = State) -> erlang:send_after(?WAIT_TO_ALLOW_RENEGOTIATION, self(), allow_renegotiate), {next_state, hello, State#state{handshake_env = HsEnv#handshake_env{renegotiation = {true, peer}, allow_renegotiate = false}}, [{next_event, internal, Hello}]}; connection(internal, #client_hello{}, #state{static_env = #static_env{role = server, protocol_cb = Connection}, handshake_env = #handshake_env{allow_renegotiate = false}} = State0) -> Alert = ?ALERT_REC(?WARNING, ?NO_RENEGOTIATION), State1 = dtls_gen_connection:send_alert(Alert, State0), {Record, State} = ssl_gen_statem:prepare_connection(State1, Connection), dtls_gen_connection:next_event(?FUNCTION_NAME, Record, State); connection(internal, new_connection, #state{ssl_options=SSLOptions, handshake_env=HsEnv, connection_states = OldCs} = State) -> case maps:get(previous_cs, OldCs, undefined) of undefined -> BeastMitigation = maps:get(beast_mitigation, SSLOptions, disabled), ConnectionStates0 = dtls_record:init_connection_states(server, BeastMitigation), ConnectionStates = ConnectionStates0#{previous_cs => OldCs}, {next_state, hello, State#state{handshake_env = HsEnv#handshake_env{renegotiation = {false, first}}, connection_states = ConnectionStates}}; _ -> {keep_state, State} end; connection({call, From}, {application_data, Data}, State) -> try send_application_data(Data, From, ?FUNCTION_NAME, State) catch throw:Error -> ssl_gen_statem:hibernate_after(?FUNCTION_NAME, State, [{reply, From, Error}]) end; connection({call, From}, {downgrade, Pid}, #state{connection_env = CEnv, static_env = #static_env{transport_cb = Transport, socket = {_Server, Socket} = DTLSSocket}} = State) -> dtls_socket:setopts(Transport, Socket, [{active, false}, {packet, 0}, {mode, binary}]), Transport:controlling_process(Socket, Pid), {stop_and_reply, {shutdown, normal}, {reply, From, {ok, DTLSSocket}}, State#state{connection_env = CEnv#connection_env{socket_terminated = true}}}; connection(Type, Event, State) -> try tls_dtls_connection:?FUNCTION_NAME(Type, Event, State) catch throw:#alert{}=Alert -> ssl_gen_statem:handle_own_alert(Alert, ?FUNCTION_NAME, State) end. TODO does this make sense for DTLS ? -spec downgrade(gen_statem:event_type(), term(), #state{}) -> gen_statem:state_function_result(). downgrade(enter, _, State) -> {keep_state, State}; downgrade(Type, Event, State) -> try tls_dtls_connection:?FUNCTION_NAME(Type, Event, State) catch throw:#alert{}=Alert -> ssl_gen_statem:handle_own_alert(Alert, ?FUNCTION_NAME, State) end. callback_mode() -> [state_functions, state_enter]. terminate(Reason, StateName, State) -> ssl_gen_statem:terminate(Reason, StateName, State). code_change(_OldVsn, StateName, State, _Extra) -> {ok, StateName, State}. format_status(Type, Data) -> ssl_gen_statem:format_status(Type, Data). Internal functions initial_state(Role, Host, Port, Socket, {#{client_renegotiation := ClientRenegotiation} = SSLOptions, SocketOptions, Trackers}, User, {CbModule, DataTag, CloseTag, ErrorTag, PassiveTag}) -> BeastMitigation = maps:get(beast_mitigation, SSLOptions, disabled), ConnectionStates = dtls_record:init_connection_states(Role, BeastMitigation), #{session_cb := SessionCacheCb} = ssl_config:pre_1_3_session_opts(Role), InternalActiveN = ssl_config:get_internal_active_n(), Monitor = erlang:monitor(process, User), InitStatEnv = #static_env{ role = Role, transport_cb = CbModule, protocol_cb = dtls_gen_connection, data_tag = DataTag, close_tag = CloseTag, error_tag = ErrorTag, passive_tag = PassiveTag, host = Host, port = Port, socket = Socket, session_cache_cb = SessionCacheCb, trackers = Trackers }, #state{static_env = InitStatEnv, handshake_env = #handshake_env{ tls_handshake_history = ssl_handshake:init_handshake_history(), renegotiation = {false, first}, allow_renegotiate = ClientRenegotiation }, connection_env = #connection_env{user_application = {Monitor, User}}, socket_options = SocketOptions, ssl_options = SSLOptions#{password => undefined}, session = #session{is_resumable = false}, connection_states = ConnectionStates, protocol_buffers = #protocol_buffers{}, user_data_buffer = {[],0,[]}, start_or_recv_from = undefined, flight_buffer = dtls_gen_connection:new_flight(), protocol_specific = #{active_n => InternalActiveN, active_n_toggle => true, flight_state => dtls_gen_connection:initial_flight_state(DataTag), ignored_alerts => 0, max_ignored_alerts => 10 } }. handle_client_hello(#client_hello{client_version = ClientVersion} = Hello, State0) -> try #state{connection_states = ConnectionStates0, static_env = #static_env{trackers = Trackers}, handshake_env = #handshake_env{kex_algorithm = KeyExAlg, renegotiation = {Renegotiation, _}, negotiated_protocol = CurrentProtocol} = HsEnv, connection_env = #connection_env{cert_key_pairs = CertKeyPairs} = CEnv, session = Session0, ssl_options = SslOpts} = tls_dtls_connection:handle_sni_extension(State0, Hello), SessionTracker = proplists:get_value(session_id_tracker, Trackers), {Version, {Type, Session}, ConnectionStates, Protocol0, ServerHelloExt, HashSign} = dtls_handshake:hello(Hello, SslOpts, {SessionTracker, Session0, ConnectionStates0, CertKeyPairs, KeyExAlg}, Renegotiation), Protocol = case Protocol0 of undefined -> CurrentProtocol; _ -> Protocol0 end, State = prepare_flight(State0#state{connection_states = ConnectionStates, connection_env = CEnv#connection_env{negotiated_version = Version}, handshake_env = HsEnv#handshake_env{ hashsign_algorithm = HashSign, client_hello_version = ClientVersion, negotiated_protocol = Protocol}, session = Session}), {next_state, hello, State, [{next_event, internal, {common_client_hello, Type, ServerHelloExt}}]} catch #alert{} = Alert -> alert_or_reset_connection(Alert, hello, State0) end. handle_state_timeout(flight_retransmission_timeout, StateName, #state{protocol_specific = #{flight_state := {retransmit, _NextTimeout}}} = State0) -> {State1, Actions0} = dtls_gen_connection:send_handshake_flight(State0, retransmit_epoch(StateName, State0)), {next_state, StateName, State, Actions} = dtls_gen_connection:next_event(StateName, no_record, State1, Actions0), {repeat_state, State, Actions}. alert_or_reset_connection(Alert, StateName, #state{connection_states = Cs} = State) -> case maps:get(previous_cs, Cs, undefined) of undefined -> ssl_gen_statem:handle_own_alert(Alert, StateName, State); PreviousConn -> HsEnv0 = State#state.handshake_env, HsEnv = HsEnv0#handshake_env{renegotiation = undefined}, NewState = State#state{connection_states = PreviousConn, handshake_env = HsEnv }, {next_state, connection, NewState} end. gen_handshake(StateName, Type, Event, State) -> try tls_dtls_connection:StateName(Type, Event, State) catch throw:#alert{}=Alert -> alert_or_reset_connection(Alert, StateName, State); error:_ -> Alert = ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE, malformed_handshake_data), alert_or_reset_connection(Alert, StateName, State) end. gen_info(Event, connection = StateName, State) -> try dtls_gen_connection:handle_info(Event, StateName, State) catch error:_ -> Alert = ?ALERT_REC(?FATAL, ?INTERNAL_ERROR, malformed_data), alert_or_reset_connection(Alert, StateName, State) end; gen_info(Event, StateName, State) -> try dtls_gen_connection:handle_info(Event, StateName, State) catch error:_ -> Alert = ?ALERT_REC(?FATAL, ?HANDSHAKE_FAILURE,malformed_handshake_data), alert_or_reset_connection(Alert, StateName, State) end. prepare_flight(#state{flight_buffer = Flight, connection_states = ConnectionStates0, protocol_buffers = #protocol_buffers{} = Buffers} = State) -> ConnectionStates = dtls_record:save_current_connection_state(ConnectionStates0, write), State#state{flight_buffer = next_flight(Flight), connection_states = ConnectionStates, protocol_buffers = Buffers#protocol_buffers{ dtls_handshake_next_fragments = [], dtls_handshake_later_fragments = []}}. next_flight(Flight) -> Flight#{handshakes => [], change_cipher_spec => undefined, handshakes_after_change_cipher_spec => []}. handle_flight_timer(#state{static_env = #static_env{data_tag = udp}, protocol_specific = #{flight_state := {retransmit, Timeout}}} = State) -> start_retransmision_timer(Timeout, State); handle_flight_timer(#state{static_env = #static_env{data_tag = udp}, protocol_specific = #{flight_state := connection}} = State) -> {State, []}; handle_flight_timer(#state{protocol_specific = #{flight_state := reliable}} = State) -> No retransmision needed i.e DTLS over SCTP {State, []}. start_retransmision_timer(Timeout, #state{protocol_specific = PS} = State) -> {State#state{protocol_specific = PS#{flight_state => {retransmit, new_timeout(Timeout)}}}, [{state_timeout, Timeout, flight_retransmission_timeout}]}. new_timeout(N) when N =< 30000 -> N * 2; new_timeout(_) -> 60000. retransmit_epoch(_StateName, #state{connection_states = ConnectionStates}) -> #{epoch := Epoch} = ssl_record:current_connection_state(ConnectionStates, write), Epoch. send_application_data(Data, From, _StateName, #state{static_env = #static_env{socket = Socket, transport_cb = Transport}, connection_env = #connection_env{negotiated_version = Version}, handshake_env = HsEnv, connection_states = ConnectionStates0, ssl_options = #{renegotiate_at := RenegotiateAt, log_level := LogLevel}} = State0) -> case time_to_renegotiate(Data, ConnectionStates0, RenegotiateAt) of true -> renegotiate(State0#state{handshake_env = HsEnv#handshake_env{renegotiation = {true, internal}}}, [{next_event, {call, From}, {application_data, Data}}]); false -> {Msgs, ConnectionStates} = dtls_record:encode_data(Data, Version, ConnectionStates0), State = State0#state{connection_states = ConnectionStates}, case send_msgs(Transport, Socket, Msgs) of ok -> ssl_logger:debug(LogLevel, outbound, 'record', Msgs), ssl_gen_statem:hibernate_after(connection, State, [{reply, From, ok}]); Result -> ssl_gen_statem:hibernate_after(connection, State, [{reply, From, Result}]) end end. send_msgs(Transport, Socket, [Msg|Msgs]) -> case dtls_gen_connection:send(Transport, Socket, Msg) of ok -> send_msgs(Transport, Socket, Msgs); Error -> Error end; send_msgs(_, _, []) -> ok. time_to_renegotiate(_Data, #{current_write := #{sequence_number := Num}}, RenegotiateAt) -> ? MAX_PLAIN_TEXT_LENGTH ) + 1 , RenegotiateAt ) , but we chose to is_time_to_renegotiate(Num, RenegotiateAt). is_time_to_renegotiate(N, M) when N < M-> false; is_time_to_renegotiate(_,_) -> true.
8cb85ad5dceaec1d1fa03cf1879603246346d923a889e120f7cfad58feb93b12
L7R7/gitlab-ci-build-statuses
Jobs.hs
# LANGUAGE DataKinds # {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE GADTs #-} # LANGUAGE TemplateHaskell # module Core.Jobs ( Job (..), JobsApi (..), getJobsWithStatuses, ) where import Core.BuildStatuses (BuildStatus, Project) import Core.Shared import Polysemy (makeSem) import Relude data Job = Job { jobId :: Id Job, jobStatus :: BuildStatus } data JobsApi m a where GetJobsWithStatuses :: Id Project -> NonEmpty BuildStatus -> JobsApi m (Either UpdateError [Job]) makeSem ''JobsApi
null
https://raw.githubusercontent.com/L7R7/gitlab-ci-build-statuses/7701ef41dad6a7015703b6e7ec26897f44fa0e6a/src/Core/Jobs.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE GADTs #
# LANGUAGE DataKinds # # LANGUAGE TemplateHaskell # module Core.Jobs ( Job (..), JobsApi (..), getJobsWithStatuses, ) where import Core.BuildStatuses (BuildStatus, Project) import Core.Shared import Polysemy (makeSem) import Relude data Job = Job { jobId :: Id Job, jobStatus :: BuildStatus } data JobsApi m a where GetJobsWithStatuses :: Id Project -> NonEmpty BuildStatus -> JobsApi m (Either UpdateError [Job]) makeSem ''JobsApi
d963dff12487284f3388e587782249119c5092702e931f6efacc96ad13612228
ocaml-omake/omake
omake_ir_semant.ml
(* * Operations: * 1. Check that all return/export operations are in legal * places. * 2. Add final operations to sequences that don't already * have them. * 3. Add return handlers to functions that have nontrivial * return statements. *) include Omake_pos.Make (struct let name = "Omake_ir_semant" end) (* * Synthesized attributes. * renv_has_return : is there a non-tail return? * renv_is_final : code after this point is never executed *) type renv = { renv_has_return : bool; renv_is_final : bool; renv_is_value : bool } (* * Inherited attributes. * env_in_function : currently within a function body * env_in_cond : currently within a conditional * env_is_tail : the current expression is in final position *) type env = { env_warnings : Lm_location.t option ref; env_in_function : Omake_ir.return_id option; env_in_cond : bool; env_section_tail : bool; env_function_tail : bool } (* * Return environments. *) let renv_empty = { renv_has_return = false; renv_is_final = false; renv_is_value = false } let renv_value = { renv_has_return = false; renv_is_final = false; renv_is_value = true } let renv_final = { renv_has_return = false; renv_is_final = true; renv_is_value = true } let renv_return = { renv_has_return = true; renv_is_final = true; renv_is_value = true } (* * Normal environment, not in a function. *) let env_empty () = { env_warnings = ref None; env_in_function = None; env_in_cond = false; env_section_tail = false; env_function_tail = false } let env_object env = { env_warnings = env.env_warnings; env_in_function = None; env_in_cond = false; env_section_tail = false; env_function_tail = false } let env_object_tail env = { env_warnings = env.env_warnings; env_in_function = None; env_in_cond = false; env_section_tail = true; env_function_tail = true } (* * Fresh environment for a function body. *) let new_return_id loc v = let _, v = Omake_ir_util.var_of_var_info v in loc, Lm_symbol.to_string v let env_fun env id = { env_warnings = env.env_warnings; env_in_function = Some id; env_in_cond = false; env_section_tail = true; env_function_tail = true } let env_anon_fun env = { env with env_in_cond = true; env_section_tail = true } let update_return renv has_return = { renv with renv_has_return = renv.renv_has_return || has_return } (* * Error checkers. *) let check_return_placement env loc = match env.env_in_function with None -> let pos = string_pos "check_in_function" (loc_exp_pos loc) in let print_error buf = Format.fprintf buf "@[<v 0>Misplaced return statement."; Format.fprintf buf "@ The return is not within a function.@]" in raise (Omake_value_type.OmakeException (pos, LazyError print_error)) | Some id -> if not (env.env_function_tail || env.env_section_tail && env.env_in_cond) then begin Lm_printf.eprintf "@[<v 3>*** omake warning: %a@ statements after this return are not reached@]@." Lm_location.pp_print_location loc; env.env_warnings := Some loc end; id (* let check_section_tail env loc = *) (* if not env.env_section_tail then *) let pos = string_pos " check_section_tail " ( ) in raise ( Omake_value_type . OmakeException ( pos , StringError " This should be the last expression in the section . " ) ) let check_object_tail env loc = if env.env_in_function <> None || not env.env_section_tail then let pos = string_pos "check_object_tail" (loc_exp_pos loc) in raise (Omake_value_type.OmakeException (pos, StringError "This should be the last expression in the object.")) (* * Convert a string expression. *) let rec build_string env s = let env = { env with env_function_tail = false } in match s with Omake_ir.NoneString _ | IntString _ | FloatString _ | WhiteString _ | ConstString _ | ThisString _ | KeyApplyString _ | VarString _ -> false, s | FunString (loc, opt_params, params, e, export) -> (* Returns propagate -through- anonymous functions *) let renv, e = build_sequence_exp (env_anon_fun env) e in let has_return, opt_params = build_keyword_param_list env opt_params in renv.renv_has_return || has_return, FunString (loc, opt_params, params, e, export) | ApplyString (loc, v, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in has_return1 || has_return2, ApplyString (loc, v, args, kargs) | SuperApplyString (loc, v1, v2, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in has_return1 || has_return2, SuperApplyString (loc, v1, v2, args, kargs) | MethodApplyString (loc, v, vl, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in has_return1 || has_return2, MethodApplyString (loc, v, vl, args, kargs) | SequenceString (loc, sl) -> let has_return, sl = build_string_list env sl in has_return, SequenceString (loc, sl) | ArrayString (loc, sl) -> let has_return, sl = build_string_list env sl in has_return, ArrayString (loc, sl) | ArrayOfString (loc, s) -> let has_return, s = build_string env s in has_return, ArrayOfString (loc, s) | QuoteString (loc, sl) -> let has_return, sl = build_string_list env sl in has_return, QuoteString (loc, sl) | QuoteStringString (loc, c, sl) -> let has_return, sl = build_string_list env sl in has_return, QuoteStringString (loc, c, sl) | ObjectString (loc, el, export) -> let el = build_object_exp env el in (* XXX: we should handle the case when an object contains a return *) false, ObjectString (loc, el, export) | BodyString (loc, el, export) -> let renv, el = build_sequence_exp env el in renv.renv_has_return, BodyString (loc, el, export) | ExpString (loc, el, export) -> let renv, el = build_sequence_exp env el in renv.renv_has_return, ExpString (loc, el, export) | CasesString (loc, cases) -> let env = { env with env_in_cond = true } in let has_return, cases = List.fold_left (fun (has_return, cases) (v, s, el, export) -> let has_return2, s = build_string env s in let renv, e = build_sequence_exp env el in let has_return = has_return || has_return2 || renv.renv_has_return in has_return, (v, s, e, export) :: cases) (false, []) cases in has_return, CasesString (loc, List.rev cases) | LazyString (loc, s) -> let has_return, s = build_string env s in has_return, LazyString (loc, s) | LetVarString (loc, v, s1, s2) -> let has_return1, s1 = build_string env s1 in let has_return2, s2 = build_string env s2 in has_return1 || has_return2, LetVarString (loc, v, s1, s2) and build_string_list env sl = let has_return, sl = List.fold_left (fun (has_return, sl) s -> let has_return2, s = build_string env s in has_return || has_return2, s :: sl) (false, []) sl in has_return, List.rev sl and build_keyword_string_list env kargs = let has_return, kargs = List.fold_left (fun (has_return, sl) (v, s) -> let has_return2, s = build_string env s in has_return || has_return2, (v, s) :: sl) (false, []) kargs in has_return, List.rev kargs and build_keyword_param_list env kargs = let has_return, kargs = List.fold_left (fun (has_return, sl) (v, v_info, s_opt) -> match s_opt with Some s -> let has_return2, s = build_string env s in has_return || has_return2, (v, v_info, Some s) :: sl | None -> has_return, (v, v_info, None) :: sl) (false, []) kargs in has_return, List.rev kargs (* * Convert the current expression. *) and build_exp env e = match e with Omake_ir.LetFunExp (loc, v, vl, curry, opt_params, vars, el, export) -> let id = new_return_id loc v in let renv, el = build_sequence_exp (env_fun env id) el in let el = if renv.renv_has_return then Omake_ir.[ReturnBodyExp (loc, el, id)] else el in let has_return, opt_params = build_keyword_param_list env opt_params in let e = Omake_ir.LetFunExp (loc, v, vl, curry, opt_params, vars, el, export) in update_return renv_empty has_return, e | LetObjectExp (loc, v, vl, s, el, export) -> let el = build_object_exp env el in let has_return, s = build_string env s in let e = Omake_ir.LetObjectExp (loc, v, vl, s, el, export) in update_return renv_empty has_return, e | StaticExp (loc, node, v, el) -> let el = build_object_exp env el in let e = Omake_ir.StaticExp (loc, node, v, el) in renv_empty, e | IfExp (loc, cases) -> let renv, cases = build_cases_exp env cases in let e = Omake_ir.IfExp (loc, cases) in renv, e | SequenceExp (loc, el) -> let renv, el = build_sequence_exp env el in let e = Omake_ir.SequenceExp (loc, el) in renv, e | SectionExp (loc, s, el, export) -> let has_return, s = build_string env s in let renv, el = build_sequence_exp env el in let e = Omake_ir.SectionExp (loc, s, el, export) in update_return renv has_return, e | ReturnBodyExp (loc, el, id) -> let renv, el = build_sequence_exp env el in let el = Omake_ir.ReturnBodyExp (loc, el, id) in renv, el | LetVarExp (loc, v, vl, kind, s) -> let has_return, s = build_string env s in let e = Omake_ir.LetVarExp (loc, v, vl, kind, s) in update_return renv_empty has_return, e | IncludeExp (loc, s, sl) -> let has_return1, s = build_string env s in let has_return2, sl = build_string_list env sl in let e = Omake_ir.IncludeExp (loc, s, sl) in update_return renv_empty (has_return1 || has_return2), e | ApplyExp (loc, v, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in let e = Omake_ir.ApplyExp (loc, v, args, kargs) in update_return renv_empty (has_return1 || has_return2), e | SuperApplyExp (loc, v1, v2, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in let e = Omake_ir.SuperApplyExp (loc, v1, v2, args, kargs) in update_return renv_empty (has_return1 || has_return2), e | MethodApplyExp (loc, v, vl, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in let e = Omake_ir.MethodApplyExp (loc, v, vl, args, kargs) in update_return renv_empty (has_return1 || has_return2), e | LetKeyExp (loc, v, kind, s) -> let has_return, s = build_string env s in let e = Omake_ir.LetKeyExp (loc, v, kind, s) in update_return renv_empty has_return, e | LetThisExp (loc, s) -> let has_return, s = build_string env s in let e = Omake_ir.LetThisExp (loc, s) in update_return renv_empty has_return, e | ShellExp (loc, s) -> let has_return, s = build_string env s in let e = Omake_ir.ShellExp (loc, s) in update_return renv_value has_return, e | KeyExp _ | OpenExp _ -> renv_empty, e | StringExp (loc, s) -> let has_return, s = build_string env s in let e = Omake_ir.StringExp (loc, s) in update_return renv_value has_return, e | ReturnExp (loc, s, _) -> let id = check_return_placement env loc in let has_return, s = build_string env s in if env.env_function_tail then update_return renv_final has_return, Omake_ir.StringExp (loc, s) else renv_return, Omake_ir.ReturnExp (loc, s, id) | ReturnObjectExp (loc, _) | ReturnSaveExp loc -> check_object_tail env loc; renv_final, e (* * An object expression is an expression sequence, * but it is not in a function. *) and build_object_exp_aux env el = match el with [e] -> let _, e = build_exp (env_object_tail env) e in [e] | e :: el -> let _, e = build_exp env e in let el = build_object_exp_aux env el in e :: el | [] -> [] and build_object_exp env el = build_object_exp_aux (env_object env) el (* * A new sequence expression. * It should be terminated with a final statement. *) and build_sequence_exp env el = let env_non_tail = { env with env_section_tail = false; env_function_tail = false } in let rec build_sequence_core has_return rel el = match el with [e] -> let env_tail = { env with env_section_tail = true } in let renv, e = build_exp env_tail e in let rel = e :: rel in update_return renv has_return, rel | e :: el -> let renv, e = build_exp env_non_tail e in let has_return = has_return || renv.renv_has_return in let rel = e :: rel in build_sequence_core has_return rel el | [] -> renv_empty, [] in let renv, rel = build_sequence_core false [] el in renv, List.rev rel (* * Cases are slightly different from sequences because * returns are always allowed. Note that the completeness is * not checked, so even if all cases end in a return, * evaluation may continue from here. *) and build_cases_exp env cases = let env = { env with env_in_cond = true; env_section_tail = true } in let has_return, cases = List.fold_left (fun (has_return, cases) (s, el, export) -> let renv, el = build_sequence_exp env el in let has_return = has_return || renv.renv_has_return in has_return, (s, el, export) :: cases) (false, []) cases in let cases = List.rev cases in let renv = { renv_is_final = false; renv_is_value = true; renv_has_return = has_return } in renv, cases (************************************************************************ * Main function *) let build_prog venv e = let env = env_empty () in let _, e = build_exp env e in let count = !(env.env_warnings) in let () = match count with |Some loc when Omake_options.opt_warn_error (Omake_env.venv_options venv) -> raise (Omake_value_type.OmakeException (loc_exp_pos loc, StringError "warnings treated as errors")) | _ -> () in e
null
https://raw.githubusercontent.com/ocaml-omake/omake/08b2a83fb558f6eb6847566cbe1a562230da2b14/src/env/omake_ir_semant.ml
ocaml
* Operations: * 1. Check that all return/export operations are in legal * places. * 2. Add final operations to sequences that don't already * have them. * 3. Add return handlers to functions that have nontrivial * return statements. * Synthesized attributes. * renv_has_return : is there a non-tail return? * renv_is_final : code after this point is never executed * Inherited attributes. * env_in_function : currently within a function body * env_in_cond : currently within a conditional * env_is_tail : the current expression is in final position * Return environments. * Normal environment, not in a function. * Fresh environment for a function body. * Error checkers. let check_section_tail env loc = if not env.env_section_tail then * Convert a string expression. Returns propagate -through- anonymous functions XXX: we should handle the case when an object contains a return * Convert the current expression. * An object expression is an expression sequence, * but it is not in a function. * A new sequence expression. * It should be terminated with a final statement. * Cases are slightly different from sequences because * returns are always allowed. Note that the completeness is * not checked, so even if all cases end in a return, * evaluation may continue from here. *********************************************************************** * Main function
include Omake_pos.Make (struct let name = "Omake_ir_semant" end) type renv = { renv_has_return : bool; renv_is_final : bool; renv_is_value : bool } type env = { env_warnings : Lm_location.t option ref; env_in_function : Omake_ir.return_id option; env_in_cond : bool; env_section_tail : bool; env_function_tail : bool } let renv_empty = { renv_has_return = false; renv_is_final = false; renv_is_value = false } let renv_value = { renv_has_return = false; renv_is_final = false; renv_is_value = true } let renv_final = { renv_has_return = false; renv_is_final = true; renv_is_value = true } let renv_return = { renv_has_return = true; renv_is_final = true; renv_is_value = true } let env_empty () = { env_warnings = ref None; env_in_function = None; env_in_cond = false; env_section_tail = false; env_function_tail = false } let env_object env = { env_warnings = env.env_warnings; env_in_function = None; env_in_cond = false; env_section_tail = false; env_function_tail = false } let env_object_tail env = { env_warnings = env.env_warnings; env_in_function = None; env_in_cond = false; env_section_tail = true; env_function_tail = true } let new_return_id loc v = let _, v = Omake_ir_util.var_of_var_info v in loc, Lm_symbol.to_string v let env_fun env id = { env_warnings = env.env_warnings; env_in_function = Some id; env_in_cond = false; env_section_tail = true; env_function_tail = true } let env_anon_fun env = { env with env_in_cond = true; env_section_tail = true } let update_return renv has_return = { renv with renv_has_return = renv.renv_has_return || has_return } let check_return_placement env loc = match env.env_in_function with None -> let pos = string_pos "check_in_function" (loc_exp_pos loc) in let print_error buf = Format.fprintf buf "@[<v 0>Misplaced return statement."; Format.fprintf buf "@ The return is not within a function.@]" in raise (Omake_value_type.OmakeException (pos, LazyError print_error)) | Some id -> if not (env.env_function_tail || env.env_section_tail && env.env_in_cond) then begin Lm_printf.eprintf "@[<v 3>*** omake warning: %a@ statements after this return are not reached@]@." Lm_location.pp_print_location loc; env.env_warnings := Some loc end; id let pos = string_pos " check_section_tail " ( ) in raise ( Omake_value_type . OmakeException ( pos , StringError " This should be the last expression in the section . " ) ) let check_object_tail env loc = if env.env_in_function <> None || not env.env_section_tail then let pos = string_pos "check_object_tail" (loc_exp_pos loc) in raise (Omake_value_type.OmakeException (pos, StringError "This should be the last expression in the object.")) let rec build_string env s = let env = { env with env_function_tail = false } in match s with Omake_ir.NoneString _ | IntString _ | FloatString _ | WhiteString _ | ConstString _ | ThisString _ | KeyApplyString _ | VarString _ -> false, s | FunString (loc, opt_params, params, e, export) -> let renv, e = build_sequence_exp (env_anon_fun env) e in let has_return, opt_params = build_keyword_param_list env opt_params in renv.renv_has_return || has_return, FunString (loc, opt_params, params, e, export) | ApplyString (loc, v, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in has_return1 || has_return2, ApplyString (loc, v, args, kargs) | SuperApplyString (loc, v1, v2, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in has_return1 || has_return2, SuperApplyString (loc, v1, v2, args, kargs) | MethodApplyString (loc, v, vl, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in has_return1 || has_return2, MethodApplyString (loc, v, vl, args, kargs) | SequenceString (loc, sl) -> let has_return, sl = build_string_list env sl in has_return, SequenceString (loc, sl) | ArrayString (loc, sl) -> let has_return, sl = build_string_list env sl in has_return, ArrayString (loc, sl) | ArrayOfString (loc, s) -> let has_return, s = build_string env s in has_return, ArrayOfString (loc, s) | QuoteString (loc, sl) -> let has_return, sl = build_string_list env sl in has_return, QuoteString (loc, sl) | QuoteStringString (loc, c, sl) -> let has_return, sl = build_string_list env sl in has_return, QuoteStringString (loc, c, sl) | ObjectString (loc, el, export) -> let el = build_object_exp env el in false, ObjectString (loc, el, export) | BodyString (loc, el, export) -> let renv, el = build_sequence_exp env el in renv.renv_has_return, BodyString (loc, el, export) | ExpString (loc, el, export) -> let renv, el = build_sequence_exp env el in renv.renv_has_return, ExpString (loc, el, export) | CasesString (loc, cases) -> let env = { env with env_in_cond = true } in let has_return, cases = List.fold_left (fun (has_return, cases) (v, s, el, export) -> let has_return2, s = build_string env s in let renv, e = build_sequence_exp env el in let has_return = has_return || has_return2 || renv.renv_has_return in has_return, (v, s, e, export) :: cases) (false, []) cases in has_return, CasesString (loc, List.rev cases) | LazyString (loc, s) -> let has_return, s = build_string env s in has_return, LazyString (loc, s) | LetVarString (loc, v, s1, s2) -> let has_return1, s1 = build_string env s1 in let has_return2, s2 = build_string env s2 in has_return1 || has_return2, LetVarString (loc, v, s1, s2) and build_string_list env sl = let has_return, sl = List.fold_left (fun (has_return, sl) s -> let has_return2, s = build_string env s in has_return || has_return2, s :: sl) (false, []) sl in has_return, List.rev sl and build_keyword_string_list env kargs = let has_return, kargs = List.fold_left (fun (has_return, sl) (v, s) -> let has_return2, s = build_string env s in has_return || has_return2, (v, s) :: sl) (false, []) kargs in has_return, List.rev kargs and build_keyword_param_list env kargs = let has_return, kargs = List.fold_left (fun (has_return, sl) (v, v_info, s_opt) -> match s_opt with Some s -> let has_return2, s = build_string env s in has_return || has_return2, (v, v_info, Some s) :: sl | None -> has_return, (v, v_info, None) :: sl) (false, []) kargs in has_return, List.rev kargs and build_exp env e = match e with Omake_ir.LetFunExp (loc, v, vl, curry, opt_params, vars, el, export) -> let id = new_return_id loc v in let renv, el = build_sequence_exp (env_fun env id) el in let el = if renv.renv_has_return then Omake_ir.[ReturnBodyExp (loc, el, id)] else el in let has_return, opt_params = build_keyword_param_list env opt_params in let e = Omake_ir.LetFunExp (loc, v, vl, curry, opt_params, vars, el, export) in update_return renv_empty has_return, e | LetObjectExp (loc, v, vl, s, el, export) -> let el = build_object_exp env el in let has_return, s = build_string env s in let e = Omake_ir.LetObjectExp (loc, v, vl, s, el, export) in update_return renv_empty has_return, e | StaticExp (loc, node, v, el) -> let el = build_object_exp env el in let e = Omake_ir.StaticExp (loc, node, v, el) in renv_empty, e | IfExp (loc, cases) -> let renv, cases = build_cases_exp env cases in let e = Omake_ir.IfExp (loc, cases) in renv, e | SequenceExp (loc, el) -> let renv, el = build_sequence_exp env el in let e = Omake_ir.SequenceExp (loc, el) in renv, e | SectionExp (loc, s, el, export) -> let has_return, s = build_string env s in let renv, el = build_sequence_exp env el in let e = Omake_ir.SectionExp (loc, s, el, export) in update_return renv has_return, e | ReturnBodyExp (loc, el, id) -> let renv, el = build_sequence_exp env el in let el = Omake_ir.ReturnBodyExp (loc, el, id) in renv, el | LetVarExp (loc, v, vl, kind, s) -> let has_return, s = build_string env s in let e = Omake_ir.LetVarExp (loc, v, vl, kind, s) in update_return renv_empty has_return, e | IncludeExp (loc, s, sl) -> let has_return1, s = build_string env s in let has_return2, sl = build_string_list env sl in let e = Omake_ir.IncludeExp (loc, s, sl) in update_return renv_empty (has_return1 || has_return2), e | ApplyExp (loc, v, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in let e = Omake_ir.ApplyExp (loc, v, args, kargs) in update_return renv_empty (has_return1 || has_return2), e | SuperApplyExp (loc, v1, v2, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in let e = Omake_ir.SuperApplyExp (loc, v1, v2, args, kargs) in update_return renv_empty (has_return1 || has_return2), e | MethodApplyExp (loc, v, vl, args, kargs) -> let has_return1, args = build_string_list env args in let has_return2, kargs = build_keyword_string_list env kargs in let e = Omake_ir.MethodApplyExp (loc, v, vl, args, kargs) in update_return renv_empty (has_return1 || has_return2), e | LetKeyExp (loc, v, kind, s) -> let has_return, s = build_string env s in let e = Omake_ir.LetKeyExp (loc, v, kind, s) in update_return renv_empty has_return, e | LetThisExp (loc, s) -> let has_return, s = build_string env s in let e = Omake_ir.LetThisExp (loc, s) in update_return renv_empty has_return, e | ShellExp (loc, s) -> let has_return, s = build_string env s in let e = Omake_ir.ShellExp (loc, s) in update_return renv_value has_return, e | KeyExp _ | OpenExp _ -> renv_empty, e | StringExp (loc, s) -> let has_return, s = build_string env s in let e = Omake_ir.StringExp (loc, s) in update_return renv_value has_return, e | ReturnExp (loc, s, _) -> let id = check_return_placement env loc in let has_return, s = build_string env s in if env.env_function_tail then update_return renv_final has_return, Omake_ir.StringExp (loc, s) else renv_return, Omake_ir.ReturnExp (loc, s, id) | ReturnObjectExp (loc, _) | ReturnSaveExp loc -> check_object_tail env loc; renv_final, e and build_object_exp_aux env el = match el with [e] -> let _, e = build_exp (env_object_tail env) e in [e] | e :: el -> let _, e = build_exp env e in let el = build_object_exp_aux env el in e :: el | [] -> [] and build_object_exp env el = build_object_exp_aux (env_object env) el and build_sequence_exp env el = let env_non_tail = { env with env_section_tail = false; env_function_tail = false } in let rec build_sequence_core has_return rel el = match el with [e] -> let env_tail = { env with env_section_tail = true } in let renv, e = build_exp env_tail e in let rel = e :: rel in update_return renv has_return, rel | e :: el -> let renv, e = build_exp env_non_tail e in let has_return = has_return || renv.renv_has_return in let rel = e :: rel in build_sequence_core has_return rel el | [] -> renv_empty, [] in let renv, rel = build_sequence_core false [] el in renv, List.rev rel and build_cases_exp env cases = let env = { env with env_in_cond = true; env_section_tail = true } in let has_return, cases = List.fold_left (fun (has_return, cases) (s, el, export) -> let renv, el = build_sequence_exp env el in let has_return = has_return || renv.renv_has_return in has_return, (s, el, export) :: cases) (false, []) cases in let cases = List.rev cases in let renv = { renv_is_final = false; renv_is_value = true; renv_has_return = has_return } in renv, cases let build_prog venv e = let env = env_empty () in let _, e = build_exp env e in let count = !(env.env_warnings) in let () = match count with |Some loc when Omake_options.opt_warn_error (Omake_env.venv_options venv) -> raise (Omake_value_type.OmakeException (loc_exp_pos loc, StringError "warnings treated as errors")) | _ -> () in e
2658edfafa8bd5d0f75808356e6fa3d005fa4e1d55f2e30ab0fe3a01bdbde5e0
garrigue/lablgtk
xml.ml
(**************************************************************************) Lablgtk - Camlirc (* *) (* * You are free to do anything you want with this code as long *) (* as it is for personal use. *) (* *) (* * Redistribution can only be "as is". Binary distribution *) (* and bug fixes are allowed, but you cannot extensively *) (* modify the code without asking the authors. *) (* *) (* The authors may choose to remove any of the above *) (* restrictions on a per request basis. *) (* *) (* Authors: *) < > < > (* *) (**************************************************************************) $ Id$ open Xml_lexer type element = { elt_desc: element_desc; elt_start: int; elt_end: int} and element_desc = | Node of string * (string * string) list * element list | Text of string type presence = [`Required | `Optional] type dtd = { tags: (string * ((string * presence) list * dtd)) list; allow: [`Mixed | `Tags | `Any] } let any = {tags = []; allow = `Any} let text = {tags = []; allow = `Mixed} let check_tag ~name ~attrs ~dtd = try let attr_dtd, child_dtd = List.assoc name dtd.tags in List.iter (fun (key,_) -> ignore (List.assoc key attr_dtd)) attrs; List.iter (function (key,`Required) -> ignore (List.assoc key attrs) | _ -> ()) attr_dtd ; child_dtd with Not_found -> if dtd.allow = `Any then any else raise (Error(Other"input does not conform to DTD", token_start ())) let check_text ~dtd = if dtd.allow = `Tags then raise (Error(Other"input does not conform to DTD", token_start ())) let parse ?doctype ?(dtd=any) lexbuf = begin match doctype with None -> () | Some doctype -> match token lexbuf with | Tag ("!doctype", attrs, _) -> if not (List.mem_assoc (String.lowercase doctype) attrs) then raise (Error(Other"Document type differs", token_start ())) | _ -> raise (Error(Other"Document type missing", token_start ())) end; let mkelt d = { elt_desc = d; elt_start = token_start (); elt_end = Lexing.lexeme_end lexbuf } in let rec parse ~prev ~dtd = match token lexbuf with | Tag (name, attrs, closed) -> let closed = closed || name.[0] = '!' in let child_dtd = check_tag ~name ~attrs:attrs ~dtd in if closed then parse ~prev:(mkelt(Node (name, attrs, [])) :: prev) ~dtd else begin let nodes, closing = parse ~prev:[] ~dtd:child_dtd in let prev = mkelt(Node (name, attrs, List.rev nodes)) :: prev in if closing = Some name then parse ~prev ~dtd else prev, closing end | Chars s -> check_text ~dtd; parse ~prev:(mkelt(Text s) :: prev) ~dtd | Endtag name -> prev, Some name | EOF -> prev, None in parse ~prev:[] ~dtd let parse_lexbuf ?doctype ?dtd lexbuf = List.rev (fst (parse lexbuf ?doctype ?dtd)) let parse_string ?doctype ?dtd s = parse_lexbuf (Lexing.from_string s) ?doctype ?dtd type 'a result = Ok of 'a | Exn of exn let protect f x = try Ok (f x) with exn -> Exn exn let return = function Ok x -> x | Exn exn -> raise exn let parse_file ?doctype ?dtd name = let ic = open_in name in let res = protect (parse_lexbuf ?doctype ?dtd) (Lexing.from_channel ic) in close_in ic; return res class reader lexbuf ~name ~closed = object ( self ) val mutable closed = closed val mutable closing = None val mutable current = None val start = token_start ( ) method name = name method attrs = attrs method get_attr key : string = List.assoc ( String.lowercase key ) attrs method has_attr key = List.mem_assoc ( String.lowercase key ) attrs method finish = while not closed do ignore ( ) done ; closing method next_child : [ ` NODE of string * reader | ` TEXT of string | ` NONE ] = begin match current with None - > ( ) | Some node - > current < - None ; match node#finish with None - > ( ) | Some name ' - > if name < > name ' then closing < - Some name ' ; closed < - true end ; if closed then ` NONE else begin match token lexbuf with | Tag ( name , attrs , closed ) - > let = List.map attrs ~f:(fun ( k , v ) - ) in let closed = closed || name.[0 ] = ' ! ' in let node = new reader lexbuf ~name ~closed in current < - Some node ; ` NODE ( name , node ) ` TEXT s | Endtag name ' - > if name ' < > name then closing < - Some name ' ; ` NONE | EOF - > closing < - Some " " ; ` NONE end method iter ( f : [ ` NODE of string * reader | ` TEXT of string ] - > unit ) = while match self#next_child with ` NODE _ | ` TEXT _ as x - > f x ; true | ` NONE - > false do ( ) done end let reader ic = new reader ( ) ~name : " " : [ ] ~closed : false let string_reader s = new reader ( ) ~name : " " : [ ] ~closed : false class reader lexbuf ~name ~attrs ~closed = object (self) val mutable closed = closed val mutable closing = None val mutable current = None val start = token_start () method name = name method attrs = attrs method get_attr key : string = List.assoc (String.lowercase key) attrs method has_attr key = List.mem_assoc (String.lowercase key) attrs method finish = while not closed do ignore (self#next_child) done; closing method next_child : [`NODE of string * reader | `TEXT of string | `NONE] = begin match current with None -> () | Some node -> current <- None; match node#finish with None -> () | Some name' -> if name <> name' then closing <- Some name'; closed <- true end; if closed then `NONE else begin match token lexbuf with | Tag (name, attrs, closed) -> let attrs = List.map attrs ~f:(fun (k,v) -> String.lowercase k,v) in let closed = closed || name.[0] = '!' in let node = new reader lexbuf ~name ~attrs ~closed in current <- Some node; `NODE (name, node) | Chars s -> `TEXT s | Endtag name' -> if name' <> name then closing <- Some name'; `NONE | EOF -> closing <- Some ""; `NONE end method iter (f : [`NODE of string * reader | `TEXT of string] -> unit) = while match self#next_child with `NODE _ | `TEXT _ as x -> f x; true | `NONE -> false do () done end let reader ic = new reader (Lexing.from_channel ic) ~name:"" ~attrs:[] ~closed:false let string_reader s = new reader (Lexing.from_string s) ~name:"" ~attrs:[] ~closed:false *)
null
https://raw.githubusercontent.com/garrigue/lablgtk/504fac1257e900e6044c638025a4d6c5a321284c/applications/camlirc/xml.ml
ocaml
************************************************************************ * You are free to do anything you want with this code as long as it is for personal use. * Redistribution can only be "as is". Binary distribution and bug fixes are allowed, but you cannot extensively modify the code without asking the authors. The authors may choose to remove any of the above restrictions on a per request basis. Authors: ************************************************************************
Lablgtk - Camlirc < > < > $ Id$ open Xml_lexer type element = { elt_desc: element_desc; elt_start: int; elt_end: int} and element_desc = | Node of string * (string * string) list * element list | Text of string type presence = [`Required | `Optional] type dtd = { tags: (string * ((string * presence) list * dtd)) list; allow: [`Mixed | `Tags | `Any] } let any = {tags = []; allow = `Any} let text = {tags = []; allow = `Mixed} let check_tag ~name ~attrs ~dtd = try let attr_dtd, child_dtd = List.assoc name dtd.tags in List.iter (fun (key,_) -> ignore (List.assoc key attr_dtd)) attrs; List.iter (function (key,`Required) -> ignore (List.assoc key attrs) | _ -> ()) attr_dtd ; child_dtd with Not_found -> if dtd.allow = `Any then any else raise (Error(Other"input does not conform to DTD", token_start ())) let check_text ~dtd = if dtd.allow = `Tags then raise (Error(Other"input does not conform to DTD", token_start ())) let parse ?doctype ?(dtd=any) lexbuf = begin match doctype with None -> () | Some doctype -> match token lexbuf with | Tag ("!doctype", attrs, _) -> if not (List.mem_assoc (String.lowercase doctype) attrs) then raise (Error(Other"Document type differs", token_start ())) | _ -> raise (Error(Other"Document type missing", token_start ())) end; let mkelt d = { elt_desc = d; elt_start = token_start (); elt_end = Lexing.lexeme_end lexbuf } in let rec parse ~prev ~dtd = match token lexbuf with | Tag (name, attrs, closed) -> let closed = closed || name.[0] = '!' in let child_dtd = check_tag ~name ~attrs:attrs ~dtd in if closed then parse ~prev:(mkelt(Node (name, attrs, [])) :: prev) ~dtd else begin let nodes, closing = parse ~prev:[] ~dtd:child_dtd in let prev = mkelt(Node (name, attrs, List.rev nodes)) :: prev in if closing = Some name then parse ~prev ~dtd else prev, closing end | Chars s -> check_text ~dtd; parse ~prev:(mkelt(Text s) :: prev) ~dtd | Endtag name -> prev, Some name | EOF -> prev, None in parse ~prev:[] ~dtd let parse_lexbuf ?doctype ?dtd lexbuf = List.rev (fst (parse lexbuf ?doctype ?dtd)) let parse_string ?doctype ?dtd s = parse_lexbuf (Lexing.from_string s) ?doctype ?dtd type 'a result = Ok of 'a | Exn of exn let protect f x = try Ok (f x) with exn -> Exn exn let return = function Ok x -> x | Exn exn -> raise exn let parse_file ?doctype ?dtd name = let ic = open_in name in let res = protect (parse_lexbuf ?doctype ?dtd) (Lexing.from_channel ic) in close_in ic; return res class reader lexbuf ~name ~closed = object ( self ) val mutable closed = closed val mutable closing = None val mutable current = None val start = token_start ( ) method name = name method attrs = attrs method get_attr key : string = List.assoc ( String.lowercase key ) attrs method has_attr key = List.mem_assoc ( String.lowercase key ) attrs method finish = while not closed do ignore ( ) done ; closing method next_child : [ ` NODE of string * reader | ` TEXT of string | ` NONE ] = begin match current with None - > ( ) | Some node - > current < - None ; match node#finish with None - > ( ) | Some name ' - > if name < > name ' then closing < - Some name ' ; closed < - true end ; if closed then ` NONE else begin match token lexbuf with | Tag ( name , attrs , closed ) - > let = List.map attrs ~f:(fun ( k , v ) - ) in let closed = closed || name.[0 ] = ' ! ' in let node = new reader lexbuf ~name ~closed in current < - Some node ; ` NODE ( name , node ) ` TEXT s | Endtag name ' - > if name ' < > name then closing < - Some name ' ; ` NONE | EOF - > closing < - Some " " ; ` NONE end method iter ( f : [ ` NODE of string * reader | ` TEXT of string ] - > unit ) = while match self#next_child with ` NODE _ | ` TEXT _ as x - > f x ; true | ` NONE - > false do ( ) done end let reader ic = new reader ( ) ~name : " " : [ ] ~closed : false let string_reader s = new reader ( ) ~name : " " : [ ] ~closed : false class reader lexbuf ~name ~attrs ~closed = object (self) val mutable closed = closed val mutable closing = None val mutable current = None val start = token_start () method name = name method attrs = attrs method get_attr key : string = List.assoc (String.lowercase key) attrs method has_attr key = List.mem_assoc (String.lowercase key) attrs method finish = while not closed do ignore (self#next_child) done; closing method next_child : [`NODE of string * reader | `TEXT of string | `NONE] = begin match current with None -> () | Some node -> current <- None; match node#finish with None -> () | Some name' -> if name <> name' then closing <- Some name'; closed <- true end; if closed then `NONE else begin match token lexbuf with | Tag (name, attrs, closed) -> let attrs = List.map attrs ~f:(fun (k,v) -> String.lowercase k,v) in let closed = closed || name.[0] = '!' in let node = new reader lexbuf ~name ~attrs ~closed in current <- Some node; `NODE (name, node) | Chars s -> `TEXT s | Endtag name' -> if name' <> name then closing <- Some name'; `NONE | EOF -> closing <- Some ""; `NONE end method iter (f : [`NODE of string * reader | `TEXT of string] -> unit) = while match self#next_child with `NODE _ | `TEXT _ as x -> f x; true | `NONE -> false do () done end let reader ic = new reader (Lexing.from_channel ic) ~name:"" ~attrs:[] ~closed:false let string_reader s = new reader (Lexing.from_string s) ~name:"" ~attrs:[] ~closed:false *)
eb4a17f7f1c7e4a8ad9ded9fe34f3f3e2f085d7c0d53efadb3435121e1707e21
exercism/babashka
project.clj
(defproject word-count "0.1.0-SNAPSHOT" :description "wordy exercise." :url "" :dependencies [[org.clojure/clojure "1.10.0"]])
null
https://raw.githubusercontent.com/exercism/babashka/707356c52e08490e66cb1b2e63e4f4439d91cf08/exercises/practice/wordy/project.clj
clojure
(defproject word-count "0.1.0-SNAPSHOT" :description "wordy exercise." :url "" :dependencies [[org.clojure/clojure "1.10.0"]])
c668c09b2f562a8db29d631b39f9089a9f47b26a3a0ebf4dcb0f400cc885ffdf
TomLisankie/static-roam
database.clj
(ns static-roam.database (:require [static-roam.parser :as parser] [static-roam.utils :as utils] [clojure.string :as str-utils] [datascript.core :as ds] [clojure.pprint :as pprint])) (defn- get-block-id [block-json] (if (:title block-json) (:title block-json) (:uid block-json))) (defn get-properties-for-block-id [block-id block-map] (get block-map block-id)) (defn- get-block-properties [block-json] { :children (map :uid (:children block-json)) :content (:string block-json (:title block-json)) :heading (:heading block-json -1) :text-align (:text-align block-json "") :entry-point (parser/entry-point? block-json) :page (if (:title block-json) true false) }) (defn- generate-block-linking-transaction [referer-eid reference-id] {:block/id reference-id :block/linked-by referer-eid}) (defn- create-id-properties-pair [block-json] [(get-block-id block-json) (get-block-properties block-json)]) (defn- create-id-properties-pairs [roam-json] (map vec (partition 2 (flatten (for [block-json roam-json] (conj (create-id-properties-pairs (:children block-json)) (create-id-properties-pair block-json))))))) (defn- create-block-map-no-links "Populate database with relevant properties of pages and blocks" [roam-json] ;; what I need to happen here is have it so if the block has children, it creates pairs for those as well ;; forget what I already implemented, I optimized too early. (into (hash-map) (create-id-properties-pairs roam-json))) (defn- clean-content-entities [string] (let [content-entities-found (utils/find-content-entities-in-string string) hashtags-found (utils/find-hashtags-in-string string) metadata-found (utils/find-metadata-in-string string) extra-paren-removed (utils/remove-heading-parens content-entities-found) cleaned-content-entities (map utils/remove-double-delimiters extra-paren-removed) cleaned-hashtags (map utils/remove-leading-char hashtags-found) cleaned-metadata (map utils/remove-double-colon metadata-found) all-cleaned-entities (concat cleaned-content-entities cleaned-hashtags cleaned-metadata)] all-cleaned-entities)) ;; sometimes people put references to other page titles inside of the title of another page. So pairs of brackets inside of other brackets when they reference them. This breaks things currently, so I'm removing all those instances here TODO: Fix so this is unnecessary (defn- filter-broken-references [pair] [(first pair) (filter #(not (str-utils/includes? % "[")) (second pair))]) (defn- generate-block-id-reference-pair [pair] [(first pair) (clean-content-entities (second pair))]) (defn- generate-block-linking-transactions-for-entity-reference-pair [entity-id-reference-pair] (let [referer-eid (first entity-id-reference-pair) reference-ids (second entity-id-reference-pair)] (map #(generate-block-linking-transaction referer-eid %) reference-ids))) (defn- generate-transactions-for-linking-blocks [entity-id-reference-pairs] (map generate-block-linking-transactions-for-entity-reference-pair entity-id-reference-pairs)) (defn- get-block-id-content-pair [pair] [(first pair) (:content (second pair))]) (defn- get-block-id-content-pairs [block-map] (map get-block-id-content-pair block-map)) (defn- add-linked-by-property [pair] [(first pair) (assoc (second pair) :linked-by '())]) (defn- get-block-id-reference-pairs [block-map] (let [block-map-with-linked-by (map add-linked-by-property block-map) block-id-content-pairs (get-block-id-content-pairs block-map) block-id-reference-pairs (map generate-block-id-reference-pair block-id-content-pairs)] block-id-reference-pairs)) (defn- get-referenced-referer-pair [referenced referer] [referenced referer]) (defn- get-referenced-referer-pairs [referer-referenced-pairs] (let [referer (first referer-referenced-pairs) referenced (second referer-referenced-pairs)] (map #(get-referenced-referer-pair % referer) referenced))) (defn- generate-links [block-id-reference-pairs block-map-no-links] (let [individual-referenced-referer-pairs (partition 2 (flatten (map get-referenced-referer-pairs block-id-reference-pairs))) grouped-by-referenced (group-by first individual-referenced-referer-pairs) reference-names-stripped (map (fn [kv] [(first kv) (map second (second kv))]) grouped-by-referenced) ] (into (hash-map) reference-names-stripped))) (defn- attach-backlinks-to-block [id-backlinks-map block] (let [block-id (first block) block-props (second block)] [block-id (assoc block-props :linked-by (set (get id-backlinks-map block-id '())))])) (defn- attach-backlinks-to-block-map [links block-map] (map #(attach-backlinks-to-block links %) block-map)) (defn- attach-links-to-block [id-reference-map block-kv] (let [block-id (first block-kv) block-props (second block-kv)] [block-id (assoc block-props :refers-to (set (get id-reference-map block-id '())))])) (defn- attach-links-to-block-map [block-id-reference-pairs block-map-no-links] (let [id-reference-map (into (hash-map) block-id-reference-pairs)] (into (hash-map) (map #(attach-links-to-block id-reference-map %) block-map-no-links)))) (defn- generate-links-and-backlinks [block-map-no-links] (let [block-id-reference-pairs (get-block-id-reference-pairs block-map-no-links) broken-references-removed (map filter-broken-references block-id-reference-pairs) block-map-with-links (attach-links-to-block-map broken-references-removed block-map-no-links) backlinks (generate-links broken-references-removed block-map-no-links) block-map-with-backlinks (attach-backlinks-to-block-map backlinks block-map-with-links)] block-map-with-backlinks)) (defn get-linked-references [block-id block-map] (let [block-props (get block-map block-id "BLOCK DOESN'T EXIST") linked-refs (:linked-by block-props)] linked-refs)) (defn- mark-block-as-included [block-kv] [(first block-kv) (assoc (second block-kv) :included true)]) (defn- entry-point? [block-kv] (true? (:entry-point (second block-kv)))) (defn- get-entry-point-ids [block-map] (into #{} (map first (filter entry-point? block-map)))) (defn- get-children-of-block [block-id block-map] (let [block-props (get block-map block-id)] (:children block-props))) (defn- get-all-children-of-blocks [block-ids block-map] (reduce into #{} (map #(get-children-of-block % block-map) block-ids))) (defn- get-references-for-block [block-id block-map] (let [block-props (get block-map block-id)] (:refers-to block-props))) (defn- get-references-for-blocks [block-ids block-map] (let [children (get-all-children-of-blocks block-ids block-map) references (reduce into #{} (map #(get-references-for-block % block-map) children))] (reduce into #{} [children references]))) (defn- get-children-recursively [entity-id block-map] (let [children (set (get-children-of-block entity-id block-map))] (if (empty? (flatten (map #(get-children-of-block % block-map) children))) children (reduce into children (flatten (map #(get-children-recursively % block-map) children)))))) (defn- get-all-children-recursively [examining block-map] (map #(get-children-recursively % block-map) examining)) (defn- aggregate-children [children-sets] (reduce into #{} children-sets)) (defn- get-child-content-references [children block-map] (map #(get-references-for-block % block-map) children)) (defn- aggregate-references [reference-sets] (reduce into #{} reference-sets)) (defn- generate-included-entities [included-entities children references] (reduce into included-entities [children references])) (defn- get-content-entity-ids-to-include [degree block-map] (let [entry-point-ids (into (get-entry-point-ids block-map) #{"SR Metadata"})] (loop [entities-to-examine entry-point-ids children-for-each-entity (get-all-children-recursively entities-to-examine block-map) all-children-of-examined (aggregate-children children-for-each-entity) references-for-children (get-child-content-references all-children-of-examined block-map) all-references-of-children (aggregate-references references-for-children) included-entities (generate-included-entities entities-to-examine all-children-of-examined all-references-of-children) current-degree 0 max-degree degree] (if (>= current-degree max-degree) included-entities (let [entities-to-examine all-references-of-children children-for-each-entity (get-all-children-recursively entities-to-examine block-map) all-children-of-examined (aggregate-children children-for-each-entity) references-for-children (get-child-content-references all-children-of-examined block-map) all-references-of-children (aggregate-references references-for-children) included-entities (generate-included-entities included-entities all-children-of-examined all-references-of-children) current-degree (inc current-degree) max-degree max-degree] (recur entities-to-examine children-for-each-entity all-children-of-examined references-for-children all-references-of-children included-entities current-degree max-degree)))))) (defn- block-id-included? [block-id included-block-ids] (contains? included-block-ids block-id)) (defn- mark-block-if-included [included-block-ids block-kv] (let [block-id (first block-kv) block-props (second block-kv)] (if (block-id-included? block-id included-block-ids) [block-id (assoc block-props :included true)] [block-id (assoc block-props :included false)]))) (defn- mark-blocks-to-include-as-included [included-block-ids block-map] (map #(mark-block-if-included included-block-ids %) block-map)) (defn- mark-content-entities-for-inclusion [degree block-map] (if (and (int? degree) (>= degree 0)) (into (hash-map) (mark-blocks-to-include-as-included (get-content-entity-ids-to-include degree block-map) block-map)) (into (hash-map) (map mark-block-as-included block-map)))) (defn- give-header [the-hiccup block-props] [(keyword (str "h" (:heading block-props))) the-hiccup]) (defn- generate-hiccup-if-block-is-included [block-kv block-map] (let [block-id (first block-kv) block-props (second block-kv)] [block-id (if (true? (:included block-props)) (assoc block-props :hiccup (let [heading (:heading block-props) the-hiccup (parser/block-content->hiccup (:content block-props) block-map)] (if (> (:heading block-props) 0) (give-header the-hiccup block-props) the-hiccup))) block-props)])) (defn generate-hiccup-for-included-blocks [block-map] (into (hash-map) (filter #(not= nil (:content (second %))) (map #(generate-hiccup-if-block-is-included % block-map) block-map)))) (defn replicate-roam-db [roam-json] (let [block-map-no-links (create-block-map-no-links roam-json) block-map-linked-by-and-refers-to (generate-links-and-backlinks block-map-no-links)] (into (hash-map) block-map-linked-by-and-refers-to))) (defn- lkjsafas [pair block-map] (let [block-id (first pair) block-props (second pair) block-content (:content block-props) block-embed-found (re-find #"\{\{embed: .*?\}\}|\{\{\[\[embed\]\]: .*?\}\}" block-content)] (if block-embed-found (let [block-ref-uncleaned (re-find #"\(\(.*?\)\)|\[\[.*?\]\]" (second (str-utils/split block-embed-found #":"))) referenced-block-id (utils/remove-double-delimiters block-ref-uncleaned) referenced-block-props (get block-map referenced-block-id)] [block-id (assoc block-props :children (into (:children block-props) (reverse (:children referenced-block-props))) :content (:content referenced-block-props))]) pair))) (defn- add-children-of-block-embeds [block-map] (into (hash-map) (map #(lkjsafas % block-map) block-map))) (defn setup-static-roam-block-map [roam-json degree] (let [replicated-roam-block-map (replicate-roam-db roam-json) blocks-tagged-for-inclusion (mark-content-entities-for-inclusion degree replicated-roam-block-map) children-of-embeds-added (add-children-of-block-embeds blocks-tagged-for-inclusion) hiccup-for-included-blocks (generate-hiccup-for-included-blocks children-of-embeds-added)] hiccup-for-included-blocks)) (defn- include-children-of-included-pages [roam-db]) (defn- include-explicitly-included-blocks [roam-db include-tags] (let [sr-info-eid (first (first (ds/q '[:find ?eid :where [?eid :node/title "Static-Roam Info"]] @roam-db))) explicit-include-eids (map #(first (first %)) (map #(ds/q '[:find ?eid :in $ ?tag :where [?eid :node/title ?tag]] @roam-db %) include-tags)) eids-of-explicit-includes (reduce into [] (map first (map #(ds/q '[:find ?parent-eid :in $ ?explicit-include-tag-eid :where [?eid :block/refs sr-info-eid] [?eid :block/refs ?explicit-include-tag-eid] [?eid :block/parents ?parent-eid]] @roam-db %) explicit-include-eids))) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) eids-of-explicit-includes)) ;; TODO include children as well ] (ds/transact! roam-db transactions))) (defn- exclude-explicitly-excluded-blocks [roam-db exclude-tags] (let [sr-info-eid (first (first (ds/q '[:find ?eid :where [?eid :node/title "Static-Roam Info"]] @roam-db))) explicit-exclude-eid (map #(first (first %)) (map #(ds/q '[:find ?eid :in $ ?tag :where [?eid :node/title ?tag]] @roam-db %) exclude-tags)) eids-of-explicit-excludes (reduce into [] (map first (map #(ds/q '[:find ?parent-eid :in $ ?explicit-exclude-tag-eid :where [?eid :block/refs sr-info-eid] [?eid :block/refs ?explicit-exclude-tag-eid] [?eid :block/parents ?parent-eid]] @roam-db %) explicit-exclude-eid))) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) eids-of-explicit-excludes)) ;; TODO exclude children as well ] (ds/transact! roam-db transactions))) (defn- mark-all-entities-as-excluded [roam-db] (let [eids (map first (ds/q '[:find ?eid :where [?eid]] @roam-db)) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) eids))] (ds/transact! roam-db transactions)) ;; might want to make this more nuanced so only entities with :block/string or :node/title get included ) (defn- get-parent-eids [roam-db sr-info-eid entity-tag-eid] (let [query-result (ds/q '[:find ?parent-eid :in $ ?entity-tag-eid ?sr-info-eid :where [?eid :block/refs ?sr-info-eid] [?eid :block/refs ?entity-tag-eid] [?parent-eid :block/children ?eid]] @roam-db entity-tag-eid sr-info-eid)] query-result)) (defn- get-all-queries [roam-db sr-info-eid entity-tag-eids] (let [nils-removed (filter #(not (nil? %)) entity-tag-eids)] (if (empty? nils-removed) [] (let [query-results (map #(get-parent-eids roam-db sr-info-eid %) entity-tag-eids)] query-results)))) (defn- get-eids-of-entities-with-tags [roam-db tags] (println tags) (let [sr-info-eid (first (first (ds/q '[:find ?eid :where [?eid :node/title "Static-Roam Info"]] @roam-db))) entity-tag-eids (map #(first (first %)) (map #(ds/q '[:find ?eid :in $ ?tag :where [?eid :node/title ?tag]] @roam-db %) tags)) eids-of-entities-with-tags (map first (reduce into [] (get-all-queries roam-db sr-info-eid entity-tag-eids)))] eids-of-entities-with-tags)) (defn- get-descendant-eids [roam-db eid] ;; This is a very important function and will be used in further steps (let [eid (if (vector? eid) (first eid) eid) children (map first (ds/q '[:find ?children-eids :in $ ?parent-eid :where [?parent-eid :block/children ?children-eids]] @roam-db eid))] (reduce into children (map #(get-descendant-eids roam-db %) children)))) (defn- get-descendant-eids-for-eids [roam-db eids] (reduce into #{} (map #(get-descendant-eids roam-db %) eids))) (defn- get-refs-for-entity [roam-db eid] (map first (ds/q '[:find ?ref-eids :in $ ?eid :where [?eid :block/refs ?ref-eids]] @roam-db eid))) (defn- get-refs-of-descendants [roam-db descendant-eids] (reduce into #{} (map #(get-refs-for-entity roam-db %) descendant-eids))) (defn- get-entities-linked-by-descendants [roam-db eid] (let [descendant-eids (get-descendant-eids roam-db eid) refs (get-refs-of-descendants roam-db descendant-eids)] refs)) (defn- get-eids-linked-by-entity [roam-db eid] (let [eids-linked (get-entities-linked-by-descendants roam-db eid)] eids-linked)) (defn- get-entities-linked-by [roam-db eids] (let [all-eids-linked (reduce into #{} (map #(get-eids-linked-by-entity roam-db %) eids))] all-eids-linked)) (defn- mark-refs-as-included [roam-db degree entry-point-eids] (let [eids entry-point-eids linked-eids (get-entities-linked-by roam-db eids) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) linked-eids))] (ds/transact! roam-db transactions) (when (> degree 0) (mark-refs-as-included roam-db (dec degree) linked-eids)))) (defn- mark-entry-points-and-refs-as-included [roam-db degree entry-point-tags other-page-tags] (let [entry-point-eids (get-eids-of-entities-with-tags roam-db (into entry-point-tags (filter (complement nil?) other-page-tags))) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) entry-point-eids))] (ds/transact! roam-db transactions) ;; mark entry points as included (mark-refs-as-included roam-db degree entry-point-eids) (include-children-of-included-pages roam-db))) (defn- get-children-recursively [roam-db eid] (let [children-eids (map #(:db/id %) (:block/children (ds/entity (ds/db roam-db) eid)))] (if (not= 0 (count children-eids)) (reduce into children-eids (map #(get-children-recursively roam-db %) children-eids)) nil))) (defn- mark-included-entity-children-as-included [roam-db] (let [entities-marked-for-inclusion (map first (ds/q '[:find ?included-eids :where [?included-eids :static-roam/included true]] @roam-db)) entity-children-seqs (map #(get-children-recursively roam-db %) entities-marked-for-inclusion) entity-children-eids (filter (complement nil?) (flatten entity-children-seqs)) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) entity-children-eids))] (ds/transact! roam-db transactions))) (defn- mark-entry-point-and-ref-pages-as-included [roam-db degree entry-point-tags other-page-tags] (mark-entry-points-and-refs-as-included roam-db degree entry-point-tags other-page-tags) (mark-included-entity-children-as-included roam-db)) (defn- mark-all-entities-as-included [roam-db] (let [eids (map first (ds/q '[:find ?eid :where [?eid]] @roam-db)) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) eids))] (ds/transact! roam-db transactions))) (defn- include-tagged [roam-db tagged] (let [explicitly-included-tag-eids (get-eids-of-entities-with-tags roam-db tagged) children-of-entities-eids (get-descendant-eids-for-eids roam-db explicitly-included-tag-eids) parent-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) explicitly-included-tag-eids)) children-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) children-of-entities-eids))] (ds/transact! roam-db parent-transactions) (ds/transact! roam-db children-transactions))) (defn- get-eid-of-node-with-title [roam-db title] (first (first (ds/q '[:find ?eid :in $ ?title :where [?eid :node/title ?title]] @roam-db title)))) (defn- get-eids-of-nodes-with-titles [roam-db titles] (map #(get-eid-of-node-with-title roam-db %) titles)) (defn- get-eids-of-entities-with-refs-to [roam-db refs] (let [ref-eids (get-eids-of-nodes-with-titles roam-db refs) eids-linking-to-ref (map first (map #(ds/q '[:find ?eid :in $ ?ref-eid :where [?eid :block/refs ?ref-eid]] @roam-db %) ref-eids))] eids-linking-to-ref)) (defn- include-refs [roam-db refs] (let [explicitly-included-ref-eids (get-eids-of-entities-with-refs-to roam-db refs) children-of-entities-eids (get-descendant-eids-for-eids roam-db explicitly-included-ref-eids) parent-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) explicitly-included-ref-eids)) children-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) children-of-entities-eids))] (ds/transact! roam-db parent-transactions) (ds/transact! roam-db children-transactions))) (defn- include-explicitly-included [roam-db tagged refs] (include-tagged roam-db tagged) (include-refs roam-db refs)) (defn- exclude-tagged [roam-db tagged] (let [explicitly-excluded-tag-eids (get-eids-of-entities-with-tags roam-db tagged) children-of-entities-eids (get-descendant-eids-for-eids roam-db explicitly-excluded-tag-eids) parent-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) explicitly-excluded-tag-eids)) children-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) children-of-entities-eids))] (ds/transact! roam-db parent-transactions) (ds/transact! roam-db children-transactions))) (defn- exclude-refs [roam-db refs] (let [explicitly-excluded-ref-eids (flatten (get-eids-of-entities-with-refs-to roam-db refs)) children-of-entities-eids (flatten (get-descendant-eids-for-eids roam-db explicitly-excluded-ref-eids)) parent-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) explicitly-excluded-ref-eids)) children-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) children-of-entities-eids))] (ds/transact! roam-db parent-transactions) (ds/transact! roam-db children-transactions))) (defn- exclude-explicitly-excluded [roam-db tagged refs] (exclude-tagged roam-db tagged) (exclude-refs roam-db refs)) (defn- retract-all-excluded-entities [roam-db] (let [excluded-eids (map first(ds/q '[:find ?eid :where [?eid :static-roam/included false]] @roam-db)) retraction-transactions (vec (map (fn [eid] [:db.fn/retractEntity eid]) excluded-eids))] (ds/transact! roam-db retraction-transactions))) (defn determine-which-content-to-include [roam-db degree config] (mark-all-entities-as-excluded roam-db) (if (int? degree) (mark-entry-point-and-ref-pages-as-included roam-db degree (:entry-point-tags config) (map :tagged-as (:template-info config))) (mark-all-entities-as-included roam-db)) (include-explicitly-included roam-db (into (into #{} (:include-tagged config)) (filter (complement nil?) (map :tagged-as (vals (:template-info config))))) (:include-refs config)) (exclude-explicitly-excluded roam-db (:exclude-tagged config) (:exclude-refs config)) (retract-all-excluded-entities roam-db))
null
https://raw.githubusercontent.com/TomLisankie/static-roam/f8f63825f0e8b7f5b53e3400025aa97a2c5c8061/src/static_roam/database.clj
clojure
what I need to happen here is have it so if the block has children, it creates pairs for those as well forget what I already implemented, I optimized too early. sometimes people put references to other page titles inside of the title of another page. So pairs of brackets inside of other brackets when they reference them. This breaks things currently, so I'm removing all those instances here TODO: Fix so this is unnecessary TODO include children as well TODO exclude children as well might want to make this more nuanced so only entities with :block/string or :node/title get included This is a very important function and will be used in further steps mark entry points as included
(ns static-roam.database (:require [static-roam.parser :as parser] [static-roam.utils :as utils] [clojure.string :as str-utils] [datascript.core :as ds] [clojure.pprint :as pprint])) (defn- get-block-id [block-json] (if (:title block-json) (:title block-json) (:uid block-json))) (defn get-properties-for-block-id [block-id block-map] (get block-map block-id)) (defn- get-block-properties [block-json] { :children (map :uid (:children block-json)) :content (:string block-json (:title block-json)) :heading (:heading block-json -1) :text-align (:text-align block-json "") :entry-point (parser/entry-point? block-json) :page (if (:title block-json) true false) }) (defn- generate-block-linking-transaction [referer-eid reference-id] {:block/id reference-id :block/linked-by referer-eid}) (defn- create-id-properties-pair [block-json] [(get-block-id block-json) (get-block-properties block-json)]) (defn- create-id-properties-pairs [roam-json] (map vec (partition 2 (flatten (for [block-json roam-json] (conj (create-id-properties-pairs (:children block-json)) (create-id-properties-pair block-json))))))) (defn- create-block-map-no-links "Populate database with relevant properties of pages and blocks" [roam-json] (into (hash-map) (create-id-properties-pairs roam-json))) (defn- clean-content-entities [string] (let [content-entities-found (utils/find-content-entities-in-string string) hashtags-found (utils/find-hashtags-in-string string) metadata-found (utils/find-metadata-in-string string) extra-paren-removed (utils/remove-heading-parens content-entities-found) cleaned-content-entities (map utils/remove-double-delimiters extra-paren-removed) cleaned-hashtags (map utils/remove-leading-char hashtags-found) cleaned-metadata (map utils/remove-double-colon metadata-found) all-cleaned-entities (concat cleaned-content-entities cleaned-hashtags cleaned-metadata)] all-cleaned-entities)) (defn- filter-broken-references [pair] [(first pair) (filter #(not (str-utils/includes? % "[")) (second pair))]) (defn- generate-block-id-reference-pair [pair] [(first pair) (clean-content-entities (second pair))]) (defn- generate-block-linking-transactions-for-entity-reference-pair [entity-id-reference-pair] (let [referer-eid (first entity-id-reference-pair) reference-ids (second entity-id-reference-pair)] (map #(generate-block-linking-transaction referer-eid %) reference-ids))) (defn- generate-transactions-for-linking-blocks [entity-id-reference-pairs] (map generate-block-linking-transactions-for-entity-reference-pair entity-id-reference-pairs)) (defn- get-block-id-content-pair [pair] [(first pair) (:content (second pair))]) (defn- get-block-id-content-pairs [block-map] (map get-block-id-content-pair block-map)) (defn- add-linked-by-property [pair] [(first pair) (assoc (second pair) :linked-by '())]) (defn- get-block-id-reference-pairs [block-map] (let [block-map-with-linked-by (map add-linked-by-property block-map) block-id-content-pairs (get-block-id-content-pairs block-map) block-id-reference-pairs (map generate-block-id-reference-pair block-id-content-pairs)] block-id-reference-pairs)) (defn- get-referenced-referer-pair [referenced referer] [referenced referer]) (defn- get-referenced-referer-pairs [referer-referenced-pairs] (let [referer (first referer-referenced-pairs) referenced (second referer-referenced-pairs)] (map #(get-referenced-referer-pair % referer) referenced))) (defn- generate-links [block-id-reference-pairs block-map-no-links] (let [individual-referenced-referer-pairs (partition 2 (flatten (map get-referenced-referer-pairs block-id-reference-pairs))) grouped-by-referenced (group-by first individual-referenced-referer-pairs) reference-names-stripped (map (fn [kv] [(first kv) (map second (second kv))]) grouped-by-referenced) ] (into (hash-map) reference-names-stripped))) (defn- attach-backlinks-to-block [id-backlinks-map block] (let [block-id (first block) block-props (second block)] [block-id (assoc block-props :linked-by (set (get id-backlinks-map block-id '())))])) (defn- attach-backlinks-to-block-map [links block-map] (map #(attach-backlinks-to-block links %) block-map)) (defn- attach-links-to-block [id-reference-map block-kv] (let [block-id (first block-kv) block-props (second block-kv)] [block-id (assoc block-props :refers-to (set (get id-reference-map block-id '())))])) (defn- attach-links-to-block-map [block-id-reference-pairs block-map-no-links] (let [id-reference-map (into (hash-map) block-id-reference-pairs)] (into (hash-map) (map #(attach-links-to-block id-reference-map %) block-map-no-links)))) (defn- generate-links-and-backlinks [block-map-no-links] (let [block-id-reference-pairs (get-block-id-reference-pairs block-map-no-links) broken-references-removed (map filter-broken-references block-id-reference-pairs) block-map-with-links (attach-links-to-block-map broken-references-removed block-map-no-links) backlinks (generate-links broken-references-removed block-map-no-links) block-map-with-backlinks (attach-backlinks-to-block-map backlinks block-map-with-links)] block-map-with-backlinks)) (defn get-linked-references [block-id block-map] (let [block-props (get block-map block-id "BLOCK DOESN'T EXIST") linked-refs (:linked-by block-props)] linked-refs)) (defn- mark-block-as-included [block-kv] [(first block-kv) (assoc (second block-kv) :included true)]) (defn- entry-point? [block-kv] (true? (:entry-point (second block-kv)))) (defn- get-entry-point-ids [block-map] (into #{} (map first (filter entry-point? block-map)))) (defn- get-children-of-block [block-id block-map] (let [block-props (get block-map block-id)] (:children block-props))) (defn- get-all-children-of-blocks [block-ids block-map] (reduce into #{} (map #(get-children-of-block % block-map) block-ids))) (defn- get-references-for-block [block-id block-map] (let [block-props (get block-map block-id)] (:refers-to block-props))) (defn- get-references-for-blocks [block-ids block-map] (let [children (get-all-children-of-blocks block-ids block-map) references (reduce into #{} (map #(get-references-for-block % block-map) children))] (reduce into #{} [children references]))) (defn- get-children-recursively [entity-id block-map] (let [children (set (get-children-of-block entity-id block-map))] (if (empty? (flatten (map #(get-children-of-block % block-map) children))) children (reduce into children (flatten (map #(get-children-recursively % block-map) children)))))) (defn- get-all-children-recursively [examining block-map] (map #(get-children-recursively % block-map) examining)) (defn- aggregate-children [children-sets] (reduce into #{} children-sets)) (defn- get-child-content-references [children block-map] (map #(get-references-for-block % block-map) children)) (defn- aggregate-references [reference-sets] (reduce into #{} reference-sets)) (defn- generate-included-entities [included-entities children references] (reduce into included-entities [children references])) (defn- get-content-entity-ids-to-include [degree block-map] (let [entry-point-ids (into (get-entry-point-ids block-map) #{"SR Metadata"})] (loop [entities-to-examine entry-point-ids children-for-each-entity (get-all-children-recursively entities-to-examine block-map) all-children-of-examined (aggregate-children children-for-each-entity) references-for-children (get-child-content-references all-children-of-examined block-map) all-references-of-children (aggregate-references references-for-children) included-entities (generate-included-entities entities-to-examine all-children-of-examined all-references-of-children) current-degree 0 max-degree degree] (if (>= current-degree max-degree) included-entities (let [entities-to-examine all-references-of-children children-for-each-entity (get-all-children-recursively entities-to-examine block-map) all-children-of-examined (aggregate-children children-for-each-entity) references-for-children (get-child-content-references all-children-of-examined block-map) all-references-of-children (aggregate-references references-for-children) included-entities (generate-included-entities included-entities all-children-of-examined all-references-of-children) current-degree (inc current-degree) max-degree max-degree] (recur entities-to-examine children-for-each-entity all-children-of-examined references-for-children all-references-of-children included-entities current-degree max-degree)))))) (defn- block-id-included? [block-id included-block-ids] (contains? included-block-ids block-id)) (defn- mark-block-if-included [included-block-ids block-kv] (let [block-id (first block-kv) block-props (second block-kv)] (if (block-id-included? block-id included-block-ids) [block-id (assoc block-props :included true)] [block-id (assoc block-props :included false)]))) (defn- mark-blocks-to-include-as-included [included-block-ids block-map] (map #(mark-block-if-included included-block-ids %) block-map)) (defn- mark-content-entities-for-inclusion [degree block-map] (if (and (int? degree) (>= degree 0)) (into (hash-map) (mark-blocks-to-include-as-included (get-content-entity-ids-to-include degree block-map) block-map)) (into (hash-map) (map mark-block-as-included block-map)))) (defn- give-header [the-hiccup block-props] [(keyword (str "h" (:heading block-props))) the-hiccup]) (defn- generate-hiccup-if-block-is-included [block-kv block-map] (let [block-id (first block-kv) block-props (second block-kv)] [block-id (if (true? (:included block-props)) (assoc block-props :hiccup (let [heading (:heading block-props) the-hiccup (parser/block-content->hiccup (:content block-props) block-map)] (if (> (:heading block-props) 0) (give-header the-hiccup block-props) the-hiccup))) block-props)])) (defn generate-hiccup-for-included-blocks [block-map] (into (hash-map) (filter #(not= nil (:content (second %))) (map #(generate-hiccup-if-block-is-included % block-map) block-map)))) (defn replicate-roam-db [roam-json] (let [block-map-no-links (create-block-map-no-links roam-json) block-map-linked-by-and-refers-to (generate-links-and-backlinks block-map-no-links)] (into (hash-map) block-map-linked-by-and-refers-to))) (defn- lkjsafas [pair block-map] (let [block-id (first pair) block-props (second pair) block-content (:content block-props) block-embed-found (re-find #"\{\{embed: .*?\}\}|\{\{\[\[embed\]\]: .*?\}\}" block-content)] (if block-embed-found (let [block-ref-uncleaned (re-find #"\(\(.*?\)\)|\[\[.*?\]\]" (second (str-utils/split block-embed-found #":"))) referenced-block-id (utils/remove-double-delimiters block-ref-uncleaned) referenced-block-props (get block-map referenced-block-id)] [block-id (assoc block-props :children (into (:children block-props) (reverse (:children referenced-block-props))) :content (:content referenced-block-props))]) pair))) (defn- add-children-of-block-embeds [block-map] (into (hash-map) (map #(lkjsafas % block-map) block-map))) (defn setup-static-roam-block-map [roam-json degree] (let [replicated-roam-block-map (replicate-roam-db roam-json) blocks-tagged-for-inclusion (mark-content-entities-for-inclusion degree replicated-roam-block-map) children-of-embeds-added (add-children-of-block-embeds blocks-tagged-for-inclusion) hiccup-for-included-blocks (generate-hiccup-for-included-blocks children-of-embeds-added)] hiccup-for-included-blocks)) (defn- include-children-of-included-pages [roam-db]) (defn- include-explicitly-included-blocks [roam-db include-tags] (let [sr-info-eid (first (first (ds/q '[:find ?eid :where [?eid :node/title "Static-Roam Info"]] @roam-db))) explicit-include-eids (map #(first (first %)) (map #(ds/q '[:find ?eid :in $ ?tag :where [?eid :node/title ?tag]] @roam-db %) include-tags)) eids-of-explicit-includes (reduce into [] (map first (map #(ds/q '[:find ?parent-eid :in $ ?explicit-include-tag-eid :where [?eid :block/refs sr-info-eid] [?eid :block/refs ?explicit-include-tag-eid] [?eid :block/parents ?parent-eid]] @roam-db %) explicit-include-eids))) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) eids-of-explicit-includes)) ] (ds/transact! roam-db transactions))) (defn- exclude-explicitly-excluded-blocks [roam-db exclude-tags] (let [sr-info-eid (first (first (ds/q '[:find ?eid :where [?eid :node/title "Static-Roam Info"]] @roam-db))) explicit-exclude-eid (map #(first (first %)) (map #(ds/q '[:find ?eid :in $ ?tag :where [?eid :node/title ?tag]] @roam-db %) exclude-tags)) eids-of-explicit-excludes (reduce into [] (map first (map #(ds/q '[:find ?parent-eid :in $ ?explicit-exclude-tag-eid :where [?eid :block/refs sr-info-eid] [?eid :block/refs ?explicit-exclude-tag-eid] [?eid :block/parents ?parent-eid]] @roam-db %) explicit-exclude-eid))) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) eids-of-explicit-excludes)) ] (ds/transact! roam-db transactions))) (defn- mark-all-entities-as-excluded [roam-db] (let [eids (map first (ds/q '[:find ?eid :where [?eid]] @roam-db)) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) eids))] ) (defn- get-parent-eids [roam-db sr-info-eid entity-tag-eid] (let [query-result (ds/q '[:find ?parent-eid :in $ ?entity-tag-eid ?sr-info-eid :where [?eid :block/refs ?sr-info-eid] [?eid :block/refs ?entity-tag-eid] [?parent-eid :block/children ?eid]] @roam-db entity-tag-eid sr-info-eid)] query-result)) (defn- get-all-queries [roam-db sr-info-eid entity-tag-eids] (let [nils-removed (filter #(not (nil? %)) entity-tag-eids)] (if (empty? nils-removed) [] (let [query-results (map #(get-parent-eids roam-db sr-info-eid %) entity-tag-eids)] query-results)))) (defn- get-eids-of-entities-with-tags [roam-db tags] (println tags) (let [sr-info-eid (first (first (ds/q '[:find ?eid :where [?eid :node/title "Static-Roam Info"]] @roam-db))) entity-tag-eids (map #(first (first %)) (map #(ds/q '[:find ?eid :in $ ?tag :where [?eid :node/title ?tag]] @roam-db %) tags)) eids-of-entities-with-tags (map first (reduce into [] (get-all-queries roam-db sr-info-eid entity-tag-eids)))] eids-of-entities-with-tags)) (defn- get-descendant-eids [roam-db eid] (let [eid (if (vector? eid) (first eid) eid) children (map first (ds/q '[:find ?children-eids :in $ ?parent-eid :where [?parent-eid :block/children ?children-eids]] @roam-db eid))] (reduce into children (map #(get-descendant-eids roam-db %) children)))) (defn- get-descendant-eids-for-eids [roam-db eids] (reduce into #{} (map #(get-descendant-eids roam-db %) eids))) (defn- get-refs-for-entity [roam-db eid] (map first (ds/q '[:find ?ref-eids :in $ ?eid :where [?eid :block/refs ?ref-eids]] @roam-db eid))) (defn- get-refs-of-descendants [roam-db descendant-eids] (reduce into #{} (map #(get-refs-for-entity roam-db %) descendant-eids))) (defn- get-entities-linked-by-descendants [roam-db eid] (let [descendant-eids (get-descendant-eids roam-db eid) refs (get-refs-of-descendants roam-db descendant-eids)] refs)) (defn- get-eids-linked-by-entity [roam-db eid] (let [eids-linked (get-entities-linked-by-descendants roam-db eid)] eids-linked)) (defn- get-entities-linked-by [roam-db eids] (let [all-eids-linked (reduce into #{} (map #(get-eids-linked-by-entity roam-db %) eids))] all-eids-linked)) (defn- mark-refs-as-included [roam-db degree entry-point-eids] (let [eids entry-point-eids linked-eids (get-entities-linked-by roam-db eids) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) linked-eids))] (ds/transact! roam-db transactions) (when (> degree 0) (mark-refs-as-included roam-db (dec degree) linked-eids)))) (defn- mark-entry-points-and-refs-as-included [roam-db degree entry-point-tags other-page-tags] (let [entry-point-eids (get-eids-of-entities-with-tags roam-db (into entry-point-tags (filter (complement nil?) other-page-tags))) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) entry-point-eids))] (mark-refs-as-included roam-db degree entry-point-eids) (include-children-of-included-pages roam-db))) (defn- get-children-recursively [roam-db eid] (let [children-eids (map #(:db/id %) (:block/children (ds/entity (ds/db roam-db) eid)))] (if (not= 0 (count children-eids)) (reduce into children-eids (map #(get-children-recursively roam-db %) children-eids)) nil))) (defn- mark-included-entity-children-as-included [roam-db] (let [entities-marked-for-inclusion (map first (ds/q '[:find ?included-eids :where [?included-eids :static-roam/included true]] @roam-db)) entity-children-seqs (map #(get-children-recursively roam-db %) entities-marked-for-inclusion) entity-children-eids (filter (complement nil?) (flatten entity-children-seqs)) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) entity-children-eids))] (ds/transact! roam-db transactions))) (defn- mark-entry-point-and-ref-pages-as-included [roam-db degree entry-point-tags other-page-tags] (mark-entry-points-and-refs-as-included roam-db degree entry-point-tags other-page-tags) (mark-included-entity-children-as-included roam-db)) (defn- mark-all-entities-as-included [roam-db] (let [eids (map first (ds/q '[:find ?eid :where [?eid]] @roam-db)) transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) eids))] (ds/transact! roam-db transactions))) (defn- include-tagged [roam-db tagged] (let [explicitly-included-tag-eids (get-eids-of-entities-with-tags roam-db tagged) children-of-entities-eids (get-descendant-eids-for-eids roam-db explicitly-included-tag-eids) parent-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) explicitly-included-tag-eids)) children-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) children-of-entities-eids))] (ds/transact! roam-db parent-transactions) (ds/transact! roam-db children-transactions))) (defn- get-eid-of-node-with-title [roam-db title] (first (first (ds/q '[:find ?eid :in $ ?title :where [?eid :node/title ?title]] @roam-db title)))) (defn- get-eids-of-nodes-with-titles [roam-db titles] (map #(get-eid-of-node-with-title roam-db %) titles)) (defn- get-eids-of-entities-with-refs-to [roam-db refs] (let [ref-eids (get-eids-of-nodes-with-titles roam-db refs) eids-linking-to-ref (map first (map #(ds/q '[:find ?eid :in $ ?ref-eid :where [?eid :block/refs ?ref-eid]] @roam-db %) ref-eids))] eids-linking-to-ref)) (defn- include-refs [roam-db refs] (let [explicitly-included-ref-eids (get-eids-of-entities-with-refs-to roam-db refs) children-of-entities-eids (get-descendant-eids-for-eids roam-db explicitly-included-ref-eids) parent-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) explicitly-included-ref-eids)) children-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included true]) children-of-entities-eids))] (ds/transact! roam-db parent-transactions) (ds/transact! roam-db children-transactions))) (defn- include-explicitly-included [roam-db tagged refs] (include-tagged roam-db tagged) (include-refs roam-db refs)) (defn- exclude-tagged [roam-db tagged] (let [explicitly-excluded-tag-eids (get-eids-of-entities-with-tags roam-db tagged) children-of-entities-eids (get-descendant-eids-for-eids roam-db explicitly-excluded-tag-eids) parent-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) explicitly-excluded-tag-eids)) children-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) children-of-entities-eids))] (ds/transact! roam-db parent-transactions) (ds/transact! roam-db children-transactions))) (defn- exclude-refs [roam-db refs] (let [explicitly-excluded-ref-eids (flatten (get-eids-of-entities-with-refs-to roam-db refs)) children-of-entities-eids (flatten (get-descendant-eids-for-eids roam-db explicitly-excluded-ref-eids)) parent-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) explicitly-excluded-ref-eids)) children-transactions (vec (map (fn [eid] [:db/add eid :static-roam/included false]) children-of-entities-eids))] (ds/transact! roam-db parent-transactions) (ds/transact! roam-db children-transactions))) (defn- exclude-explicitly-excluded [roam-db tagged refs] (exclude-tagged roam-db tagged) (exclude-refs roam-db refs)) (defn- retract-all-excluded-entities [roam-db] (let [excluded-eids (map first(ds/q '[:find ?eid :where [?eid :static-roam/included false]] @roam-db)) retraction-transactions (vec (map (fn [eid] [:db.fn/retractEntity eid]) excluded-eids))] (ds/transact! roam-db retraction-transactions))) (defn determine-which-content-to-include [roam-db degree config] (mark-all-entities-as-excluded roam-db) (if (int? degree) (mark-entry-point-and-ref-pages-as-included roam-db degree (:entry-point-tags config) (map :tagged-as (:template-info config))) (mark-all-entities-as-included roam-db)) (include-explicitly-included roam-db (into (into #{} (:include-tagged config)) (filter (complement nil?) (map :tagged-as (vals (:template-info config))))) (:include-refs config)) (exclude-explicitly-excluded roam-db (:exclude-tagged config) (:exclude-refs config)) (retract-all-excluded-entities roam-db))
1e08ab99a08595773356a8ecf9dddaddef81a490130a343930c70813031ff23f
aryx/ocamltarzan
builtins.ml
type 'a ref = { (* mutable *) contents: 'a } (* with tarzan *) type 'a option = | None | Some of 'a (* with tarzan *)
null
https://raw.githubusercontent.com/aryx/ocamltarzan/4140f5102cee83a2ca7be996ca2d92e9cb035f9c/tests/builtins.ml
ocaml
mutable with tarzan with tarzan
type 'a option = | None | Some of 'a
640da0d4fffbba5faab9642086614c10a414d3c19ae68ce8fdfe3250d29508fb
nedap/formatting-stack
git_diff.clj
(ns formatting-stack.strategies.impl.git-diff "Functions for `git diff --name-status` parsing. Note that commands such as `git status`, `git ls-files` do not share its output format." (:require [clojure.string :as string] [nedap.speced.def :as speced])) (speced/defn deletion? [^string? s] (-> s (string/starts-with? "D\t"))) ;; See: `git diff --help`, `diff-filter` section (speced/defn remove-markers [^string? s] (-> s (string/replace-first #"^(A|C|D|M|R|T|U|X|B)\t" "")))
null
https://raw.githubusercontent.com/nedap/formatting-stack/c43e74d5409e9338f208457bb8928ce437381a3f/src/formatting_stack/strategies/impl/git_diff.clj
clojure
See: `git diff --help`, `diff-filter` section
(ns formatting-stack.strategies.impl.git-diff "Functions for `git diff --name-status` parsing. Note that commands such as `git status`, `git ls-files` do not share its output format." (:require [clojure.string :as string] [nedap.speced.def :as speced])) (speced/defn deletion? [^string? s] (-> s (string/starts-with? "D\t"))) (speced/defn remove-markers [^string? s] (-> s (string/replace-first #"^(A|C|D|M|R|T|U|X|B)\t" "")))
c356bf4a95ad0e6510ea664c509daedaf958777e1ca8333cc88cb1fca03d6168
ghcjs/ghcjs
t10962.hs
# LANGUAGE MagicHash # # LANGUAGE UnboxedTuples # module Main (main) where import GHC.Base unW# :: Word -> Word# unW# (W# w) = w type WordOpC = Word# -> Word# -> (# Word#, Int# #) check :: WordOpC -> Word# -> Word# -> IO () check op a b = do let (# w, c #) = op a b print (W# w, I# c) checkSubInlNoInl :: WordOpC -> Word# -> Word# -> IO () checkSubInlNoInl op a b = do inline check op a b -- constant folding noinline check op a b -- lowering of PrimOp # INLINE checkSubInlNoInl # main :: IO () main = do -- Overflow. checkSubInlNoInl subWordC# 1## 3## checkSubInlNoInl addWordC# (unW# (inline maxBound)) 3## -- No overflow. checkSubInlNoInl subWordC# 5## 2## checkSubInlNoInl addWordC# (unW# (inline maxBound-1)) 1##
null
https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/ghc/numeric/t10962.hs
haskell
constant folding lowering of PrimOp Overflow. No overflow.
# LANGUAGE MagicHash # # LANGUAGE UnboxedTuples # module Main (main) where import GHC.Base unW# :: Word -> Word# unW# (W# w) = w type WordOpC = Word# -> Word# -> (# Word#, Int# #) check :: WordOpC -> Word# -> Word# -> IO () check op a b = do let (# w, c #) = op a b print (W# w, I# c) checkSubInlNoInl :: WordOpC -> Word# -> Word# -> IO () checkSubInlNoInl op a b = do # INLINE checkSubInlNoInl # main :: IO () main = do checkSubInlNoInl subWordC# 1## 3## checkSubInlNoInl addWordC# (unW# (inline maxBound)) 3## checkSubInlNoInl subWordC# 5## 2## checkSubInlNoInl addWordC# (unW# (inline maxBound-1)) 1##
b6871ccb7c4dfc3d37aa16d535251c7385776df29c85bf6b02f5b32e85e0a631
zclj/replication-packages
handler.clj
(ns graphql-toy.test.handler (:require [clojure.test :refer :all] [ring.mock.request :refer :all] [graphql-toy.handler :refer :all] [graphql-toy.middleware.formats :as formats] [muuntaja.core :as m] [mount.core :as mount])) (defn parse-json [body] (m/decode formats/instance "application/json" body)) (use-fixtures :once (fn [f] (mount/start #'graphql-toy.config/env #'graphql-toy.handler/app-routes) (f))) (deftest test-app (testing "main route" (let [response ((app) (request :get "/"))] (is (= 200 (:status response))))) (testing "not-found route" (let [response ((app) (request :get "/invalid"))] (is (= 404 (:status response))))) (testing "services" (testing "success" (let [response ((app) (-> (request :post "/api/math/plus") (json-body {:x 10, :y 6})))] (is (= 200 (:status response))) (is (= {:total 16} (m/decode-response-body response))))) (testing "parameter coercion error" (let [response ((app) (-> (request :post "/api/math/plus") (json-body {:x 10, :y "invalid"})))] (is (= 400 (:status response))))) (testing "response coercion error" (let [response ((app) (-> (request :post "/api/math/plus") (json-body {:x -10, :y 6})))] (is (= 500 (:status response))))) (testing "content negotiation" (let [response ((app) (-> (request :post "/api/math/plus") (body (pr-str {:x 10, :y 6})) (content-type "application/edn") (header "accept" "application/transit+json")))] (is (= 200 (:status response))) (is (= {:total 16} (m/decode-response-body response)))))))
null
https://raw.githubusercontent.com/zclj/replication-packages/8a5cb02e4fdda74107b5dcc34cbfa5cb5ae34dcf/GraphQL/graphql-toy/test/clj/graphql_toy/test/handler.clj
clojure
(ns graphql-toy.test.handler (:require [clojure.test :refer :all] [ring.mock.request :refer :all] [graphql-toy.handler :refer :all] [graphql-toy.middleware.formats :as formats] [muuntaja.core :as m] [mount.core :as mount])) (defn parse-json [body] (m/decode formats/instance "application/json" body)) (use-fixtures :once (fn [f] (mount/start #'graphql-toy.config/env #'graphql-toy.handler/app-routes) (f))) (deftest test-app (testing "main route" (let [response ((app) (request :get "/"))] (is (= 200 (:status response))))) (testing "not-found route" (let [response ((app) (request :get "/invalid"))] (is (= 404 (:status response))))) (testing "services" (testing "success" (let [response ((app) (-> (request :post "/api/math/plus") (json-body {:x 10, :y 6})))] (is (= 200 (:status response))) (is (= {:total 16} (m/decode-response-body response))))) (testing "parameter coercion error" (let [response ((app) (-> (request :post "/api/math/plus") (json-body {:x 10, :y "invalid"})))] (is (= 400 (:status response))))) (testing "response coercion error" (let [response ((app) (-> (request :post "/api/math/plus") (json-body {:x -10, :y 6})))] (is (= 500 (:status response))))) (testing "content negotiation" (let [response ((app) (-> (request :post "/api/math/plus") (body (pr-str {:x 10, :y 6})) (content-type "application/edn") (header "accept" "application/transit+json")))] (is (= 200 (:status response))) (is (= {:total 16} (m/decode-response-body response)))))))
6eaf7a24a8f0931b39576b09b72fd986b086cdb6b6388f591f6c5dbe190349a8
arnihermann/osxmonad
Keys.hs
module OSXMonad.Keys where import XMonad From HIToolbox / Events.h osxKeyToX11 :: Int -> KeySym osxKeyToX11 0x00 = xK_a osxKeyToX11 0x01 = xK_s osxKeyToX11 0x02 = xK_d osxKeyToX11 0x03 = xK_f osxKeyToX11 0x04 = xK_h osxKeyToX11 0x05 = xK_g osxKeyToX11 0x06 = xK_z osxKeyToX11 0x07 = xK_x osxKeyToX11 0x08 = xK_c osxKeyToX11 0x09 = xK_v osxKeyToX11 0x0B = xK_b osxKeyToX11 0x0C = xK_q osxKeyToX11 0x0D = xK_w osxKeyToX11 0x0E = xK_e osxKeyToX11 0x0F = xK_r osxKeyToX11 0x10 = xK_y osxKeyToX11 0x11 = xK_t osxKeyToX11 0x12 = xK_1 osxKeyToX11 0x13 = xK_2 osxKeyToX11 0x14 = xK_3 osxKeyToX11 0x15 = xK_4 osxKeyToX11 0x16 = xK_6 osxKeyToX11 0x17 = xK_5 osxKeyToX11 0x18 = xK_equal osxKeyToX11 0x19 = xK_9 osxKeyToX11 0x1A = xK_7 osxKeyToX11 0x1B = xK_minus osxKeyToX11 0x1C = xK_8 osxKeyToX11 0x1D = xK_0 osxKeyToX11 0x1E = xK_bracketright osxKeyToX11 0x1F = xK_o osxKeyToX11 0x20 = xK_u osxKeyToX11 0x21 = xK_bracketleft osxKeyToX11 0x22 = xK_i osxKeyToX11 0x23 = xK_p osxKeyToX11 0x25 = xK_l osxKeyToX11 0x26 = xK_j TODO : 0x27 osxKeyToX11 0x28 = xK_k osxKeyToX11 0x29 = xK_semicolon osxKeyToX11 0x2A = xK_backslash osxKeyToX11 0x2B = xK_comma osxKeyToX11 0x2C = xK_slash osxKeyToX11 0x2D = xK_n osxKeyToX11 0x2E = xK_m osxKeyToX11 0x2F = xK_period osxKeyToX11 0x32 = xK_grave osxKeyToX11 0x41 = xK_KP_Decimal osxKeyToX11 0x43 = xK_KP_Multiply osxKeyToX11 0x45 = xK_KP_Add TODO : 0x47 osxKeyToX11 0x48 = xK_KP_Divide osxKeyToX11 0x4C = xK_KP_Enter osxKeyToX11 0x4E = xK_KP_Subtract osxKeyToX11 0x51 = xK_KP_Equal osxKeyToX11 0x52 = xK_KP_0 osxKeyToX11 0x53 = xK_KP_1 osxKeyToX11 0x54 = xK_KP_2 osxKeyToX11 0x55 = xK_KP_3 osxKeyToX11 0x56 = xK_KP_4 osxKeyToX11 0x57 = xK_KP_5 osxKeyToX11 0x58 = xK_KP_6 osxKeyToX11 0x59 = xK_KP_7 osxKeyToX11 0x5B = xK_KP_8 osxKeyToX11 0x5C = xK_KP_9 osxKeyToX11 0x24 = xK_Return osxKeyToX11 0x30 = xK_Tab osxKeyToX11 0x31 = xK_space osxKeyToX11 0x33 = xK_Delete osxKeyToX11 0x35 = xK_Escape osxKeyToX11 0x37 = xK_Super_L osxKeyToX11 0x38 = xK_Shift_L osxKeyToX11 0x39 = xK_Caps_Lock osxKeyToX11 0x3A = xK_Alt_L osxKeyToX11 0x3B = xK_Control_L osxKeyToX11 0x3C = xK_Shift_R osxKeyToX11 0x3D = xK_Alt_R osxKeyToX11 0x3E = xK_Control_R TODO : 0x3F osxKeyToX11 0x40 = xK_F17 TODO : 0x48 -- TODO: 0x49 TODO : 0x4A osxKeyToX11 0x4F = xK_F18 osxKeyToX11 0x50 = xK_F19 osxKeyToX11 0x5A = xK_F20 osxKeyToX11 0x60 = xK_F5 osxKeyToX11 0x61 = xK_F6 osxKeyToX11 0x62 = xK_F7 osxKeyToX11 0x63 = xK_F3 osxKeyToX11 0x64 = xK_F8 osxKeyToX11 0x65 = xK_F9 osxKeyToX11 0x67 = xK_F11 osxKeyToX11 0x69 = xK_F13 osxKeyToX11 0x6A = xK_F16 osxKeyToX11 0x6B = xK_F14 osxKeyToX11 0x6D = xK_F10 osxKeyToX11 0x6F = xK_F12 osxKeyToX11 0x71 = xK_F15 osxKeyToX11 0x72 = xK_Help osxKeyToX11 0x73 = xK_Home osxKeyToX11 0x74 = xK_Page_Up osxKeyToX11 0x75 = xK_Delete osxKeyToX11 0x76 = xK_F4 osxKeyToX11 0x77 = xK_End osxKeyToX11 0x78 = xK_F2 osxKeyToX11 0x79 = xK_Page_Down osxKeyToX11 0x7A = xK_F1 osxKeyToX11 0x7B = xK_Left osxKeyToX11 0x7C = xK_Right osxKeyToX11 0x7D = xK_Down osxKeyToX11 0x7E = xK_Up osxKeyToX11 _ = 0
null
https://raw.githubusercontent.com/arnihermann/osxmonad/b15cf78ef25456b7c0e759a531343ba01a84919b/OSXMonad/Keys.hs
haskell
TODO: 0x49
module OSXMonad.Keys where import XMonad From HIToolbox / Events.h osxKeyToX11 :: Int -> KeySym osxKeyToX11 0x00 = xK_a osxKeyToX11 0x01 = xK_s osxKeyToX11 0x02 = xK_d osxKeyToX11 0x03 = xK_f osxKeyToX11 0x04 = xK_h osxKeyToX11 0x05 = xK_g osxKeyToX11 0x06 = xK_z osxKeyToX11 0x07 = xK_x osxKeyToX11 0x08 = xK_c osxKeyToX11 0x09 = xK_v osxKeyToX11 0x0B = xK_b osxKeyToX11 0x0C = xK_q osxKeyToX11 0x0D = xK_w osxKeyToX11 0x0E = xK_e osxKeyToX11 0x0F = xK_r osxKeyToX11 0x10 = xK_y osxKeyToX11 0x11 = xK_t osxKeyToX11 0x12 = xK_1 osxKeyToX11 0x13 = xK_2 osxKeyToX11 0x14 = xK_3 osxKeyToX11 0x15 = xK_4 osxKeyToX11 0x16 = xK_6 osxKeyToX11 0x17 = xK_5 osxKeyToX11 0x18 = xK_equal osxKeyToX11 0x19 = xK_9 osxKeyToX11 0x1A = xK_7 osxKeyToX11 0x1B = xK_minus osxKeyToX11 0x1C = xK_8 osxKeyToX11 0x1D = xK_0 osxKeyToX11 0x1E = xK_bracketright osxKeyToX11 0x1F = xK_o osxKeyToX11 0x20 = xK_u osxKeyToX11 0x21 = xK_bracketleft osxKeyToX11 0x22 = xK_i osxKeyToX11 0x23 = xK_p osxKeyToX11 0x25 = xK_l osxKeyToX11 0x26 = xK_j TODO : 0x27 osxKeyToX11 0x28 = xK_k osxKeyToX11 0x29 = xK_semicolon osxKeyToX11 0x2A = xK_backslash osxKeyToX11 0x2B = xK_comma osxKeyToX11 0x2C = xK_slash osxKeyToX11 0x2D = xK_n osxKeyToX11 0x2E = xK_m osxKeyToX11 0x2F = xK_period osxKeyToX11 0x32 = xK_grave osxKeyToX11 0x41 = xK_KP_Decimal osxKeyToX11 0x43 = xK_KP_Multiply osxKeyToX11 0x45 = xK_KP_Add TODO : 0x47 osxKeyToX11 0x48 = xK_KP_Divide osxKeyToX11 0x4C = xK_KP_Enter osxKeyToX11 0x4E = xK_KP_Subtract osxKeyToX11 0x51 = xK_KP_Equal osxKeyToX11 0x52 = xK_KP_0 osxKeyToX11 0x53 = xK_KP_1 osxKeyToX11 0x54 = xK_KP_2 osxKeyToX11 0x55 = xK_KP_3 osxKeyToX11 0x56 = xK_KP_4 osxKeyToX11 0x57 = xK_KP_5 osxKeyToX11 0x58 = xK_KP_6 osxKeyToX11 0x59 = xK_KP_7 osxKeyToX11 0x5B = xK_KP_8 osxKeyToX11 0x5C = xK_KP_9 osxKeyToX11 0x24 = xK_Return osxKeyToX11 0x30 = xK_Tab osxKeyToX11 0x31 = xK_space osxKeyToX11 0x33 = xK_Delete osxKeyToX11 0x35 = xK_Escape osxKeyToX11 0x37 = xK_Super_L osxKeyToX11 0x38 = xK_Shift_L osxKeyToX11 0x39 = xK_Caps_Lock osxKeyToX11 0x3A = xK_Alt_L osxKeyToX11 0x3B = xK_Control_L osxKeyToX11 0x3C = xK_Shift_R osxKeyToX11 0x3D = xK_Alt_R osxKeyToX11 0x3E = xK_Control_R TODO : 0x3F osxKeyToX11 0x40 = xK_F17 TODO : 0x48 TODO : 0x4A osxKeyToX11 0x4F = xK_F18 osxKeyToX11 0x50 = xK_F19 osxKeyToX11 0x5A = xK_F20 osxKeyToX11 0x60 = xK_F5 osxKeyToX11 0x61 = xK_F6 osxKeyToX11 0x62 = xK_F7 osxKeyToX11 0x63 = xK_F3 osxKeyToX11 0x64 = xK_F8 osxKeyToX11 0x65 = xK_F9 osxKeyToX11 0x67 = xK_F11 osxKeyToX11 0x69 = xK_F13 osxKeyToX11 0x6A = xK_F16 osxKeyToX11 0x6B = xK_F14 osxKeyToX11 0x6D = xK_F10 osxKeyToX11 0x6F = xK_F12 osxKeyToX11 0x71 = xK_F15 osxKeyToX11 0x72 = xK_Help osxKeyToX11 0x73 = xK_Home osxKeyToX11 0x74 = xK_Page_Up osxKeyToX11 0x75 = xK_Delete osxKeyToX11 0x76 = xK_F4 osxKeyToX11 0x77 = xK_End osxKeyToX11 0x78 = xK_F2 osxKeyToX11 0x79 = xK_Page_Down osxKeyToX11 0x7A = xK_F1 osxKeyToX11 0x7B = xK_Left osxKeyToX11 0x7C = xK_Right osxKeyToX11 0x7D = xK_Down osxKeyToX11 0x7E = xK_Up osxKeyToX11 _ = 0
122649d3ce8c6538a2d13660b1fef5e240a844b4bb949943182787448b15f42e
SimulaVR/godot-haskell
RichTextLabel.hs
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.RichTextLabel (Godot.Core.RichTextLabel._ITEM_UNDERLINE, Godot.Core.RichTextLabel._ITEM_RAINBOW, Godot.Core.RichTextLabel._ITEM_CUSTOMFX, Godot.Core.RichTextLabel._ITEM_META, Godot.Core.RichTextLabel._ITEM_ALIGN, Godot.Core.RichTextLabel._ITEM_TORNADO, Godot.Core.RichTextLabel._ITEM_FRAME, Godot.Core.RichTextLabel._ALIGN_RIGHT, Godot.Core.RichTextLabel._ALIGN_FILL, Godot.Core.RichTextLabel._ITEM_STRIKETHROUGH, Godot.Core.RichTextLabel._ITEM_SHAKE, Godot.Core.RichTextLabel._ITEM_FONT, Godot.Core.RichTextLabel._ITEM_FADE, Godot.Core.RichTextLabel._ITEM_TABLE, Godot.Core.RichTextLabel._ITEM_WAVE, Godot.Core.RichTextLabel._ITEM_COLOR, Godot.Core.RichTextLabel._ITEM_TEXT, Godot.Core.RichTextLabel._ITEM_IMAGE, Godot.Core.RichTextLabel._LIST_NUMBERS, Godot.Core.RichTextLabel._LIST_LETTERS, Godot.Core.RichTextLabel._ITEM_LIST, Godot.Core.RichTextLabel._ITEM_NEWLINE, Godot.Core.RichTextLabel._ITEM_INDENT, Godot.Core.RichTextLabel._LIST_DOTS, Godot.Core.RichTextLabel._ALIGN_LEFT, Godot.Core.RichTextLabel._ALIGN_CENTER, Godot.Core.RichTextLabel.sig_meta_clicked, Godot.Core.RichTextLabel.sig_meta_hover_ended, Godot.Core.RichTextLabel.sig_meta_hover_started, Godot.Core.RichTextLabel._gui_input, Godot.Core.RichTextLabel._scroll_changed, Godot.Core.RichTextLabel.add_image, Godot.Core.RichTextLabel.add_text, Godot.Core.RichTextLabel.append_bbcode, Godot.Core.RichTextLabel.clear, Godot.Core.RichTextLabel.get_bbcode, Godot.Core.RichTextLabel.get_content_height, Godot.Core.RichTextLabel.get_effects, Godot.Core.RichTextLabel.get_line_count, Godot.Core.RichTextLabel.get_percent_visible, Godot.Core.RichTextLabel.get_tab_size, Godot.Core.RichTextLabel.get_text, Godot.Core.RichTextLabel.get_total_character_count, Godot.Core.RichTextLabel.get_v_scroll, Godot.Core.RichTextLabel.get_visible_characters, Godot.Core.RichTextLabel.get_visible_line_count, Godot.Core.RichTextLabel.install_effect, Godot.Core.RichTextLabel.is_meta_underlined, Godot.Core.RichTextLabel.is_overriding_selected_font_color, Godot.Core.RichTextLabel.is_scroll_active, Godot.Core.RichTextLabel.is_scroll_following, Godot.Core.RichTextLabel.is_selection_enabled, Godot.Core.RichTextLabel.is_using_bbcode, Godot.Core.RichTextLabel.newline, Godot.Core.RichTextLabel.parse_bbcode, Godot.Core.RichTextLabel.parse_expressions_for_values, Godot.Core.RichTextLabel.pop, Godot.Core.RichTextLabel.push_align, Godot.Core.RichTextLabel.push_bold, Godot.Core.RichTextLabel.push_bold_italics, Godot.Core.RichTextLabel.push_cell, Godot.Core.RichTextLabel.push_color, Godot.Core.RichTextLabel.push_font, Godot.Core.RichTextLabel.push_indent, Godot.Core.RichTextLabel.push_italics, Godot.Core.RichTextLabel.push_list, Godot.Core.RichTextLabel.push_meta, Godot.Core.RichTextLabel.push_mono, Godot.Core.RichTextLabel.push_normal, Godot.Core.RichTextLabel.push_strikethrough, Godot.Core.RichTextLabel.push_table, Godot.Core.RichTextLabel.push_underline, Godot.Core.RichTextLabel.remove_line, Godot.Core.RichTextLabel.scroll_to_line, Godot.Core.RichTextLabel.set_bbcode, Godot.Core.RichTextLabel.set_effects, Godot.Core.RichTextLabel.set_meta_underline, Godot.Core.RichTextLabel.set_override_selected_font_color, Godot.Core.RichTextLabel.set_percent_visible, Godot.Core.RichTextLabel.set_scroll_active, Godot.Core.RichTextLabel.set_scroll_follow, Godot.Core.RichTextLabel.set_selection_enabled, Godot.Core.RichTextLabel.set_tab_size, Godot.Core.RichTextLabel.set_table_column_expand, Godot.Core.RichTextLabel.set_text, Godot.Core.RichTextLabel.set_use_bbcode, Godot.Core.RichTextLabel.set_visible_characters) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.Control() _ITEM_UNDERLINE :: Int _ITEM_UNDERLINE = 6 _ITEM_RAINBOW :: Int _ITEM_RAINBOW = 16 _ITEM_CUSTOMFX :: Int _ITEM_CUSTOMFX = 18 _ITEM_META :: Int _ITEM_META = 17 _ITEM_ALIGN :: Int _ITEM_ALIGN = 8 _ITEM_TORNADO :: Int _ITEM_TORNADO = 15 _ITEM_FRAME :: Int _ITEM_FRAME = 0 _ALIGN_RIGHT :: Int _ALIGN_RIGHT = 2 _ALIGN_FILL :: Int _ALIGN_FILL = 3 _ITEM_STRIKETHROUGH :: Int _ITEM_STRIKETHROUGH = 7 _ITEM_SHAKE :: Int _ITEM_SHAKE = 13 _ITEM_FONT :: Int _ITEM_FONT = 4 _ITEM_FADE :: Int _ITEM_FADE = 12 _ITEM_TABLE :: Int _ITEM_TABLE = 11 _ITEM_WAVE :: Int _ITEM_WAVE = 14 _ITEM_COLOR :: Int _ITEM_COLOR = 5 _ITEM_TEXT :: Int _ITEM_TEXT = 1 _ITEM_IMAGE :: Int _ITEM_IMAGE = 2 _LIST_NUMBERS :: Int _LIST_NUMBERS = 0 _LIST_LETTERS :: Int _LIST_LETTERS = 1 _ITEM_LIST :: Int _ITEM_LIST = 10 _ITEM_NEWLINE :: Int _ITEM_NEWLINE = 3 _ITEM_INDENT :: Int _ITEM_INDENT = 9 _LIST_DOTS :: Int _LIST_DOTS = 2 _ALIGN_LEFT :: Int _ALIGN_LEFT = 0 _ALIGN_CENTER :: Int _ALIGN_CENTER = 1 -- | Triggered when the user clicks on content between meta tags. If the meta is defined in text, e.g. @@url={"data"="hi"}@hi@/url@@, then the parameter for this signal will be a @String@ type. If a particular type or an object is desired, the @method push_meta@ method must be used to manually insert the data into the tag stack. sig_meta_clicked :: Godot.Internal.Dispatch.Signal RichTextLabel sig_meta_clicked = Godot.Internal.Dispatch.Signal "meta_clicked" instance NodeSignal RichTextLabel "meta_clicked" '[GodotVariant] -- | Triggers when the mouse exits a meta tag. sig_meta_hover_ended :: Godot.Internal.Dispatch.Signal RichTextLabel sig_meta_hover_ended = Godot.Internal.Dispatch.Signal "meta_hover_ended" instance NodeSignal RichTextLabel "meta_hover_ended" '[GodotVariant] -- | Triggers when the mouse enters a meta tag. sig_meta_hover_started :: Godot.Internal.Dispatch.Signal RichTextLabel sig_meta_hover_started = Godot.Internal.Dispatch.Signal "meta_hover_started" instance NodeSignal RichTextLabel "meta_hover_started" '[GodotVariant] instance NodeProperty RichTextLabel "bbcode_enabled" Bool 'False where nodeProperty = (is_using_bbcode, wrapDroppingSetter set_use_bbcode, Nothing) instance NodeProperty RichTextLabel "bbcode_text" GodotString 'False where nodeProperty = (get_bbcode, wrapDroppingSetter set_bbcode, Nothing) instance NodeProperty RichTextLabel "custom_effects" Array 'False where nodeProperty = (get_effects, wrapDroppingSetter set_effects, Nothing) instance NodeProperty RichTextLabel "meta_underlined" Bool 'False where nodeProperty = (is_meta_underlined, wrapDroppingSetter set_meta_underline, Nothing) instance NodeProperty RichTextLabel "override_selected_font_color" Bool 'False where nodeProperty = (is_overriding_selected_font_color, wrapDroppingSetter set_override_selected_font_color, Nothing) instance NodeProperty RichTextLabel "percent_visible" Float 'False where nodeProperty = (get_percent_visible, wrapDroppingSetter set_percent_visible, Nothing) instance NodeProperty RichTextLabel "scroll_active" Bool 'False where nodeProperty = (is_scroll_active, wrapDroppingSetter set_scroll_active, Nothing) instance NodeProperty RichTextLabel "scroll_following" Bool 'False where nodeProperty = (is_scroll_following, wrapDroppingSetter set_scroll_follow, Nothing) instance NodeProperty RichTextLabel "selection_enabled" Bool 'False where nodeProperty = (is_selection_enabled, wrapDroppingSetter set_selection_enabled, Nothing) instance NodeProperty RichTextLabel "tab_size" Int 'False where nodeProperty = (get_tab_size, wrapDroppingSetter set_tab_size, Nothing) instance NodeProperty RichTextLabel "text" GodotString 'False where nodeProperty = (get_text, wrapDroppingSetter set_text, Nothing) instance NodeProperty RichTextLabel "visible_characters" Int 'False where nodeProperty = (get_visible_characters, wrapDroppingSetter set_visible_characters, Nothing) {-# NOINLINE bindRichTextLabel__gui_input #-} bindRichTextLabel__gui_input :: MethodBind bindRichTextLabel__gui_input = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "_gui_input" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr _gui_input :: (RichTextLabel :< cls, Object :< cls) => cls -> InputEvent -> IO () _gui_input cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel__gui_input (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "_gui_input" '[InputEvent] (IO ()) where nodeMethod = Godot.Core.RichTextLabel._gui_input # NOINLINE bindRichTextLabel__scroll_changed # bindRichTextLabel__scroll_changed :: MethodBind bindRichTextLabel__scroll_changed = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "_scroll_changed" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr _scroll_changed :: (RichTextLabel :< cls, Object :< cls) => cls -> Float -> IO () _scroll_changed cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel__scroll_changed (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "_scroll_changed" '[Float] (IO ()) where nodeMethod = Godot.Core.RichTextLabel._scroll_changed # NOINLINE bindRichTextLabel_add_image # | Adds an image 's opening and closing tags to the tag stack , optionally providing a @width@ and @height@ to resize the image . If @width@ or @height@ is set to 0 , the image size will be adjusted in order to keep the original aspect ratio . bindRichTextLabel_add_image :: MethodBind bindRichTextLabel_add_image = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "add_image" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds an image 's opening and closing tags to the tag stack , optionally providing a @width@ and @height@ to resize the image . If @width@ or @height@ is set to 0 , the image size will be adjusted in order to keep the original aspect ratio . add_image :: (RichTextLabel :< cls, Object :< cls) => cls -> Texture -> Maybe Int -> Maybe Int -> IO () add_image cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, maybe (VariantInt (0)) toVariant arg2, maybe (VariantInt (0)) toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_add_image (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "add_image" '[Texture, Maybe Int, Maybe Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.add_image # NOINLINE bindRichTextLabel_add_text # -- | Adds raw non-BBCode-parsed text to the tag stack. bindRichTextLabel_add_text :: MethodBind bindRichTextLabel_add_text = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "add_text" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Adds raw non-BBCode-parsed text to the tag stack. add_text :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotString -> IO () add_text cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_add_text (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "add_text" '[GodotString] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.add_text # NOINLINE bindRichTextLabel_append_bbcode # -- | Parses @bbcode@ and adds tags to the tag stack as needed. Returns the result of the parsing, @OK@ if successful. bindRichTextLabel_append_bbcode :: MethodBind bindRichTextLabel_append_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "append_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Parses @bbcode@ and adds tags to the tag stack as needed. Returns the result of the parsing, @OK@ if successful. append_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotString -> IO Int append_bbcode cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_append_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "append_bbcode" '[GodotString] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.append_bbcode # NOINLINE bindRichTextLabel_clear # -- | Clears the tag stack and sets @bbcode_text@ to an empty string. bindRichTextLabel_clear :: MethodBind bindRichTextLabel_clear = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "clear" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Clears the tag stack and sets @bbcode_text@ to an empty string. clear :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () clear cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_clear (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "clear" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.clear # NOINLINE bindRichTextLabel_get_bbcode # | The label 's text in BBCode format . Is not representative of manual modifications to the internal tag stack . Erases changes made by other methods when edited . -- __Note:__ It is unadvised to use @+=@ operator with @bbcode_text@ (e.g. @bbcode_text += "some string"@) as it replaces the whole text and can cause slowdowns. Use @method append_bbcode@ for adding text instead. bindRichTextLabel_get_bbcode :: MethodBind bindRichTextLabel_get_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The label 's text in BBCode format . Is not representative of manual modifications to the internal tag stack . Erases changes made by other methods when edited . -- __Note:__ It is unadvised to use @+=@ operator with @bbcode_text@ (e.g. @bbcode_text += "some string"@) as it replaces the whole text and can cause slowdowns. Use @method append_bbcode@ for adding text instead. get_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> IO GodotString get_bbcode cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_bbcode" '[] (IO GodotString) where nodeMethod = Godot.Core.RichTextLabel.get_bbcode # NOINLINE bindRichTextLabel_get_content_height # -- | Returns the height of the content. bindRichTextLabel_get_content_height :: MethodBind bindRichTextLabel_get_content_height = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_content_height" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns the height of the content. get_content_height :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_content_height cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_content_height (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_content_height" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_content_height # NOINLINE bindRichTextLabel_get_effects # -- | The currently installed custom effects. This is an array of @RichTextEffect@s. -- To add a custom effect, it's more convenient to use @method install_effect@. bindRichTextLabel_get_effects :: MethodBind bindRichTextLabel_get_effects = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_effects" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The currently installed custom effects. This is an array of @RichTextEffect@s. -- To add a custom effect, it's more convenient to use @method install_effect@. get_effects :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Array get_effects cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_effects (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_effects" '[] (IO Array) where nodeMethod = Godot.Core.RichTextLabel.get_effects # NOINLINE bindRichTextLabel_get_line_count # | Returns the total number of newlines in the tag stack 's text tags . Considers wrapped text as one line . bindRichTextLabel_get_line_count :: MethodBind bindRichTextLabel_get_line_count = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_line_count" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns the total number of newlines in the tag stack 's text tags . Considers wrapped text as one line . get_line_count :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_line_count cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_line_count (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_line_count" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_line_count # NOINLINE bindRichTextLabel_get_percent_visible # | The range of characters to display , as a @float@ between 0.0 and 1.0 . When assigned an out of range value , it 's the same as assigning 1.0 . _ _ Note : _ _ Setting this property updates @visible_characters@ based on current @method get_total_character_count@. bindRichTextLabel_get_percent_visible :: MethodBind bindRichTextLabel_get_percent_visible = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_percent_visible" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The range of characters to display , as a @float@ between 0.0 and 1.0 . When assigned an out of range value , it 's the same as assigning 1.0 . _ _ Note : _ _ Setting this property updates @visible_characters@ based on current @method get_total_character_count@. get_percent_visible :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Float get_percent_visible cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_percent_visible (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_percent_visible" '[] (IO Float) where nodeMethod = Godot.Core.RichTextLabel.get_percent_visible # NOINLINE bindRichTextLabel_get_tab_size # -- | The number of spaces associated with a single tab length. Does not affect @\t@ in text tags, only indent tags. bindRichTextLabel_get_tab_size :: MethodBind bindRichTextLabel_get_tab_size = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_tab_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The number of spaces associated with a single tab length. Does not affect @\t@ in text tags, only indent tags. get_tab_size :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_tab_size cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_tab_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_tab_size" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_tab_size # NOINLINE bindRichTextLabel_get_text # -- | The raw text of the label. When set , clears the tag stack and adds a raw text tag to the top of it . Does not parse . Does not modify @bbcode_text@. bindRichTextLabel_get_text :: MethodBind bindRichTextLabel_get_text = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_text" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The raw text of the label. When set , clears the tag stack and adds a raw text tag to the top of it . Does not parse . Does not modify @bbcode_text@. get_text :: (RichTextLabel :< cls, Object :< cls) => cls -> IO GodotString get_text cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_text (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_text" '[] (IO GodotString) where nodeMethod = Godot.Core.RichTextLabel.get_text # NOINLINE bindRichTextLabel_get_total_character_count # | Returns the total number of characters from text tags . Does not include BBCodes . bindRichTextLabel_get_total_character_count :: MethodBind bindRichTextLabel_get_total_character_count = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_total_character_count" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns the total number of characters from text tags . Does not include BBCodes . get_total_character_count :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_total_character_count cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_total_character_count (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_total_character_count" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_total_character_count # NOINLINE bindRichTextLabel_get_v_scroll # -- | Returns the vertical scrollbar. bindRichTextLabel_get_v_scroll :: MethodBind bindRichTextLabel_get_v_scroll = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_v_scroll" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns the vertical scrollbar. get_v_scroll :: (RichTextLabel :< cls, Object :< cls) => cls -> IO VScrollBar get_v_scroll cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_v_scroll (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_v_scroll" '[] (IO VScrollBar) where nodeMethod = Godot.Core.RichTextLabel.get_v_scroll # NOINLINE bindRichTextLabel_get_visible_characters # -- | The restricted number of characters to display in the label. If @-1@, all characters will be displayed. bindRichTextLabel_get_visible_characters :: MethodBind bindRichTextLabel_get_visible_characters = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_visible_characters" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The restricted number of characters to display in the label. If @-1@, all characters will be displayed. get_visible_characters :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_visible_characters cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_visible_characters (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_visible_characters" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_visible_characters # NOINLINE bindRichTextLabel_get_visible_line_count # -- | Returns the number of visible lines. bindRichTextLabel_get_visible_line_count :: MethodBind bindRichTextLabel_get_visible_line_count = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_visible_line_count" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns the number of visible lines. get_visible_line_count :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_visible_line_count cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_visible_line_count (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_visible_line_count" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_visible_line_count # NOINLINE bindRichTextLabel_install_effect # -- | Installs a custom effect. @effect@ should be a valid @RichTextEffect@. bindRichTextLabel_install_effect :: MethodBind bindRichTextLabel_install_effect = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "install_effect" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Installs a custom effect. @effect@ should be a valid @RichTextEffect@. install_effect :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotVariant -> IO () install_effect cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_install_effect (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "install_effect" '[GodotVariant] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.install_effect # NOINLINE bindRichTextLabel_is_meta_underlined # | If @true@ , the label underlines meta tags such as @@url@{text}@/url@@. bindRichTextLabel_is_meta_underlined :: MethodBind bindRichTextLabel_is_meta_underlined = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_meta_underlined" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label underlines meta tags such as @@url@{text}@/url@@. is_meta_underlined :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_meta_underlined cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_meta_underlined (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_meta_underlined" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_meta_underlined # NOINLINE bindRichTextLabel_is_overriding_selected_font_color # #-} | If @true@ , the label uses the custom font color . bindRichTextLabel_is_overriding_selected_font_color :: MethodBind bindRichTextLabel_is_overriding_selected_font_color = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_overriding_selected_font_color" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label uses the custom font color . is_overriding_selected_font_color :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_overriding_selected_font_color cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_overriding_selected_font_color (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_overriding_selected_font_color" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_overriding_selected_font_color # NOINLINE bindRichTextLabel_is_scroll_active # | If @true@ , the scrollbar is visible . Setting this to @false@ does not block scrolling completely . See @method scroll_to_line@. bindRichTextLabel_is_scroll_active :: MethodBind bindRichTextLabel_is_scroll_active = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_scroll_active" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the scrollbar is visible . Setting this to @false@ does not block scrolling completely . See @method scroll_to_line@. is_scroll_active :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_scroll_active cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_scroll_active (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_scroll_active" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_scroll_active {-# NOINLINE bindRichTextLabel_is_scroll_following #-} | If @true@ , the window scrolls down to display new content automatically . bindRichTextLabel_is_scroll_following :: MethodBind bindRichTextLabel_is_scroll_following = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_scroll_following" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the window scrolls down to display new content automatically . is_scroll_following :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_scroll_following cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_scroll_following (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_scroll_following" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_scroll_following # NOINLINE bindRichTextLabel_is_selection_enabled # | If @true@ , the label allows text selection . bindRichTextLabel_is_selection_enabled :: MethodBind bindRichTextLabel_is_selection_enabled = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_selection_enabled" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label allows text selection . is_selection_enabled :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_selection_enabled cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_selection_enabled (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_selection_enabled" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_selection_enabled # NOINLINE bindRichTextLabel_is_using_bbcode # | If @true@ , the label uses BBCode formatting . bindRichTextLabel_is_using_bbcode :: MethodBind bindRichTextLabel_is_using_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_using_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label uses BBCode formatting . is_using_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_using_bbcode cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_using_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_using_bbcode" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_using_bbcode # NOINLINE bindRichTextLabel_newline # -- | Adds a newline tag to the tag stack. bindRichTextLabel_newline :: MethodBind bindRichTextLabel_newline = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "newline" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Adds a newline tag to the tag stack. newline :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () newline cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_newline (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "newline" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.newline {-# NOINLINE bindRichTextLabel_parse_bbcode #-} -- | The assignment version of @method append_bbcode@. Clears the tag stack and inserts the new content. Returns @OK@ if parses @bbcode@ successfully. bindRichTextLabel_parse_bbcode :: MethodBind bindRichTextLabel_parse_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "parse_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The assignment version of @method append_bbcode@. Clears the tag stack and inserts the new content. Returns @OK@ if parses @bbcode@ successfully. parse_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotString -> IO Int parse_bbcode cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_parse_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "parse_bbcode" '[GodotString] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.parse_bbcode # NOINLINE bindRichTextLabel_parse_expressions_for_values # -- | Parses BBCode parameter @expressions@ into a dictionary. bindRichTextLabel_parse_expressions_for_values :: MethodBind bindRichTextLabel_parse_expressions_for_values = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "parse_expressions_for_values" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Parses BBCode parameter @expressions@ into a dictionary. parse_expressions_for_values :: (RichTextLabel :< cls, Object :< cls) => cls -> PoolStringArray -> IO Dictionary parse_expressions_for_values cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_parse_expressions_for_values (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "parse_expressions_for_values" '[PoolStringArray] (IO Dictionary) where nodeMethod = Godot.Core.RichTextLabel.parse_expressions_for_values # NOINLINE bindRichTextLabel_pop # | Terminates the current tag . Use after @push_*@ methods to close BBCodes manually . Does not need to follow @add_*@ methods . bindRichTextLabel_pop :: MethodBind bindRichTextLabel_pop = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "pop" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Terminates the current tag . Use after @push_*@ methods to close BBCodes manually . Does not need to follow @add_*@ methods . pop :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () pop cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_pop (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "pop" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.pop # NOINLINE bindRichTextLabel_push_align # | Adds an @@align@@ tag based on the given @align@ value . See @enum Align@ for possible values . bindRichTextLabel_push_align :: MethodBind bindRichTextLabel_push_align = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_align" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds an @@align@@ tag based on the given @align@ value . See @enum Align@ for possible values . push_align :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () push_align cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_align (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_align" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_align # NOINLINE bindRichTextLabel_push_bold # | Adds a @@font@@ tag with a bold font to the tag stack . This is the same as adding a tag if not currently in a @@i@@ tag . bindRichTextLabel_push_bold :: MethodBind bindRichTextLabel_push_bold = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_bold" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@font@@ tag with a bold font to the tag stack . This is the same as adding a tag if not currently in a @@i@@ tag . push_bold :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_bold cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_bold (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_bold" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_bold # NOINLINE bindRichTextLabel_push_bold_italics # -- | Adds a @@font@@ tag with a bold italics font to the tag stack. bindRichTextLabel_push_bold_italics :: MethodBind bindRichTextLabel_push_bold_italics = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_bold_italics" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Adds a @@font@@ tag with a bold italics font to the tag stack. push_bold_italics :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_bold_italics cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_bold_italics (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_bold_italics" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_bold_italics {-# NOINLINE bindRichTextLabel_push_cell #-} -- | Adds a @@cell@@ tag to the tag stack. Must be inside a @@table@@ tag. See @method push_table@ for details. bindRichTextLabel_push_cell :: MethodBind bindRichTextLabel_push_cell = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_cell" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Adds a @@cell@@ tag to the tag stack. Must be inside a @@table@@ tag. See @method push_table@ for details. push_cell :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_cell cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_cell (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_cell" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_cell # NOINLINE bindRichTextLabel_push_color # | Adds a @@color@@ tag to the tag stack . bindRichTextLabel_push_color :: MethodBind bindRichTextLabel_push_color = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_color" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@color@@ tag to the tag stack . push_color :: (RichTextLabel :< cls, Object :< cls) => cls -> Color -> IO () push_color cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_color (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_color" '[Color] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_color # NOINLINE bindRichTextLabel_push_font # -- | Adds a @@font@@ tag to the tag stack. Overrides default fonts for its duration. bindRichTextLabel_push_font :: MethodBind bindRichTextLabel_push_font = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_font" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Adds a @@font@@ tag to the tag stack. Overrides default fonts for its duration. push_font :: (RichTextLabel :< cls, Object :< cls) => cls -> Font -> IO () push_font cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_font (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_font" '[Font] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_font # NOINLINE bindRichTextLabel_push_indent # | Adds an @@indent@@ tag to the tag stack . Multiplies @level@ by current @tab_size@ to determine new margin length . bindRichTextLabel_push_indent :: MethodBind bindRichTextLabel_push_indent = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_indent" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds an @@indent@@ tag to the tag stack . Multiplies @level@ by current @tab_size@ to determine new margin length . push_indent :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () push_indent cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_indent (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_indent" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_indent # NOINLINE bindRichTextLabel_push_italics # | Adds a @@font@@ tag with a italics font to the tag stack . This is the same as adding a @@i@@ tag if not currently in a tag . bindRichTextLabel_push_italics :: MethodBind bindRichTextLabel_push_italics = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_italics" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@font@@ tag with a italics font to the tag stack . This is the same as adding a @@i@@ tag if not currently in a tag . push_italics :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_italics cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_italics (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_italics" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_italics # NOINLINE bindRichTextLabel_push_list # | Adds a @@list@@ tag to the tag stack . Similar to the BBCodes @@ol@@ or @@ul@@ , but supports more list types . Not fully implemented ! bindRichTextLabel_push_list :: MethodBind bindRichTextLabel_push_list = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_list" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@list@@ tag to the tag stack . Similar to the BBCodes @@ol@@ or @@ul@@ , but supports more list types . Not fully implemented ! push_list :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () push_list cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_list (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_list" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_list # NOINLINE bindRichTextLabel_push_meta # | Adds a @@meta@@ tag to the tag stack . Similar to the @@url = something@{text}@/url@@ , but supports non-@String@ metadata types . bindRichTextLabel_push_meta :: MethodBind bindRichTextLabel_push_meta = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_meta" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@meta@@ tag to the tag stack . Similar to the @@url = something@{text}@/url@@ , but supports non-@String@ metadata types . push_meta :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotVariant -> IO () push_meta cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_meta (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_meta" '[GodotVariant] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_meta # NOINLINE bindRichTextLabel_push_mono # -- | Adds a @@font@@ tag with a monospace font to the tag stack. bindRichTextLabel_push_mono :: MethodBind bindRichTextLabel_push_mono = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_mono" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Adds a @@font@@ tag with a monospace font to the tag stack. push_mono :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_mono cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_mono (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_mono" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_mono # NOINLINE bindRichTextLabel_push_normal # -- | Adds a @@font@@ tag with a normal font to the tag stack. bindRichTextLabel_push_normal :: MethodBind bindRichTextLabel_push_normal = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_normal" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Adds a @@font@@ tag with a normal font to the tag stack. push_normal :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_normal cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_normal (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_normal" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_normal {-# NOINLINE bindRichTextLabel_push_strikethrough #-} -- | Adds a @@s@@ tag to the tag stack. bindRichTextLabel_push_strikethrough :: MethodBind bindRichTextLabel_push_strikethrough = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_strikethrough" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Adds a @@s@@ tag to the tag stack. push_strikethrough :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_strikethrough cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_strikethrough (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_strikethrough" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_strikethrough # NOINLINE bindRichTextLabel_push_table # -- | Adds a @@table=columns@@ tag to the tag stack. bindRichTextLabel_push_table :: MethodBind bindRichTextLabel_push_table = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_table" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Adds a @@table=columns@@ tag to the tag stack. push_table :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () push_table cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_table (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_table" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_table # NOINLINE bindRichTextLabel_push_underline # | Adds a @@u@@ tag to the tag stack . bindRichTextLabel_push_underline :: MethodBind bindRichTextLabel_push_underline = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_underline" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@u@@ tag to the tag stack . push_underline :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_underline cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_underline (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_underline" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_underline # NOINLINE bindRichTextLabel_remove_line # -- | Removes a line of content from the label. Returns @true@ if the line exists. The @line@ argument is the index of the line to remove , it can take values in the interval @@0 , get_line_count ( ) - 1@@. bindRichTextLabel_remove_line :: MethodBind bindRichTextLabel_remove_line = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "remove_line" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Removes a line of content from the label. Returns @true@ if the line exists. The @line@ argument is the index of the line to remove , it can take values in the interval @@0 , get_line_count ( ) - 1@@. remove_line :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO Bool remove_line cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_remove_line (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "remove_line" '[Int] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.remove_line # NOINLINE bindRichTextLabel_scroll_to_line # -- | Scrolls the window's top line to match @line@. bindRichTextLabel_scroll_to_line :: MethodBind bindRichTextLabel_scroll_to_line = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "scroll_to_line" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Scrolls the window's top line to match @line@. scroll_to_line :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () scroll_to_line cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_scroll_to_line (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "scroll_to_line" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.scroll_to_line # NOINLINE bindRichTextLabel_set_bbcode # | The label 's text in BBCode format . Is not representative of manual modifications to the internal tag stack . Erases changes made by other methods when edited . -- __Note:__ It is unadvised to use @+=@ operator with @bbcode_text@ (e.g. @bbcode_text += "some string"@) as it replaces the whole text and can cause slowdowns. Use @method append_bbcode@ for adding text instead. bindRichTextLabel_set_bbcode :: MethodBind bindRichTextLabel_set_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The label 's text in BBCode format . Is not representative of manual modifications to the internal tag stack . Erases changes made by other methods when edited . -- __Note:__ It is unadvised to use @+=@ operator with @bbcode_text@ (e.g. @bbcode_text += "some string"@) as it replaces the whole text and can cause slowdowns. Use @method append_bbcode@ for adding text instead. set_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotString -> IO () set_bbcode cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_bbcode" '[GodotString] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_bbcode # NOINLINE bindRichTextLabel_set_effects # -- | The currently installed custom effects. This is an array of @RichTextEffect@s. -- To add a custom effect, it's more convenient to use @method install_effect@. bindRichTextLabel_set_effects :: MethodBind bindRichTextLabel_set_effects = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_effects" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The currently installed custom effects. This is an array of @RichTextEffect@s. -- To add a custom effect, it's more convenient to use @method install_effect@. set_effects :: (RichTextLabel :< cls, Object :< cls) => cls -> Array -> IO () set_effects cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_effects (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_effects" '[Array] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_effects # NOINLINE bindRichTextLabel_set_meta_underline # | If @true@ , the label underlines meta tags such as @@url@{text}@/url@@. bindRichTextLabel_set_meta_underline :: MethodBind bindRichTextLabel_set_meta_underline = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_meta_underline" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label underlines meta tags such as @@url@{text}@/url@@. set_meta_underline :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_meta_underline cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_meta_underline (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_meta_underline" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_meta_underline # NOINLINE bindRichTextLabel_set_override_selected_font_color # | If @true@ , the label uses the custom font color . bindRichTextLabel_set_override_selected_font_color :: MethodBind bindRichTextLabel_set_override_selected_font_color = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_override_selected_font_color" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label uses the custom font color . set_override_selected_font_color :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_override_selected_font_color cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_override_selected_font_color (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_override_selected_font_color" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_override_selected_font_color # NOINLINE bindRichTextLabel_set_percent_visible # | The range of characters to display , as a @float@ between 0.0 and 1.0 . When assigned an out of range value , it 's the same as assigning 1.0 . _ _ Note : _ _ Setting this property updates @visible_characters@ based on current @method get_total_character_count@. bindRichTextLabel_set_percent_visible :: MethodBind bindRichTextLabel_set_percent_visible = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_percent_visible" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The range of characters to display , as a @float@ between 0.0 and 1.0 . When assigned an out of range value , it 's the same as assigning 1.0 . _ _ Note : _ _ Setting this property updates @visible_characters@ based on current @method get_total_character_count@. set_percent_visible :: (RichTextLabel :< cls, Object :< cls) => cls -> Float -> IO () set_percent_visible cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_percent_visible (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_percent_visible" '[Float] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_percent_visible # NOINLINE bindRichTextLabel_set_scroll_active # | If @true@ , the scrollbar is visible . Setting this to @false@ does not block scrolling completely . See @method scroll_to_line@. bindRichTextLabel_set_scroll_active :: MethodBind bindRichTextLabel_set_scroll_active = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_scroll_active" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the scrollbar is visible . Setting this to @false@ does not block scrolling completely . See @method scroll_to_line@. set_scroll_active :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_scroll_active cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_scroll_active (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_scroll_active" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_scroll_active # NOINLINE bindRichTextLabel_set_scroll_follow # | If @true@ , the window scrolls down to display new content automatically . bindRichTextLabel_set_scroll_follow :: MethodBind bindRichTextLabel_set_scroll_follow = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_scroll_follow" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the window scrolls down to display new content automatically . set_scroll_follow :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_scroll_follow cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_scroll_follow (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_scroll_follow" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_scroll_follow # NOINLINE bindRichTextLabel_set_selection_enabled # | If @true@ , the label allows text selection . bindRichTextLabel_set_selection_enabled :: MethodBind bindRichTextLabel_set_selection_enabled = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_selection_enabled" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label allows text selection . set_selection_enabled :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_selection_enabled cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_selection_enabled (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_selection_enabled" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_selection_enabled # NOINLINE bindRichTextLabel_set_tab_size # -- | The number of spaces associated with a single tab length. Does not affect @\t@ in text tags, only indent tags. bindRichTextLabel_set_tab_size :: MethodBind bindRichTextLabel_set_tab_size = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_tab_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The number of spaces associated with a single tab length. Does not affect @\t@ in text tags, only indent tags. set_tab_size :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () set_tab_size cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_tab_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_tab_size" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_tab_size # NOINLINE bindRichTextLabel_set_table_column_expand # | Edits the selected column 's expansion options . If @expand@ is @true@ , the column expands in proportion to its expansion ratio versus the other columns ' ratios . For example , 2 columns with ratios 3 and 4 plus 70 pixels in available width would expand 30 and 40 pixels , respectively . If @expand@ is @false@ , the column will not contribute to the total ratio . bindRichTextLabel_set_table_column_expand :: MethodBind bindRichTextLabel_set_table_column_expand = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_table_column_expand" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Edits the selected column 's expansion options . If @expand@ is @true@ , the column expands in proportion to its expansion ratio versus the other columns ' ratios . For example , 2 columns with ratios 3 and 4 plus 70 pixels in available width would expand 30 and 40 pixels , respectively . If @expand@ is @false@ , the column will not contribute to the total ratio . set_table_column_expand :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> Bool -> Int -> IO () set_table_column_expand cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_table_column_expand (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_table_column_expand" '[Int, Bool, Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_table_column_expand # NOINLINE bindRichTextLabel_set_text # -- | The raw text of the label. When set , clears the tag stack and adds a raw text tag to the top of it . Does not parse . Does not modify @bbcode_text@. bindRichTextLabel_set_text :: MethodBind bindRichTextLabel_set_text = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_text" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The raw text of the label. When set , clears the tag stack and adds a raw text tag to the top of it . Does not parse . Does not modify @bbcode_text@. set_text :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotString -> IO () set_text cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_text (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_text" '[GodotString] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_text {-# NOINLINE bindRichTextLabel_set_use_bbcode #-} | If @true@ , the label uses BBCode formatting . bindRichTextLabel_set_use_bbcode :: MethodBind bindRichTextLabel_set_use_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_use_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label uses BBCode formatting . set_use_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_use_bbcode cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_use_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_use_bbcode" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_use_bbcode # NOINLINE bindRichTextLabel_set_visible_characters # -- | The restricted number of characters to display in the label. If @-1@, all characters will be displayed. bindRichTextLabel_set_visible_characters :: MethodBind bindRichTextLabel_set_visible_characters = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_visible_characters" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The restricted number of characters to display in the label. If @-1@, all characters will be displayed. set_visible_characters :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () set_visible_characters cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_visible_characters (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_visible_characters" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_visible_characters
null
https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/RichTextLabel.hs
haskell
| Triggered when the user clicks on content between meta tags. If the meta is defined in text, e.g. @@url={"data"="hi"}@hi@/url@@, then the parameter for this signal will be a @String@ type. If a particular type or an object is desired, the @method push_meta@ method must be used to manually insert the data into the tag stack. | Triggers when the mouse exits a meta tag. | Triggers when the mouse enters a meta tag. # NOINLINE bindRichTextLabel__gui_input # | Adds raw non-BBCode-parsed text to the tag stack. | Adds raw non-BBCode-parsed text to the tag stack. | Parses @bbcode@ and adds tags to the tag stack as needed. Returns the result of the parsing, @OK@ if successful. | Parses @bbcode@ and adds tags to the tag stack as needed. Returns the result of the parsing, @OK@ if successful. | Clears the tag stack and sets @bbcode_text@ to an empty string. | Clears the tag stack and sets @bbcode_text@ to an empty string. __Note:__ It is unadvised to use @+=@ operator with @bbcode_text@ (e.g. @bbcode_text += "some string"@) as it replaces the whole text and can cause slowdowns. Use @method append_bbcode@ for adding text instead. __Note:__ It is unadvised to use @+=@ operator with @bbcode_text@ (e.g. @bbcode_text += "some string"@) as it replaces the whole text and can cause slowdowns. Use @method append_bbcode@ for adding text instead. | Returns the height of the content. | Returns the height of the content. | The currently installed custom effects. This is an array of @RichTextEffect@s. To add a custom effect, it's more convenient to use @method install_effect@. | The currently installed custom effects. This is an array of @RichTextEffect@s. To add a custom effect, it's more convenient to use @method install_effect@. | The number of spaces associated with a single tab length. Does not affect @\t@ in text tags, only indent tags. | The number of spaces associated with a single tab length. Does not affect @\t@ in text tags, only indent tags. | The raw text of the label. | The raw text of the label. | Returns the vertical scrollbar. | Returns the vertical scrollbar. | The restricted number of characters to display in the label. If @-1@, all characters will be displayed. | The restricted number of characters to display in the label. If @-1@, all characters will be displayed. | Returns the number of visible lines. | Returns the number of visible lines. | Installs a custom effect. @effect@ should be a valid @RichTextEffect@. | Installs a custom effect. @effect@ should be a valid @RichTextEffect@. # NOINLINE bindRichTextLabel_is_scroll_following # | Adds a newline tag to the tag stack. | Adds a newline tag to the tag stack. # NOINLINE bindRichTextLabel_parse_bbcode # | The assignment version of @method append_bbcode@. Clears the tag stack and inserts the new content. Returns @OK@ if parses @bbcode@ successfully. | The assignment version of @method append_bbcode@. Clears the tag stack and inserts the new content. Returns @OK@ if parses @bbcode@ successfully. | Parses BBCode parameter @expressions@ into a dictionary. | Parses BBCode parameter @expressions@ into a dictionary. | Adds a @@font@@ tag with a bold italics font to the tag stack. | Adds a @@font@@ tag with a bold italics font to the tag stack. # NOINLINE bindRichTextLabel_push_cell # | Adds a @@cell@@ tag to the tag stack. Must be inside a @@table@@ tag. See @method push_table@ for details. | Adds a @@cell@@ tag to the tag stack. Must be inside a @@table@@ tag. See @method push_table@ for details. | Adds a @@font@@ tag to the tag stack. Overrides default fonts for its duration. | Adds a @@font@@ tag to the tag stack. Overrides default fonts for its duration. | Adds a @@font@@ tag with a monospace font to the tag stack. | Adds a @@font@@ tag with a monospace font to the tag stack. | Adds a @@font@@ tag with a normal font to the tag stack. | Adds a @@font@@ tag with a normal font to the tag stack. # NOINLINE bindRichTextLabel_push_strikethrough # | Adds a @@s@@ tag to the tag stack. | Adds a @@s@@ tag to the tag stack. | Adds a @@table=columns@@ tag to the tag stack. | Adds a @@table=columns@@ tag to the tag stack. | Removes a line of content from the label. Returns @true@ if the line exists. | Removes a line of content from the label. Returns @true@ if the line exists. | Scrolls the window's top line to match @line@. | Scrolls the window's top line to match @line@. __Note:__ It is unadvised to use @+=@ operator with @bbcode_text@ (e.g. @bbcode_text += "some string"@) as it replaces the whole text and can cause slowdowns. Use @method append_bbcode@ for adding text instead. __Note:__ It is unadvised to use @+=@ operator with @bbcode_text@ (e.g. @bbcode_text += "some string"@) as it replaces the whole text and can cause slowdowns. Use @method append_bbcode@ for adding text instead. | The currently installed custom effects. This is an array of @RichTextEffect@s. To add a custom effect, it's more convenient to use @method install_effect@. | The currently installed custom effects. This is an array of @RichTextEffect@s. To add a custom effect, it's more convenient to use @method install_effect@. | The number of spaces associated with a single tab length. Does not affect @\t@ in text tags, only indent tags. | The number of spaces associated with a single tab length. Does not affect @\t@ in text tags, only indent tags. | The raw text of the label. | The raw text of the label. # NOINLINE bindRichTextLabel_set_use_bbcode # | The restricted number of characters to display in the label. If @-1@, all characters will be displayed. | The restricted number of characters to display in the label. If @-1@, all characters will be displayed.
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.RichTextLabel (Godot.Core.RichTextLabel._ITEM_UNDERLINE, Godot.Core.RichTextLabel._ITEM_RAINBOW, Godot.Core.RichTextLabel._ITEM_CUSTOMFX, Godot.Core.RichTextLabel._ITEM_META, Godot.Core.RichTextLabel._ITEM_ALIGN, Godot.Core.RichTextLabel._ITEM_TORNADO, Godot.Core.RichTextLabel._ITEM_FRAME, Godot.Core.RichTextLabel._ALIGN_RIGHT, Godot.Core.RichTextLabel._ALIGN_FILL, Godot.Core.RichTextLabel._ITEM_STRIKETHROUGH, Godot.Core.RichTextLabel._ITEM_SHAKE, Godot.Core.RichTextLabel._ITEM_FONT, Godot.Core.RichTextLabel._ITEM_FADE, Godot.Core.RichTextLabel._ITEM_TABLE, Godot.Core.RichTextLabel._ITEM_WAVE, Godot.Core.RichTextLabel._ITEM_COLOR, Godot.Core.RichTextLabel._ITEM_TEXT, Godot.Core.RichTextLabel._ITEM_IMAGE, Godot.Core.RichTextLabel._LIST_NUMBERS, Godot.Core.RichTextLabel._LIST_LETTERS, Godot.Core.RichTextLabel._ITEM_LIST, Godot.Core.RichTextLabel._ITEM_NEWLINE, Godot.Core.RichTextLabel._ITEM_INDENT, Godot.Core.RichTextLabel._LIST_DOTS, Godot.Core.RichTextLabel._ALIGN_LEFT, Godot.Core.RichTextLabel._ALIGN_CENTER, Godot.Core.RichTextLabel.sig_meta_clicked, Godot.Core.RichTextLabel.sig_meta_hover_ended, Godot.Core.RichTextLabel.sig_meta_hover_started, Godot.Core.RichTextLabel._gui_input, Godot.Core.RichTextLabel._scroll_changed, Godot.Core.RichTextLabel.add_image, Godot.Core.RichTextLabel.add_text, Godot.Core.RichTextLabel.append_bbcode, Godot.Core.RichTextLabel.clear, Godot.Core.RichTextLabel.get_bbcode, Godot.Core.RichTextLabel.get_content_height, Godot.Core.RichTextLabel.get_effects, Godot.Core.RichTextLabel.get_line_count, Godot.Core.RichTextLabel.get_percent_visible, Godot.Core.RichTextLabel.get_tab_size, Godot.Core.RichTextLabel.get_text, Godot.Core.RichTextLabel.get_total_character_count, Godot.Core.RichTextLabel.get_v_scroll, Godot.Core.RichTextLabel.get_visible_characters, Godot.Core.RichTextLabel.get_visible_line_count, Godot.Core.RichTextLabel.install_effect, Godot.Core.RichTextLabel.is_meta_underlined, Godot.Core.RichTextLabel.is_overriding_selected_font_color, Godot.Core.RichTextLabel.is_scroll_active, Godot.Core.RichTextLabel.is_scroll_following, Godot.Core.RichTextLabel.is_selection_enabled, Godot.Core.RichTextLabel.is_using_bbcode, Godot.Core.RichTextLabel.newline, Godot.Core.RichTextLabel.parse_bbcode, Godot.Core.RichTextLabel.parse_expressions_for_values, Godot.Core.RichTextLabel.pop, Godot.Core.RichTextLabel.push_align, Godot.Core.RichTextLabel.push_bold, Godot.Core.RichTextLabel.push_bold_italics, Godot.Core.RichTextLabel.push_cell, Godot.Core.RichTextLabel.push_color, Godot.Core.RichTextLabel.push_font, Godot.Core.RichTextLabel.push_indent, Godot.Core.RichTextLabel.push_italics, Godot.Core.RichTextLabel.push_list, Godot.Core.RichTextLabel.push_meta, Godot.Core.RichTextLabel.push_mono, Godot.Core.RichTextLabel.push_normal, Godot.Core.RichTextLabel.push_strikethrough, Godot.Core.RichTextLabel.push_table, Godot.Core.RichTextLabel.push_underline, Godot.Core.RichTextLabel.remove_line, Godot.Core.RichTextLabel.scroll_to_line, Godot.Core.RichTextLabel.set_bbcode, Godot.Core.RichTextLabel.set_effects, Godot.Core.RichTextLabel.set_meta_underline, Godot.Core.RichTextLabel.set_override_selected_font_color, Godot.Core.RichTextLabel.set_percent_visible, Godot.Core.RichTextLabel.set_scroll_active, Godot.Core.RichTextLabel.set_scroll_follow, Godot.Core.RichTextLabel.set_selection_enabled, Godot.Core.RichTextLabel.set_tab_size, Godot.Core.RichTextLabel.set_table_column_expand, Godot.Core.RichTextLabel.set_text, Godot.Core.RichTextLabel.set_use_bbcode, Godot.Core.RichTextLabel.set_visible_characters) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.Control() _ITEM_UNDERLINE :: Int _ITEM_UNDERLINE = 6 _ITEM_RAINBOW :: Int _ITEM_RAINBOW = 16 _ITEM_CUSTOMFX :: Int _ITEM_CUSTOMFX = 18 _ITEM_META :: Int _ITEM_META = 17 _ITEM_ALIGN :: Int _ITEM_ALIGN = 8 _ITEM_TORNADO :: Int _ITEM_TORNADO = 15 _ITEM_FRAME :: Int _ITEM_FRAME = 0 _ALIGN_RIGHT :: Int _ALIGN_RIGHT = 2 _ALIGN_FILL :: Int _ALIGN_FILL = 3 _ITEM_STRIKETHROUGH :: Int _ITEM_STRIKETHROUGH = 7 _ITEM_SHAKE :: Int _ITEM_SHAKE = 13 _ITEM_FONT :: Int _ITEM_FONT = 4 _ITEM_FADE :: Int _ITEM_FADE = 12 _ITEM_TABLE :: Int _ITEM_TABLE = 11 _ITEM_WAVE :: Int _ITEM_WAVE = 14 _ITEM_COLOR :: Int _ITEM_COLOR = 5 _ITEM_TEXT :: Int _ITEM_TEXT = 1 _ITEM_IMAGE :: Int _ITEM_IMAGE = 2 _LIST_NUMBERS :: Int _LIST_NUMBERS = 0 _LIST_LETTERS :: Int _LIST_LETTERS = 1 _ITEM_LIST :: Int _ITEM_LIST = 10 _ITEM_NEWLINE :: Int _ITEM_NEWLINE = 3 _ITEM_INDENT :: Int _ITEM_INDENT = 9 _LIST_DOTS :: Int _LIST_DOTS = 2 _ALIGN_LEFT :: Int _ALIGN_LEFT = 0 _ALIGN_CENTER :: Int _ALIGN_CENTER = 1 sig_meta_clicked :: Godot.Internal.Dispatch.Signal RichTextLabel sig_meta_clicked = Godot.Internal.Dispatch.Signal "meta_clicked" instance NodeSignal RichTextLabel "meta_clicked" '[GodotVariant] sig_meta_hover_ended :: Godot.Internal.Dispatch.Signal RichTextLabel sig_meta_hover_ended = Godot.Internal.Dispatch.Signal "meta_hover_ended" instance NodeSignal RichTextLabel "meta_hover_ended" '[GodotVariant] sig_meta_hover_started :: Godot.Internal.Dispatch.Signal RichTextLabel sig_meta_hover_started = Godot.Internal.Dispatch.Signal "meta_hover_started" instance NodeSignal RichTextLabel "meta_hover_started" '[GodotVariant] instance NodeProperty RichTextLabel "bbcode_enabled" Bool 'False where nodeProperty = (is_using_bbcode, wrapDroppingSetter set_use_bbcode, Nothing) instance NodeProperty RichTextLabel "bbcode_text" GodotString 'False where nodeProperty = (get_bbcode, wrapDroppingSetter set_bbcode, Nothing) instance NodeProperty RichTextLabel "custom_effects" Array 'False where nodeProperty = (get_effects, wrapDroppingSetter set_effects, Nothing) instance NodeProperty RichTextLabel "meta_underlined" Bool 'False where nodeProperty = (is_meta_underlined, wrapDroppingSetter set_meta_underline, Nothing) instance NodeProperty RichTextLabel "override_selected_font_color" Bool 'False where nodeProperty = (is_overriding_selected_font_color, wrapDroppingSetter set_override_selected_font_color, Nothing) instance NodeProperty RichTextLabel "percent_visible" Float 'False where nodeProperty = (get_percent_visible, wrapDroppingSetter set_percent_visible, Nothing) instance NodeProperty RichTextLabel "scroll_active" Bool 'False where nodeProperty = (is_scroll_active, wrapDroppingSetter set_scroll_active, Nothing) instance NodeProperty RichTextLabel "scroll_following" Bool 'False where nodeProperty = (is_scroll_following, wrapDroppingSetter set_scroll_follow, Nothing) instance NodeProperty RichTextLabel "selection_enabled" Bool 'False where nodeProperty = (is_selection_enabled, wrapDroppingSetter set_selection_enabled, Nothing) instance NodeProperty RichTextLabel "tab_size" Int 'False where nodeProperty = (get_tab_size, wrapDroppingSetter set_tab_size, Nothing) instance NodeProperty RichTextLabel "text" GodotString 'False where nodeProperty = (get_text, wrapDroppingSetter set_text, Nothing) instance NodeProperty RichTextLabel "visible_characters" Int 'False where nodeProperty = (get_visible_characters, wrapDroppingSetter set_visible_characters, Nothing) bindRichTextLabel__gui_input :: MethodBind bindRichTextLabel__gui_input = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "_gui_input" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr _gui_input :: (RichTextLabel :< cls, Object :< cls) => cls -> InputEvent -> IO () _gui_input cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel__gui_input (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "_gui_input" '[InputEvent] (IO ()) where nodeMethod = Godot.Core.RichTextLabel._gui_input # NOINLINE bindRichTextLabel__scroll_changed # bindRichTextLabel__scroll_changed :: MethodBind bindRichTextLabel__scroll_changed = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "_scroll_changed" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr _scroll_changed :: (RichTextLabel :< cls, Object :< cls) => cls -> Float -> IO () _scroll_changed cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel__scroll_changed (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "_scroll_changed" '[Float] (IO ()) where nodeMethod = Godot.Core.RichTextLabel._scroll_changed # NOINLINE bindRichTextLabel_add_image # | Adds an image 's opening and closing tags to the tag stack , optionally providing a @width@ and @height@ to resize the image . If @width@ or @height@ is set to 0 , the image size will be adjusted in order to keep the original aspect ratio . bindRichTextLabel_add_image :: MethodBind bindRichTextLabel_add_image = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "add_image" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds an image 's opening and closing tags to the tag stack , optionally providing a @width@ and @height@ to resize the image . If @width@ or @height@ is set to 0 , the image size will be adjusted in order to keep the original aspect ratio . add_image :: (RichTextLabel :< cls, Object :< cls) => cls -> Texture -> Maybe Int -> Maybe Int -> IO () add_image cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, maybe (VariantInt (0)) toVariant arg2, maybe (VariantInt (0)) toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_add_image (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "add_image" '[Texture, Maybe Int, Maybe Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.add_image # NOINLINE bindRichTextLabel_add_text # bindRichTextLabel_add_text :: MethodBind bindRichTextLabel_add_text = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "add_text" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr add_text :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotString -> IO () add_text cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_add_text (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "add_text" '[GodotString] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.add_text # NOINLINE bindRichTextLabel_append_bbcode # bindRichTextLabel_append_bbcode :: MethodBind bindRichTextLabel_append_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "append_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr append_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotString -> IO Int append_bbcode cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_append_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "append_bbcode" '[GodotString] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.append_bbcode # NOINLINE bindRichTextLabel_clear # bindRichTextLabel_clear :: MethodBind bindRichTextLabel_clear = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "clear" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr clear :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () clear cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_clear (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "clear" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.clear # NOINLINE bindRichTextLabel_get_bbcode # | The label 's text in BBCode format . Is not representative of manual modifications to the internal tag stack . Erases changes made by other methods when edited . bindRichTextLabel_get_bbcode :: MethodBind bindRichTextLabel_get_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The label 's text in BBCode format . Is not representative of manual modifications to the internal tag stack . Erases changes made by other methods when edited . get_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> IO GodotString get_bbcode cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_bbcode" '[] (IO GodotString) where nodeMethod = Godot.Core.RichTextLabel.get_bbcode # NOINLINE bindRichTextLabel_get_content_height # bindRichTextLabel_get_content_height :: MethodBind bindRichTextLabel_get_content_height = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_content_height" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_content_height :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_content_height cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_content_height (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_content_height" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_content_height # NOINLINE bindRichTextLabel_get_effects # bindRichTextLabel_get_effects :: MethodBind bindRichTextLabel_get_effects = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_effects" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_effects :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Array get_effects cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_effects (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_effects" '[] (IO Array) where nodeMethod = Godot.Core.RichTextLabel.get_effects # NOINLINE bindRichTextLabel_get_line_count # | Returns the total number of newlines in the tag stack 's text tags . Considers wrapped text as one line . bindRichTextLabel_get_line_count :: MethodBind bindRichTextLabel_get_line_count = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_line_count" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns the total number of newlines in the tag stack 's text tags . Considers wrapped text as one line . get_line_count :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_line_count cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_line_count (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_line_count" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_line_count # NOINLINE bindRichTextLabel_get_percent_visible # | The range of characters to display , as a @float@ between 0.0 and 1.0 . When assigned an out of range value , it 's the same as assigning 1.0 . _ _ Note : _ _ Setting this property updates @visible_characters@ based on current @method get_total_character_count@. bindRichTextLabel_get_percent_visible :: MethodBind bindRichTextLabel_get_percent_visible = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_percent_visible" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The range of characters to display , as a @float@ between 0.0 and 1.0 . When assigned an out of range value , it 's the same as assigning 1.0 . _ _ Note : _ _ Setting this property updates @visible_characters@ based on current @method get_total_character_count@. get_percent_visible :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Float get_percent_visible cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_percent_visible (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_percent_visible" '[] (IO Float) where nodeMethod = Godot.Core.RichTextLabel.get_percent_visible # NOINLINE bindRichTextLabel_get_tab_size # bindRichTextLabel_get_tab_size :: MethodBind bindRichTextLabel_get_tab_size = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_tab_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_tab_size :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_tab_size cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_tab_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_tab_size" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_tab_size # NOINLINE bindRichTextLabel_get_text # When set , clears the tag stack and adds a raw text tag to the top of it . Does not parse . Does not modify @bbcode_text@. bindRichTextLabel_get_text :: MethodBind bindRichTextLabel_get_text = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_text" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr When set , clears the tag stack and adds a raw text tag to the top of it . Does not parse . Does not modify @bbcode_text@. get_text :: (RichTextLabel :< cls, Object :< cls) => cls -> IO GodotString get_text cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_text (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_text" '[] (IO GodotString) where nodeMethod = Godot.Core.RichTextLabel.get_text # NOINLINE bindRichTextLabel_get_total_character_count # | Returns the total number of characters from text tags . Does not include BBCodes . bindRichTextLabel_get_total_character_count :: MethodBind bindRichTextLabel_get_total_character_count = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_total_character_count" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns the total number of characters from text tags . Does not include BBCodes . get_total_character_count :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_total_character_count cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_total_character_count (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_total_character_count" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_total_character_count # NOINLINE bindRichTextLabel_get_v_scroll # bindRichTextLabel_get_v_scroll :: MethodBind bindRichTextLabel_get_v_scroll = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_v_scroll" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_v_scroll :: (RichTextLabel :< cls, Object :< cls) => cls -> IO VScrollBar get_v_scroll cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_v_scroll (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_v_scroll" '[] (IO VScrollBar) where nodeMethod = Godot.Core.RichTextLabel.get_v_scroll # NOINLINE bindRichTextLabel_get_visible_characters # bindRichTextLabel_get_visible_characters :: MethodBind bindRichTextLabel_get_visible_characters = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_visible_characters" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_visible_characters :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_visible_characters cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_visible_characters (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_visible_characters" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_visible_characters # NOINLINE bindRichTextLabel_get_visible_line_count # bindRichTextLabel_get_visible_line_count :: MethodBind bindRichTextLabel_get_visible_line_count = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "get_visible_line_count" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_visible_line_count :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Int get_visible_line_count cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_get_visible_line_count (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "get_visible_line_count" '[] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.get_visible_line_count # NOINLINE bindRichTextLabel_install_effect # bindRichTextLabel_install_effect :: MethodBind bindRichTextLabel_install_effect = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "install_effect" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr install_effect :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotVariant -> IO () install_effect cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_install_effect (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "install_effect" '[GodotVariant] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.install_effect # NOINLINE bindRichTextLabel_is_meta_underlined # | If @true@ , the label underlines meta tags such as @@url@{text}@/url@@. bindRichTextLabel_is_meta_underlined :: MethodBind bindRichTextLabel_is_meta_underlined = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_meta_underlined" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label underlines meta tags such as @@url@{text}@/url@@. is_meta_underlined :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_meta_underlined cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_meta_underlined (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_meta_underlined" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_meta_underlined # NOINLINE bindRichTextLabel_is_overriding_selected_font_color # #-} | If @true@ , the label uses the custom font color . bindRichTextLabel_is_overriding_selected_font_color :: MethodBind bindRichTextLabel_is_overriding_selected_font_color = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_overriding_selected_font_color" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label uses the custom font color . is_overriding_selected_font_color :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_overriding_selected_font_color cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_overriding_selected_font_color (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_overriding_selected_font_color" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_overriding_selected_font_color # NOINLINE bindRichTextLabel_is_scroll_active # | If @true@ , the scrollbar is visible . Setting this to @false@ does not block scrolling completely . See @method scroll_to_line@. bindRichTextLabel_is_scroll_active :: MethodBind bindRichTextLabel_is_scroll_active = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_scroll_active" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the scrollbar is visible . Setting this to @false@ does not block scrolling completely . See @method scroll_to_line@. is_scroll_active :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_scroll_active cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_scroll_active (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_scroll_active" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_scroll_active | If @true@ , the window scrolls down to display new content automatically . bindRichTextLabel_is_scroll_following :: MethodBind bindRichTextLabel_is_scroll_following = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_scroll_following" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the window scrolls down to display new content automatically . is_scroll_following :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_scroll_following cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_scroll_following (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_scroll_following" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_scroll_following # NOINLINE bindRichTextLabel_is_selection_enabled # | If @true@ , the label allows text selection . bindRichTextLabel_is_selection_enabled :: MethodBind bindRichTextLabel_is_selection_enabled = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_selection_enabled" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label allows text selection . is_selection_enabled :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_selection_enabled cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_selection_enabled (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_selection_enabled" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_selection_enabled # NOINLINE bindRichTextLabel_is_using_bbcode # | If @true@ , the label uses BBCode formatting . bindRichTextLabel_is_using_bbcode :: MethodBind bindRichTextLabel_is_using_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "is_using_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label uses BBCode formatting . is_using_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> IO Bool is_using_bbcode cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_is_using_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "is_using_bbcode" '[] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.is_using_bbcode # NOINLINE bindRichTextLabel_newline # bindRichTextLabel_newline :: MethodBind bindRichTextLabel_newline = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "newline" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr newline :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () newline cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_newline (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "newline" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.newline bindRichTextLabel_parse_bbcode :: MethodBind bindRichTextLabel_parse_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "parse_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr parse_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotString -> IO Int parse_bbcode cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_parse_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "parse_bbcode" '[GodotString] (IO Int) where nodeMethod = Godot.Core.RichTextLabel.parse_bbcode # NOINLINE bindRichTextLabel_parse_expressions_for_values # bindRichTextLabel_parse_expressions_for_values :: MethodBind bindRichTextLabel_parse_expressions_for_values = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "parse_expressions_for_values" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr parse_expressions_for_values :: (RichTextLabel :< cls, Object :< cls) => cls -> PoolStringArray -> IO Dictionary parse_expressions_for_values cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_parse_expressions_for_values (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "parse_expressions_for_values" '[PoolStringArray] (IO Dictionary) where nodeMethod = Godot.Core.RichTextLabel.parse_expressions_for_values # NOINLINE bindRichTextLabel_pop # | Terminates the current tag . Use after @push_*@ methods to close BBCodes manually . Does not need to follow @add_*@ methods . bindRichTextLabel_pop :: MethodBind bindRichTextLabel_pop = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "pop" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Terminates the current tag . Use after @push_*@ methods to close BBCodes manually . Does not need to follow @add_*@ methods . pop :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () pop cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_pop (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "pop" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.pop # NOINLINE bindRichTextLabel_push_align # | Adds an @@align@@ tag based on the given @align@ value . See @enum Align@ for possible values . bindRichTextLabel_push_align :: MethodBind bindRichTextLabel_push_align = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_align" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds an @@align@@ tag based on the given @align@ value . See @enum Align@ for possible values . push_align :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () push_align cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_align (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_align" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_align # NOINLINE bindRichTextLabel_push_bold # | Adds a @@font@@ tag with a bold font to the tag stack . This is the same as adding a tag if not currently in a @@i@@ tag . bindRichTextLabel_push_bold :: MethodBind bindRichTextLabel_push_bold = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_bold" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@font@@ tag with a bold font to the tag stack . This is the same as adding a tag if not currently in a @@i@@ tag . push_bold :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_bold cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_bold (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_bold" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_bold # NOINLINE bindRichTextLabel_push_bold_italics # bindRichTextLabel_push_bold_italics :: MethodBind bindRichTextLabel_push_bold_italics = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_bold_italics" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr push_bold_italics :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_bold_italics cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_bold_italics (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_bold_italics" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_bold_italics bindRichTextLabel_push_cell :: MethodBind bindRichTextLabel_push_cell = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_cell" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr push_cell :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_cell cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_cell (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_cell" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_cell # NOINLINE bindRichTextLabel_push_color # | Adds a @@color@@ tag to the tag stack . bindRichTextLabel_push_color :: MethodBind bindRichTextLabel_push_color = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_color" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@color@@ tag to the tag stack . push_color :: (RichTextLabel :< cls, Object :< cls) => cls -> Color -> IO () push_color cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_color (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_color" '[Color] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_color # NOINLINE bindRichTextLabel_push_font # bindRichTextLabel_push_font :: MethodBind bindRichTextLabel_push_font = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_font" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr push_font :: (RichTextLabel :< cls, Object :< cls) => cls -> Font -> IO () push_font cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_font (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_font" '[Font] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_font # NOINLINE bindRichTextLabel_push_indent # | Adds an @@indent@@ tag to the tag stack . Multiplies @level@ by current @tab_size@ to determine new margin length . bindRichTextLabel_push_indent :: MethodBind bindRichTextLabel_push_indent = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_indent" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds an @@indent@@ tag to the tag stack . Multiplies @level@ by current @tab_size@ to determine new margin length . push_indent :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () push_indent cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_indent (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_indent" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_indent # NOINLINE bindRichTextLabel_push_italics # | Adds a @@font@@ tag with a italics font to the tag stack . This is the same as adding a @@i@@ tag if not currently in a tag . bindRichTextLabel_push_italics :: MethodBind bindRichTextLabel_push_italics = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_italics" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@font@@ tag with a italics font to the tag stack . This is the same as adding a @@i@@ tag if not currently in a tag . push_italics :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_italics cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_italics (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_italics" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_italics # NOINLINE bindRichTextLabel_push_list # | Adds a @@list@@ tag to the tag stack . Similar to the BBCodes @@ol@@ or @@ul@@ , but supports more list types . Not fully implemented ! bindRichTextLabel_push_list :: MethodBind bindRichTextLabel_push_list = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_list" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@list@@ tag to the tag stack . Similar to the BBCodes @@ol@@ or @@ul@@ , but supports more list types . Not fully implemented ! push_list :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () push_list cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_list (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_list" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_list # NOINLINE bindRichTextLabel_push_meta # | Adds a @@meta@@ tag to the tag stack . Similar to the @@url = something@{text}@/url@@ , but supports non-@String@ metadata types . bindRichTextLabel_push_meta :: MethodBind bindRichTextLabel_push_meta = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_meta" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@meta@@ tag to the tag stack . Similar to the @@url = something@{text}@/url@@ , but supports non-@String@ metadata types . push_meta :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotVariant -> IO () push_meta cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_meta (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_meta" '[GodotVariant] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_meta # NOINLINE bindRichTextLabel_push_mono # bindRichTextLabel_push_mono :: MethodBind bindRichTextLabel_push_mono = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_mono" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr push_mono :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_mono cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_mono (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_mono" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_mono # NOINLINE bindRichTextLabel_push_normal # bindRichTextLabel_push_normal :: MethodBind bindRichTextLabel_push_normal = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_normal" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr push_normal :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_normal cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_normal (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_normal" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_normal bindRichTextLabel_push_strikethrough :: MethodBind bindRichTextLabel_push_strikethrough = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_strikethrough" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr push_strikethrough :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_strikethrough cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_strikethrough (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_strikethrough" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_strikethrough # NOINLINE bindRichTextLabel_push_table # bindRichTextLabel_push_table :: MethodBind bindRichTextLabel_push_table = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_table" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr push_table :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () push_table cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_table (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_table" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_table # NOINLINE bindRichTextLabel_push_underline # | Adds a @@u@@ tag to the tag stack . bindRichTextLabel_push_underline :: MethodBind bindRichTextLabel_push_underline = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "push_underline" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a @@u@@ tag to the tag stack . push_underline :: (RichTextLabel :< cls, Object :< cls) => cls -> IO () push_underline cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_push_underline (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "push_underline" '[] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.push_underline # NOINLINE bindRichTextLabel_remove_line # The @line@ argument is the index of the line to remove , it can take values in the interval @@0 , get_line_count ( ) - 1@@. bindRichTextLabel_remove_line :: MethodBind bindRichTextLabel_remove_line = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "remove_line" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr The @line@ argument is the index of the line to remove , it can take values in the interval @@0 , get_line_count ( ) - 1@@. remove_line :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO Bool remove_line cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_remove_line (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "remove_line" '[Int] (IO Bool) where nodeMethod = Godot.Core.RichTextLabel.remove_line # NOINLINE bindRichTextLabel_scroll_to_line # bindRichTextLabel_scroll_to_line :: MethodBind bindRichTextLabel_scroll_to_line = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "scroll_to_line" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr scroll_to_line :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () scroll_to_line cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_scroll_to_line (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "scroll_to_line" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.scroll_to_line # NOINLINE bindRichTextLabel_set_bbcode # | The label 's text in BBCode format . Is not representative of manual modifications to the internal tag stack . Erases changes made by other methods when edited . bindRichTextLabel_set_bbcode :: MethodBind bindRichTextLabel_set_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The label 's text in BBCode format . Is not representative of manual modifications to the internal tag stack . Erases changes made by other methods when edited . set_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotString -> IO () set_bbcode cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_bbcode" '[GodotString] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_bbcode # NOINLINE bindRichTextLabel_set_effects # bindRichTextLabel_set_effects :: MethodBind bindRichTextLabel_set_effects = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_effects" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_effects :: (RichTextLabel :< cls, Object :< cls) => cls -> Array -> IO () set_effects cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_effects (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_effects" '[Array] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_effects # NOINLINE bindRichTextLabel_set_meta_underline # | If @true@ , the label underlines meta tags such as @@url@{text}@/url@@. bindRichTextLabel_set_meta_underline :: MethodBind bindRichTextLabel_set_meta_underline = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_meta_underline" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label underlines meta tags such as @@url@{text}@/url@@. set_meta_underline :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_meta_underline cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_meta_underline (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_meta_underline" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_meta_underline # NOINLINE bindRichTextLabel_set_override_selected_font_color # | If @true@ , the label uses the custom font color . bindRichTextLabel_set_override_selected_font_color :: MethodBind bindRichTextLabel_set_override_selected_font_color = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_override_selected_font_color" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label uses the custom font color . set_override_selected_font_color :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_override_selected_font_color cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_override_selected_font_color (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_override_selected_font_color" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_override_selected_font_color # NOINLINE bindRichTextLabel_set_percent_visible # | The range of characters to display , as a @float@ between 0.0 and 1.0 . When assigned an out of range value , it 's the same as assigning 1.0 . _ _ Note : _ _ Setting this property updates @visible_characters@ based on current @method get_total_character_count@. bindRichTextLabel_set_percent_visible :: MethodBind bindRichTextLabel_set_percent_visible = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_percent_visible" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The range of characters to display , as a @float@ between 0.0 and 1.0 . When assigned an out of range value , it 's the same as assigning 1.0 . _ _ Note : _ _ Setting this property updates @visible_characters@ based on current @method get_total_character_count@. set_percent_visible :: (RichTextLabel :< cls, Object :< cls) => cls -> Float -> IO () set_percent_visible cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_percent_visible (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_percent_visible" '[Float] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_percent_visible # NOINLINE bindRichTextLabel_set_scroll_active # | If @true@ , the scrollbar is visible . Setting this to @false@ does not block scrolling completely . See @method scroll_to_line@. bindRichTextLabel_set_scroll_active :: MethodBind bindRichTextLabel_set_scroll_active = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_scroll_active" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the scrollbar is visible . Setting this to @false@ does not block scrolling completely . See @method scroll_to_line@. set_scroll_active :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_scroll_active cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_scroll_active (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_scroll_active" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_scroll_active # NOINLINE bindRichTextLabel_set_scroll_follow # | If @true@ , the window scrolls down to display new content automatically . bindRichTextLabel_set_scroll_follow :: MethodBind bindRichTextLabel_set_scroll_follow = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_scroll_follow" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the window scrolls down to display new content automatically . set_scroll_follow :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_scroll_follow cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_scroll_follow (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_scroll_follow" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_scroll_follow # NOINLINE bindRichTextLabel_set_selection_enabled # | If @true@ , the label allows text selection . bindRichTextLabel_set_selection_enabled :: MethodBind bindRichTextLabel_set_selection_enabled = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_selection_enabled" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label allows text selection . set_selection_enabled :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_selection_enabled cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_selection_enabled (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_selection_enabled" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_selection_enabled # NOINLINE bindRichTextLabel_set_tab_size # bindRichTextLabel_set_tab_size :: MethodBind bindRichTextLabel_set_tab_size = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_tab_size" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_tab_size :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () set_tab_size cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_tab_size (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_tab_size" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_tab_size # NOINLINE bindRichTextLabel_set_table_column_expand # | Edits the selected column 's expansion options . If @expand@ is @true@ , the column expands in proportion to its expansion ratio versus the other columns ' ratios . For example , 2 columns with ratios 3 and 4 plus 70 pixels in available width would expand 30 and 40 pixels , respectively . If @expand@ is @false@ , the column will not contribute to the total ratio . bindRichTextLabel_set_table_column_expand :: MethodBind bindRichTextLabel_set_table_column_expand = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_table_column_expand" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Edits the selected column 's expansion options . If @expand@ is @true@ , the column expands in proportion to its expansion ratio versus the other columns ' ratios . For example , 2 columns with ratios 3 and 4 plus 70 pixels in available width would expand 30 and 40 pixels , respectively . If @expand@ is @false@ , the column will not contribute to the total ratio . set_table_column_expand :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> Bool -> Int -> IO () set_table_column_expand cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_table_column_expand (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_table_column_expand" '[Int, Bool, Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_table_column_expand # NOINLINE bindRichTextLabel_set_text # When set , clears the tag stack and adds a raw text tag to the top of it . Does not parse . Does not modify @bbcode_text@. bindRichTextLabel_set_text :: MethodBind bindRichTextLabel_set_text = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_text" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr When set , clears the tag stack and adds a raw text tag to the top of it . Does not parse . Does not modify @bbcode_text@. set_text :: (RichTextLabel :< cls, Object :< cls) => cls -> GodotString -> IO () set_text cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_text (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_text" '[GodotString] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_text | If @true@ , the label uses BBCode formatting . bindRichTextLabel_set_use_bbcode :: MethodBind bindRichTextLabel_set_use_bbcode = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_use_bbcode" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | If @true@ , the label uses BBCode formatting . set_use_bbcode :: (RichTextLabel :< cls, Object :< cls) => cls -> Bool -> IO () set_use_bbcode cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_use_bbcode (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_use_bbcode" '[Bool] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_use_bbcode # NOINLINE bindRichTextLabel_set_visible_characters # bindRichTextLabel_set_visible_characters :: MethodBind bindRichTextLabel_set_visible_characters = unsafePerformIO $ withCString "RichTextLabel" $ \ clsNamePtr -> withCString "set_visible_characters" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_visible_characters :: (RichTextLabel :< cls, Object :< cls) => cls -> Int -> IO () set_visible_characters cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindRichTextLabel_set_visible_characters (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod RichTextLabel "set_visible_characters" '[Int] (IO ()) where nodeMethod = Godot.Core.RichTextLabel.set_visible_characters
cbdc9729e29c6b9ff6f8aa9540dc87dcfb514c1b721f5eea33c4ca9b193163ee
hidaris/thinking-dumps
2-31.rkt
#lang eopl (require "base.ss") (define-datatype prefix-list prefix-list? (a-prefix-list (exp prefix-exp?) (rest (list-of prefix-exp?)))) (define-datatype prefix-exp prefix-exp? (const-exp (num integer?)) (diff-exp (operand1 prefix-exp?) (operand2 prefix-exp?))) ;; ; (- - 3 2 - 4 - 12 7) (define parse-pexp (lambda (pexp) (cond ((integer? pexp) (const-exp pexp)) ((list? pexp) (if (eqv? (car pexp) '-) (if (eqv? (length pexp) 3) (diff-exp (parse-pexp (list-ref pexp 1)) (parse-pexp (list-ref pexp 2))) 3) (eopl:error 'parse-pexp "invalid prefix-exp"))) (else (eopl:error 'parse-pexp "not a prefix-exp")))))
null
https://raw.githubusercontent.com/hidaris/thinking-dumps/3fceaf9e6195ab99c8315749814a7377ef8baf86/eopl-solutions/chap2/2-31.rkt
racket
; (- - 3 2 - 4 - 12 7)
#lang eopl (require "base.ss") (define-datatype prefix-list prefix-list? (a-prefix-list (exp prefix-exp?) (rest (list-of prefix-exp?)))) (define-datatype prefix-exp prefix-exp? (const-exp (num integer?)) (diff-exp (operand1 prefix-exp?) (operand2 prefix-exp?))) (define parse-pexp (lambda (pexp) (cond ((integer? pexp) (const-exp pexp)) ((list? pexp) (if (eqv? (car pexp) '-) (if (eqv? (length pexp) 3) (diff-exp (parse-pexp (list-ref pexp 1)) (parse-pexp (list-ref pexp 2))) 3) (eopl:error 'parse-pexp "invalid prefix-exp"))) (else (eopl:error 'parse-pexp "not a prefix-exp")))))
fea86ee346c8281016a32765f9a32a064846d3ecf28a6dd5f9386c724e70bc22
suprematic/zipkin-clj
core_test.clj
(ns zipkin-clj.core-test (:require [clojure.core.match :refer [match]] [clojure.test :refer [deftest is]] [zipkin-clj.core :as zipkin])) ;; ==================================================================== Internal ;; ==================================================================== (defn- collecting-sender [collect-to-atom spans] (swap! collect-to-atom concat spans)) (defmacro ^:private find-matches [match-spec coll] `(filter #(match % ~match-spec true :else false) ~coll)) (defn- nested-span [i] (zipkin/child-trace! {:span "my-span-2" :annotations ["sleep250"] :tags {"nested span" "yes"}} (zipkin/tag! {"i" i}) (zipkin/annotate! i))) ;; ==================================================================== ;; Tests ;; ==================================================================== (deftest a-test (let [spans (atom [])] (zipkin/configure! :sender (partial collecting-sender spans) :endpoint {:service-name "my-service"}) (zipkin/trace! {:span "my-span-1" :tags {"root span" "yes"}} (nested-span 1) (nested-span 2)) (let [spans @spans] (is (= 3 (count spans)) "3 spans must be collected") (is (apply = (map :traceId spans)) "all spans must belong to the same trace (have the same trace id)") (is (= 3 (count (find-matches {:id (_ :guard #(re-matches #"[a-z0-9]{16}" %)) :traceId (_ :guard #(re-matches #"[a-z0-9]{16,32}" %)) :localEndpoint {:serviceName "my-service"} :duration (_ :guard pos?) :timestamp (_ :guard integer?)} spans))) (str "all spans must have: id, trace id, duration, serice name" " and timestamp")) (is (= 1 (count (find-matches {:name "my-span-1" :tags {"root span" "yes"}} spans))) "root span must present with its name and tags") (let [[{root-span-id :id}] (find-matches {:name "my-span-1"} spans)] (is (= 1 (count (find-matches {:name "my-span-2" :parentId root-span-id :annotations ([{:value "sleep250" :timestamp _} {:value 1 :timestamp _}] :seq) :tags {"nested span" "yes" "i" 1}} spans))) (str "first nested span must present with its name, tags," " parent id and anotations")) (is (= 1 (count (find-matches {:name "my-span-2" :parentId root-span-id :annotations ([{:value "sleep250" :timestamp _} {:value 2 :timestamp _}] :seq) :tags {"nested span" "yes" "i" 2}} spans))) (str "second nested span must present with its name, tags," " parent id and anotations"))))))
null
https://raw.githubusercontent.com/suprematic/zipkin-clj/fb7cb0b08e970312e6de71611a48cdefd4e40bc0/test/zipkin_clj/core_test.clj
clojure
==================================================================== ==================================================================== ==================================================================== Tests ====================================================================
(ns zipkin-clj.core-test (:require [clojure.core.match :refer [match]] [clojure.test :refer [deftest is]] [zipkin-clj.core :as zipkin])) Internal (defn- collecting-sender [collect-to-atom spans] (swap! collect-to-atom concat spans)) (defmacro ^:private find-matches [match-spec coll] `(filter #(match % ~match-spec true :else false) ~coll)) (defn- nested-span [i] (zipkin/child-trace! {:span "my-span-2" :annotations ["sleep250"] :tags {"nested span" "yes"}} (zipkin/tag! {"i" i}) (zipkin/annotate! i))) (deftest a-test (let [spans (atom [])] (zipkin/configure! :sender (partial collecting-sender spans) :endpoint {:service-name "my-service"}) (zipkin/trace! {:span "my-span-1" :tags {"root span" "yes"}} (nested-span 1) (nested-span 2)) (let [spans @spans] (is (= 3 (count spans)) "3 spans must be collected") (is (apply = (map :traceId spans)) "all spans must belong to the same trace (have the same trace id)") (is (= 3 (count (find-matches {:id (_ :guard #(re-matches #"[a-z0-9]{16}" %)) :traceId (_ :guard #(re-matches #"[a-z0-9]{16,32}" %)) :localEndpoint {:serviceName "my-service"} :duration (_ :guard pos?) :timestamp (_ :guard integer?)} spans))) (str "all spans must have: id, trace id, duration, serice name" " and timestamp")) (is (= 1 (count (find-matches {:name "my-span-1" :tags {"root span" "yes"}} spans))) "root span must present with its name and tags") (let [[{root-span-id :id}] (find-matches {:name "my-span-1"} spans)] (is (= 1 (count (find-matches {:name "my-span-2" :parentId root-span-id :annotations ([{:value "sleep250" :timestamp _} {:value 1 :timestamp _}] :seq) :tags {"nested span" "yes" "i" 1}} spans))) (str "first nested span must present with its name, tags," " parent id and anotations")) (is (= 1 (count (find-matches {:name "my-span-2" :parentId root-span-id :annotations ([{:value "sleep250" :timestamp _} {:value 2 :timestamp _}] :seq) :tags {"nested span" "yes" "i" 2}} spans))) (str "second nested span must present with its name, tags," " parent id and anotations"))))))
16ac9af3f5630f6890e9697ccb6f2680f4b7fc3eaeb8d3e4ba2ffc65da3642eb
jumper149/go
Main.hs
module Main ( main ) where import qualified Test.Board.Default main :: IO () main = Test.Board.Default.runTests
null
https://raw.githubusercontent.com/jumper149/go/603e61f64e8e7c890bbc914fef6033b5ed7dd005/test/Main.hs
haskell
module Main ( main ) where import qualified Test.Board.Default main :: IO () main = Test.Board.Default.runTests
f136537e8b3dce6a70544c91751c73716913bc33771ac81e8cc50d088b8f3489
ahmed-abdelmotey/AutoCAD-LISP
Match Block Orientation.lsp
(princ "Author: Ahmed Abd-elmotey - NOV 2015 - ") (defun c:MZBO () (setq ss (ssget) i 0 j 0) (while (< i (sslength ss)) (progn (setq ro (* 180.0 (/ (vla-get-rotation (vlax-ename->vla-object (ssname ss i))) pi))) (if (/= 0 ro) (setq rott ro)) (setq i (1+ i)) ) ) (while rott (progn (vla-put-rotation (vlax-ename->vla-object (ssname ss j)) (* pi (/ rott 180.0))) (setq j (1+ j)))) ) (defun c:MBO () (setq ro (vla-get-rotation (vlax-ename->vla-object (car (entsel "\nSelect Block Object"))))) (setq ss (ssget) i 0) (repeat (sslength ss) (vla-put-rotation (vlax-ename->vla-object (ssname ss i)) ro) (setq i (1+ i)) ) )
null
https://raw.githubusercontent.com/ahmed-abdelmotey/AutoCAD-LISP/32b59bb5dd7e67727d81faefd93dbca70c3efcde/3-%20Match%20Block%20orientation/Match%20Block%20Orientation.lsp
lisp
(princ "Author: Ahmed Abd-elmotey - NOV 2015 - ") (defun c:MZBO () (setq ss (ssget) i 0 j 0) (while (< i (sslength ss)) (progn (setq ro (* 180.0 (/ (vla-get-rotation (vlax-ename->vla-object (ssname ss i))) pi))) (if (/= 0 ro) (setq rott ro)) (setq i (1+ i)) ) ) (while rott (progn (vla-put-rotation (vlax-ename->vla-object (ssname ss j)) (* pi (/ rott 180.0))) (setq j (1+ j)))) ) (defun c:MBO () (setq ro (vla-get-rotation (vlax-ename->vla-object (car (entsel "\nSelect Block Object"))))) (setq ss (ssget) i 0) (repeat (sslength ss) (vla-put-rotation (vlax-ename->vla-object (ssname ss i)) ro) (setq i (1+ i)) ) )
c0d4f3632284ad459d3576bc398d257020dfbca954413153d716f5d161a160a7
Yuras/bindings-gobject
GObject.hs
module Bindings.GObject ( module Bindings.GObject.BaseObjectType, module Bindings.GObject.BoxedTypes, module Bindings.GObject.Closures, module Bindings.GObject.EnumerationAndFlagTypes, module Bindings.GObject.GenericValues, module Bindings.GObject.GParamSpec, module Bindings.GObject.GTypeModule, module Bindings.GObject.GTypePlugin, module Bindings.GObject.ParametersAndValues, module Bindings.GObject.Signals, module Bindings.GObject.TypeInformation, module Bindings.GObject.ValueArrays, module Bindings.GObject.Varargs ) where import Bindings.GObject.BaseObjectType import Bindings.GObject.BoxedTypes import Bindings.GObject.Closures import Bindings.GObject.EnumerationAndFlagTypes import Bindings.GObject.GenericValues import Bindings.GObject.GParamSpec import Bindings.GObject.GTypeModule import Bindings.GObject.GTypePlugin import Bindings.GObject.ParametersAndValues import Bindings.GObject.Signals import Bindings.GObject.TypeInformation import Bindings.GObject.ValueArrays import Bindings.GObject.Varargs
null
https://raw.githubusercontent.com/Yuras/bindings-gobject/330747ad08cb16bc3f77509f356ec431aa12d05e/src/Bindings/GObject.hs
haskell
module Bindings.GObject ( module Bindings.GObject.BaseObjectType, module Bindings.GObject.BoxedTypes, module Bindings.GObject.Closures, module Bindings.GObject.EnumerationAndFlagTypes, module Bindings.GObject.GenericValues, module Bindings.GObject.GParamSpec, module Bindings.GObject.GTypeModule, module Bindings.GObject.GTypePlugin, module Bindings.GObject.ParametersAndValues, module Bindings.GObject.Signals, module Bindings.GObject.TypeInformation, module Bindings.GObject.ValueArrays, module Bindings.GObject.Varargs ) where import Bindings.GObject.BaseObjectType import Bindings.GObject.BoxedTypes import Bindings.GObject.Closures import Bindings.GObject.EnumerationAndFlagTypes import Bindings.GObject.GenericValues import Bindings.GObject.GParamSpec import Bindings.GObject.GTypeModule import Bindings.GObject.GTypePlugin import Bindings.GObject.ParametersAndValues import Bindings.GObject.Signals import Bindings.GObject.TypeInformation import Bindings.GObject.ValueArrays import Bindings.GObject.Varargs
a7a63dc229f038c42a023cf043386076fd9714754648ca079f0da12e3c1b57cc
dmjio/miso
Event.hs
# LANGUAGE FlexibleInstances # # LANGUAGE TypeFamilies # {-# LANGUAGE DataKinds #-} # LANGUAGE OverloadedStrings # # LANGUAGE MultiParamTypeClasses # ----------------------------------------------------------------------------- -- | -- Module : Miso.Svg.Events Copyright : ( C ) 2016 - 2018 -- License : BSD3-style (see the file LICENSE) Maintainer : < > -- Stability : experimental -- Portability : non-portable ---------------------------------------------------------------------------- module Miso.Svg.Event ( -- * Animation event handlers onBegin , onEnd , onRepeat -- * Document event attributes , onAbort , onError , onResize , onScroll , onLoad , onUnload , onZoom -- * Graphical Event Attributes , onActivate , onClick , onFocusIn , onFocusOut , onMouseDown , onMouseMove , onMouseOut , onMouseOver , onMouseUp ) where import Miso.Event import Miso.Html.Event (onClick) import Miso.Html.Types -- | onBegin event onBegin :: action -> Attribute action onBegin action = on "begin" emptyDecoder $ \() -> action -- | onEnd event onEnd :: action -> Attribute action onEnd action = on "end" emptyDecoder $ \() -> action -- | onRepeat event onRepeat :: action -> Attribute action onRepeat action = on "repeat" emptyDecoder $ \() -> action -- | onAbort event onAbort :: action -> Attribute action onAbort action = on "abort" emptyDecoder $ \() -> action -- | onError event onError :: action -> Attribute action onError action = on "error" emptyDecoder $ \() -> action -- | onResize event onResize :: action -> Attribute action onResize action = on "resize" emptyDecoder $ \() -> action -- | onScroll event onScroll :: action -> Attribute action onScroll action = on "scroll" emptyDecoder $ \() -> action -- | onLoad event onLoad :: action -> Attribute action onLoad action = on "load" emptyDecoder $ \() -> action -- | onUnload event onUnload :: action -> Attribute action onUnload action = on "unload" emptyDecoder $ \() -> action -- | onZoom event onZoom :: action -> Attribute action onZoom action = on "zoom" emptyDecoder $ \() -> action -- | onActivate event onActivate :: action -> Attribute action onActivate action = on "activate" emptyDecoder $ \() -> action -- | onFocusIn event onFocusIn :: action -> Attribute action onFocusIn action = on "focusin" emptyDecoder $ \() -> action -- | onFocusOut event onFocusOut :: action -> Attribute action onFocusOut action = on "focusout" emptyDecoder $ \() -> action -- | onMouseDown event onMouseDown :: action -> Attribute action onMouseDown action = on "mousedown" emptyDecoder $ \() -> action -- | onMouseMove event onMouseMove :: action -> Attribute action onMouseMove action = on "mousemove" emptyDecoder $ \() -> action -- | onMouseOut event onMouseOut :: action -> Attribute action onMouseOut action = on "mouseout" emptyDecoder $ \() -> action -- | onMouseOver event onMouseOver :: action -> Attribute action onMouseOver action = on "mouseover" emptyDecoder $ \() -> action -- | onMouseUp event onMouseUp :: action -> Attribute action onMouseUp action = on "mouseup" emptyDecoder $ \() -> action
null
https://raw.githubusercontent.com/dmjio/miso/339505587fd8576c7f89484d3a4244732a9f00e6/src/Miso/Svg/Event.hs
haskell
# LANGUAGE DataKinds # --------------------------------------------------------------------------- | Module : Miso.Svg.Events License : BSD3-style (see the file LICENSE) Stability : experimental Portability : non-portable -------------------------------------------------------------------------- * Animation event handlers * Document event attributes * Graphical Event Attributes | onBegin event | onEnd event | onRepeat event | onAbort event | onError event | onResize event | onScroll event | onLoad event | onUnload event | onZoom event | onActivate event | onFocusIn event | onFocusOut event | onMouseDown event | onMouseMove event | onMouseOut event | onMouseOver event | onMouseUp event
# LANGUAGE FlexibleInstances # # LANGUAGE TypeFamilies # # LANGUAGE OverloadedStrings # # LANGUAGE MultiParamTypeClasses # Copyright : ( C ) 2016 - 2018 Maintainer : < > module Miso.Svg.Event onBegin , onEnd , onRepeat , onAbort , onError , onResize , onScroll , onLoad , onUnload , onZoom , onActivate , onClick , onFocusIn , onFocusOut , onMouseDown , onMouseMove , onMouseOut , onMouseOver , onMouseUp ) where import Miso.Event import Miso.Html.Event (onClick) import Miso.Html.Types onBegin :: action -> Attribute action onBegin action = on "begin" emptyDecoder $ \() -> action onEnd :: action -> Attribute action onEnd action = on "end" emptyDecoder $ \() -> action onRepeat :: action -> Attribute action onRepeat action = on "repeat" emptyDecoder $ \() -> action onAbort :: action -> Attribute action onAbort action = on "abort" emptyDecoder $ \() -> action onError :: action -> Attribute action onError action = on "error" emptyDecoder $ \() -> action onResize :: action -> Attribute action onResize action = on "resize" emptyDecoder $ \() -> action onScroll :: action -> Attribute action onScroll action = on "scroll" emptyDecoder $ \() -> action onLoad :: action -> Attribute action onLoad action = on "load" emptyDecoder $ \() -> action onUnload :: action -> Attribute action onUnload action = on "unload" emptyDecoder $ \() -> action onZoom :: action -> Attribute action onZoom action = on "zoom" emptyDecoder $ \() -> action onActivate :: action -> Attribute action onActivate action = on "activate" emptyDecoder $ \() -> action onFocusIn :: action -> Attribute action onFocusIn action = on "focusin" emptyDecoder $ \() -> action onFocusOut :: action -> Attribute action onFocusOut action = on "focusout" emptyDecoder $ \() -> action onMouseDown :: action -> Attribute action onMouseDown action = on "mousedown" emptyDecoder $ \() -> action onMouseMove :: action -> Attribute action onMouseMove action = on "mousemove" emptyDecoder $ \() -> action onMouseOut :: action -> Attribute action onMouseOut action = on "mouseout" emptyDecoder $ \() -> action onMouseOver :: action -> Attribute action onMouseOver action = on "mouseover" emptyDecoder $ \() -> action onMouseUp :: action -> Attribute action onMouseUp action = on "mouseup" emptyDecoder $ \() -> action
6405d1625b8bb924c4a08b1d27f8c0fabc0a70031f9d0c63a5c53636841b9f15
cdepillabout/servant-static-th
HelperFuncSpec.hs
# LANGUAGE OverloadedLists # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE NoMonomorphismRestriction # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module Spec.HelperFuncSpec where import System.FilePath ((</>)) import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit ((@?=), testCase) import Servant.Static.TH.Internal (FileTree(..), FileType(..), getFileTreeIgnoreEmpty, getFileType) import Spec.TastyHelpers ((@!), anyException) import Spec.TestDirLocation (testDir) helperFuncTests :: TestTree helperFuncTests = testGroup "helper functions" [ getFileTypeTests , getFileTreeIgnoreEmptyTests ] getFileTypeTests :: TestTree getFileTypeTests = testGroup "getFileType" [ testCase "correctly checks files" $ do let helloHtmlPath = testDir </> "hello.html" fileType <- getFileType helloHtmlPath FileTypeFile helloHtmlPath @?= fileType , testCase "correctly checks directories" $ do fileType <- getFileType testDir FileTypeDir testDir @?= fileType , testCase "fails for anything else" $ getFileType "somelongfilethatdoesntexist" @! anyException ] getFileTreeIgnoreEmptyTests :: TestTree getFileTreeIgnoreEmptyTests = testGroup "getFileTreeIgnoreEmpty" [ testCase "correctly gets file tree" $ do actualFileTree <- getFileTreeIgnoreEmpty testDir let expectedFileTree = [ FileTreeDir (testDir </> "dir") [ FileTreeFile (testDir </> "dir" </> "inner-file.html") "Inner File\n" , FileTreeFile (testDir </> "dir" </> "test.js") "console.log(\"hello world\");\n" ] , FileTreeFile (testDir </> "hello.html") "Hello World\n" , FileTreeFile (testDir </> "index.html") "Index\n" ] actualFileTree @?= expectedFileTree , testCase "fails on empty directory" $ getFileTreeIgnoreEmpty (testDir </> "empty-dir") @! anyException ]
null
https://raw.githubusercontent.com/cdepillabout/servant-static-th/5ec0027ed2faa6f8c42a2259a963f52e6b30edad/test/Spec/HelperFuncSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE OverloadedLists # # LANGUAGE NoMonomorphismRestriction # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module Spec.HelperFuncSpec where import System.FilePath ((</>)) import Test.Tasty (TestTree, testGroup) import Test.Tasty.HUnit ((@?=), testCase) import Servant.Static.TH.Internal (FileTree(..), FileType(..), getFileTreeIgnoreEmpty, getFileType) import Spec.TastyHelpers ((@!), anyException) import Spec.TestDirLocation (testDir) helperFuncTests :: TestTree helperFuncTests = testGroup "helper functions" [ getFileTypeTests , getFileTreeIgnoreEmptyTests ] getFileTypeTests :: TestTree getFileTypeTests = testGroup "getFileType" [ testCase "correctly checks files" $ do let helloHtmlPath = testDir </> "hello.html" fileType <- getFileType helloHtmlPath FileTypeFile helloHtmlPath @?= fileType , testCase "correctly checks directories" $ do fileType <- getFileType testDir FileTypeDir testDir @?= fileType , testCase "fails for anything else" $ getFileType "somelongfilethatdoesntexist" @! anyException ] getFileTreeIgnoreEmptyTests :: TestTree getFileTreeIgnoreEmptyTests = testGroup "getFileTreeIgnoreEmpty" [ testCase "correctly gets file tree" $ do actualFileTree <- getFileTreeIgnoreEmpty testDir let expectedFileTree = [ FileTreeDir (testDir </> "dir") [ FileTreeFile (testDir </> "dir" </> "inner-file.html") "Inner File\n" , FileTreeFile (testDir </> "dir" </> "test.js") "console.log(\"hello world\");\n" ] , FileTreeFile (testDir </> "hello.html") "Hello World\n" , FileTreeFile (testDir </> "index.html") "Index\n" ] actualFileTree @?= expectedFileTree , testCase "fails on empty directory" $ getFileTreeIgnoreEmpty (testDir </> "empty-dir") @! anyException ]
b121eca96182288ccc769a7b533887ae97837f60c057c26afb27cd15929f4696
trystan/voronoi-diagram
project.clj
(defproject trystan/voronoi-diagram "1.0.1" :description "Create a Voronoi diagram from a collection of points." :url "-diagram" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.7.0"] [trystan/delaunay-triangulation "1.0.2"]])
null
https://raw.githubusercontent.com/trystan/voronoi-diagram/e89a3753cf4974b472303f751ef73f8481d06fe0/project.clj
clojure
(defproject trystan/voronoi-diagram "1.0.1" :description "Create a Voronoi diagram from a collection of points." :url "-diagram" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.7.0"] [trystan/delaunay-triangulation "1.0.2"]])
443437d204a720f154045c7d4e9954d1d81bb435772fa039ef58820473026f61
racket/gui
test.rkt
#lang at-exp racket/base (require racket/class racket/contract/base racket/gui/base scribble/srcdoc (for-syntax racket/base) (prefix-in :: framework/private/focus-table)) (generate-delayed-documents) ; enables for-doc--for-label import of `framework' (require/doc scheme/base scribble/manual (for-label framework)) (define (test:top-level-focus-window-has? pred) (let ([tlw (test:get-active-top-level-window)]) (and tlw (let loop ([tlw tlw]) (or (pred tlw) (and (is-a? tlw area-container<%>) (ormap loop (send tlw get-children)))))))) (define initial-run-interval 0) ;; milliseconds ;; ;; The minimum time an action is allowed to run before returning from ;; mred:test:action. Controls the rate at which actions are started, ;; and gives some slack time for real events to complete (eg, update). ;; Make-parameter doesn't do what we need across threads. ;; Probably don't need semaphores here (set! is atomic). ;; Units are in milliseconds (as in mred:timer%). ;; (define run-interval (let ([tag 'test:run-interval] [msec initial-run-interval]) (case-lambda [() msec] [(x) (if (and (integer? x) (exact? x) (<= 0 x)) (set! msec x) (error tag "expects exact, non-negative integer, given: ~e" x))]))) ;; ;; How we get into the handler thread, and put fake actions ;; on the real event queue. ;; (define install-timer (λ (msec thunk) (let ([timer (instantiate timer% () [notify-callback (λ () (thunk))])]) (send timer start msec #t)))) ;; ;; Simple accounting of actions and errors. ;; ;; Keep number of unfinished actions. An error in the buffer ;; (caught but not-yet-reraised) counts as an unfinished action. ;; (but kept in the-error, not count). ;; Keep buffer of one error , and reraise at first opportunity . Keep just first error , any others are thrown on the floor . ;; Reraising the error flushes the buffer. ;; Store exn in box, so can correctly catch (raise #f). ;; ;; These values are set in handler thread and read in main thread, ;; so certainly need semaphores here. ;; (define-values (begin-action end-action end-action-with-error get-exn-box is-exn? num-actions) (let ([sem (make-semaphore 1)] [count 0] ;; number unfinished actions. boxed exn struct , or else # f. (letrec ([begin-action (λ () (semaphore-wait sem) (set! count (add1 count)) (semaphore-post sem))] [end-action (λ () (semaphore-wait sem) (set! count (sub1 count)) (semaphore-post sem))] [end-action-with-error (λ (exn) (semaphore-wait sem) (set! count (sub1 count)) (unless the-error (set! the-error (box exn))) (semaphore-post sem))] [get-exn-box (λ () (semaphore-wait sem) (let ([ans the-error]) (set! the-error #f) (semaphore-post sem) ans))] [is-exn? (λ () (semaphore-wait sem) (let ([ans (if the-error #t #f)]) (semaphore-post sem) ans))] [num-actions (λ () (semaphore-wait sem) (let ([ans (+ count (if the-error 1 0))]) (semaphore-post sem) ans))]) (values begin-action end-action end-action-with-error get-exn-box is-exn? num-actions)))) ;; Functions to export, always in main thread. (define number-pending-actions num-actions) (define reraise-error (λ () (let ([exn-box (get-exn-box)]) (if exn-box (raise (unbox exn-box)) (void))))) ;; ;; Start running thunk in handler thread. ;; Don't return until run-interval expires, and thunk finishes, ;; raises error, or yields (ie, at event boundary). error ( if exists ) even from previous action . Note : never more than one timer ( of ours ) on real event queue . ;; (define run-one (let ([yield-semaphore (make-semaphore 0)] [thread-semaphore (make-semaphore 0)]) (thread (λ () (let loop () (semaphore-wait thread-semaphore) (sleep) (semaphore-post yield-semaphore) (loop)))) (λ (thunk) (let ([sem (make-semaphore 0)]) (letrec ([start (λ () ;; eventspace main thread ;; guarantee (probably) that some events are handled (semaphore-post thread-semaphore) (yield yield-semaphore) (install-timer (run-interval) return) (unless (is-exn?) (begin-action) (call-with-exception-handler (λ (exn) (end-action-with-error exn) ((error-escape-handler))) thunk) (end-action)))] [return (λ () (semaphore-post sem))]) (install-timer 0 start) (semaphore-wait sem) (reraise-error)))))) (define current-get-eventspaces (make-parameter (λ () (list (current-eventspace))))) (define test:use-focus-table (make-parameter #f)) (define (test:get-active-top-level-window) (ormap (λ (eventspace) (parameterize ([current-eventspace eventspace]) (cond [(test:use-focus-table) (define lst (::frame:lookup-focus-table)) (define focusd (and (not (null? lst)) (car lst))) (when (eq? (test:use-focus-table) 'debug) (define f2 (get-top-level-focus-window)) (unless (eq? focusd f2) (eprintf "found mismatch focus-table: ~s vs get-top-level-focus-window: ~s\n" (map (λ (x) (send x get-label)) lst) (and f2 (list (send f2 get-label)))))) focusd] [else (get-top-level-focus-window)]))) ((current-get-eventspaces)))) (define (get-focused-window) (let ([f (test:get-active-top-level-window)]) (and f (send f get-edit-target-window)))) (define time-stamp current-milliseconds) ;; ;; Return list of window's ancestors from root down to window ;; (including window). Used for on-subwindow-char and on-subwindow-event. ;; get-parent returns #f for no parent. ;; If stop-at-top-level-window? is #t, then the ancestors up to the first top - level - window are returned . ;; (define ancestor-list (λ (window stop-at-top-level-window?) (let loop ([w window] [l null]) (if (or (not w) (and stop-at-top-level-window? (is-a? w top-level-window<%>))) l (loop (send w get-parent) (cons w l)))))) ;; Returns # t if window is in active - frame , else # f. ;; get-parent returns () for no parent. ;; (define (in-active-frame? window) (let ([frame (test:get-active-top-level-window)]) (let loop ([window window]) (cond [(not window) #f] [(not frame) #f] [(null? window) #f] ;; is this test needed? [(object=? window frame) #t] [else (loop (send window get-parent))])))) ;; ;; Verify modifier list. ;; l, valid : lists of symbols. returns first item in l * not * in valid , or else # f. ;; (define verify-list (λ (l valid) (cond [(null? l) #f] [(member (car l) valid) (verify-list (cdr l) valid)] [else (car l)]))) (define verify-item (λ (item valid) (verify-list (list item) valid))) ;;; ;;; find-object obj-class b-desc ;;; returns an object belonging to obj-class, where b-desc ;;; is either an object, or a string ;;; (define object-tag 'test:find-object) ;; find-object : class (union string regexp (object -> boolean)) -> object (define (find-object obj-class b-desc) (λ () (cond [(or (string? b-desc) (regexp? b-desc) (procedure? b-desc)) (let* ([active-frame (test:get-active-top-level-window)] [_ (unless active-frame (error object-tag "could not find object: ~e, no active frame" b-desc))] [child-matches? (λ (child) (cond [(string? b-desc) (equal? (send child get-label) b-desc)] [(regexp? b-desc) (and (send child get-label) (regexp-match? b-desc (send child get-label)))] [(procedure? b-desc) (b-desc child)]))] [found (let loop ([panel active-frame]) (ormap (λ (child) (cond [(and (is-a? child obj-class) (child-matches? child)) child] [(is-a? child area-container-window<%>) (and (send child is-shown?) (loop child))] [(is-a? child area-container<%>) (loop child)] [else #f])) (send panel get-children)))]) (or found (error object-tag "no object of class ~e named ~e in active frame" obj-class b-desc)))] [(is-a? b-desc obj-class) b-desc] [else (error object-tag "expected either a string or an object of class ~e as input, received: ~e" obj-class b-desc)]))) ;;; functions specific to various user input ;;; CONTROL functions, to be specialized for individual controls (define control-action (λ (error-tag event-sym find-ctrl update-control) (run-one (λ () (let ([event (make-object control-event% event-sym)] [ctrl (find-ctrl)]) (cond [(not (send ctrl is-shown?)) (error error-tag "control ~e is not shown (label ~e)" ctrl (send ctrl get-label))] [(not (send ctrl is-enabled?)) (error error-tag "control ~e is not enabled (label ~e)" ctrl (send ctrl get-label))] [(not (in-active-frame? ctrl)) (error error-tag "control ~e is not in active frame (label ~e)" ctrl (send ctrl get-label))] [else (update-control ctrl) (send ctrl command event) (void)])))))) ;; ;; BUTTON ;; (define (button-push button) (control-action 'test:button-push 'button (find-object button% button) void)) ;; ;; CHECK-BOX ;; (define (set-check-box! in-cb state) (control-action 'test:set-check-box! 'check-box (find-object check-box% in-cb) (λ (cb) (send cb set-value state)))) ;; ;; RADIO-BOX ;; (define (build-labels radio-box) (string-append (format "~s" (send radio-box get-item-label 0)) (let loop ([n (- (send radio-box get-number) 1)]) (cond [(zero? n) ""] [else (string-append " " (format "~s" (send radio-box get-item-label (- (send radio-box get-number) n))) (loop (- n 1)))])))) (define (set-radio-box! in-cb state) (control-action 'test:set-radio-box! 'radio-box (find-object radio-box% in-cb) (λ (rb) (cond [(string? state) (let ([total (send rb get-number)]) (let loop ([n total]) (cond [(zero? n) (error 'test:set-radio-box! "did not find ~e as a label for ~e; labels: ~a" state in-cb (build-labels rb))] [else (let ([i (- total n)]) (if (ith-item-matches? rb state i) (if (send rb is-enabled? i) (send rb set-selection i) (error 'test:set-radio-box! "label ~e is disabled" state)) (loop (- n 1))))])))] [(number? state) (unless (send rb is-enabled? state) (error 'test:set-radio-box! "item ~a is not enabled\n" state)) (send rb set-selection state)] [else (error 'test:set-radio-box! "expected a string or a number as second arg, got: ~e (other arg: ~e)" state in-cb)])))) (define (ith-item-matches? rb state i) (cond [(string? state) (or (string=? state (send rb get-item-label i)) (string=? state (send rb get-item-plain-label i)))] [(regexp? state) (or (regexp-match state (send rb get-item-label i)) (regexp-match state (send rb get-item-plain-label i)))])) ;; set-radio-box-item! : string -> void (define (set-radio-box-item! state) (control-action 'test:set-check-box-state! 'radio-box (find-object radio-box% (entry-matches state)) (λ (rb) (let ([total (send rb get-number)]) (let loop ([n total]) (cond [(zero? n) (error 'test:set-radio-box-item! "internal error")] [else (let ([i (- total n)]) (if (ith-item-matches? rb state i) (if (send rb is-enabled? i) (send rb set-selection i) (error 'test:set-radio-box! "label ~e is disabled" state)) (loop (- n 1))))])))))) ;; entry-matches : string | regexp -> radio-box -> boolean (define (entry-matches name) (procedure-rename (λ (rb) (let loop ([n (send rb get-number)]) (cond [(zero? n) #f] [else (let ([itm (send rb get-item-label (- n 1))] [pln-itm (send rb get-item-plain-label (- n 1))]) (or (cond [(string? name) (or (equal? name itm) (equal? name pln-itm))] [(regexp? name) (or (regexp-match name itm) (regexp-match name pln-itm))]) (loop (- n 1))))]))) (string->symbol (if (regexp? name) (object-name name) name)))) ;;; CHOICE ; set-choice! : ((instance in-choice%) (union string number) -> void) (define (set-choice! in-choice str) (control-action 'test:set-choice! 'choice (find-object choice% in-choice) (λ (choice) (cond [(number? str) (send choice set-selection str)] [(string? str) (send choice set-string-selection str)] [else (error 'test:set-choice! "expected a string or a number as second arg, got: ~e (other arg: ~e)" str in-choice)])))) (define (set-list-box! in-lb str) (control-action 'test:set-list-box! 'list-box (find-object list-box% in-lb) (λ (lb) (cond [(number? str) (send lb set-selection str)] [(string? str) (send lb set-string-selection str)] [else (error 'test:set-list-box! "expected a string or a number as second arg, got: ~e (other arg: ~e)" str in-lb)])))) ;; KEYSTROKES ;; ;; Give ancestors (from root down) option of handling key event ;; with on-subwindow-char. If none want it, then send to focused window ;; with (send <window> on-char <wx:key-event>). ;; ;; key: char or integer. ;; optional modifiers: 'alt, 'control, 'meta, 'shift, ' noalt , ' nocontrol , ' nometa , ' noshift . ;; ;; Window must be shown, in active frame, and either the window has ;; on-char, or else some ancestor must grab key with on-subwindow-char. ;; (define key-tag 'test:keystroke) (define legal-keystroke-modifiers (list 'alt 'control 'meta 'shift 'noalt 'nocontrol 'nometa 'noshift)) (define valid-key-symbols just trying this for the heck of it -- JBC , 2010 - 08 - 13 'start 'cancel 'clear 'shift 'control 'menu 'pause 'capital 'prior 'next 'end 'home 'left 'up 'right 'down 'select 'print 'execute 'snapshot 'insert 'help 'numpad0 'numpad1 'numpad2 'numpad3 'numpad4 'numpad5 'numpad6 'numpad7 'numpad8 'numpad9 'multiply 'add 'separator 'subtract 'decimal 'divide 'f1 'f2 'f3 'f4 'f5 'f6 'f7 'f8 'f9 'f10 'f11 'f12 'f13 'f14 'f15 'f16 'f17 'f18 'f19 'f20 'f21 'f22 'f23 'f24 'numlock 'scroll)) (define keystroke (case-lambda [(key) (keystroke key null)] [(key modifier-list) (cond [(not (or (char? key) (memq key valid-key-symbols))) (error key-tag "expects char or valid key symbol, given: ~e" key)] [(not (list? modifier-list)) (error key-tag "expected a list as second argument, got: ~e" modifier-list)] [(verify-list modifier-list legal-keystroke-modifiers) => (λ (mod) (error key-tag "unknown key modifier: ~e" mod))] [else (run-one (λ () (let ([window (get-focused-window)]) (cond [(not window) (error key-tag "no focused window")] [(not (send window is-shown?)) (error key-tag "focused window is not shown")] [(not (send window is-enabled?)) (error key-tag "focused window is not enabled")] [(not (in-active-frame? window)) (error key-tag (string-append "focused window is not in active frame;" "active frame's label is ~s and focused window is in a frame with label ~s") (let ([f (test:get-active-top-level-window)]) (and f (send (test:get-active-top-level-window) get-label))) (let loop ([p window]) (cond [(is-a? p top-level-window<%>) (send p get-label)] [(is-a? p area<%>) (loop (send p get-parent))] [else #f])))] [else (let ([event (make-key-event key window modifier-list)]) (send-key-event window event) (void))]))))])])) ;; delay test for on-char until all ancestors decline on-subwindow-char. (define (send-key-event window event) (let loop ([l (ancestor-list window #t)]) (cond [(null? l) (cond [(method-in-interface? 'on-char (object-interface window)) (send window on-char event)] [(is-a? window text-field%) (send (send window get-editor) on-char event)] [else (error key-tag "focused window is not a text-field% and does not have on-char, ~e" window)])] [else (define ancestor (car l)) (cond [(and (is-a? ancestor window<%>) (send ancestor on-subwindow-char window event)) #f] [else (loop (cdr l))])]))) ;; Make full key-event% object. ;; Shift is determined implicitly from key-code. Alt , Meta , Control come from modifier - list . get - alt - down , etc are # f unless explicitly set to # t. WILL WANT TO ADD SET - POSITION WHEN THAT GETS IMPLEMENTED . (define make-key-event (λ (key window modifier-list) (let ([event (make-object key-event%)]) (send event set-key-code key) (send event set-time-stamp (time-stamp)) (set-key-modifiers event key modifier-list) event))) (define set-key-modifiers (λ (event key modifier-list) (when (shifted? key) (send event set-shift-down #t)) (let loop ([l modifier-list]) (unless (null? l) (let ([mod (car l)]) (cond [(eq? mod 'alt) (send event set-alt-down #t)] [(eq? mod 'control) (send event set-control-down #t)] [(eq? mod 'meta) (send event set-meta-down #t)] [(eq? mod 'shift) (send event set-shift-down #t)] [(eq? mod 'noalt) (send event set-alt-down #f)] [(eq? mod 'nocontrol) (send event set-control-down #f)] [(eq? mod 'nometa) (send event set-meta-down #f)] [(eq? mod 'noshift) (send event set-shift-down #f)] [else (error key-tag "unknown key modifier: ~e" mod)]) (loop (cdr l))))))) (define shifted? (let* ([shifted-keys '(#\? #\: #\~ #\\ #\| #\< #\> #\{ #\} #\[ #\] #\( #\) #\! #\@ #\# #\$ #\% #\^ #\& #\* #\_ #\+ #\A #\B #\C #\D #\E #\F #\G #\H #\I #\J #\K #\L #\M #\N #\O #\P #\Q #\R #\S #\T #\U #\V #\W #\X #\Y #\Z)]) (λ (key) (memq shifted-keys shifted-keys)))) ;; MENU ITEMS ;; ;; Select menu item with: ;; (send <frame> command <menu-item-id>) ;; menu, item: strings ;; ;; DOESN'T HANDLE MENU CHECKBOXES YET. ;; (define menu-tag 'test:menu-select) (define (menu-select menu-name . item-names) (cond [(not (string? menu-name)) (error menu-tag "expects string, given: ~e" menu-name)] [(not (andmap string? item-names)) (error menu-tag "expects strings, given: ~e" item-names)] [else (run-one (λ () (let* ([frame (test:get-active-top-level-window)] [item (get-menu-item frame (cons menu-name item-names))] [evt (make-object control-event% 'menu)]) (send evt set-time-stamp (current-milliseconds)) (send item command evt))))])) (define get-menu-item (λ (frame item-names) (cond [(not frame) (error menu-tag "no active frame")] [(not (method-in-interface? 'get-menu-bar (object-interface frame))) (error menu-tag "active frame does not have menu bar")] [else (let ([menu-bar (send frame get-menu-bar)]) (unless menu-bar (error menu-tag "active frame does not have menu bar")) (send menu-bar on-demand) (let* ([items (send menu-bar get-items)]) (let loop ([all-items-this-level items] [items items] [this-name (car item-names)] [wanted-names (cdr item-names)]) (cond [(null? items) (error 'menu-select "didn't find a menu: ~e, desired list: ~e, all items at this level ~e" this-name item-names (map (λ (x) (and (is-a? x labelled-menu-item<%>) (send x get-plain-label))) all-items-this-level))] [else (let ([i (car items)]) (cond [(not (is-a? i labelled-menu-item<%>)) (loop all-items-this-level (cdr items) this-name wanted-names)] [(string=? this-name (send i get-plain-label)) (cond [(and (null? wanted-names) (not (is-a? i menu-item-container<%>))) i] [(and (not (null? wanted-names)) (is-a? i menu-item-container<%>)) (loop (send i get-items) (send i get-items) (car wanted-names) (cdr wanted-names))] [else (error menu-tag "no menu matching ~e" item-names)])] [else (loop all-items-this-level (cdr items) this-name wanted-names)]))]))))]))) ;; ;; SIMPLE MOUSE EVENTS ;; ;; Simple left-click mouse in current canvas. Sends 3 mouse - events to canvas : motion , down , up . ;; ;; Give ancestors (from root down) option of handling mouse event ;; with pre-on-event. If none want it, then send to focused window ;; with on-event. ;; ;; NEED TO EXPAND: DRAGGING, DOUBLE-CLICK, MOVING TO OTHER CANVASES, MODIFIER KEYS ( SHIFT , META , CONTROL , ALT ) . ;; (define mouse-tag 'test:mouse-action) (define legal-mouse-buttons (list 'left 'middle 'right)) (define legal-mouse-modifiers (list 'alt 'control 'meta 'shift 'noalt 'nocontrol 'nometa 'noshift)) (define mouse-click (case-lambda [(button x y) (mouse-click button x y null)] [(button x y modifier-list) (cond [(verify-item button legal-mouse-buttons) => (λ (button) (error mouse-tag "unknown mouse button: ~e" button))] [(not (real? x)) (error mouse-tag "expected real, given: ~e" x)] [(not (real? y)) (error mouse-tag "expected real, given: ~e" y)] [(verify-list modifier-list legal-mouse-modifiers) => (λ (mod) (error mouse-tag "unknown mouse modifier: ~e" mod))] [else (run-one (λ () (let ([window (get-focused-window)]) (cond [(not window) (error mouse-tag "no focused window")] [(not (send window is-shown?)) (error mouse-tag "focused window is not shown")] [(not (send window is-enabled?)) (error mouse-tag "focused window is not enabled")] [(not (in-active-frame? window)) (error mouse-tag "focused window is not in active frame")] [else (let ([motion (make-mouse-event 'motion x y modifier-list)] [down (make-mouse-event (list button 'down) x y modifier-list)] [up (make-mouse-event (list button 'up) x y modifier-list)]) (send-mouse-event window motion) (send-mouse-event window down) (send-mouse-event window up) (void))]))))])])) ;; NEED TO MOVE THE CHECK FOR 'ON-EVENT TO HERE. (define send-mouse-event (λ (window event) (let loop ([l (ancestor-list window #t)]) (cond [(null? l) (if (method-in-interface? 'on-event (object-interface window)) (send window on-event event) (error mouse-tag "focused window does not have on-event"))] [(and (is-a? (car l) window<%>) (send (car l) on-subwindow-event window event)) #f] [else (loop (cdr l))])))) ;; ;; Make mouse event. ;; (define make-mouse-event (λ (type x y modifier-list) (let ([event (make-object mouse-event% (mouse-type-const type))]) (when (and (pair? type) (not (eq? (cadr type) 'up))) (set-mouse-modifiers event (list (car type)))) (set-mouse-modifiers event modifier-list) (send event set-x x) (send event set-y y) (send event set-time-stamp (time-stamp)) event))) (define set-mouse-modifiers (λ (event modifier-list) (unless (null? modifier-list) (let ([mod (car modifier-list)]) (cond [(eq? mod 'alt) (send event set-alt-down #t)] [(eq? mod 'control) (send event set-control-down #t)] [(eq? mod 'meta) (send event set-meta-down #t)] [(eq? mod 'shift) (send event set-shift-down #t)] [(eq? mod 'left) (send event set-left-down #t)] [(eq? mod 'middle) (send event set-middle-down #t)] [(eq? mod 'right) (send event set-right-down #t)] [(eq? mod 'noalt) (send event set-alt-down #f)] [(eq? mod 'nocontrol) (send event set-control-down #f)] [(eq? mod 'nometa) (send event set-meta-down #f)] [(eq? mod 'noshift) (send event set-shift-down #f)] [else (error mouse-tag "unknown mouse modifier: ~e" mod)])) (set-mouse-modifiers event (cdr modifier-list))))) (define mouse-type-const (λ (type) (cond [(symbol? type) (cond [(eq? type 'motion) 'motion] [(eq? type 'enter) 'enter] [(eq? type 'leave) 'leave] [else (bad-mouse-type type)])] [(and (pair? type) (pair? (cdr type))) (let ([button (car type)] [action (cadr type)]) (cond [(eq? button 'left) (cond [(eq? action 'down) 'left-down] [(eq? action 'up) 'left-up] [(eq? action 'dclick) 'left-dclick] [else (bad-mouse-type type)])] [(eq? button 'middle) (cond [(eq? action 'down) 'middle-down] [(eq? action 'up) 'middle-up] [(eq? action 'dclick) 'middle-dclick] [else (bad-mouse-type type)])] [(eq? button 'right) (cond [(eq? action 'down) 'right-down] [(eq? action 'up) 'right-up] [(eq? action 'dclick) 'right-dclick] [else (bad-mouse-type type)])] [else (bad-mouse-type type)]))] [else (bad-mouse-type type)]))) (define bad-mouse-type (λ (type) (error mouse-tag "unknown mouse event type: ~e" type))) ;; ;; Move mouse to new window. Implement with three events : ;; leave old window, show top-level frame, enter new window, focus. ;; ;; NEED TO CLEAN UP ACTIONS FOR MOVING TO NEW FRAME. ;; (define new-window (let ([tag 'test:new-window]) (λ (new-window) (cond [(not (is-a? new-window window<%>)) (error tag "new-window is not a window<%>")] [else (run-one (λ () (let ([old-window (get-focused-window)] [leave (make-object mouse-event% 'leave)] [enter (make-object mouse-event% 'enter)] [root (for/or ([ancestor (ancestor-list new-window #t)]) (and (is-a? ancestor window<%>) ancestor))]) (send leave set-x 0) (send leave set-y 0) (send enter set-x 0) (send enter set-y 0) SOME HERE TO WORK AROUND TEXT% PROBLEMS . (when (and old-window (method-in-interface? 'on-event (object-interface old-window))) (send-mouse-event old-window leave)) (send root show #t) (when (method-in-interface? 'on-event (object-interface new-window)) (send-mouse-event new-window enter)) (send new-window focus) (void))))])))) (define (close-top-level-window tlw) (when (send tlw can-close?) (send tlw on-close) (send tlw show #f))) ;; manual renaming (define test:run-interval run-interval) (define test:number-pending-actions number-pending-actions) (define test:reraise-error reraise-error) (define test:run-one run-one) (define test:current-get-eventspaces current-get-eventspaces) (define test:close-top-level-window close-top-level-window) (define test:button-push button-push) (define test:set-radio-box! set-radio-box!) (define test:set-radio-box-item! set-radio-box-item!) (define test:set-check-box! set-check-box!) (define test:set-choice! set-choice!) (define test:set-list-box! set-list-box!) (define test:keystroke keystroke) (define test:menu-select menu-select) (define test:mouse-click mouse-click) (define test:new-window new-window) (define (label-of-enabled/shown-button-in-top-level-window? str) (test:top-level-focus-window-has? (λ (c) (and (is-a? c button%) (string=? (send c get-label) str) (send c is-enabled?) (send c is-shown?))))) (define (enabled-shown-button? btn) (and (send btn is-enabled?) (send btn is-shown?))) (define (button-in-top-level-focusd-window? btn) (test:top-level-focus-window-has? (λ (c) (eq? c btn)))) (provide/doc (proc-doc/names test:button-push (-> (or/c (and/c string? label-of-enabled/shown-button-in-top-level-window?) (and/c (is-a?/c button%) enabled-shown-button? button-in-top-level-focusd-window?)) void?) (button) @{Simulates pushing @racket[button]. If a string is supplied, the primitive searches for a button labelled with that string in the active frame. Otherwise, it pushes the button argument.}) (proc-doc/names test:set-radio-box! (-> (or/c string? regexp? (is-a?/c radio-box%)) (or/c string? number?) void?) (radio-box state) @{Sets the radio-box to the label matching @racket[state]. If @racket[state] is a string, this function finds the choice with that label. If it is a regexp, this function finds the first choice whose label matches the regexp. If it is a number, it uses the number as an index into the state. If the number is out of range or if the label isn't in the radio box, an exception is raised. If @racket[radio-box] is a string, this function searches for a @racket[radio-box%] object with a label matching that string, otherwise it uses @racket[radio-box] itself.}) (proc-doc/names test:set-radio-box-item! (-> (or/c string? regexp?) void?) (entry) @{Finds a @racket[radio-box%] that has a label matching @racket[entry] and sets the radio-box to @racket[entry].}) (proc-doc/names test:set-check-box! (-> (or/c string? (is-a?/c check-box%)) boolean? void?) (check-box state) @{Clears the @racket[check-box%] item if @racket[state] is @racket[#f], and sets it otherwise. If @racket[check-box] is a string, this function searches for a @racket[check-box%] with a label matching that string, otherwise it uses @racket[check-box] itself.}) (proc-doc/names test:set-choice! (-> (or/c string? (is-a?/c choice%)) (or/c string? (and/c number? exact? integer? positive?)) void?) (choice str) @{Selects @racket[choice]'s item @racket[str]. If @racket[choice] is a string, this function searches for a @racket[choice%] with a label matching that string, otherwise it uses @racket[choice] itself.}) (proc-doc/names test:set-list-box! (-> (or/c string? (is-a?/c list-box%)) (or/c string? exact-nonnegative-integer?) void?) (choice str/index) @{Selects @racket[list-box]'s item @racket[str]. If @racket[list-box] is a string, this function searches for a @racket[list-box%] with a label matching that string, otherwise it uses @racket[list-box] itself. The @racket[str/index] field is used to control which entry in the list box is chosen.}) (proc-doc/names test:keystroke (->* ((or/c char? symbol?)) ((listof (or/c 'alt 'control 'meta 'shift 'noalt 'nocontrol 'nometa 'noshift))) void?) ((key) ((modifier-list null))) @{This function simulates a user pressing a key. The argument, @racket[key], is just like the argument to the @method[key-event% get-key-code] method of the @racket[key-event%] class. @italic{Note:} To send the ``Enter'' key, use @racket[#\return], not @racket[#\newline]. The @racket['shift] or @racket['noshift] modifier is implicitly set from @racket[key], but is overridden by the argument list. The @racket['shift] modifier is set for any capitol alpha-numeric letters and any of the following characters: @racketblock[ #\? #\: #\~ #\\ #\| #\< #\> #\{ #\} #\[ #\] #\( #\) #\! #\@ #\# #\$ #\% #\^ #\& #\* #\_ #\+ ] If conflicting modifiers are provided, the ones later in the list are used.}) (proc-doc test:menu-select (->i ([menu string?]) () #:rest [items (listof string?)] [res void?]) @{Selects the menu-item named by the @racket[item]s in the menu named @racket[menu]. @italic{Note:} The string for the menu item does not include its keyboard equivalent. For example, to select ``New'' from the ``File'' menu, use ``New'', not ``New Ctrl+N''.}) (proc-doc/names test:mouse-click (->* ((or/c 'left 'middle 'right) (and/c exact? integer?) (and/c exact? integer?)) ((listof (or/c 'alt 'control 'meta 'shift 'noalt 'nocontrol 'nometa 'noshift))) void?) ((button x y) ((modifiers null))) @{Simulates a mouse click at the coordinate (x,y) in the currently focused @racket[window], assuming that it supports the @method[canvas<%> on-event] method. Use @racket[test:button-push] to click on a button. Under Mac OS, @racket['right] corresponds to holding down the command modifier key while clicking and @racket['middle] cannot be generated. Under Windows, @racket['middle] can only be generated if the user has a three button mouse. The modifiers later in the list @racket[modifiers] take precedence over ones that appear earlier.}) (proc-doc/names test:run-interval (case-> (number? . -> . void?) (-> number?)) ((msec) ()) @{See also @secref{test:actions-completeness}. The first case in the case-lambda sets the run interval to @racket[msec] milliseconds and the second returns the current setting.}) (parameter-doc test:current-get-eventspaces (parameter/c (-> (listof eventspace?))) func @{This parameter that specifies which evenspaces (see also @secref[#:doc '(lib "scribblings/gui/gui.scrbl") "eventspaceinfo"]) are considered when finding the frontmost frame. The first case sets the parameter to @racket[func]. The procedure @racket[func] will be invoked with no arguments to determine the eventspaces to consider when finding the frontmost frame for simulated user events. The second case returns the current value of the parameter. This will be a procedure which, when invoked, returns a list of eventspaces.}) (proc-doc/names test:new-window (-> (is-a?/c window<%>) void?) (window) @{Moves the keyboard focus to a new window within the currently active frame. Unfortunately, neither this function nor any other function in the test engine can cause the focus to move from the top-most (active) frame.}) (proc-doc/names test:close-top-level-window (-> (is-a?/c top-level-window<%>) void?) (tlw) @{Use this function to simulate clicking on the close box of a frame. Closes @racket[tlw] with this expression: @racketblock[ (when (send tlw can-close?) (send tlw on-close) (send tlw show #f))]}) (proc-doc/names test:top-level-focus-window-has? (-> (-> (is-a?/c area<%>) boolean?) boolean?) (test) @{Calls @racket[test] for each child of the @racket[test:get-active-top-level-window] and returns @racket[#t] if @racket[test] ever does, otherwise returns @racket[#f]. If there is no top-level-focus-window, returns @racket[#f].}) (proc-doc test:number-pending-actions (-> number?) @{Returns the number of pending events (those that haven't completed yet)}) (proc-doc test:reraise-error (-> void?) @{See also @secref{test:errors}.}) (proc-doc/names test:run-one (-> (-> void?) void?) (f) @{Runs the function @racket[f] as if it was a simulated event.}) (parameter-doc test:use-focus-table (parameter/c (or/c boolean? 'debug)) use-focus-table? @{If @racket[#t], then the test framework uses @racket[frame:lookup-focus-table] to determine which is the focused frame. If @racket[#f], then it uses @racket[get-top-level-focus-window]. If @racket[test:use-focus-table]'s value is @racket['debug], then it still uses @racket[frame:lookup-focus-table] but it also prints a message to the @racket[current-error-port] when the two methods would give different results.}) (proc-doc/names test:get-active-top-level-window (-> (or/c (is-a?/c frame%) (is-a?/c dialog%) #f)) () @{Returns the frontmost frame, based on @racket[test:use-focus-table].}) (proc-doc/names label-of-enabled/shown-button-in-top-level-window? (-> string? boolean?) (label) @{Returns @racket[#t] when @racket[label] is the label of an enabled and shown @racket[button%] instance that is in the top-level window that currently has the focus, using @racket[test:top-level-focus-window-has?].}) (proc-doc/names enabled-shown-button? (-> (is-a?/c button%) boolean?) (button) @{Returns @racket[#t] when @racket[button] is both enabled and shown.}) (proc-doc/names button-in-top-level-focusd-window? (-> (is-a?/c button%) boolean?) (button) @{Returns @racket[#t] when @racket[button] is in the top-level focused window.}))
null
https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/framework/test.rkt
racket
enables for-doc--for-label import of `framework' milliseconds The minimum time an action is allowed to run before returning from mred:test:action. Controls the rate at which actions are started, and gives some slack time for real events to complete (eg, update). Make-parameter doesn't do what we need across threads. Probably don't need semaphores here (set! is atomic). Units are in milliseconds (as in mred:timer%). How we get into the handler thread, and put fake actions on the real event queue. Simple accounting of actions and errors. Keep number of unfinished actions. An error in the buffer (caught but not-yet-reraised) counts as an unfinished action. (but kept in the-error, not count). Reraising the error flushes the buffer. Store exn in box, so can correctly catch (raise #f). These values are set in handler thread and read in main thread, so certainly need semaphores here. number unfinished actions. Functions to export, always in main thread. Start running thunk in handler thread. Don't return until run-interval expires, and thunk finishes, raises error, or yields (ie, at event boundary). eventspace main thread guarantee (probably) that some events are handled Return list of window's ancestors from root down to window (including window). Used for on-subwindow-char and on-subwindow-event. get-parent returns #f for no parent. If stop-at-top-level-window? is #t, then the ancestors up to the get-parent returns () for no parent. is this test needed? Verify modifier list. l, valid : lists of symbols. find-object obj-class b-desc returns an object belonging to obj-class, where b-desc is either an object, or a string find-object : class (union string regexp (object -> boolean)) -> object functions specific to various user input CONTROL functions, to be specialized for individual controls BUTTON CHECK-BOX RADIO-BOX set-radio-box-item! : string -> void entry-matches : string | regexp -> radio-box -> boolean CHOICE set-choice! : ((instance in-choice%) (union string number) -> void) Give ancestors (from root down) option of handling key event with on-subwindow-char. If none want it, then send to focused window with (send <window> on-char <wx:key-event>). key: char or integer. optional modifiers: 'alt, 'control, 'meta, 'shift, Window must be shown, in active frame, and either the window has on-char, or else some ancestor must grab key with on-subwindow-char. delay test for on-char until all ancestors decline on-subwindow-char. Make full key-event% object. Shift is determined implicitly from key-code. Select menu item with: (send <frame> command <menu-item-id>) menu, item: strings DOESN'T HANDLE MENU CHECKBOXES YET. SIMPLE MOUSE EVENTS Simple left-click mouse in current canvas. Give ancestors (from root down) option of handling mouse event with pre-on-event. If none want it, then send to focused window with on-event. NEED TO EXPAND: DRAGGING, DOUBLE-CLICK, MOVING TO OTHER CANVASES, NEED TO MOVE THE CHECK FOR 'ON-EVENT TO HERE. Make mouse event. Move mouse to new window. leave old window, show top-level frame, enter new window, focus. NEED TO CLEAN UP ACTIONS FOR MOVING TO NEW FRAME. manual renaming
#lang at-exp racket/base (require racket/class racket/contract/base racket/gui/base scribble/srcdoc (for-syntax racket/base) (prefix-in :: framework/private/focus-table)) (require/doc scheme/base scribble/manual (for-label framework)) (define (test:top-level-focus-window-has? pred) (let ([tlw (test:get-active-top-level-window)]) (and tlw (let loop ([tlw tlw]) (or (pred tlw) (and (is-a? tlw area-container<%>) (ormap loop (send tlw get-children)))))))) (define run-interval (let ([tag 'test:run-interval] [msec initial-run-interval]) (case-lambda [() msec] [(x) (if (and (integer? x) (exact? x) (<= 0 x)) (set! msec x) (error tag "expects exact, non-negative integer, given: ~e" x))]))) (define install-timer (λ (msec thunk) (let ([timer (instantiate timer% () [notify-callback (λ () (thunk))])]) (send timer start msec #t)))) Keep buffer of one error , and reraise at first opportunity . Keep just first error , any others are thrown on the floor . (define-values (begin-action end-action end-action-with-error get-exn-box is-exn? num-actions) (let ([sem (make-semaphore 1)] boxed exn struct , or else # f. (letrec ([begin-action (λ () (semaphore-wait sem) (set! count (add1 count)) (semaphore-post sem))] [end-action (λ () (semaphore-wait sem) (set! count (sub1 count)) (semaphore-post sem))] [end-action-with-error (λ (exn) (semaphore-wait sem) (set! count (sub1 count)) (unless the-error (set! the-error (box exn))) (semaphore-post sem))] [get-exn-box (λ () (semaphore-wait sem) (let ([ans the-error]) (set! the-error #f) (semaphore-post sem) ans))] [is-exn? (λ () (semaphore-wait sem) (let ([ans (if the-error #t #f)]) (semaphore-post sem) ans))] [num-actions (λ () (semaphore-wait sem) (let ([ans (+ count (if the-error 1 0))]) (semaphore-post sem) ans))]) (values begin-action end-action end-action-with-error get-exn-box is-exn? num-actions)))) (define number-pending-actions num-actions) (define reraise-error (λ () (let ([exn-box (get-exn-box)]) (if exn-box (raise (unbox exn-box)) (void))))) error ( if exists ) even from previous action . Note : never more than one timer ( of ours ) on real event queue . (define run-one (let ([yield-semaphore (make-semaphore 0)] [thread-semaphore (make-semaphore 0)]) (thread (λ () (let loop () (semaphore-wait thread-semaphore) (sleep) (semaphore-post yield-semaphore) (loop)))) (λ (thunk) (let ([sem (make-semaphore 0)]) (letrec ([start (semaphore-post thread-semaphore) (yield yield-semaphore) (install-timer (run-interval) return) (unless (is-exn?) (begin-action) (call-with-exception-handler (λ (exn) (end-action-with-error exn) ((error-escape-handler))) thunk) (end-action)))] [return (λ () (semaphore-post sem))]) (install-timer 0 start) (semaphore-wait sem) (reraise-error)))))) (define current-get-eventspaces (make-parameter (λ () (list (current-eventspace))))) (define test:use-focus-table (make-parameter #f)) (define (test:get-active-top-level-window) (ormap (λ (eventspace) (parameterize ([current-eventspace eventspace]) (cond [(test:use-focus-table) (define lst (::frame:lookup-focus-table)) (define focusd (and (not (null? lst)) (car lst))) (when (eq? (test:use-focus-table) 'debug) (define f2 (get-top-level-focus-window)) (unless (eq? focusd f2) (eprintf "found mismatch focus-table: ~s vs get-top-level-focus-window: ~s\n" (map (λ (x) (send x get-label)) lst) (and f2 (list (send f2 get-label)))))) focusd] [else (get-top-level-focus-window)]))) ((current-get-eventspaces)))) (define (get-focused-window) (let ([f (test:get-active-top-level-window)]) (and f (send f get-edit-target-window)))) (define time-stamp current-milliseconds) first top - level - window are returned . (define ancestor-list (λ (window stop-at-top-level-window?) (let loop ([w window] [l null]) (if (or (not w) (and stop-at-top-level-window? (is-a? w top-level-window<%>))) l (loop (send w get-parent) (cons w l)))))) Returns # t if window is in active - frame , else # f. (define (in-active-frame? window) (let ([frame (test:get-active-top-level-window)]) (let loop ([window window]) (cond [(not window) #f] [(not frame) #f] [(object=? window frame) #t] [else (loop (send window get-parent))])))) returns first item in l * not * in valid , or else # f. (define verify-list (λ (l valid) (cond [(null? l) #f] [(member (car l) valid) (verify-list (cdr l) valid)] [else (car l)]))) (define verify-item (λ (item valid) (verify-list (list item) valid))) (define object-tag 'test:find-object) (define (find-object obj-class b-desc) (λ () (cond [(or (string? b-desc) (regexp? b-desc) (procedure? b-desc)) (let* ([active-frame (test:get-active-top-level-window)] [_ (unless active-frame (error object-tag "could not find object: ~e, no active frame" b-desc))] [child-matches? (λ (child) (cond [(string? b-desc) (equal? (send child get-label) b-desc)] [(regexp? b-desc) (and (send child get-label) (regexp-match? b-desc (send child get-label)))] [(procedure? b-desc) (b-desc child)]))] [found (let loop ([panel active-frame]) (ormap (λ (child) (cond [(and (is-a? child obj-class) (child-matches? child)) child] [(is-a? child area-container-window<%>) (and (send child is-shown?) (loop child))] [(is-a? child area-container<%>) (loop child)] [else #f])) (send panel get-children)))]) (or found (error object-tag "no object of class ~e named ~e in active frame" obj-class b-desc)))] [(is-a? b-desc obj-class) b-desc] [else (error object-tag "expected either a string or an object of class ~e as input, received: ~e" obj-class b-desc)]))) (define control-action (λ (error-tag event-sym find-ctrl update-control) (run-one (λ () (let ([event (make-object control-event% event-sym)] [ctrl (find-ctrl)]) (cond [(not (send ctrl is-shown?)) (error error-tag "control ~e is not shown (label ~e)" ctrl (send ctrl get-label))] [(not (send ctrl is-enabled?)) (error error-tag "control ~e is not enabled (label ~e)" ctrl (send ctrl get-label))] [(not (in-active-frame? ctrl)) (error error-tag "control ~e is not in active frame (label ~e)" ctrl (send ctrl get-label))] [else (update-control ctrl) (send ctrl command event) (void)])))))) (define (button-push button) (control-action 'test:button-push 'button (find-object button% button) void)) (define (set-check-box! in-cb state) (control-action 'test:set-check-box! 'check-box (find-object check-box% in-cb) (λ (cb) (send cb set-value state)))) (define (build-labels radio-box) (string-append (format "~s" (send radio-box get-item-label 0)) (let loop ([n (- (send radio-box get-number) 1)]) (cond [(zero? n) ""] [else (string-append " " (format "~s" (send radio-box get-item-label (- (send radio-box get-number) n))) (loop (- n 1)))])))) (define (set-radio-box! in-cb state) (control-action 'test:set-radio-box! 'radio-box (find-object radio-box% in-cb) (λ (rb) (cond [(string? state) (let ([total (send rb get-number)]) (let loop ([n total]) (cond [(zero? n) (error 'test:set-radio-box! "did not find ~e as a label for ~e; labels: ~a" state in-cb (build-labels rb))] [else (let ([i (- total n)]) (if (ith-item-matches? rb state i) (if (send rb is-enabled? i) (send rb set-selection i) (error 'test:set-radio-box! "label ~e is disabled" state)) (loop (- n 1))))])))] [(number? state) (unless (send rb is-enabled? state) (error 'test:set-radio-box! "item ~a is not enabled\n" state)) (send rb set-selection state)] [else (error 'test:set-radio-box! "expected a string or a number as second arg, got: ~e (other arg: ~e)" state in-cb)])))) (define (ith-item-matches? rb state i) (cond [(string? state) (or (string=? state (send rb get-item-label i)) (string=? state (send rb get-item-plain-label i)))] [(regexp? state) (or (regexp-match state (send rb get-item-label i)) (regexp-match state (send rb get-item-plain-label i)))])) (define (set-radio-box-item! state) (control-action 'test:set-check-box-state! 'radio-box (find-object radio-box% (entry-matches state)) (λ (rb) (let ([total (send rb get-number)]) (let loop ([n total]) (cond [(zero? n) (error 'test:set-radio-box-item! "internal error")] [else (let ([i (- total n)]) (if (ith-item-matches? rb state i) (if (send rb is-enabled? i) (send rb set-selection i) (error 'test:set-radio-box! "label ~e is disabled" state)) (loop (- n 1))))])))))) (define (entry-matches name) (procedure-rename (λ (rb) (let loop ([n (send rb get-number)]) (cond [(zero? n) #f] [else (let ([itm (send rb get-item-label (- n 1))] [pln-itm (send rb get-item-plain-label (- n 1))]) (or (cond [(string? name) (or (equal? name itm) (equal? name pln-itm))] [(regexp? name) (or (regexp-match name itm) (regexp-match name pln-itm))]) (loop (- n 1))))]))) (string->symbol (if (regexp? name) (object-name name) name)))) (define (set-choice! in-choice str) (control-action 'test:set-choice! 'choice (find-object choice% in-choice) (λ (choice) (cond [(number? str) (send choice set-selection str)] [(string? str) (send choice set-string-selection str)] [else (error 'test:set-choice! "expected a string or a number as second arg, got: ~e (other arg: ~e)" str in-choice)])))) (define (set-list-box! in-lb str) (control-action 'test:set-list-box! 'list-box (find-object list-box% in-lb) (λ (lb) (cond [(number? str) (send lb set-selection str)] [(string? str) (send lb set-string-selection str)] [else (error 'test:set-list-box! "expected a string or a number as second arg, got: ~e (other arg: ~e)" str in-lb)])))) KEYSTROKES ' noalt , ' nocontrol , ' nometa , ' noshift . (define key-tag 'test:keystroke) (define legal-keystroke-modifiers (list 'alt 'control 'meta 'shift 'noalt 'nocontrol 'nometa 'noshift)) (define valid-key-symbols just trying this for the heck of it -- JBC , 2010 - 08 - 13 'start 'cancel 'clear 'shift 'control 'menu 'pause 'capital 'prior 'next 'end 'home 'left 'up 'right 'down 'select 'print 'execute 'snapshot 'insert 'help 'numpad0 'numpad1 'numpad2 'numpad3 'numpad4 'numpad5 'numpad6 'numpad7 'numpad8 'numpad9 'multiply 'add 'separator 'subtract 'decimal 'divide 'f1 'f2 'f3 'f4 'f5 'f6 'f7 'f8 'f9 'f10 'f11 'f12 'f13 'f14 'f15 'f16 'f17 'f18 'f19 'f20 'f21 'f22 'f23 'f24 'numlock 'scroll)) (define keystroke (case-lambda [(key) (keystroke key null)] [(key modifier-list) (cond [(not (or (char? key) (memq key valid-key-symbols))) (error key-tag "expects char or valid key symbol, given: ~e" key)] [(not (list? modifier-list)) (error key-tag "expected a list as second argument, got: ~e" modifier-list)] [(verify-list modifier-list legal-keystroke-modifiers) => (λ (mod) (error key-tag "unknown key modifier: ~e" mod))] [else (run-one (λ () (let ([window (get-focused-window)]) (cond [(not window) (error key-tag "no focused window")] [(not (send window is-shown?)) (error key-tag "focused window is not shown")] [(not (send window is-enabled?)) (error key-tag "focused window is not enabled")] [(not (in-active-frame? window)) (error key-tag (string-append "focused window is not in active frame;" "active frame's label is ~s and focused window is in a frame with label ~s") (let ([f (test:get-active-top-level-window)]) (and f (send (test:get-active-top-level-window) get-label))) (let loop ([p window]) (cond [(is-a? p top-level-window<%>) (send p get-label)] [(is-a? p area<%>) (loop (send p get-parent))] [else #f])))] [else (let ([event (make-key-event key window modifier-list)]) (send-key-event window event) (void))]))))])])) (define (send-key-event window event) (let loop ([l (ancestor-list window #t)]) (cond [(null? l) (cond [(method-in-interface? 'on-char (object-interface window)) (send window on-char event)] [(is-a? window text-field%) (send (send window get-editor) on-char event)] [else (error key-tag "focused window is not a text-field% and does not have on-char, ~e" window)])] [else (define ancestor (car l)) (cond [(and (is-a? ancestor window<%>) (send ancestor on-subwindow-char window event)) #f] [else (loop (cdr l))])]))) Alt , Meta , Control come from modifier - list . get - alt - down , etc are # f unless explicitly set to # t. WILL WANT TO ADD SET - POSITION WHEN THAT GETS IMPLEMENTED . (define make-key-event (λ (key window modifier-list) (let ([event (make-object key-event%)]) (send event set-key-code key) (send event set-time-stamp (time-stamp)) (set-key-modifiers event key modifier-list) event))) (define set-key-modifiers (λ (event key modifier-list) (when (shifted? key) (send event set-shift-down #t)) (let loop ([l modifier-list]) (unless (null? l) (let ([mod (car l)]) (cond [(eq? mod 'alt) (send event set-alt-down #t)] [(eq? mod 'control) (send event set-control-down #t)] [(eq? mod 'meta) (send event set-meta-down #t)] [(eq? mod 'shift) (send event set-shift-down #t)] [(eq? mod 'noalt) (send event set-alt-down #f)] [(eq? mod 'nocontrol) (send event set-control-down #f)] [(eq? mod 'nometa) (send event set-meta-down #f)] [(eq? mod 'noshift) (send event set-shift-down #f)] [else (error key-tag "unknown key modifier: ~e" mod)]) (loop (cdr l))))))) (define shifted? (let* ([shifted-keys '(#\? #\: #\~ #\\ #\| #\< #\> #\{ #\} #\[ #\] #\( #\) #\! #\@ #\# #\$ #\% #\^ #\& #\* #\_ #\+ #\A #\B #\C #\D #\E #\F #\G #\H #\I #\J #\K #\L #\M #\N #\O #\P #\Q #\R #\S #\T #\U #\V #\W #\X #\Y #\Z)]) (λ (key) (memq shifted-keys shifted-keys)))) MENU ITEMS (define menu-tag 'test:menu-select) (define (menu-select menu-name . item-names) (cond [(not (string? menu-name)) (error menu-tag "expects string, given: ~e" menu-name)] [(not (andmap string? item-names)) (error menu-tag "expects strings, given: ~e" item-names)] [else (run-one (λ () (let* ([frame (test:get-active-top-level-window)] [item (get-menu-item frame (cons menu-name item-names))] [evt (make-object control-event% 'menu)]) (send evt set-time-stamp (current-milliseconds)) (send item command evt))))])) (define get-menu-item (λ (frame item-names) (cond [(not frame) (error menu-tag "no active frame")] [(not (method-in-interface? 'get-menu-bar (object-interface frame))) (error menu-tag "active frame does not have menu bar")] [else (let ([menu-bar (send frame get-menu-bar)]) (unless menu-bar (error menu-tag "active frame does not have menu bar")) (send menu-bar on-demand) (let* ([items (send menu-bar get-items)]) (let loop ([all-items-this-level items] [items items] [this-name (car item-names)] [wanted-names (cdr item-names)]) (cond [(null? items) (error 'menu-select "didn't find a menu: ~e, desired list: ~e, all items at this level ~e" this-name item-names (map (λ (x) (and (is-a? x labelled-menu-item<%>) (send x get-plain-label))) all-items-this-level))] [else (let ([i (car items)]) (cond [(not (is-a? i labelled-menu-item<%>)) (loop all-items-this-level (cdr items) this-name wanted-names)] [(string=? this-name (send i get-plain-label)) (cond [(and (null? wanted-names) (not (is-a? i menu-item-container<%>))) i] [(and (not (null? wanted-names)) (is-a? i menu-item-container<%>)) (loop (send i get-items) (send i get-items) (car wanted-names) (cdr wanted-names))] [else (error menu-tag "no menu matching ~e" item-names)])] [else (loop all-items-this-level (cdr items) this-name wanted-names)]))]))))]))) Sends 3 mouse - events to canvas : motion , down , up . MODIFIER KEYS ( SHIFT , META , CONTROL , ALT ) . (define mouse-tag 'test:mouse-action) (define legal-mouse-buttons (list 'left 'middle 'right)) (define legal-mouse-modifiers (list 'alt 'control 'meta 'shift 'noalt 'nocontrol 'nometa 'noshift)) (define mouse-click (case-lambda [(button x y) (mouse-click button x y null)] [(button x y modifier-list) (cond [(verify-item button legal-mouse-buttons) => (λ (button) (error mouse-tag "unknown mouse button: ~e" button))] [(not (real? x)) (error mouse-tag "expected real, given: ~e" x)] [(not (real? y)) (error mouse-tag "expected real, given: ~e" y)] [(verify-list modifier-list legal-mouse-modifiers) => (λ (mod) (error mouse-tag "unknown mouse modifier: ~e" mod))] [else (run-one (λ () (let ([window (get-focused-window)]) (cond [(not window) (error mouse-tag "no focused window")] [(not (send window is-shown?)) (error mouse-tag "focused window is not shown")] [(not (send window is-enabled?)) (error mouse-tag "focused window is not enabled")] [(not (in-active-frame? window)) (error mouse-tag "focused window is not in active frame")] [else (let ([motion (make-mouse-event 'motion x y modifier-list)] [down (make-mouse-event (list button 'down) x y modifier-list)] [up (make-mouse-event (list button 'up) x y modifier-list)]) (send-mouse-event window motion) (send-mouse-event window down) (send-mouse-event window up) (void))]))))])])) (define send-mouse-event (λ (window event) (let loop ([l (ancestor-list window #t)]) (cond [(null? l) (if (method-in-interface? 'on-event (object-interface window)) (send window on-event event) (error mouse-tag "focused window does not have on-event"))] [(and (is-a? (car l) window<%>) (send (car l) on-subwindow-event window event)) #f] [else (loop (cdr l))])))) (define make-mouse-event (λ (type x y modifier-list) (let ([event (make-object mouse-event% (mouse-type-const type))]) (when (and (pair? type) (not (eq? (cadr type) 'up))) (set-mouse-modifiers event (list (car type)))) (set-mouse-modifiers event modifier-list) (send event set-x x) (send event set-y y) (send event set-time-stamp (time-stamp)) event))) (define set-mouse-modifiers (λ (event modifier-list) (unless (null? modifier-list) (let ([mod (car modifier-list)]) (cond [(eq? mod 'alt) (send event set-alt-down #t)] [(eq? mod 'control) (send event set-control-down #t)] [(eq? mod 'meta) (send event set-meta-down #t)] [(eq? mod 'shift) (send event set-shift-down #t)] [(eq? mod 'left) (send event set-left-down #t)] [(eq? mod 'middle) (send event set-middle-down #t)] [(eq? mod 'right) (send event set-right-down #t)] [(eq? mod 'noalt) (send event set-alt-down #f)] [(eq? mod 'nocontrol) (send event set-control-down #f)] [(eq? mod 'nometa) (send event set-meta-down #f)] [(eq? mod 'noshift) (send event set-shift-down #f)] [else (error mouse-tag "unknown mouse modifier: ~e" mod)])) (set-mouse-modifiers event (cdr modifier-list))))) (define mouse-type-const (λ (type) (cond [(symbol? type) (cond [(eq? type 'motion) 'motion] [(eq? type 'enter) 'enter] [(eq? type 'leave) 'leave] [else (bad-mouse-type type)])] [(and (pair? type) (pair? (cdr type))) (let ([button (car type)] [action (cadr type)]) (cond [(eq? button 'left) (cond [(eq? action 'down) 'left-down] [(eq? action 'up) 'left-up] [(eq? action 'dclick) 'left-dclick] [else (bad-mouse-type type)])] [(eq? button 'middle) (cond [(eq? action 'down) 'middle-down] [(eq? action 'up) 'middle-up] [(eq? action 'dclick) 'middle-dclick] [else (bad-mouse-type type)])] [(eq? button 'right) (cond [(eq? action 'down) 'right-down] [(eq? action 'up) 'right-up] [(eq? action 'dclick) 'right-dclick] [else (bad-mouse-type type)])] [else (bad-mouse-type type)]))] [else (bad-mouse-type type)]))) (define bad-mouse-type (λ (type) (error mouse-tag "unknown mouse event type: ~e" type))) Implement with three events : (define new-window (let ([tag 'test:new-window]) (λ (new-window) (cond [(not (is-a? new-window window<%>)) (error tag "new-window is not a window<%>")] [else (run-one (λ () (let ([old-window (get-focused-window)] [leave (make-object mouse-event% 'leave)] [enter (make-object mouse-event% 'enter)] [root (for/or ([ancestor (ancestor-list new-window #t)]) (and (is-a? ancestor window<%>) ancestor))]) (send leave set-x 0) (send leave set-y 0) (send enter set-x 0) (send enter set-y 0) SOME HERE TO WORK AROUND TEXT% PROBLEMS . (when (and old-window (method-in-interface? 'on-event (object-interface old-window))) (send-mouse-event old-window leave)) (send root show #t) (when (method-in-interface? 'on-event (object-interface new-window)) (send-mouse-event new-window enter)) (send new-window focus) (void))))])))) (define (close-top-level-window tlw) (when (send tlw can-close?) (send tlw on-close) (send tlw show #f))) (define test:run-interval run-interval) (define test:number-pending-actions number-pending-actions) (define test:reraise-error reraise-error) (define test:run-one run-one) (define test:current-get-eventspaces current-get-eventspaces) (define test:close-top-level-window close-top-level-window) (define test:button-push button-push) (define test:set-radio-box! set-radio-box!) (define test:set-radio-box-item! set-radio-box-item!) (define test:set-check-box! set-check-box!) (define test:set-choice! set-choice!) (define test:set-list-box! set-list-box!) (define test:keystroke keystroke) (define test:menu-select menu-select) (define test:mouse-click mouse-click) (define test:new-window new-window) (define (label-of-enabled/shown-button-in-top-level-window? str) (test:top-level-focus-window-has? (λ (c) (and (is-a? c button%) (string=? (send c get-label) str) (send c is-enabled?) (send c is-shown?))))) (define (enabled-shown-button? btn) (and (send btn is-enabled?) (send btn is-shown?))) (define (button-in-top-level-focusd-window? btn) (test:top-level-focus-window-has? (λ (c) (eq? c btn)))) (provide/doc (proc-doc/names test:button-push (-> (or/c (and/c string? label-of-enabled/shown-button-in-top-level-window?) (and/c (is-a?/c button%) enabled-shown-button? button-in-top-level-focusd-window?)) void?) (button) @{Simulates pushing @racket[button]. If a string is supplied, the primitive searches for a button labelled with that string in the active frame. Otherwise, it pushes the button argument.}) (proc-doc/names test:set-radio-box! (-> (or/c string? regexp? (is-a?/c radio-box%)) (or/c string? number?) void?) (radio-box state) @{Sets the radio-box to the label matching @racket[state]. If @racket[state] is a string, this function finds the choice with that label. If it is a regexp, this function finds the first choice whose label matches the regexp. If it is a number, it uses the number as an index into the state. If the number is out of range or if the label isn't in the radio box, an exception is raised. If @racket[radio-box] is a string, this function searches for a @racket[radio-box%] object with a label matching that string, otherwise it uses @racket[radio-box] itself.}) (proc-doc/names test:set-radio-box-item! (-> (or/c string? regexp?) void?) (entry) @{Finds a @racket[radio-box%] that has a label matching @racket[entry] and sets the radio-box to @racket[entry].}) (proc-doc/names test:set-check-box! (-> (or/c string? (is-a?/c check-box%)) boolean? void?) (check-box state) @{Clears the @racket[check-box%] item if @racket[state] is @racket[#f], and sets it otherwise. If @racket[check-box] is a string, this function searches for a @racket[check-box%] with a label matching that string, otherwise it uses @racket[check-box] itself.}) (proc-doc/names test:set-choice! (-> (or/c string? (is-a?/c choice%)) (or/c string? (and/c number? exact? integer? positive?)) void?) (choice str) @{Selects @racket[choice]'s item @racket[str]. If @racket[choice] is a string, this function searches for a @racket[choice%] with a label matching that string, otherwise it uses @racket[choice] itself.}) (proc-doc/names test:set-list-box! (-> (or/c string? (is-a?/c list-box%)) (or/c string? exact-nonnegative-integer?) void?) (choice str/index) @{Selects @racket[list-box]'s item @racket[str]. If @racket[list-box] is a string, this function searches for a @racket[list-box%] with a label matching that string, otherwise it uses @racket[list-box] itself. The @racket[str/index] field is used to control which entry in the list box is chosen.}) (proc-doc/names test:keystroke (->* ((or/c char? symbol?)) ((listof (or/c 'alt 'control 'meta 'shift 'noalt 'nocontrol 'nometa 'noshift))) void?) ((key) ((modifier-list null))) @{This function simulates a user pressing a key. The argument, @racket[key], is just like the argument to the @method[key-event% get-key-code] method of the @racket[key-event%] class. @italic{Note:} To send the ``Enter'' key, use @racket[#\return], not @racket[#\newline]. The @racket['shift] or @racket['noshift] modifier is implicitly set from @racket[key], but is overridden by the argument list. The @racket['shift] modifier is set for any capitol alpha-numeric letters and any of the following characters: @racketblock[ #\? #\: #\~ #\\ #\| #\< #\> #\{ #\} #\[ #\] #\( #\) #\! #\@ #\# #\$ #\% #\^ #\& #\* #\_ #\+ ] If conflicting modifiers are provided, the ones later in the list are used.}) (proc-doc test:menu-select (->i ([menu string?]) () #:rest [items (listof string?)] [res void?]) @{Selects the menu-item named by the @racket[item]s in the menu named @racket[menu]. @italic{Note:} The string for the menu item does not include its keyboard equivalent. For example, to select ``New'' from the ``File'' menu, use ``New'', not ``New Ctrl+N''.}) (proc-doc/names test:mouse-click (->* ((or/c 'left 'middle 'right) (and/c exact? integer?) (and/c exact? integer?)) ((listof (or/c 'alt 'control 'meta 'shift 'noalt 'nocontrol 'nometa 'noshift))) void?) ((button x y) ((modifiers null))) @{Simulates a mouse click at the coordinate (x,y) in the currently focused @racket[window], assuming that it supports the @method[canvas<%> on-event] method. Use @racket[test:button-push] to click on a button. Under Mac OS, @racket['right] corresponds to holding down the command modifier key while clicking and @racket['middle] cannot be generated. Under Windows, @racket['middle] can only be generated if the user has a three button mouse. The modifiers later in the list @racket[modifiers] take precedence over ones that appear earlier.}) (proc-doc/names test:run-interval (case-> (number? . -> . void?) (-> number?)) ((msec) ()) @{See also @secref{test:actions-completeness}. The first case in the case-lambda sets the run interval to @racket[msec] milliseconds and the second returns the current setting.}) (parameter-doc test:current-get-eventspaces (parameter/c (-> (listof eventspace?))) func @{This parameter that specifies which evenspaces (see also @secref[#:doc '(lib "scribblings/gui/gui.scrbl") "eventspaceinfo"]) are considered when finding the frontmost frame. The first case sets the parameter to @racket[func]. The procedure @racket[func] will be invoked with no arguments to determine the eventspaces to consider when finding the frontmost frame for simulated user events. The second case returns the current value of the parameter. This will be a procedure which, when invoked, returns a list of eventspaces.}) (proc-doc/names test:new-window (-> (is-a?/c window<%>) void?) (window) @{Moves the keyboard focus to a new window within the currently active frame. Unfortunately, neither this function nor any other function in the test engine can cause the focus to move from the top-most (active) frame.}) (proc-doc/names test:close-top-level-window (-> (is-a?/c top-level-window<%>) void?) (tlw) @{Use this function to simulate clicking on the close box of a frame. Closes @racket[tlw] with this expression: @racketblock[ (when (send tlw can-close?) (send tlw on-close) (send tlw show #f))]}) (proc-doc/names test:top-level-focus-window-has? (-> (-> (is-a?/c area<%>) boolean?) boolean?) (test) @{Calls @racket[test] for each child of the @racket[test:get-active-top-level-window] and returns @racket[#t] if @racket[test] ever does, otherwise returns @racket[#f]. If there is no top-level-focus-window, returns @racket[#f].}) (proc-doc test:number-pending-actions (-> number?) @{Returns the number of pending events (those that haven't completed yet)}) (proc-doc test:reraise-error (-> void?) @{See also @secref{test:errors}.}) (proc-doc/names test:run-one (-> (-> void?) void?) (f) @{Runs the function @racket[f] as if it was a simulated event.}) (parameter-doc test:use-focus-table (parameter/c (or/c boolean? 'debug)) use-focus-table? @{If @racket[#t], then the test framework uses @racket[frame:lookup-focus-table] to determine which is the focused frame. If @racket[#f], then it uses @racket[get-top-level-focus-window]. If @racket[test:use-focus-table]'s value is @racket['debug], then it still uses @racket[frame:lookup-focus-table] but it also prints a message to the @racket[current-error-port] when the two methods would give different results.}) (proc-doc/names test:get-active-top-level-window (-> (or/c (is-a?/c frame%) (is-a?/c dialog%) #f)) () @{Returns the frontmost frame, based on @racket[test:use-focus-table].}) (proc-doc/names label-of-enabled/shown-button-in-top-level-window? (-> string? boolean?) (label) @{Returns @racket[#t] when @racket[label] is the label of an enabled and shown @racket[button%] instance that is in the top-level window that currently has the focus, using @racket[test:top-level-focus-window-has?].}) (proc-doc/names enabled-shown-button? (-> (is-a?/c button%) boolean?) (button) @{Returns @racket[#t] when @racket[button] is both enabled and shown.}) (proc-doc/names button-in-top-level-focusd-window? (-> (is-a?/c button%) boolean?) (button) @{Returns @racket[#t] when @racket[button] is in the top-level focused window.}))
6131c57623c8f61a7f27341a6523442ff230496f1e8abae0707dd12aa3c5c76e
diagrams/geometry
Trace.hs
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # {-# LANGUAGE UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Geometry.Trace Copyright : ( c ) 2012 - 2017 diagrams team ( see LICENSE ) -- License : BSD-style (see LICENSE) -- Maintainer : -- The @Trace@ module defines a data type and type class for -- \"traces\", aka functional boundaries, essentially corresponding to -- a raytracer. -- ----------------------------------------------------------------------------- module Geometry.Trace ( -- * Traces Trace(Trace) , appTrace , mkTrace -- * Traced class , Traced(..) -- * Computing with traces , traceV, traceP , maxTraceV, maxTraceP , getRayTrace , rayTraceV, rayTraceP , maxRayTraceV, maxRayTraceP ) where import Control.Lens import qualified Data.Map as M import qualified Data.Semigroup as Sem import Data.Sequence (Seq) import qualified Data.Sequence as Seq import qualified Data.Set as S import Geometry.HasOrigin import Geometry.Space import Geometry.Transform import Linear.Affine import Linear.Vector ------------------------------------------------------------------------ Trace ------------------------------------------------------------------------ -- > traceEx = mkTraceDia def -- | A trace for a given object is like a raytracer: given a ray -- (represented as a base point and a direction vector), the trace -- computes a list of signed distances from the base point to all -- intersections of the ray with the boundary of the object. -- -- Note that the outputs are not absolute distances, but multipliers relative to the input vector . That is , if the base point is @p@ and direction vector is @v@ , and one of the output scalars is -- @s@, then there is an intersection at the point @p .+^ (s *^ v)@. -- -- <<diagrams/src_Diagrams_Core_Trace_traceEx.svg#diagram=traceEx&width=200>> -- -- Traces form a semigroup with pointwise minimum as composition. newtype Trace v n = Trace { appTrace :: Point v n -> v n -> Seq n } deriving (Sem.Semigroup, Monoid) type instance V (Trace v n) = v type instance N (Trace v n) = n instance Rewrapped (Trace v n) (Trace v' n') instance Wrapped (Trace v n) where type Unwrapped (Trace v n) = Point v n -> v n -> Seq n _Wrapped' = iso appTrace Trace {-# INLINE _Wrapped' #-} mkTrace :: (Point v n -> v n -> Seq n) -> Trace v n mkTrace = Trace # INLINE mkTrace # instance (Additive v, Num n) => HasOrigin (Trace v n) where moveOriginTo (P u) = _Wrapping' Trace %~ \f p -> f (p .+^ u) instance Show (Trace v n) where show _ = "<trace>" instance (Additive v, Foldable v, Num n) => Transformable (Trace v n) where transform t = _Wrapped %~ \f p v -> f (papply (inv t) p) (apply (inv t) v) # INLINE transform # ------------------------------------------------------------------------ -- Class ------------------------------------------------------------------------ -- | @Traced@ abstracts over things which have a trace. -- -- If @a@ is also a 'Semigroup' then 'getTrace' must satisfy the law -- -- @ -- 'getTrace' (a1 <> a2) = 'getTrace' a1 <> 'getTrace' a2 -- @ class (Additive (V a), Ord (N a)) => Traced a where -- | Compute the trace of an object. getTrace :: a -> Trace (V a) (N a) instance (Additive v, Ord n) => Traced (Trace v n) where getTrace = id | The trace of a single point is the empty trace , /i.e./ the one -- which returns no intersection points for every query. Arguably -- it should return a single finite distance for vectors aimed -- directly at the given point, but due to floating-point inaccuracy -- this is problematic. Note that the envelope for a single point is /not/ the empty envelope ( see " Geometry . Envelope " ) . instance (Additive v, Ord n) => Traced (Point v n) where getTrace = const mempty instance Traced t => Traced (TransInv t) where getTrace = getTrace . op TransInv instance (Traced a, Traced b, SameSpace a b) => Traced (a,b) where getTrace (x,y) = getTrace x Sem.<> getTrace y instance Traced t => Traced [t] where getTrace = mconcat . map getTrace instance Traced t => Traced (M.Map k t) where getTrace = mconcat . map getTrace . M.elems instance Traced t => Traced (S.Set t) where getTrace = mconcat . map getTrace . S.elems ------------------------------------------------------------------------ -- Computing traces ------------------------------------------------------------------------ | Compute the vector from the given point to the \"smallest\ " -- boundary intersection along the given vector @v@. The -- \"smallest\" boundary intersection is defined as the one given by -- @p .+^ (s *^ v)@ for the smallest (most negative) value of -- @s@. Return @Nothing@ if there is no intersection. See also -- 'traceP'. -- -- See also 'rayTraceV' which uses the smallest /positive/ -- intersection, which is often more intuitive behavior. -- < < diagrams / src_Diagrams_Core_Trace_traceVEx.svg#diagram = traceVEx&width=600 > > traceV :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (v n) traceV = \p v a -> fmap (*^ v) . minimumOf folded $ appTrace (getTrace a) p v # INLINE traceV # > traceVEx = mkTraceDiasABC def { drawV = True , sFilter = take 1 } | Compute the \"smallest\ " boundary point along the line determined by the given point @p@ and vector @v@. The \"smallest\ " boundary point is defined as the one given by @p .+^ ( s * ^ v)@ for the smallest ( most negative ) value of @s@. Return @Nothing@ if -- there is no such boundary point. See also 'traceV'. -- -- See also 'rayTraceP' which uses the smallest /positive/ -- intersection, which is often more intuitive behavior. -- -- <<diagrams/src_Diagrams_Core_Trace_tracePEx.svg#diagram=tracePEx&width=600>> traceP :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (Point v n) traceP p v a = (p .+^) <$> traceV p v a > tracePEx = mkTraceDiasABC def { sFilter = take 1 } -- | Like 'traceV', but computes a vector to the \"largest\" boundary -- point instead of the smallest. (Note, however, the \"largest\" -- boundary point may still be in the opposite direction from the given vector , if all the boundary points are , as in the third -- example shown below.) -- -- <<diagrams/src_Diagrams_Core_Trace_maxTraceVEx.svg#diagram=maxTraceVEx&width=600>> maxTraceV :: (InSpace v n a, Traced a) => Point v n -> V a n -> a -> Maybe (v n) maxTraceV p = traceV p . negated # INLINE maxTraceV # -- > maxTraceVEx = mkTraceDiasABC def { drawV = True, sFilter = dropAllBut1 } -- | Like 'traceP', but computes the \"largest\" boundary point -- instead of the smallest. (Note, however, the \"largest\" boundary -- point may still be in the opposite direction from the given -- vector, if all the boundary points are.) -- -- <<diagrams/src_Diagrams_Core_Trace_maxTracePEx.svg#diagram=maxTracePEx&width=600>> maxTraceP :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (Point v n) maxTraceP p v a = (p .+^) <$> maxTraceV p v a # INLINE maxTraceP # -- > maxTracePEx = mkTraceDiasABC def { sFilter = dropAllBut1 } | Get a modified ' Trace ' for an object which only returns positive -- boundary points, /i.e./ those boundary points given by a positive -- scalar multiple of the direction vector. Note, this property may be destroyed if the resulting ' Trace ' is translated at all . getRayTrace :: (InSpace v n a, Traced a) => a -> Trace v n getRayTrace = \a -> Trace $ \p v -> Seq.filter (>=0) $ appTrace (getTrace a) p v # INLINE getRayTrace # -- | Compute the vector from the given point to the closest boundary -- point of the given object in the given direction, or @Nothing@ if there is no such boundary point ( as in the third example -- below). Note that unlike 'traceV', only /positive/ boundary -- points are considered, /i.e./ boundary points corresponding to a -- positive scalar multiple of the direction vector. This is intuitively the " behavior of a raytracer , which only considers intersections front of\ " the camera . Compare the second example diagram below with the second example shown for -- 'traceV'. -- -- <<diagrams/src_Diagrams_Core_Trace_rayTraceVEx.svg#diagram=rayTraceVEx&width=600>> rayTraceV :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (v n) rayTraceV = \p v a -> fmap (*^ v) . minimumOf folded $ appTrace (getRayTrace a) p v # INLINE rayTraceV # > rayTraceVEx = mkTraceDiasABC def { drawV = True , sFilter = take 1 . filter ( > 0 ) } -- | Compute the boundary point on an object which is closest to the -- given base point in the given direction, or @Nothing@ if there is -- no such boundary point. Note that unlike 'traceP', only /positive/ -- boundary points are considered, /i.e./ boundary points -- corresponding to a positive scalar multiple of the direction vector . This is intuitively the " behavior of a raytracer , which only considers intersection points of\ " the -- camera. -- -- <<diagrams/src_Diagrams_Core_Trace_rayTracePEx.svg#diagram=rayTracePEx&width=600>> rayTraceP :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (Point v n) rayTraceP = \p v a -> (p .+^) <$> rayTraceV p v a > rayTracePEx = mkTraceDiasABC def { sFilter = take 1 . filter ( > 0 ) } -- | Like 'rayTraceV', but computes a vector to the \"largest\" -- boundary point instead of the smallest. Considers only -- /positive/ boundary points. -- < < diagrams / src_Diagrams_Core_Trace_maxRayTraceVEx.svg#diagram = maxRayTraceVEx&width=600 > > maxRayTraceV :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (v n) maxRayTraceV = \p v a -> fmap (*^ v) . maximumOf folded $ appTrace (getRayTrace a) p v -- > maxRayTraceVEx = mkTraceDiasABC def { drawV = True, sFilter = dropAllBut1 . filter (>0) } -- | Like 'rayTraceP', but computes the \"largest\" boundary point -- instead of the smallest. Considers only /positive/ boundary -- points. -- -- <<diagrams/src_Diagrams_Core_Trace_maxRayTracePEx.svg#diagram=maxRayTracePEx&width=600>> maxRayTraceP :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (Point v n) maxRayTraceP p v a = (p .+^) <$> maxRayTraceV p v a # INLINE maxRayTraceP # -- > maxRayTracePEx = mkTraceDiasABC def { sFilter = dropAllBut1 . filter (>0) } ------------------------------------------------------------ -- Drawing trace diagrams ------------------------------------------------------------ -- > import Data.Default.Class -- > import Control.Lens ((^.)) -- > import Data.Maybe (fromMaybe) -- > > thingyT : : Trail V2 Double -- > thingyT = -- > fromOffsets > [ 3 * ^ unitX , 3 * ^ unitY , 2 * ^ unit_X , 1 * ^ unit_Y > , 1 * ^ unitX , 1 * ^ unit_Y , 2 * ^ unit_X , 1 * ^ unit_Y ] -- > -- > -- thingy = strokeTrail thingyT -- > thingy = stroke thingyT -- > > data TraceDiaOpts > = TDO { : : Diagram V2 -- > , basePt :: P2 Double -- > , dirV :: V2 Double -- > , sFilter :: [Double] -> [Double] > , drawV : : -- > } -- > -- > instance Default TraceDiaOpts where > def = TDO { traceShape = thingy -- > , basePt = pointB > , dirV = 0.3 ^ & 0.5 -- > , sFilter = id -- > , drawV = False -- > } -- > > pointA = 1 ^ & ( -1.5 ) > pointB = 1 ^ & 1.2 > pointC = 2.5 ^ & 3.5 -- > > dot ' = circle 0.05 # lw none -- > > mkTraceDia : : TraceDiaOpts - > Diagram V2 -- > mkTraceDia tdo = mconcat -- > [ mconcat $ map (place (dot' # fc red)) pts > , if drawV tdo then resultArrow else -- > , arrowAt (basePt tdo) (dirV tdo) # lc blue > , dot ' # fc blue # moveTo ( basePt tdo ) -- > , traceLine (basePt tdo) maxPosPt -- > , traceLine (basePt tdo) minNegPt > , -- > ] > # centerXY # pad 1.1 -- > where > ss = sFilter tdo . getSortedList > $ appTrace ( ) ( basePt tdo ) ( dirV tdo ) -- > pts = map mkPt ss > = basePt tdo .+^ ( s * ^ dirV tdo ) > maxPosPt = ( mkPt < $ > ) . safeLast $ filter ( > 0 ) ss > minNegPt = ( mkPt < $ > ) . safeHead $ filter ( < 0 ) ss > ( mkPt < $ > ) . safeHead $ ss > fromMaybe mempty ( ( basePt tdo ) < $ > minPt ) -- > # lc green -- > -- > safeLast [] = Nothing > safeLast xs = Just $ last xs -- > safeHead [] = Nothing -- > safeHead (x:_) = Just x -- > dropAllBut1 [] = [] -- > dropAllBut1 xs = [last xs] -- > > traceLine _ Nothing = > traceLine p ( Just q ) = ( p ~~ q ) # dashingG [ 0.1,0.1 ] 0 -- > > mkTraceDias : : [ TraceDiaOpts ] - > Diagram V2 > mkTraceDias = hcat ' ( with & sep .~ 1 ) . map mkTraceDia -- > > mkTraceDiasABC : : TraceDiaOpts - > Diagram V2 > ( map ( - > tdo { basePt = p } ) [ pointA , pointB , pointC ] )
null
https://raw.githubusercontent.com/diagrams/geometry/945c8c36b22e71d0c0e4427f23de6614f4e7594a/src/Geometry/Trace.hs
haskell
# LANGUAGE UndecidableInstances # --------------------------------------------------------------------------- | Module : Geometry.Trace License : BSD-style (see LICENSE) Maintainer : \"traces\", aka functional boundaries, essentially corresponding to a raytracer. --------------------------------------------------------------------------- * Traces * Traced class * Computing with traces ---------------------------------------------------------------------- ---------------------------------------------------------------------- > traceEx = mkTraceDia def | A trace for a given object is like a raytracer: given a ray (represented as a base point and a direction vector), the trace computes a list of signed distances from the base point to all intersections of the ray with the boundary of the object. Note that the outputs are not absolute distances, but multipliers @s@, then there is an intersection at the point @p .+^ (s *^ v)@. <<diagrams/src_Diagrams_Core_Trace_traceEx.svg#diagram=traceEx&width=200>> Traces form a semigroup with pointwise minimum as composition. # INLINE _Wrapped' # ---------------------------------------------------------------------- Class ---------------------------------------------------------------------- | @Traced@ abstracts over things which have a trace. If @a@ is also a 'Semigroup' then 'getTrace' must satisfy the law @ 'getTrace' (a1 <> a2) = 'getTrace' a1 <> 'getTrace' a2 @ | Compute the trace of an object. which returns no intersection points for every query. Arguably it should return a single finite distance for vectors aimed directly at the given point, but due to floating-point inaccuracy this is problematic. Note that the envelope for a single point ---------------------------------------------------------------------- Computing traces ---------------------------------------------------------------------- boundary intersection along the given vector @v@. The \"smallest\" boundary intersection is defined as the one given by @p .+^ (s *^ v)@ for the smallest (most negative) value of @s@. Return @Nothing@ if there is no intersection. See also 'traceP'. See also 'rayTraceV' which uses the smallest /positive/ intersection, which is often more intuitive behavior. there is no such boundary point. See also 'traceV'. See also 'rayTraceP' which uses the smallest /positive/ intersection, which is often more intuitive behavior. <<diagrams/src_Diagrams_Core_Trace_tracePEx.svg#diagram=tracePEx&width=600>> | Like 'traceV', but computes a vector to the \"largest\" boundary point instead of the smallest. (Note, however, the \"largest\" boundary point may still be in the opposite direction from the example shown below.) <<diagrams/src_Diagrams_Core_Trace_maxTraceVEx.svg#diagram=maxTraceVEx&width=600>> > maxTraceVEx = mkTraceDiasABC def { drawV = True, sFilter = dropAllBut1 } | Like 'traceP', but computes the \"largest\" boundary point instead of the smallest. (Note, however, the \"largest\" boundary point may still be in the opposite direction from the given vector, if all the boundary points are.) <<diagrams/src_Diagrams_Core_Trace_maxTracePEx.svg#diagram=maxTracePEx&width=600>> > maxTracePEx = mkTraceDiasABC def { sFilter = dropAllBut1 } boundary points, /i.e./ those boundary points given by a positive scalar multiple of the direction vector. Note, this property | Compute the vector from the given point to the closest boundary point of the given object in the given direction, or @Nothing@ if below). Note that unlike 'traceV', only /positive/ boundary points are considered, /i.e./ boundary points corresponding to a positive scalar multiple of the direction vector. This is 'traceV'. <<diagrams/src_Diagrams_Core_Trace_rayTraceVEx.svg#diagram=rayTraceVEx&width=600>> | Compute the boundary point on an object which is closest to the given base point in the given direction, or @Nothing@ if there is no such boundary point. Note that unlike 'traceP', only /positive/ boundary points are considered, /i.e./ boundary points corresponding to a positive scalar multiple of the direction camera. <<diagrams/src_Diagrams_Core_Trace_rayTracePEx.svg#diagram=rayTracePEx&width=600>> | Like 'rayTraceV', but computes a vector to the \"largest\" boundary point instead of the smallest. Considers only /positive/ boundary points. > maxRayTraceVEx = mkTraceDiasABC def { drawV = True, sFilter = dropAllBut1 . filter (>0) } | Like 'rayTraceP', but computes the \"largest\" boundary point instead of the smallest. Considers only /positive/ boundary points. <<diagrams/src_Diagrams_Core_Trace_maxRayTracePEx.svg#diagram=maxRayTracePEx&width=600>> > maxRayTracePEx = mkTraceDiasABC def { sFilter = dropAllBut1 . filter (>0) } ---------------------------------------------------------- Drawing trace diagrams ---------------------------------------------------------- > import Data.Default.Class > import Control.Lens ((^.)) > import Data.Maybe (fromMaybe) > > thingyT = > fromOffsets > > -- thingy = strokeTrail thingyT > thingy = stroke thingyT > > , basePt :: P2 Double > , dirV :: V2 Double > , sFilter :: [Double] -> [Double] > } > > instance Default TraceDiaOpts where > , basePt = pointB > , sFilter = id > , drawV = False > } > > > > mkTraceDia tdo = mconcat > [ mconcat $ map (place (dot' # fc red)) pts > , arrowAt (basePt tdo) (dirV tdo) # lc blue > , traceLine (basePt tdo) maxPosPt > , traceLine (basePt tdo) minNegPt > ] > where > pts = map mkPt ss > # lc green > > safeLast [] = Nothing > safeHead [] = Nothing > safeHead (x:_) = Just x > dropAllBut1 [] = [] > dropAllBut1 xs = [last xs] > > >
# LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE MultiParamTypeClasses # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # Copyright : ( c ) 2012 - 2017 diagrams team ( see LICENSE ) The @Trace@ module defines a data type and type class for module Geometry.Trace ( Trace(Trace) , appTrace , mkTrace , Traced(..) , traceV, traceP , maxTraceV, maxTraceP , getRayTrace , rayTraceV, rayTraceP , maxRayTraceV, maxRayTraceP ) where import Control.Lens import qualified Data.Map as M import qualified Data.Semigroup as Sem import Data.Sequence (Seq) import qualified Data.Sequence as Seq import qualified Data.Set as S import Geometry.HasOrigin import Geometry.Space import Geometry.Transform import Linear.Affine import Linear.Vector Trace relative to the input vector . That is , if the base point is @p@ and direction vector is @v@ , and one of the output scalars is newtype Trace v n = Trace { appTrace :: Point v n -> v n -> Seq n } deriving (Sem.Semigroup, Monoid) type instance V (Trace v n) = v type instance N (Trace v n) = n instance Rewrapped (Trace v n) (Trace v' n') instance Wrapped (Trace v n) where type Unwrapped (Trace v n) = Point v n -> v n -> Seq n _Wrapped' = iso appTrace Trace mkTrace :: (Point v n -> v n -> Seq n) -> Trace v n mkTrace = Trace # INLINE mkTrace # instance (Additive v, Num n) => HasOrigin (Trace v n) where moveOriginTo (P u) = _Wrapping' Trace %~ \f p -> f (p .+^ u) instance Show (Trace v n) where show _ = "<trace>" instance (Additive v, Foldable v, Num n) => Transformable (Trace v n) where transform t = _Wrapped %~ \f p v -> f (papply (inv t) p) (apply (inv t) v) # INLINE transform # class (Additive (V a), Ord (N a)) => Traced a where getTrace :: a -> Trace (V a) (N a) instance (Additive v, Ord n) => Traced (Trace v n) where getTrace = id | The trace of a single point is the empty trace , /i.e./ the one is /not/ the empty envelope ( see " Geometry . Envelope " ) . instance (Additive v, Ord n) => Traced (Point v n) where getTrace = const mempty instance Traced t => Traced (TransInv t) where getTrace = getTrace . op TransInv instance (Traced a, Traced b, SameSpace a b) => Traced (a,b) where getTrace (x,y) = getTrace x Sem.<> getTrace y instance Traced t => Traced [t] where getTrace = mconcat . map getTrace instance Traced t => Traced (M.Map k t) where getTrace = mconcat . map getTrace . M.elems instance Traced t => Traced (S.Set t) where getTrace = mconcat . map getTrace . S.elems | Compute the vector from the given point to the \"smallest\ " < < diagrams / src_Diagrams_Core_Trace_traceVEx.svg#diagram = traceVEx&width=600 > > traceV :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (v n) traceV = \p v a -> fmap (*^ v) . minimumOf folded $ appTrace (getTrace a) p v # INLINE traceV # > traceVEx = mkTraceDiasABC def { drawV = True , sFilter = take 1 } | Compute the \"smallest\ " boundary point along the line determined by the given point @p@ and vector @v@. The \"smallest\ " boundary point is defined as the one given by @p .+^ ( s * ^ v)@ for the smallest ( most negative ) value of @s@. Return @Nothing@ if traceP :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (Point v n) traceP p v a = (p .+^) <$> traceV p v a > tracePEx = mkTraceDiasABC def { sFilter = take 1 } given vector , if all the boundary points are , as in the third maxTraceV :: (InSpace v n a, Traced a) => Point v n -> V a n -> a -> Maybe (v n) maxTraceV p = traceV p . negated # INLINE maxTraceV # maxTraceP :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (Point v n) maxTraceP p v a = (p .+^) <$> maxTraceV p v a # INLINE maxTraceP # | Get a modified ' Trace ' for an object which only returns positive may be destroyed if the resulting ' Trace ' is translated at all . getRayTrace :: (InSpace v n a, Traced a) => a -> Trace v n getRayTrace = \a -> Trace $ \p v -> Seq.filter (>=0) $ appTrace (getTrace a) p v # INLINE getRayTrace # there is no such boundary point ( as in the third example intuitively the " behavior of a raytracer , which only considers intersections front of\ " the camera . Compare the second example diagram below with the second example shown for rayTraceV :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (v n) rayTraceV = \p v a -> fmap (*^ v) . minimumOf folded $ appTrace (getRayTrace a) p v # INLINE rayTraceV # > rayTraceVEx = mkTraceDiasABC def { drawV = True , sFilter = take 1 . filter ( > 0 ) } vector . This is intuitively the " behavior of a raytracer , which only considers intersection points of\ " the rayTraceP :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (Point v n) rayTraceP = \p v a -> (p .+^) <$> rayTraceV p v a > rayTracePEx = mkTraceDiasABC def { sFilter = take 1 . filter ( > 0 ) } < < diagrams / src_Diagrams_Core_Trace_maxRayTraceVEx.svg#diagram = maxRayTraceVEx&width=600 > > maxRayTraceV :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (v n) maxRayTraceV = \p v a -> fmap (*^ v) . maximumOf folded $ appTrace (getRayTrace a) p v maxRayTraceP :: (InSpace v n a, Traced a) => Point v n -> v n -> a -> Maybe (Point v n) maxRayTraceP p v a = (p .+^) <$> maxRayTraceV p v a # INLINE maxRayTraceP # > thingyT : : Trail V2 Double > [ 3 * ^ unitX , 3 * ^ unitY , 2 * ^ unit_X , 1 * ^ unit_Y > , 1 * ^ unitX , 1 * ^ unit_Y , 2 * ^ unit_X , 1 * ^ unit_Y ] > data TraceDiaOpts > = TDO { : : Diagram V2 > , drawV : : > def = TDO { traceShape = thingy > , dirV = 0.3 ^ & 0.5 > pointA = 1 ^ & ( -1.5 ) > pointB = 1 ^ & 1.2 > pointC = 2.5 ^ & 3.5 > dot ' = circle 0.05 # lw none > mkTraceDia : : TraceDiaOpts - > Diagram V2 > , if drawV tdo then resultArrow else > , dot ' # fc blue # moveTo ( basePt tdo ) > , > # centerXY # pad 1.1 > ss = sFilter tdo . getSortedList > $ appTrace ( ) ( basePt tdo ) ( dirV tdo ) > = basePt tdo .+^ ( s * ^ dirV tdo ) > maxPosPt = ( mkPt < $ > ) . safeLast $ filter ( > 0 ) ss > minNegPt = ( mkPt < $ > ) . safeHead $ filter ( < 0 ) ss > ( mkPt < $ > ) . safeHead $ ss > fromMaybe mempty ( ( basePt tdo ) < $ > minPt ) > safeLast xs = Just $ last xs > traceLine _ Nothing = > traceLine p ( Just q ) = ( p ~~ q ) # dashingG [ 0.1,0.1 ] 0 > mkTraceDias : : [ TraceDiaOpts ] - > Diagram V2 > mkTraceDias = hcat ' ( with & sep .~ 1 ) . map mkTraceDia > mkTraceDiasABC : : TraceDiaOpts - > Diagram V2 > ( map ( - > tdo { basePt = p } ) [ pointA , pointB , pointC ] )
abbe8e8b878160937bb29e8e5727e7094032322cfcc41a7d0e820c2f11168632
disteph/cdsat
terms.ml
open Format open General open Basic open Interfaces_basic open Variables type _ free = private Free type bound_prim = private Bound type bound = BoundVar.t*bound_prim type (_,_) xterm = | V : 'l -> (_, 'l*_) xterm | C : Symbols.t * ('a list) -> ('a,_) xterm | FB : Sorts.t*'a* 'l DSubst.t -> (_,'l*'a free) xterm | BB : Sorts.t*'a -> ('a, bound) xterm type (_,_) func_prim = | BoundFunc : (bound_prim,_) func_prim | FreeFunc : ('a -> 'b) -> ('a free,'b free) func_prim type ('a,'b) func = ('a,'b free) func_prim let equal (type l b a) (eqLeaf: l -> l -> bool) (eqSub:(b,(b,bool)func)func) eqRec (t1:(a,l*b)xterm) (t2:(a,l*b)xterm) = match t1,t2 with | V l1, V l2 -> eqLeaf l1 l2 | C(s1,l1), C(s2,l2) -> Symbols.equal s1 s2 && List.equal eqRec l1 l2 | FB(s1,x1,d1), FB(s2,x2,d2)-> let FreeFunc eqSub = eqSub in let FreeFunc eqSub = eqSub x1 in eqSub x2 && DSubst.equal eqLeaf d1 d2 | BB(s1,x1), BB(s2,x2) -> eqRec x1 x2 | _, _ -> false let hash (type a l b) (hLeaf:l->int) (hSub:(b,int)func) hRec : (a,l*b)xterm -> int = function | V l -> hLeaf l | C(symb,l) -> 5*(Symbols.hash symb)+17*(List.hash hRec l) | FB(so,x,d) -> let FreeFunc hSub = hSub in 19*Sorts.hash so+31*(hSub x)+23*(Hash.wrap1 DSubst.hash_fold_t hLeaf d) | BB(so,x) -> 31*(hRec x) (* Displays a formula *) let pp (type a l b) (pLeaf:formatter->l->unit) (pSub:(b,formatter->unit)func) pRec = let aux fmt: (a,l*b)xterm -> unit = function | V l -> fprintf fmt "%a" pLeaf l | C(symb,[]) -> fprintf fmt "%a" Symbols.pp symb | C(symb,l) -> fprintf fmt "%a%a" Symbols.pp symb (List.pp ~sep:", " ~wrap:("(",")") pRec) l | FB(so,f,d) -> let FreeFunc pif = pSub in fprintf fmt "%a%a" (fun fmt a -> pif a fmt) f (DSubst.pp pLeaf) d | BB(so,f) -> fprintf fmt "%a" pRec f in fun reveal fmt t -> aux fmt (reveal t) let get_sort (type a l b) sLeaf (sSub:(b,Sorts.t)func) sRec = let aux : (a,l*b)xterm -> Sorts.t = function | V bv -> sLeaf bv | C(symb,_) -> let so,_ = Symbols.arity symb in so | FB(_,t,_) -> let FreeFunc sSub = sSub in sSub t | BB(_,f) -> sRec f in fun reveal t -> aux (reveal t) module type Leaf = sig include PH val get_sort : t -> Sorts.t end (******************************) (* Terms with bound variables *) (******************************) module TermB = struct module B = struct type nonrec 'a t = ('a,bound) xterm let equal eqRec = equal BoundVar.equal BoundFunc eqRec let hash hRec = hash BoundVar.hash BoundFunc hRec let hash_fold_t hash_fold_a = Hash.hash2fold(hash(Hash.fold2hash hash_fold_a)) let name = "TermB" end include HCons.Make(B) include Init(HCons.NoBackIndex) let pp = let rec aux fmt t = pp BoundVar.pp BoundFunc aux reveal fmt t in aux let show = Print.stringOf pp let get_sort = let rec aux t = get_sort BoundVar.get_sort BoundFunc aux reveal t in aux let bV i = build(V i) let bC f l = build(C(f,l)) let bB so t = build(BB(so,t)) end (******************************) (* Terms with bound variables *) (******************************) module F = struct type ('a,'l) t = ('a, 'l * TermB.t free) xterm let equal eqRec eqPar = equal eqPar (FreeFunc(fun x->FreeFunc(TermB.equal x))) eqRec let hash hRec hPar = hash hPar (FreeFunc TermB.hash) hRec let hash_fold_t hash_fold_a hash_fold_l = Hash.hash2fold(hash(Hash.fold2hash hash_fold_a)(Hash.fold2hash hash_fold_l)) let name = "TermF" end include HCons.MakePoly(F) type ('leaf,'datatype) termF = ('leaf,'datatype) generic module type DataType = sig type t type leaf val bV : int -> leaf -> t val bC : int -> Symbols.t -> t list -> t val bB : int -> Sorts.t*TermB.t*leaf DSubst.t -> t end module type S = sig type datatype type leaf include PHCons with type t = (leaf,datatype) termF val print_of_id: Format.formatter -> int -> unit val get_sort : t -> Sorts.t val term_of_id: int -> t val bV : leaf -> t val bC : Symbols.t -> t list -> t val bB : Sorts.t -> TermB.t -> leaf DSubst.t -> t module Homo(Mon: MonadType) : sig val lift : ('a -> leaf Mon.t) -> ('a,_) termF -> (leaf,datatype) termF Mon.t val lifttl : ('a -> leaf Mon.t) -> ('a,_) termF list -> (leaf,datatype) termF list Mon.t end val subst : ('a -> leaf) -> ('a,_) termF -> (leaf,datatype) termF val lift : leaf DSubst.t -> TermB.t -> t end module Make(Leaf: Leaf) (Data : DataType with type leaf = Leaf.t) = struct type leaf = Leaf.t include InitData(HCons.BackIndex)(Leaf) (struct type t = Data.t let build tag = function | V v -> Data.bV tag v | C(f,l) -> Data.bC tag f (List.map data l) | FB(so,t,d) -> Data.bB tag (so,t,d) end) type datatype = Data.t let Opt.Some term_of_id = backindex let id = id let compare = compare let bV i = build(V i) let bC f l = build(C(f,l)) let bB so t d = build(FB(so,t,d)) let pp fmt t = let rec aux fmt t = pp Leaf.pp (FreeFunc(fun t fmt->TermB.pp fmt t)) aux reveal fmt t in aux fmt t let show a = Print.stringOf pp a let print_of_id fmt index = let atom = term_of_id index in pp fmt atom let get_sort = let rec aux t = get_sort Leaf.get_sort (FreeFunc(TermB.get_sort)) aux reveal t in aux module Homo(Mon: MonadType) = struct let rec lift update t = match reveal t with | V i -> Mon.bind (fun v -> Mon.return (bV v)) (update i) | C(f,l) -> Mon.bind (fun l -> Mon.return (bC f l)) (lifttl update l) | FB(so,t,d) -> Mon.bind(fun d -> Mon.return(bB so t d)) (liftd update d) and lifttl update = function | [] -> Mon.return [] | t::tl -> let aux t' tl' = Mon.return(t'::tl') in let aux' t' = Mon.bind (aux t') (lifttl update tl) in Mon.bind aux' (lift update t) and liftd update = function | [] -> Mon.return [] | (t,w)::tl -> let aux t' tl' = Mon.return((t',w)::tl') in let aux' t' = Mon.bind (aux t') (liftd update tl) in Mon.bind aux' (update t) end module M = Homo(Basic.IdMon) let subst = M.lift let get_in_subst d intso = let fv,_ = BoundVar.get_from_context intso (fun k -> DSubst.get (fun fmt v->pp fmt (bV v)) k d) in fv let rec lift d t = match TermB.reveal t with | V i -> bV (get_in_subst d i) | C(f,l) -> bC f (List.map (lift d) l) | BB(so,t) -> bB so t d end module EmptyData(Leaf:Leaf) = struct type t = unit type leaf = Leaf.t let bC _ _ _ = () let bV _ _ = () let bB _ _ = () end
null
https://raw.githubusercontent.com/disteph/cdsat/1b569f3eae59802148f4274186746a9ed3e667ed/src/kernel/kernel.mld/top.mld/terms.ml
ocaml
Displays a formula **************************** Terms with bound variables **************************** **************************** Terms with bound variables ****************************
open Format open General open Basic open Interfaces_basic open Variables type _ free = private Free type bound_prim = private Bound type bound = BoundVar.t*bound_prim type (_,_) xterm = | V : 'l -> (_, 'l*_) xterm | C : Symbols.t * ('a list) -> ('a,_) xterm | FB : Sorts.t*'a* 'l DSubst.t -> (_,'l*'a free) xterm | BB : Sorts.t*'a -> ('a, bound) xterm type (_,_) func_prim = | BoundFunc : (bound_prim,_) func_prim | FreeFunc : ('a -> 'b) -> ('a free,'b free) func_prim type ('a,'b) func = ('a,'b free) func_prim let equal (type l b a) (eqLeaf: l -> l -> bool) (eqSub:(b,(b,bool)func)func) eqRec (t1:(a,l*b)xterm) (t2:(a,l*b)xterm) = match t1,t2 with | V l1, V l2 -> eqLeaf l1 l2 | C(s1,l1), C(s2,l2) -> Symbols.equal s1 s2 && List.equal eqRec l1 l2 | FB(s1,x1,d1), FB(s2,x2,d2)-> let FreeFunc eqSub = eqSub in let FreeFunc eqSub = eqSub x1 in eqSub x2 && DSubst.equal eqLeaf d1 d2 | BB(s1,x1), BB(s2,x2) -> eqRec x1 x2 | _, _ -> false let hash (type a l b) (hLeaf:l->int) (hSub:(b,int)func) hRec : (a,l*b)xterm -> int = function | V l -> hLeaf l | C(symb,l) -> 5*(Symbols.hash symb)+17*(List.hash hRec l) | FB(so,x,d) -> let FreeFunc hSub = hSub in 19*Sorts.hash so+31*(hSub x)+23*(Hash.wrap1 DSubst.hash_fold_t hLeaf d) | BB(so,x) -> 31*(hRec x) let pp (type a l b) (pLeaf:formatter->l->unit) (pSub:(b,formatter->unit)func) pRec = let aux fmt: (a,l*b)xterm -> unit = function | V l -> fprintf fmt "%a" pLeaf l | C(symb,[]) -> fprintf fmt "%a" Symbols.pp symb | C(symb,l) -> fprintf fmt "%a%a" Symbols.pp symb (List.pp ~sep:", " ~wrap:("(",")") pRec) l | FB(so,f,d) -> let FreeFunc pif = pSub in fprintf fmt "%a%a" (fun fmt a -> pif a fmt) f (DSubst.pp pLeaf) d | BB(so,f) -> fprintf fmt "%a" pRec f in fun reveal fmt t -> aux fmt (reveal t) let get_sort (type a l b) sLeaf (sSub:(b,Sorts.t)func) sRec = let aux : (a,l*b)xterm -> Sorts.t = function | V bv -> sLeaf bv | C(symb,_) -> let so,_ = Symbols.arity symb in so | FB(_,t,_) -> let FreeFunc sSub = sSub in sSub t | BB(_,f) -> sRec f in fun reveal t -> aux (reveal t) module type Leaf = sig include PH val get_sort : t -> Sorts.t end module TermB = struct module B = struct type nonrec 'a t = ('a,bound) xterm let equal eqRec = equal BoundVar.equal BoundFunc eqRec let hash hRec = hash BoundVar.hash BoundFunc hRec let hash_fold_t hash_fold_a = Hash.hash2fold(hash(Hash.fold2hash hash_fold_a)) let name = "TermB" end include HCons.Make(B) include Init(HCons.NoBackIndex) let pp = let rec aux fmt t = pp BoundVar.pp BoundFunc aux reveal fmt t in aux let show = Print.stringOf pp let get_sort = let rec aux t = get_sort BoundVar.get_sort BoundFunc aux reveal t in aux let bV i = build(V i) let bC f l = build(C(f,l)) let bB so t = build(BB(so,t)) end module F = struct type ('a,'l) t = ('a, 'l * TermB.t free) xterm let equal eqRec eqPar = equal eqPar (FreeFunc(fun x->FreeFunc(TermB.equal x))) eqRec let hash hRec hPar = hash hPar (FreeFunc TermB.hash) hRec let hash_fold_t hash_fold_a hash_fold_l = Hash.hash2fold(hash(Hash.fold2hash hash_fold_a)(Hash.fold2hash hash_fold_l)) let name = "TermF" end include HCons.MakePoly(F) type ('leaf,'datatype) termF = ('leaf,'datatype) generic module type DataType = sig type t type leaf val bV : int -> leaf -> t val bC : int -> Symbols.t -> t list -> t val bB : int -> Sorts.t*TermB.t*leaf DSubst.t -> t end module type S = sig type datatype type leaf include PHCons with type t = (leaf,datatype) termF val print_of_id: Format.formatter -> int -> unit val get_sort : t -> Sorts.t val term_of_id: int -> t val bV : leaf -> t val bC : Symbols.t -> t list -> t val bB : Sorts.t -> TermB.t -> leaf DSubst.t -> t module Homo(Mon: MonadType) : sig val lift : ('a -> leaf Mon.t) -> ('a,_) termF -> (leaf,datatype) termF Mon.t val lifttl : ('a -> leaf Mon.t) -> ('a,_) termF list -> (leaf,datatype) termF list Mon.t end val subst : ('a -> leaf) -> ('a,_) termF -> (leaf,datatype) termF val lift : leaf DSubst.t -> TermB.t -> t end module Make(Leaf: Leaf) (Data : DataType with type leaf = Leaf.t) = struct type leaf = Leaf.t include InitData(HCons.BackIndex)(Leaf) (struct type t = Data.t let build tag = function | V v -> Data.bV tag v | C(f,l) -> Data.bC tag f (List.map data l) | FB(so,t,d) -> Data.bB tag (so,t,d) end) type datatype = Data.t let Opt.Some term_of_id = backindex let id = id let compare = compare let bV i = build(V i) let bC f l = build(C(f,l)) let bB so t d = build(FB(so,t,d)) let pp fmt t = let rec aux fmt t = pp Leaf.pp (FreeFunc(fun t fmt->TermB.pp fmt t)) aux reveal fmt t in aux fmt t let show a = Print.stringOf pp a let print_of_id fmt index = let atom = term_of_id index in pp fmt atom let get_sort = let rec aux t = get_sort Leaf.get_sort (FreeFunc(TermB.get_sort)) aux reveal t in aux module Homo(Mon: MonadType) = struct let rec lift update t = match reveal t with | V i -> Mon.bind (fun v -> Mon.return (bV v)) (update i) | C(f,l) -> Mon.bind (fun l -> Mon.return (bC f l)) (lifttl update l) | FB(so,t,d) -> Mon.bind(fun d -> Mon.return(bB so t d)) (liftd update d) and lifttl update = function | [] -> Mon.return [] | t::tl -> let aux t' tl' = Mon.return(t'::tl') in let aux' t' = Mon.bind (aux t') (lifttl update tl) in Mon.bind aux' (lift update t) and liftd update = function | [] -> Mon.return [] | (t,w)::tl -> let aux t' tl' = Mon.return((t',w)::tl') in let aux' t' = Mon.bind (aux t') (liftd update tl) in Mon.bind aux' (update t) end module M = Homo(Basic.IdMon) let subst = M.lift let get_in_subst d intso = let fv,_ = BoundVar.get_from_context intso (fun k -> DSubst.get (fun fmt v->pp fmt (bV v)) k d) in fv let rec lift d t = match TermB.reveal t with | V i -> bV (get_in_subst d i) | C(f,l) -> bC f (List.map (lift d) l) | BB(so,t) -> bB so t d end module EmptyData(Leaf:Leaf) = struct type t = unit type leaf = Leaf.t let bC _ _ _ = () let bV _ _ = () let bB _ _ = () end
b629a5889eb1a4733aef0737f05472a5857d2882da3dd33caac5bb69764effad
someteam/acha
achievement_static.clj
(ns acha.achievement-static) (def ^:private -table [ {:description "Delete a file that has been added in the initial commit (and at least a year has passed)", :key :all-things-die, :name "All Things Die"} {:description "Commit time is 1 month or more after the author time", :key :alzheimers, :name "Alzheimer's"} {:description "Commit on the project’s birthday", :key :anniversary, :name "Anniversary"} {:description "Swear in a commit message", :key :bad-motherfucker, :name "Bad Motherf*cker", :level-description "One level for each swear word in a message"} {:description "Add Basic file to the repo", :key :basic, :name "Cradle of Civilization"} {:description "Ask for an achievement in a commit message", :key :beggar, :name "Beggar"} {:description "Use someone else’s name in a commit message", :key :blamer, :name "Blamer"} {:description "Misspell a word in a commit message", :key :borat, :name "Borat", :level-description "One level for each misspelled word in a message"} {:description "Add C# file to the repo", :key :c-sharp, :name "It's Dangerous to Go Alone, Take LINQ"} {:description "Make 10+ commits with the same message", :key :catchphrase, :name "Catchphrase"} {:description "Change license type or edit license file", :key :change-of-mind, :name "Change of Mind"} {:description "Commit on Dec 25", :key :christmas, :name "Ruined Christmas"} {:description "StackOverflow URL in a commit body or message", :key :citation-needed, :name "Citation Needed"} {:description "Add Clojure file to the repo", :key :clojure, :name "Even Lispers Hate Lisp"} {:description "Add ClojureScript file to the repo", :key :clojurescript, :name "Even Lispers Hate Lisp (in a browser)"} {:description "Publish commit with the same N first chars of SHA-1 as existing commit", :key :collision, :name "Collision"} {:description "10+ commits in a row", :key :combo, :name "Combo"} {:description "Make a commit after someone had 10+ commits in a row", :key :combo-breaker, :name "Combo Breaker"} {:description "Only add a comment", :key :commenter, :name "Commenter"} {:description "Add CSS file to the repo", :key :css, :name "You Designer Now?"} {:description "Add C++ file to the repo", :key :cxx, :name "Troubles++14"} {:description "Commit after 6PM friday", :key :dangerous-game, :name "Dangerous Game"} {:description "Add Dart file to the repo", :key :dart, :name "You Work in Google?"} {:description "Update master branch with force mode", :key :deal-with-it, :name "Deal with it"} {:description "Swap two lines", :key :easy-fix, :name "Easy Fix"} {:description "Use emoji in a commit message", :key :emoji, :name "C00l kid"} {:description "Make an empty commit", :key :empty-commit, :name "<empty title>"} {:description "Make a commit with no lines added, only deletions", :key :eraser, :name "Eraser"} {:description "Add Erlang file to the repo", :key :erlang, :name "It’s like ObjC, but for Ericsson phones"} {:description "Commit 2Mb file or bigger", :key :fat-ass, :name "Fat Ass"} {:description "Use word “fix” in a commit message", :key :fix, :name "Save the Day"} {:description "Two different commits within 15 seconds", :key :flash, :name "Flash"} {:description "Commit on Apr 1", :key :fools-day, :name "Fools’ Code"} {:description "Add GPL license file to the repo", :key :for-stallman, :name "For Stallman!"} {:description "Use word “forgot” in a commit message", :key :forgot, :name "Second Thoughts"} {:description "Make commit #1000, or #1111, or #1234", :key :get, :name "Get"} {:description "Add .gitignore", :key :gitignore, :name "Gitignore"} {:description "Add Go file to the repo", :key :go, :name "In Google we trust"} {:description "Create 'test' or 'doc' directory (not in the first commit)", :key :good-boy, :name "Good Boy"} {:description "Use word “google” in a commit message", :key :google, :name "I Can Sort It out Myself"} {:description "Use word “hack” in a commit message", :key :hack, :name "Real Hacker"} {:description "Commit on Oct 31", :key :halloween, :name "This Code Looks Scary"} {:description "Add Haskell file to the repo", :key :haskell, :name "Ivory Tower"} {:description "5+ swear words in a commit message", :key :hello-linus, :name "Hello, Linus", :level-description "One level for each 5 swear words in a message"} {:description "Change tabs to spaces or vice versa", :key :holy-war, :name "Holy War"} {:description "Make a commit with 3+ parents", :key :hydra, :name "Hydra"} {:description "Use word “impossible” in a commit message", :key :impossible, :name "Mission Impossible"} {:description "Add Java file to the repo", :key :java, :name "Write Once. Run. Anywhere"} {:description "Add JS file to the repo", :key :javascript, :name "Happily Never After"} {:description "Commit on Feb 29", :key :leap-day, :name "Rare Occasion"} {:description "More than 10 lines in a commit message", :key :leo-tolstoy, :name "Leo Tolstoy"} {:description "You are the only committer for a month", :key :loneliness, :name "Loneliness"} {:description "Consecutive 777 in SHA-1", :key :lucky, :name "Lucky"} {:description "Use word “magic” in a commit message", :key :magic, :name "The Colour of Magic"} {:description "Commit message with 3 letters or less", :key :man-of-few-words, :name "A Man of Few Words"} {:description "Consecutive 666 in SHA-1", :key :mark-of-the-beast, :name "Mark of the Beast"} {:description "Add more than 1000 lines in a single commit", :key :massive, :name "Massive"} {:description "Move a file from one place to another without changing it", :key :mover, :name "Mover"} {:description "Add/edit files in 3+ different languages in a single commit", :key :multilingual, :name "Multilingual"} {:description "Get 5 achievements with 1 commit", :key :munchkin, :name "Munchkin"} {:description "Use your own name in a commit message", :key :narcissist, :name "Narcissist"} {:description "Make a commit to a repo that hasn’t been touched for 1 month or more", :key :necromancer, :name "Necromancer"} {:description "Use word “later” in a commit message", :key :never-probably, :name "Never, Probably"} {:description "Commit on Jan 1", :key :new-year, :name "New Year, New Bugs"} {:description "Write a commit message without any letters", :key :no-more-letters, :name "No More Letters"} {:description "Commit id_rsa file", :key :nothing-to-hide, :name "Nothing to Hide"} {:description "Add Objective-C file to the repo", :key :objective-c, :name "NSVeryDescriptiveAchievementNameWithParame..."} {:description "Commit a file with just trailing spaces removed", :key :ocd, :name "OCD"} {:description "Commit and revert commit within 1 minute", :key :ooops, :name "Ooops"} {:description "Commit between 4am and 7am local time", :key :owl, :name "Owl"} {:description "Add Pascal file to the repo", :key :pascal, :name "Really?"} {:description "Resolve 100 conflicts", :key :peacemaker, :name "Peacemaker"} {:description "Add Perl file to the repo", :key :perl, :name "Chmod 200"} {:description "Add PHP file to the repo", :key :php, :name "New Facebook is Born"} {:description "Commit on Programmers' Day", :key :programmers-day, :name "Professional Pride"} {:description "Add Python file to the repo", :key :python, :name "Why not Ruby?"} {:description "Get all achievements", :key :quest-complete, :name "Quest Complete"} {:description "Add Ruby file to the repo", :key :ruby, :name "Back on the Rails"} {:description "Commit on Russia Day", :key :russia-day, :name "From Russia with Love"} {:description "Add Scala file to the repo", :key :scala, :name "Well Typed, Bro"} {:description "Create a README", :key :scribbler, :name "Scribbler"} {:description "Use word “secure” in a commit message", :key :secure, :name "We’re Safe Now"} {:description "Add Bash file to the repo", :key :shell, :name "We’ll Rewrite that Later"} {:description "Use word “sorry” in a commit message", :key :sorry, :name "Salvation"} {:description "Add SQL file to the repo", :key :sql, :name "Not a Web Scale"} {:description "Add Swift file to the repo", :key :swift, :name "I Need to Sort Complex Objects Fast!"} {:description "Commit on Thanksgiving", :key :thanksgiving, :name "Turkey Code"} {:description "Commit exactly at 00:00", :key :time-get, :name "Get"} {:description "Zero achievments after 100 your own commits", :key :unpretending, :name "Unpretending"} {:description "Commit on Feb 14", :key :valentine, :name "In Love with Work"} {:description "Your commit was reverted completely by someone else", :key :waste, :name "Waste"} {:description "Edit a file that hasn’t been touched for a year", :key :what-happened-here, :name "What Happened Here?"} {:description "Add Windows Shell file to the repo", :key :windows-language, :name "You Can't Program on Windows, Can You?"} {:description "Make 100+ non-merge commits", :key :worker-bee, :name "Worker Bee"} {:description "Number of lines added == number of lines deleted", :key :world-balance, :name "World Balance"} {:description "Use word “wow” in a commit message", :key :wow, :name "Wow"} {:description "Change more than 100 files in one commit", :key :wrecking-ball, :name "Wrecking Ball"} {:description "Add XML file to the repo", :key :xml, :name "Zed’s Dead, Baby"} ]) (def table (map (fn [a i] (assoc a :id (+ i 100))) -table (range))) (def table-map (into {} (map #(vector (:key %) %) table)))
null
https://raw.githubusercontent.com/someteam/acha/6b957f6cb6773f4fc184d094b40de79039bb58cc/src-clj/acha/achievement_static.clj
clojure
(ns acha.achievement-static) (def ^:private -table [ {:description "Delete a file that has been added in the initial commit (and at least a year has passed)", :key :all-things-die, :name "All Things Die"} {:description "Commit time is 1 month or more after the author time", :key :alzheimers, :name "Alzheimer's"} {:description "Commit on the project’s birthday", :key :anniversary, :name "Anniversary"} {:description "Swear in a commit message", :key :bad-motherfucker, :name "Bad Motherf*cker", :level-description "One level for each swear word in a message"} {:description "Add Basic file to the repo", :key :basic, :name "Cradle of Civilization"} {:description "Ask for an achievement in a commit message", :key :beggar, :name "Beggar"} {:description "Use someone else’s name in a commit message", :key :blamer, :name "Blamer"} {:description "Misspell a word in a commit message", :key :borat, :name "Borat", :level-description "One level for each misspelled word in a message"} {:description "Add C# file to the repo", :key :c-sharp, :name "It's Dangerous to Go Alone, Take LINQ"} {:description "Make 10+ commits with the same message", :key :catchphrase, :name "Catchphrase"} {:description "Change license type or edit license file", :key :change-of-mind, :name "Change of Mind"} {:description "Commit on Dec 25", :key :christmas, :name "Ruined Christmas"} {:description "StackOverflow URL in a commit body or message", :key :citation-needed, :name "Citation Needed"} {:description "Add Clojure file to the repo", :key :clojure, :name "Even Lispers Hate Lisp"} {:description "Add ClojureScript file to the repo", :key :clojurescript, :name "Even Lispers Hate Lisp (in a browser)"} {:description "Publish commit with the same N first chars of SHA-1 as existing commit", :key :collision, :name "Collision"} {:description "10+ commits in a row", :key :combo, :name "Combo"} {:description "Make a commit after someone had 10+ commits in a row", :key :combo-breaker, :name "Combo Breaker"} {:description "Only add a comment", :key :commenter, :name "Commenter"} {:description "Add CSS file to the repo", :key :css, :name "You Designer Now?"} {:description "Add C++ file to the repo", :key :cxx, :name "Troubles++14"} {:description "Commit after 6PM friday", :key :dangerous-game, :name "Dangerous Game"} {:description "Add Dart file to the repo", :key :dart, :name "You Work in Google?"} {:description "Update master branch with force mode", :key :deal-with-it, :name "Deal with it"} {:description "Swap two lines", :key :easy-fix, :name "Easy Fix"} {:description "Use emoji in a commit message", :key :emoji, :name "C00l kid"} {:description "Make an empty commit", :key :empty-commit, :name "<empty title>"} {:description "Make a commit with no lines added, only deletions", :key :eraser, :name "Eraser"} {:description "Add Erlang file to the repo", :key :erlang, :name "It’s like ObjC, but for Ericsson phones"} {:description "Commit 2Mb file or bigger", :key :fat-ass, :name "Fat Ass"} {:description "Use word “fix” in a commit message", :key :fix, :name "Save the Day"} {:description "Two different commits within 15 seconds", :key :flash, :name "Flash"} {:description "Commit on Apr 1", :key :fools-day, :name "Fools’ Code"} {:description "Add GPL license file to the repo", :key :for-stallman, :name "For Stallman!"} {:description "Use word “forgot” in a commit message", :key :forgot, :name "Second Thoughts"} {:description "Make commit #1000, or #1111, or #1234", :key :get, :name "Get"} {:description "Add .gitignore", :key :gitignore, :name "Gitignore"} {:description "Add Go file to the repo", :key :go, :name "In Google we trust"} {:description "Create 'test' or 'doc' directory (not in the first commit)", :key :good-boy, :name "Good Boy"} {:description "Use word “google” in a commit message", :key :google, :name "I Can Sort It out Myself"} {:description "Use word “hack” in a commit message", :key :hack, :name "Real Hacker"} {:description "Commit on Oct 31", :key :halloween, :name "This Code Looks Scary"} {:description "Add Haskell file to the repo", :key :haskell, :name "Ivory Tower"} {:description "5+ swear words in a commit message", :key :hello-linus, :name "Hello, Linus", :level-description "One level for each 5 swear words in a message"} {:description "Change tabs to spaces or vice versa", :key :holy-war, :name "Holy War"} {:description "Make a commit with 3+ parents", :key :hydra, :name "Hydra"} {:description "Use word “impossible” in a commit message", :key :impossible, :name "Mission Impossible"} {:description "Add Java file to the repo", :key :java, :name "Write Once. Run. Anywhere"} {:description "Add JS file to the repo", :key :javascript, :name "Happily Never After"} {:description "Commit on Feb 29", :key :leap-day, :name "Rare Occasion"} {:description "More than 10 lines in a commit message", :key :leo-tolstoy, :name "Leo Tolstoy"} {:description "You are the only committer for a month", :key :loneliness, :name "Loneliness"} {:description "Consecutive 777 in SHA-1", :key :lucky, :name "Lucky"} {:description "Use word “magic” in a commit message", :key :magic, :name "The Colour of Magic"} {:description "Commit message with 3 letters or less", :key :man-of-few-words, :name "A Man of Few Words"} {:description "Consecutive 666 in SHA-1", :key :mark-of-the-beast, :name "Mark of the Beast"} {:description "Add more than 1000 lines in a single commit", :key :massive, :name "Massive"} {:description "Move a file from one place to another without changing it", :key :mover, :name "Mover"} {:description "Add/edit files in 3+ different languages in a single commit", :key :multilingual, :name "Multilingual"} {:description "Get 5 achievements with 1 commit", :key :munchkin, :name "Munchkin"} {:description "Use your own name in a commit message", :key :narcissist, :name "Narcissist"} {:description "Make a commit to a repo that hasn’t been touched for 1 month or more", :key :necromancer, :name "Necromancer"} {:description "Use word “later” in a commit message", :key :never-probably, :name "Never, Probably"} {:description "Commit on Jan 1", :key :new-year, :name "New Year, New Bugs"} {:description "Write a commit message without any letters", :key :no-more-letters, :name "No More Letters"} {:description "Commit id_rsa file", :key :nothing-to-hide, :name "Nothing to Hide"} {:description "Add Objective-C file to the repo", :key :objective-c, :name "NSVeryDescriptiveAchievementNameWithParame..."} {:description "Commit a file with just trailing spaces removed", :key :ocd, :name "OCD"} {:description "Commit and revert commit within 1 minute", :key :ooops, :name "Ooops"} {:description "Commit between 4am and 7am local time", :key :owl, :name "Owl"} {:description "Add Pascal file to the repo", :key :pascal, :name "Really?"} {:description "Resolve 100 conflicts", :key :peacemaker, :name "Peacemaker"} {:description "Add Perl file to the repo", :key :perl, :name "Chmod 200"} {:description "Add PHP file to the repo", :key :php, :name "New Facebook is Born"} {:description "Commit on Programmers' Day", :key :programmers-day, :name "Professional Pride"} {:description "Add Python file to the repo", :key :python, :name "Why not Ruby?"} {:description "Get all achievements", :key :quest-complete, :name "Quest Complete"} {:description "Add Ruby file to the repo", :key :ruby, :name "Back on the Rails"} {:description "Commit on Russia Day", :key :russia-day, :name "From Russia with Love"} {:description "Add Scala file to the repo", :key :scala, :name "Well Typed, Bro"} {:description "Create a README", :key :scribbler, :name "Scribbler"} {:description "Use word “secure” in a commit message", :key :secure, :name "We’re Safe Now"} {:description "Add Bash file to the repo", :key :shell, :name "We’ll Rewrite that Later"} {:description "Use word “sorry” in a commit message", :key :sorry, :name "Salvation"} {:description "Add SQL file to the repo", :key :sql, :name "Not a Web Scale"} {:description "Add Swift file to the repo", :key :swift, :name "I Need to Sort Complex Objects Fast!"} {:description "Commit on Thanksgiving", :key :thanksgiving, :name "Turkey Code"} {:description "Commit exactly at 00:00", :key :time-get, :name "Get"} {:description "Zero achievments after 100 your own commits", :key :unpretending, :name "Unpretending"} {:description "Commit on Feb 14", :key :valentine, :name "In Love with Work"} {:description "Your commit was reverted completely by someone else", :key :waste, :name "Waste"} {:description "Edit a file that hasn’t been touched for a year", :key :what-happened-here, :name "What Happened Here?"} {:description "Add Windows Shell file to the repo", :key :windows-language, :name "You Can't Program on Windows, Can You?"} {:description "Make 100+ non-merge commits", :key :worker-bee, :name "Worker Bee"} {:description "Number of lines added == number of lines deleted", :key :world-balance, :name "World Balance"} {:description "Use word “wow” in a commit message", :key :wow, :name "Wow"} {:description "Change more than 100 files in one commit", :key :wrecking-ball, :name "Wrecking Ball"} {:description "Add XML file to the repo", :key :xml, :name "Zed’s Dead, Baby"} ]) (def table (map (fn [a i] (assoc a :id (+ i 100))) -table (range))) (def table-map (into {} (map #(vector (:key %) %) table)))
85034a7c1aedfa51a834e410708dc66b49b0b372b80cb03e52e5c8eb46e1dd4c
zchn/ethereum-analyzer
BytecodeVisMain.hs
# LANGUAGE OverloadedStrings , TemplateHaskell , FlexibleContexts # #-} # LANGUAGE NoImplicitPrelude # -- | Dump all contracts. module Main ( main ) where import Control.Monad.Logger import Ethereum.Executable.BytecodeVisMain (bytecodeVisMain) import HFlags import Protolude defineFlag "bytecode" ("" :: Text) "The bytecode. Will read from STDIN if empty." defineFlag "outDot" ("" :: Text) "The dot file path. Will print to STDOUT if empty" defineFlag "dummy" False "dummy flag for " main :: IO () main = do s <- $initHFlags "ea-bytecode-vis" putText $ "Flags: " <> show s runStdoutLoggingT (bytecodeVisMain flags_bytecode flags_outDot)
null
https://raw.githubusercontent.com/zchn/ethereum-analyzer/f2a60d8b451358971f1e3b1a61658f5741c4c099/ethereum-analyzer-cli/exec_src/BytecodeVisMain.hs
haskell
| Dump all contracts.
# LANGUAGE OverloadedStrings , TemplateHaskell , FlexibleContexts # #-} # LANGUAGE NoImplicitPrelude # module Main ( main ) where import Control.Monad.Logger import Ethereum.Executable.BytecodeVisMain (bytecodeVisMain) import HFlags import Protolude defineFlag "bytecode" ("" :: Text) "The bytecode. Will read from STDIN if empty." defineFlag "outDot" ("" :: Text) "The dot file path. Will print to STDOUT if empty" defineFlag "dummy" False "dummy flag for " main :: IO () main = do s <- $initHFlags "ea-bytecode-vis" putText $ "Flags: " <> show s runStdoutLoggingT (bytecodeVisMain flags_bytecode flags_outDot)
4002e8df6f69be404d0d4ed88e3884f7b07e696ccf74bc64f032590a8ac59fb8
geostarling/guix-packages
emacs-xyz.scm
;;; Copyright © 2022 < > ;;;;;; The Work 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. ;;; ;;; The Work 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 The Work . If not , see < / > . (define-module (personal packages emacs-xyz) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix build-system emacs) #:use-module (guix git-download) #:use-module (personal packages text-editors)) (define-public emacs-parinfer-rust-mode (let ((commit "c2c1bbec6cc7dad4f546868aa07609b8d58a78f8") (revision "3")) (package (name "emacs-parinfer-rust-mode") (version (git-version "0.8.3" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "-rust-mode.git") (commit commit))) (file-name (git-file-name name version)) (sha256 (base32 "0az4qp118vsqzgsl87wgszzq91qzqkpabifd8qrr2li3sizsn049")))) (build-system emacs-build-system) ( concat user - emacs - directory " parinfer - rust/ " ) ) ( - library - directory ( locate - user - emacs - file ( concat user - emacs - directory " parinfer - rust/ " ) ) ;; (arguments `(#:phases (modify-phases %standard-phases (delete 'build) (add-after 'unpack 'parinfer-rust-path-patch (lambda* (#:key inputs #:allow-other-keys) (let* ((parinfer-rust-libdir (string-append (assoc-ref inputs "parinfer-rust") "/lib/")) (parinfer-rust-lib (string-append parinfer-rust-libdir "parinfer-rust-linux.so"))) ;; (substitute* "parinfer-rust-changes.el" ;; (("user-emacs-directory \"parinfer-rust/\"") ;; (string-append " \ " " parinfer - rust - libdir " \ " " ) ) ) (substitute* "parinfer-rust-mode.el" (("\\(concat user-emacs-directory \"parinfer-rust/\"\\)") (string-append "\"" parinfer-rust-libdir "\""))))))))) ( ( " 0.4.4 - beta " ) ;; "0.4.3") ;; (("\\(locate-user-emacs-file \\(concat \"parinfer-rust/\"") ;; (string-append " ( concat \ " " parinfer - rust - libdir " \ " " ) ) ;; (("^[ ]+parinfer-rust--lib-name\\)\\)") " parinfer - rust -- lib - name ) " ) ) ) ) ) ) ) ) (inputs (list parinfer-rust)) (synopsis "Parinfer-rust-mode aims to be a simpler adaptation of Parinfer for Emacs") (description "") (home-page "-rust-mode") (license license:gpl3))))
null
https://raw.githubusercontent.com/geostarling/guix-packages/765e0c14fd49c1c04e9af17176f93a30f829b6e8/personal/packages/emacs-xyz.scm
scheme
you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. The Work 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. (substitute* "parinfer-rust-changes.el" (("user-emacs-directory \"parinfer-rust/\"") (string-append "0.4.3") (("\\(locate-user-emacs-file \\(concat \"parinfer-rust/\"") (string-append (("^[ ]+parinfer-rust--lib-name\\)\\)")
Copyright © 2022 < > 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 The Work . If not , see < / > . (define-module (personal packages emacs-xyz) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix build-system emacs) #:use-module (guix git-download) #:use-module (personal packages text-editors)) (define-public emacs-parinfer-rust-mode (let ((commit "c2c1bbec6cc7dad4f546868aa07609b8d58a78f8") (revision "3")) (package (name "emacs-parinfer-rust-mode") (version (git-version "0.8.3" revision commit)) (source (origin (method git-fetch) (uri (git-reference (url "-rust-mode.git") (commit commit))) (file-name (git-file-name name version)) (sha256 (base32 "0az4qp118vsqzgsl87wgszzq91qzqkpabifd8qrr2li3sizsn049")))) (build-system emacs-build-system) ( concat user - emacs - directory " parinfer - rust/ " ) ) ( - library - directory ( locate - user - emacs - file ( concat user - emacs - directory " parinfer - rust/ " ) ) (arguments `(#:phases (modify-phases %standard-phases (delete 'build) (add-after 'unpack 'parinfer-rust-path-patch (lambda* (#:key inputs #:allow-other-keys) (let* ((parinfer-rust-libdir (string-append (assoc-ref inputs "parinfer-rust") "/lib/")) (parinfer-rust-lib (string-append parinfer-rust-libdir "parinfer-rust-linux.so"))) " \ " " parinfer - rust - libdir " \ " " ) ) ) (substitute* "parinfer-rust-mode.el" (("\\(concat user-emacs-directory \"parinfer-rust/\"\\)") (string-append "\"" parinfer-rust-libdir "\""))))))))) ( ( " 0.4.4 - beta " ) " ( concat \ " " parinfer - rust - libdir " \ " " ) ) " parinfer - rust -- lib - name ) " ) ) ) ) ) ) ) ) (inputs (list parinfer-rust)) (synopsis "Parinfer-rust-mode aims to be a simpler adaptation of Parinfer for Emacs") (description "") (home-page "-rust-mode") (license license:gpl3))))
13599c2644b1061f7965dabc00c254fdc731a41e3ee944404343ca1bbaaea32f
MailOnline/s-metric
padded_hamming.clj
(ns s-metric.padded-hamming (:require [s-metric.protocols :as p])) (defn pad [s size] "Fill s with filler up to size." (let [padded (str "%-" size "s")] (format padded s))) (defn make-same-size [x y] (cond (= (count x) (count y)) [x y] (> (count x) (count y)) [x (pad y (count x))] (< (count x) (count y)) [(pad x (count y)) y])) (defn distance [s target] "Calculate the hamming distance between s and target, right padding the shortest to the left if necessary." (let [[x y] (make-same-size s target)] (count (filter true? (map (partial reduce not=) (map vector x y)))))) (defn match [_ s target] "Return a matching score as the inverse of the hamming distance." (let [mmax (max (count s) (count target))] (- mmax (if (< (count s) (count target)) (distance s target) (distance target s))))) (defn best-score [_ s target] "Calculate the miminum hamming distance for a n-length string s" (max (count s) (count target))) (deftype HammingDistance []) (extend HammingDistance p/Score (assoc p/ScoreImpl :match #'match :best-score #'best-score))
null
https://raw.githubusercontent.com/MailOnline/s-metric/991c84f3cc1c8c3ac55981f7eb1788385927fba0/src/s_metric/padded_hamming.clj
clojure
(ns s-metric.padded-hamming (:require [s-metric.protocols :as p])) (defn pad [s size] "Fill s with filler up to size." (let [padded (str "%-" size "s")] (format padded s))) (defn make-same-size [x y] (cond (= (count x) (count y)) [x y] (> (count x) (count y)) [x (pad y (count x))] (< (count x) (count y)) [(pad x (count y)) y])) (defn distance [s target] "Calculate the hamming distance between s and target, right padding the shortest to the left if necessary." (let [[x y] (make-same-size s target)] (count (filter true? (map (partial reduce not=) (map vector x y)))))) (defn match [_ s target] "Return a matching score as the inverse of the hamming distance." (let [mmax (max (count s) (count target))] (- mmax (if (< (count s) (count target)) (distance s target) (distance target s))))) (defn best-score [_ s target] "Calculate the miminum hamming distance for a n-length string s" (max (count s) (count target))) (deftype HammingDistance []) (extend HammingDistance p/Score (assoc p/ScoreImpl :match #'match :best-score #'best-score))
63f6eb9dece403c3cbd0d92df66267a855a9260d8077ca2731be070d7a4b16a5
jarvinet/scheme
let.scm
(let ((a 1) (b 2)) (+ a b)) ; The above let is converted into this: ( ( lambda ( a b ) ( + a b ) ) 1 2 )
null
https://raw.githubusercontent.com/jarvinet/scheme/47633d7fc4d82d739a62ceec75c111f6549b1650/bin/test/let.scm
scheme
The above let is converted into this:
(let ((a 1) (b 2)) (+ a b)) ( ( lambda ( a b ) ( + a b ) ) 1 2 )
f3d1d6bd446f8f0ca6454547018e05cc5b0516b5bb3080908cb41eb1a4d6dd29
Kappa-Dev/KappaTools
wrapped_modules.mli
module ParanoCharSet : Map_wrapper.Set_with_logs with type elt = char module ParanoCharMap : Map_wrapper.Map_with_logs with type elt = char module ParanoStringSet : Map_wrapper.Set_with_logs with type elt = string module ParanoStringMap : Map_wrapper.Map_with_logs with type elt = string module ParanoIntSet : Map_wrapper.Set_with_logs with type elt = int module ParanoIntMap : Map_wrapper.Map_with_logs with type elt = int module ParanoInt2Set : Map_wrapper.Set_with_logs with type elt = int * int module ParanoInt2Map : Map_wrapper.Map_with_logs with type elt = int * int module LoggedCharSet : Map_wrapper.Set_with_logs with type elt = char module LoggedCharMap : Map_wrapper.Map_with_logs with type elt = char module LoggedStringSet : Map_wrapper.Set_with_logs with type elt = string module LoggedStringMap : Map_wrapper.Map_with_logs with type elt = string module LoggedIntSet : Map_wrapper.Set_with_logs with type elt = int module LoggedIntMap : Map_wrapper.Map_with_logs with type elt = int module LoggedInt2Set : Map_wrapper.Set_with_logs with type elt = int * int module LoggedInt2Map : Map_wrapper.Map_with_logs with type elt = int * int
null
https://raw.githubusercontent.com/Kappa-Dev/KappaTools/5e756eb3529db9976cf0a0884a22676925985978/core/KaSa_rep/more_datastructures/wrapped_modules.mli
ocaml
module ParanoCharSet : Map_wrapper.Set_with_logs with type elt = char module ParanoCharMap : Map_wrapper.Map_with_logs with type elt = char module ParanoStringSet : Map_wrapper.Set_with_logs with type elt = string module ParanoStringMap : Map_wrapper.Map_with_logs with type elt = string module ParanoIntSet : Map_wrapper.Set_with_logs with type elt = int module ParanoIntMap : Map_wrapper.Map_with_logs with type elt = int module ParanoInt2Set : Map_wrapper.Set_with_logs with type elt = int * int module ParanoInt2Map : Map_wrapper.Map_with_logs with type elt = int * int module LoggedCharSet : Map_wrapper.Set_with_logs with type elt = char module LoggedCharMap : Map_wrapper.Map_with_logs with type elt = char module LoggedStringSet : Map_wrapper.Set_with_logs with type elt = string module LoggedStringMap : Map_wrapper.Map_with_logs with type elt = string module LoggedIntSet : Map_wrapper.Set_with_logs with type elt = int module LoggedIntMap : Map_wrapper.Map_with_logs with type elt = int module LoggedInt2Set : Map_wrapper.Set_with_logs with type elt = int * int module LoggedInt2Map : Map_wrapper.Map_with_logs with type elt = int * int
322711d7aa3a6aaf8859f1894c8c9b48f552e4f8f89e192188d73f7597391b86
jphmrst/bps
ATMSTrun.hs
module ATMSTrun where import Control.Monad.State import Data.TMS.Formatters import Data.TMS.ATMS.ATMST -- Corresponds to Lisp function `book-1` in src/main/lisp/atms/atest.lisp runATMS1 :: IO (Either AtmsErr ()) runATMS1 = do runATMST $ do do atms <- createATMS "Ex1" setInformantStringViaString atms setDatumStringViaString atms debugAtms " Created " atms na <- createNode atms "A" True False debugAtms " Added assumption node A " atms nc <- createNode atms "C" True False debugAtms " Added assumption node C " atms ne <- createNode atms "E" True False debugAtms " Added assumption node E " atms nh <- createNode atms "H" False False debugAtms " Added non - assumption node H " atms justifyNode "R1" nh [nc, ne] debugAtms " After rule R1 " atms ng <- createNode atms "G" False False debugAtms " After non - assumption node G " atms justifyNode "R2" ng [na, nc] debugAtms " After rule R2 " atms nx <- createNode atms "X" False True debugAtms " After contradiction node X " atms justifyNode "R3" nx [ng] debugAtms " After rule R3 " atms nb <- createNode atms "B" True False liftIO $ putStrLn "Added assumption node B" debug atms justifyNode "R4" nh [nb, nc] liftIO $ putStrLn "After rule R4" debug atms liftIO $ putStrLn "----------------------------------------" i1 <- interpretations atms [[na, nc], [nh, ng]] liftIO $ putStrLn "Interpretations for (a, c); (h, g): " forM_ i1 $ debug liftIO $ putStrLn "----------------------------------------" i2 <- interpretations atms [[nh, ng]] liftIO $ putStrLn "Interpretations for (h, g): " forM_ i2 $ debug liftIO $ putStrLn "----------------------------------------" i3 <- interpretations atms [[nh]] liftIO $ putStrLn "Interpretations for (h): " forM_ i3 $ debug do liftIO $ putStrLn "========================================" atms <- createATMS "Ex2" setInformantStringViaString atms setDatumStringViaString atms na <- createNode atms "A" True False nb <- createNode atms "B" True False nc <- createNode atms "C" True False nd <- createNode atms "D" True False ne <- createNode atms "E" True False nf <- createNode atms "F" True False ng <- createNode atms "G" True False nh <- createNode atms "H" True False nm <- createNode atms "M" False False nn <- createNode atms "N" False False np <- createNode atms "P" False False nq <- createNode atms "Q" False False nr <- createNode atms "R" False False ns <- createNode atms "S" False False nk1 <- createNode atms "K1" False False nk2 <- createNode atms "K2" False False nk3 <- createNode atms "K3" False False justifyNode "R01" nm [na, nb] justifyNode "R02" nm [nc, nd] justifyNode "R03" nn [nb, nc] justifyNode "R04" np [nc] justifyNode "R05" nq [nc, nd, ne] justifyNode "R06" nr [nf, ng] justifyNode "R07" ns [nf, nh] justifyNode "R08" nk1 [nm, np] justifyNode "R09" nk1 [nn, nq] justifyNode "R10" nk2 [nn] justifyNode "R11" nk2 [np] justifyNode "R12" nk3 [nn, nq] justifyNode "R13" nk3 [nq, nr, ns] nx <- createNode atms "X" False True justifyNode "X" nx [nc, nf] debug atms liftIO $ putStrLn "----------------------------------------" i3 <- interpretations atms [[nk3]] liftIO $ putStrLn "Interpretations for (k3): " forM_ i3 $ debug
null
https://raw.githubusercontent.com/jphmrst/bps/2bfa66c6a4b6dfdf17e71bae1c1fa4bcfe283a20/src/main/haskell/app/ATMSTrun.hs
haskell
Corresponds to Lisp function `book-1` in src/main/lisp/atms/atest.lisp
module ATMSTrun where import Control.Monad.State import Data.TMS.Formatters import Data.TMS.ATMS.ATMST runATMS1 :: IO (Either AtmsErr ()) runATMS1 = do runATMST $ do do atms <- createATMS "Ex1" setInformantStringViaString atms setDatumStringViaString atms debugAtms " Created " atms na <- createNode atms "A" True False debugAtms " Added assumption node A " atms nc <- createNode atms "C" True False debugAtms " Added assumption node C " atms ne <- createNode atms "E" True False debugAtms " Added assumption node E " atms nh <- createNode atms "H" False False debugAtms " Added non - assumption node H " atms justifyNode "R1" nh [nc, ne] debugAtms " After rule R1 " atms ng <- createNode atms "G" False False debugAtms " After non - assumption node G " atms justifyNode "R2" ng [na, nc] debugAtms " After rule R2 " atms nx <- createNode atms "X" False True debugAtms " After contradiction node X " atms justifyNode "R3" nx [ng] debugAtms " After rule R3 " atms nb <- createNode atms "B" True False liftIO $ putStrLn "Added assumption node B" debug atms justifyNode "R4" nh [nb, nc] liftIO $ putStrLn "After rule R4" debug atms liftIO $ putStrLn "----------------------------------------" i1 <- interpretations atms [[na, nc], [nh, ng]] liftIO $ putStrLn "Interpretations for (a, c); (h, g): " forM_ i1 $ debug liftIO $ putStrLn "----------------------------------------" i2 <- interpretations atms [[nh, ng]] liftIO $ putStrLn "Interpretations for (h, g): " forM_ i2 $ debug liftIO $ putStrLn "----------------------------------------" i3 <- interpretations atms [[nh]] liftIO $ putStrLn "Interpretations for (h): " forM_ i3 $ debug do liftIO $ putStrLn "========================================" atms <- createATMS "Ex2" setInformantStringViaString atms setDatumStringViaString atms na <- createNode atms "A" True False nb <- createNode atms "B" True False nc <- createNode atms "C" True False nd <- createNode atms "D" True False ne <- createNode atms "E" True False nf <- createNode atms "F" True False ng <- createNode atms "G" True False nh <- createNode atms "H" True False nm <- createNode atms "M" False False nn <- createNode atms "N" False False np <- createNode atms "P" False False nq <- createNode atms "Q" False False nr <- createNode atms "R" False False ns <- createNode atms "S" False False nk1 <- createNode atms "K1" False False nk2 <- createNode atms "K2" False False nk3 <- createNode atms "K3" False False justifyNode "R01" nm [na, nb] justifyNode "R02" nm [nc, nd] justifyNode "R03" nn [nb, nc] justifyNode "R04" np [nc] justifyNode "R05" nq [nc, nd, ne] justifyNode "R06" nr [nf, ng] justifyNode "R07" ns [nf, nh] justifyNode "R08" nk1 [nm, np] justifyNode "R09" nk1 [nn, nq] justifyNode "R10" nk2 [nn] justifyNode "R11" nk2 [np] justifyNode "R12" nk3 [nn, nq] justifyNode "R13" nk3 [nq, nr, ns] nx <- createNode atms "X" False True justifyNode "X" nx [nc, nf] debug atms liftIO $ putStrLn "----------------------------------------" i3 <- interpretations atms [[nk3]] liftIO $ putStrLn "Interpretations for (k3): " forM_ i3 $ debug
1a1309656d53a5d03a90f975b917a9687681e239856a7856b567fc5ab84f4423
con-kitty/categorifier-c
Main.hs
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import Categorifier.C.Generate (writeCFiles) import F (fCategorified) -- This generates /tmp/sum_types.c main :: IO () main = writeCFiles "/tmp" "sum_types" fCategorified
null
https://raw.githubusercontent.com/con-kitty/categorifier-c/40b673c955dc5212fc18015ab44378a58e68c1c6/examples/sum-types/Main.hs
haskell
# LANGUAGE OverloadedStrings # This generates /tmp/sum_types.c
module Main (main) where import Categorifier.C.Generate (writeCFiles) import F (fCategorified) main :: IO () main = writeCFiles "/tmp" "sum_types" fCategorified
1602fca6a418c5244b795dea9f4174919f307ad9bef321e185099c03737a0de7
haskell-servant/servant
Docs.hs
# OPTIONS_GHC -fno - warn - orphans # module Servant.Auth.Docs ( -- | The purpose of this package is provide the instance for 'servant-auth' -- combinators needed for 'servant-docs' documentation generation. -- > > > type API = Auth ' [ JWT , Cookie , BasicAuth ] Int :> Get ' [ JSON ] Int > > > putStr $ markdown $ docs ( Proxy : : Proxy API ) # # GET / -- ... -- ... Authentication -- ... -- This part of the API is protected by the following authentication mechanisms: -- ... -- * JSON Web Tokens ([JWTs]()) -- * [Cookies]() -- * [Basic Authentication]() -- ... -- Clients must supply the following data -- ... One of the following : -- ... -- * A JWT Token signed with this server's key -- * Cookies automatically set by browsers, plus a header -- * Cookies automatically set by browsers, plus a header -- ... -- * Re-export JWT , BasicAuth , Cookie , Auth ) where import Control.Lens ((%~), (&), (|>)) import Data.List (intercalate) import Data.Monoid import Data.Proxy (Proxy (Proxy)) import Servant.API hiding (BasicAuth) import Servant.Auth import Servant.Docs hiding (pretty) import Servant.Docs.Internal (DocAuthentication (..), authInfo) instance (AllDocs auths, HasDocs api) => HasDocs (Auth auths r :> api) where docsFor _ (endpoint, action) = docsFor (Proxy :: Proxy api) (endpoint, action & authInfo %~ (|> info)) where (intro, reqData) = pretty $ allDocs (Proxy :: Proxy auths) info = DocAuthentication intro reqData pretty :: [(String, String)] -> (String, String) pretty [] = error "shouldn't happen" pretty [(i, d)] = ( "This part of the API is protected by " <> i , d ) pretty rs = ( "This part of the API is protected by the following authentication mechanisms:\n\n" ++ " * " <> intercalate "\n * " (fst <$> rs) , "\nOne of the following:\n\n" ++ " * " <> intercalate "\n * " (snd <$> rs) ) class AllDocs (x :: [*]) where allDocs :: proxy x intro , req -> [(String, String)] instance (OneDoc a, AllDocs as) => AllDocs (a ': as) where allDocs _ = oneDoc (Proxy :: Proxy a) : allDocs (Proxy :: Proxy as) instance AllDocs '[] where allDocs _ = [] class OneDoc a where oneDoc :: proxy a -> (String, String) instance OneDoc JWT where oneDoc _ = ("JSON Web Tokens ([JWTs]())" , "A JWT Token signed with this server's key") instance OneDoc Cookie where oneDoc _ = ("[Cookies]()" , "Cookies automatically set by browsers, plus a header") instance OneDoc BasicAuth where oneDoc _ = ( "[Basic Authentication]()" , "Cookies automatically set by browsers, plus a header") -- $setup -- >>> instance ToSample Int where toSamples _ = singleSample 1729
null
https://raw.githubusercontent.com/haskell-servant/servant/bd9e4b10900d04bb5a24bcbb8ab2f7246fcd15c7/servant-auth/servant-auth-docs/src/Servant/Auth/Docs.hs
haskell
| The purpose of this package is provide the instance for 'servant-auth' combinators needed for 'servant-docs' documentation generation. ... ... Authentication ... This part of the API is protected by the following authentication mechanisms: ... * JSON Web Tokens ([JWTs]()) * [Cookies]() * [Basic Authentication]() ... Clients must supply the following data ... ... * A JWT Token signed with this server's key * Cookies automatically set by browsers, plus a header * Cookies automatically set by browsers, plus a header ... * Re-export $setup >>> instance ToSample Int where toSamples _ = singleSample 1729
# OPTIONS_GHC -fno - warn - orphans # module Servant.Auth.Docs ( > > > type API = Auth ' [ JWT , Cookie , BasicAuth ] Int :> Get ' [ JSON ] Int > > > putStr $ markdown $ docs ( Proxy : : Proxy API ) # # GET / One of the following : JWT , BasicAuth , Cookie , Auth ) where import Control.Lens ((%~), (&), (|>)) import Data.List (intercalate) import Data.Monoid import Data.Proxy (Proxy (Proxy)) import Servant.API hiding (BasicAuth) import Servant.Auth import Servant.Docs hiding (pretty) import Servant.Docs.Internal (DocAuthentication (..), authInfo) instance (AllDocs auths, HasDocs api) => HasDocs (Auth auths r :> api) where docsFor _ (endpoint, action) = docsFor (Proxy :: Proxy api) (endpoint, action & authInfo %~ (|> info)) where (intro, reqData) = pretty $ allDocs (Proxy :: Proxy auths) info = DocAuthentication intro reqData pretty :: [(String, String)] -> (String, String) pretty [] = error "shouldn't happen" pretty [(i, d)] = ( "This part of the API is protected by " <> i , d ) pretty rs = ( "This part of the API is protected by the following authentication mechanisms:\n\n" ++ " * " <> intercalate "\n * " (fst <$> rs) , "\nOne of the following:\n\n" ++ " * " <> intercalate "\n * " (snd <$> rs) ) class AllDocs (x :: [*]) where allDocs :: proxy x intro , req -> [(String, String)] instance (OneDoc a, AllDocs as) => AllDocs (a ': as) where allDocs _ = oneDoc (Proxy :: Proxy a) : allDocs (Proxy :: Proxy as) instance AllDocs '[] where allDocs _ = [] class OneDoc a where oneDoc :: proxy a -> (String, String) instance OneDoc JWT where oneDoc _ = ("JSON Web Tokens ([JWTs]())" , "A JWT Token signed with this server's key") instance OneDoc Cookie where oneDoc _ = ("[Cookies]()" , "Cookies automatically set by browsers, plus a header") instance OneDoc BasicAuth where oneDoc _ = ( "[Basic Authentication]()" , "Cookies automatically set by browsers, plus a header")
b2e4b624b60b7667b6c1701fe30945c9845061567839cf850f16bac6dfea2d59
janestreet/patdiff
ascii_output.mli
open! Core open! Import include Output.S
null
https://raw.githubusercontent.com/janestreet/patdiff/ffbf5d785addb18fec3df454f256b4978bb5d9df/kernel/src/ascii_output.mli
ocaml
open! Core open! Import include Output.S
8a28226993cd4931cbb155a8286a22d820af5b8c24477ef93af12c95f64372f5
techascent/tech.io
url.clj
(ns tech.v3.io.url (:require [clojure.string :as s]) (:import [java.net URL] [java.io File])) (set! *warn-on-reflection* true) (defn maybe-url [^String url] (re-find #"[A-Za-z0-9]+:\/\/" url) ;;Leaving here to make a point. The below fails for any url that does n't have a scheme registered with the central java url system - such as s3 or azb . #_(try (java.net.URL. url) (catch Exception e nil))) (defn parse-url-arguments [args] (->> (s/split args #"&") (mapv (fn [^String arg-str] (let [eq-sign (.indexOf arg-str "=")] (if (>= eq-sign 0) [(.substring arg-str 0 eq-sign) (.substring arg-str (+ eq-sign 1))] arg-str)))))) (defn url->parts "It is not a great idea to add custom java url protocls as it involves creating a new stream handler and that is a one-off (per-program) operation thus you would potentially conflict with anyone else who did such a thing: -and-using-a-custom-java-net-url-protocol" [url] (let [url (str url) [url args] (let [arg-delimiter (.indexOf url "?")] (if (>= arg-delimiter 0) [(.substring url 0 arg-delimiter) (.substring url (+ arg-delimiter 1))] [url nil])) parts (s/split url #"/") ^String protocol-part (first parts) parts (rest parts) path (if (= 0 (count (first parts))) (rest parts) (throw (ex-info (format "Unrecognized url: %s" url) {:url url}))) args (when args (parse-url-arguments args))] {:protocol (keyword (.substring protocol-part 0 (- (count protocol-part) 1))) :path path :arguments args})) (defn- join-forward-slash ^String [path] (s/join "/" path)) (defn parts->url "Returns a string. Not a java url." ^String [{:keys [protocol path arguments]}] (if arguments (str (name protocol) "://" (join-forward-slash path) "?" (s/join "&" (->> arguments (map (fn [arg] (if (= 2 (count arg)) (str (first arg) "=" (second arg)) arg)))))) (str (name protocol) "://" (join-forward-slash path)))) (defn url? [url] (if (string? url) (when (maybe-url url) (try (:protocol (url->parts url)) (catch Throwable e false))) false)) (defn string-seq->file-path [str-seq] (s/join File/separator str-seq)) (defn parts->file-path ^String [{:keys [protocol path] :as url-parts}] (when-not (= protocol :file) (throw (ex-info "Not a file url" url-parts))) (string-seq->file-path path)) (defn url->file-path [url] (-> (url->parts url) parts->file-path)) (defn extension ^String [^String str-url] (.substring str-url (+ 1 (.lastIndexOf str-url "."))))
null
https://raw.githubusercontent.com/techascent/tech.io/3bb251ff299c239e768c27c0d8ce29f132f7d2a9/src/tech/v3/io/url.clj
clojure
Leaving here to make a point. The below fails for any url
(ns tech.v3.io.url (:require [clojure.string :as s]) (:import [java.net URL] [java.io File])) (set! *warn-on-reflection* true) (defn maybe-url [^String url] (re-find #"[A-Za-z0-9]+:\/\/" url) that does n't have a scheme registered with the central java url system - such as s3 or azb . #_(try (java.net.URL. url) (catch Exception e nil))) (defn parse-url-arguments [args] (->> (s/split args #"&") (mapv (fn [^String arg-str] (let [eq-sign (.indexOf arg-str "=")] (if (>= eq-sign 0) [(.substring arg-str 0 eq-sign) (.substring arg-str (+ eq-sign 1))] arg-str)))))) (defn url->parts "It is not a great idea to add custom java url protocls as it involves creating a new stream handler and that is a one-off (per-program) operation thus you would potentially conflict with anyone else who did such a thing: -and-using-a-custom-java-net-url-protocol" [url] (let [url (str url) [url args] (let [arg-delimiter (.indexOf url "?")] (if (>= arg-delimiter 0) [(.substring url 0 arg-delimiter) (.substring url (+ arg-delimiter 1))] [url nil])) parts (s/split url #"/") ^String protocol-part (first parts) parts (rest parts) path (if (= 0 (count (first parts))) (rest parts) (throw (ex-info (format "Unrecognized url: %s" url) {:url url}))) args (when args (parse-url-arguments args))] {:protocol (keyword (.substring protocol-part 0 (- (count protocol-part) 1))) :path path :arguments args})) (defn- join-forward-slash ^String [path] (s/join "/" path)) (defn parts->url "Returns a string. Not a java url." ^String [{:keys [protocol path arguments]}] (if arguments (str (name protocol) "://" (join-forward-slash path) "?" (s/join "&" (->> arguments (map (fn [arg] (if (= 2 (count arg)) (str (first arg) "=" (second arg)) arg)))))) (str (name protocol) "://" (join-forward-slash path)))) (defn url? [url] (if (string? url) (when (maybe-url url) (try (:protocol (url->parts url)) (catch Throwable e false))) false)) (defn string-seq->file-path [str-seq] (s/join File/separator str-seq)) (defn parts->file-path ^String [{:keys [protocol path] :as url-parts}] (when-not (= protocol :file) (throw (ex-info "Not a file url" url-parts))) (string-seq->file-path path)) (defn url->file-path [url] (-> (url->parts url) parts->file-path)) (defn extension ^String [^String str-url] (.substring str-url (+ 1 (.lastIndexOf str-url "."))))
cf0aa0d6926196c4c1edc08ad8d502bedce0f9b1835631e776bbb4bf1ffba3a1
luceracloud/tachyon-aggregator
tachyon_c.erl
-module(tachyon_c). -export([c/2]). < < _ HostSize:32 / integer , _ / binary , %% _UuidSize:32/integer, _Uuid:_UuidSize/binary, %% _SnapTime:64/integer, _ NameSize:32 / integer , _ Name:_NameSize / binary , %% _ModuleSize:32/integer, _Module:_ModuleSize/binary, %% _ClassSize:32/integer, _Class:_ClassSize/binary, %% _Instance:64/integer, _ / integer , Key:_KeySize / binary _ Type , V:64 / intege > > c(Module, File) -> case file:read_file(File) of {ok, Content} -> case tl_lexer:string(binary_to_list(Content)) of {ok, L, _} -> case tl_parser:parse(L) of {ok, Matches} -> M1 = [c1(Target, lists:map(fun expand/1, Data)) || {Target, Data} <- Matches, Target /= fn], {ok, [header(Module), $\n, M1, "match(_, State) ->\n", mk_target(ignore), ".\n"] ++ [[Data, $\n] || {fn, Data} <- Matches]}; E1 -> {L, E1} end; E2 -> E2 end; E3 -> E3 end. c1(raw, Data) -> Data; c1(Target, Data) -> Data1 = case Target of {_, Ts} -> Data ++ [T || T <- Ts, is_atom(T)] ++ [T || {_, T} <- Ts]; _ -> Data end, Ignore = Target == ignore, Instance = (not proplists:get_bool(instance, Data1)) orelse Ignore, I = " ", R = [ "<<", mk_bin(Data1, host, Ignore), ",\n", I, mk_bin(Data1, uuid, Ignore), ",\n", I, ignore(Ignore), "SnapTime:64/integer,\n", I, mk_bin(Data1, name, Ignore), ",\n", I, mk_bin(Data1, module, Ignore), ",\n", I, mk_bin(Data1, class, Ignore), ",\n", I, ignore(Instance), "Instance:64/integer,\n", I, mk_bin(Data1, key, Ignore), ",\n" ], R1 = case Ignore of true -> R ++ I ++ "_/binary>>"; false -> R ++ I ++ "$i, V:64/integer>>" end, R2 = ["match(", R1, ", State) ->\n", mk_target(Target), ";\n\n"], R2. expand(gz) -> {uuid, "global"}; expand(Other) -> Other. mk_target(ignore) -> " tachyon_mps:provide(),\n" " {ok, State}"; mk_target({Bucket, L}) -> L1 = [mk_elem(E) || E <- L], case [mk_elem(Fn) || Fn = {_, _} <- L] of [] -> [" putb(<<\"", atom_to_list(Bucket), "\">>, [", string:join(L1, ", "), "], " "SnapTime, V, State)"]; FNs -> FNs1 = [["do_ignore(", F, $)] || F <- FNs], [" case ", string:join(FNs1, " orelse ")," of\n" " true -> {ok, State};\n" " _ ->\n" " putb(<<\"", atom_to_list(Bucket), "\">>, [", string:join(L1, ", "), "], " "SnapTime, V, State)\n" " end"] end. mk_elem(instance) -> "integer_to_binary(Instance)"; mk_elem({Fn, A}) when is_atom(A) -> [atom_to_list(Fn), $(, to_cap(atom_to_list(A)), $)]; mk_elem(A) when is_atom(A) -> to_cap(atom_to_list(A)); mk_elem(L) when is_list(L) -> ["<<\"", L, "\">>"]. mk_bin(Data, Key, Ignore) -> case proplists:get_value(Key, Data) of undefined -> mk_bin(atom_to_list(Key), true); true -> mk_bin(to_cap(atom_to_list(Key)), Ignore); Val when is_list(Val) -> mk_bin(Val); Name when is_atom(Name) -> mk_bin(to_cap(atom_to_list(Name)), Ignore) end. mk_bin(Val) -> Size = integer_to_list(length(Val)), [Size, ":32/integer, ", $", Val, $"]. mk_bin(Name, Ignore) -> SizeName = [$_, Name, "Size"], [SizeName, ":32/integer, ", ignore(Ignore), Name, $:, SizeName, "/binary"]. ignore(true) -> $_; ignore(_) -> "". header(Module) -> ["-module(", atom_to_list(Module) ,").\n" "-behaviour(ensq_channel_behaviour).\n" "-record(state, {host, port, connections = #{}}).\n" "-export([init/0, response/2, message/3, error/2]).\n" "init() ->\n" " {ok, {Host, Port}} = application:get_env(tachyon, ddb_ip),\n" " {ok, #state{host = Host, port = Port}}.\n" "response(_Msg, State) ->\n" " {ok, State}.\n" "error(_Msg, State) ->\n" " {ok, State}.\n" "message(M, _, State) ->\n" " match(M, State).\n" "putb(Bucket, Metric, Time, Value,\n" " State = #state{host = H, port = P, connections = Cs}) ->\n" " C1 = case maps:find(Bucket, Cs) of\n" " {ok, C} ->\n" " C;\n" " error ->\n" " {ok, CN0} = ddb_tcp:connect(H, P),\n" " {ok, CN1} = ddb_tcp:stream_mode(Bucket, 2, CN0),\n" " CN1\n" " end,\n" " tachyon_mps:send(),\n" " tachyon_mps:provide(),\n" " tachyon_mps:handle(),\n" " Metric2 = dproto:metric_from_list(Metric),\n" " case ddb_tcp:send(Metric2, Time, mmath_bin:from_list([Value]), C1) of\n" " {ok, C2} ->\n" " Cs1 = maps:put(Bucket, C2, Cs),\n" " {ok, State#state{connections = Cs1}};\n" " {error, _, C2} ->\n" " Cs1 = maps:put(Bucket, C2, Cs),\n" " {ok, State#state{connections = Cs1}}\n" " end.\n" "do_ignore(ignore) -> true;\n" "do_ignore(_) -> false.\n" ]. to_cap([C | R]) -> [C1] = string:to_upper([C]), [C1 | R].
null
https://raw.githubusercontent.com/luceracloud/tachyon-aggregator/1da71c902d974e0d9abb21a3825a9a07f5c0b8da/apps/tachyon/src/tachyon_c.erl
erlang
_UuidSize:32/integer, _Uuid:_UuidSize/binary, _SnapTime:64/integer, _ModuleSize:32/integer, _Module:_ModuleSize/binary, _ClassSize:32/integer, _Class:_ClassSize/binary, _Instance:64/integer,
-module(tachyon_c). -export([c/2]). < < _ HostSize:32 / integer , _ / binary , _ NameSize:32 / integer , _ Name:_NameSize / binary , _ / integer , Key:_KeySize / binary _ Type , V:64 / intege > > c(Module, File) -> case file:read_file(File) of {ok, Content} -> case tl_lexer:string(binary_to_list(Content)) of {ok, L, _} -> case tl_parser:parse(L) of {ok, Matches} -> M1 = [c1(Target, lists:map(fun expand/1, Data)) || {Target, Data} <- Matches, Target /= fn], {ok, [header(Module), $\n, M1, "match(_, State) ->\n", mk_target(ignore), ".\n"] ++ [[Data, $\n] || {fn, Data} <- Matches]}; E1 -> {L, E1} end; E2 -> E2 end; E3 -> E3 end. c1(raw, Data) -> Data; c1(Target, Data) -> Data1 = case Target of {_, Ts} -> Data ++ [T || T <- Ts, is_atom(T)] ++ [T || {_, T} <- Ts]; _ -> Data end, Ignore = Target == ignore, Instance = (not proplists:get_bool(instance, Data1)) orelse Ignore, I = " ", R = [ "<<", mk_bin(Data1, host, Ignore), ",\n", I, mk_bin(Data1, uuid, Ignore), ",\n", I, ignore(Ignore), "SnapTime:64/integer,\n", I, mk_bin(Data1, name, Ignore), ",\n", I, mk_bin(Data1, module, Ignore), ",\n", I, mk_bin(Data1, class, Ignore), ",\n", I, ignore(Instance), "Instance:64/integer,\n", I, mk_bin(Data1, key, Ignore), ",\n" ], R1 = case Ignore of true -> R ++ I ++ "_/binary>>"; false -> R ++ I ++ "$i, V:64/integer>>" end, R2 = ["match(", R1, ", State) ->\n", mk_target(Target), ";\n\n"], R2. expand(gz) -> {uuid, "global"}; expand(Other) -> Other. mk_target(ignore) -> " tachyon_mps:provide(),\n" " {ok, State}"; mk_target({Bucket, L}) -> L1 = [mk_elem(E) || E <- L], case [mk_elem(Fn) || Fn = {_, _} <- L] of [] -> [" putb(<<\"", atom_to_list(Bucket), "\">>, [", string:join(L1, ", "), "], " "SnapTime, V, State)"]; FNs -> FNs1 = [["do_ignore(", F, $)] || F <- FNs], [" case ", string:join(FNs1, " orelse ")," of\n" " true -> {ok, State};\n" " _ ->\n" " putb(<<\"", atom_to_list(Bucket), "\">>, [", string:join(L1, ", "), "], " "SnapTime, V, State)\n" " end"] end. mk_elem(instance) -> "integer_to_binary(Instance)"; mk_elem({Fn, A}) when is_atom(A) -> [atom_to_list(Fn), $(, to_cap(atom_to_list(A)), $)]; mk_elem(A) when is_atom(A) -> to_cap(atom_to_list(A)); mk_elem(L) when is_list(L) -> ["<<\"", L, "\">>"]. mk_bin(Data, Key, Ignore) -> case proplists:get_value(Key, Data) of undefined -> mk_bin(atom_to_list(Key), true); true -> mk_bin(to_cap(atom_to_list(Key)), Ignore); Val when is_list(Val) -> mk_bin(Val); Name when is_atom(Name) -> mk_bin(to_cap(atom_to_list(Name)), Ignore) end. mk_bin(Val) -> Size = integer_to_list(length(Val)), [Size, ":32/integer, ", $", Val, $"]. mk_bin(Name, Ignore) -> SizeName = [$_, Name, "Size"], [SizeName, ":32/integer, ", ignore(Ignore), Name, $:, SizeName, "/binary"]. ignore(true) -> $_; ignore(_) -> "". header(Module) -> ["-module(", atom_to_list(Module) ,").\n" "-behaviour(ensq_channel_behaviour).\n" "-record(state, {host, port, connections = #{}}).\n" "-export([init/0, response/2, message/3, error/2]).\n" "init() ->\n" " {ok, {Host, Port}} = application:get_env(tachyon, ddb_ip),\n" " {ok, #state{host = Host, port = Port}}.\n" "response(_Msg, State) ->\n" " {ok, State}.\n" "error(_Msg, State) ->\n" " {ok, State}.\n" "message(M, _, State) ->\n" " match(M, State).\n" "putb(Bucket, Metric, Time, Value,\n" " State = #state{host = H, port = P, connections = Cs}) ->\n" " C1 = case maps:find(Bucket, Cs) of\n" " {ok, C} ->\n" " C;\n" " error ->\n" " {ok, CN0} = ddb_tcp:connect(H, P),\n" " {ok, CN1} = ddb_tcp:stream_mode(Bucket, 2, CN0),\n" " CN1\n" " end,\n" " tachyon_mps:send(),\n" " tachyon_mps:provide(),\n" " tachyon_mps:handle(),\n" " Metric2 = dproto:metric_from_list(Metric),\n" " case ddb_tcp:send(Metric2, Time, mmath_bin:from_list([Value]), C1) of\n" " {ok, C2} ->\n" " Cs1 = maps:put(Bucket, C2, Cs),\n" " {ok, State#state{connections = Cs1}};\n" " {error, _, C2} ->\n" " Cs1 = maps:put(Bucket, C2, Cs),\n" " {ok, State#state{connections = Cs1}}\n" " end.\n" "do_ignore(ignore) -> true;\n" "do_ignore(_) -> false.\n" ]. to_cap([C | R]) -> [C1] = string:to_upper([C]), [C1 | R].
163464176fb539b05dadcd13f91e5dacd0746d0c763c5d7545f1a5922d5b9577
kupl/LearnML
original.ml
type aexp = | Const of int | Var of string | Power of (string * int) | Times of aexp list | Sum of aexp list let rec reverse (lst : 'b list) : 'a list = match lst with [] -> lst | hd :: tl -> reverse tl @ [ hd ] let rec diff ((exp : aexp), (x : string)) : aexp = match exp with | Const a -> Const 0 | Var a -> if a = x then Const 1 else Var a | Power (a, b) -> if a = x then match b with | 2 -> Times [ Const 2; Var a ] | _ -> Times [ Const b; Power (a, b - 1) ] else Const 0 | Times l -> ( match l with | [] -> Times l | _ -> ( let newList : aexp list = reverse l in match newList with | [] -> Times l | hd :: tl -> Times (diff (hd, x) :: tl) ) ) | Sum l -> ( match l with | [] -> Sum l | hd :: tl -> Sum [ diff (hd, x); diff (Sum tl, x) ] )
null
https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/diff/sub156/original.ml
ocaml
type aexp = | Const of int | Var of string | Power of (string * int) | Times of aexp list | Sum of aexp list let rec reverse (lst : 'b list) : 'a list = match lst with [] -> lst | hd :: tl -> reverse tl @ [ hd ] let rec diff ((exp : aexp), (x : string)) : aexp = match exp with | Const a -> Const 0 | Var a -> if a = x then Const 1 else Var a | Power (a, b) -> if a = x then match b with | 2 -> Times [ Const 2; Var a ] | _ -> Times [ Const b; Power (a, b - 1) ] else Const 0 | Times l -> ( match l with | [] -> Times l | _ -> ( let newList : aexp list = reverse l in match newList with | [] -> Times l | hd :: tl -> Times (diff (hd, x) :: tl) ) ) | Sum l -> ( match l with | [] -> Sum l | hd :: tl -> Sum [ diff (hd, x); diff (Sum tl, x) ] )
a956182f7d32ef34e4e849ac745a0bf37e6a439f404ed70c33b4d42df4ef33ab
somnusand/Poker
metrics_dummy.erl
%%% -*- erlang -*- %%% This file is part of metrics released under the BSD license . %%% See the LICENSE for more information. %%% %%% @doc dummy metric module %%% -module(metrics_dummy). -export([ new/2, delete/1, increment_counter/1, increment_counter/2, decrement_counter/1, decrement_counter/2, update_histogram/2, update_gauge/2, update_meter/2]). new(_, _) -> ok. delete(_) -> ok. increment_counter(_) -> ok. increment_counter(_, _) -> ok. decrement_counter(_) -> ok. decrement_counter(_, _) -> ok. update_histogram(_, Fun) when is_function(Fun, 0) -> Fun(); update_histogram(_, _) -> ok. update_gauge(_, _) -> ok. update_meter(_, _) -> ok.
null
https://raw.githubusercontent.com/somnusand/Poker/4934582a4a37f28c53108a6f6e09b55d21925ffa/server/deps/metrics/src/metrics_dummy.erl
erlang
-*- erlang -*- See the LICENSE for more information. @doc dummy metric module
This file is part of metrics released under the BSD license . -module(metrics_dummy). -export([ new/2, delete/1, increment_counter/1, increment_counter/2, decrement_counter/1, decrement_counter/2, update_histogram/2, update_gauge/2, update_meter/2]). new(_, _) -> ok. delete(_) -> ok. increment_counter(_) -> ok. increment_counter(_, _) -> ok. decrement_counter(_) -> ok. decrement_counter(_, _) -> ok. update_histogram(_, Fun) when is_function(Fun, 0) -> Fun(); update_histogram(_, _) -> ok. update_gauge(_, _) -> ok. update_meter(_, _) -> ok.
beba0259f8269a5964c65b906b2549bc9a409a5a110b9841f623172f8ddc29b1
erszcz/learning
elixir_libs_qwe_mod.erl
-module(elixir_libs_qwe_mod). -compile([export_all]). f() -> ok.
null
https://raw.githubusercontent.com/erszcz/learning/b21c58a09598e2aa5fa8a6909a80c81dc6be1601/erlang-elixir-libs/src/qwe/elixir_libs_qwe_mod.erl
erlang
-module(elixir_libs_qwe_mod). -compile([export_all]). f() -> ok.
eb8cc2e35ff098fee62f3797b8fd634cbf725c149a1aa8364734ea835ab5dcd5
ahrefs/atd
biniou.mli
(** Biniou-specific options derived from ATD annotations. *) type biniou_int = [ `Svint | `Uvint | `Int8 | `Int16 | `Int32 | `Int64 ] type biniou_float = [ `Float32 | `Float64 ] type biniou_list = [ `Array | `Table ] type biniou_field = { biniou_unwrapped : bool } (** Biniou-specific options that decorate each kind of ATD AST node. *) type biniou_repr = | Unit | Bool | Int of biniou_int | Float of biniou_float | String | Sum | Record | Tuple | List of biniou_list | Option | Nullable | Wrap | External | Cell | Field of biniou_field | Variant | Def val annot_schema_biniou : Atd.Annot.schema val get_biniou_float : Atd.Annot.t -> biniou_float val get_biniou_int : Atd.Annot.t -> biniou_int val get_biniou_list : Atd.Annot.t -> biniou_list
null
https://raw.githubusercontent.com/ahrefs/atd/d225acd3d0f6c2acda7c103286874b2541470eb1/atdgen/src/biniou.mli
ocaml
* Biniou-specific options derived from ATD annotations. * Biniou-specific options that decorate each kind of ATD AST node.
type biniou_int = [ `Svint | `Uvint | `Int8 | `Int16 | `Int32 | `Int64 ] type biniou_float = [ `Float32 | `Float64 ] type biniou_list = [ `Array | `Table ] type biniou_field = { biniou_unwrapped : bool } type biniou_repr = | Unit | Bool | Int of biniou_int | Float of biniou_float | String | Sum | Record | Tuple | List of biniou_list | Option | Nullable | Wrap | External | Cell | Field of biniou_field | Variant | Def val annot_schema_biniou : Atd.Annot.schema val get_biniou_float : Atd.Annot.t -> biniou_float val get_biniou_int : Atd.Annot.t -> biniou_int val get_biniou_list : Atd.Annot.t -> biniou_list
82562a75c6845ad97f6d11f86725fdcdc35371e06a4645ecea9de509906becfa
labra/Haws
TestSemantics.hs
module Haws.ShEx.TestSemantics where import Haws.ShEx.Shape import Haws.ShEx.Result import Haws.ShEx.Semantics import Haws.ShEx.Context import Haws.ShEx.Typing hiding (main,tests) import Haws.ShEx.RDFModel import qualified Test.HUnit as Test import Data.Set (Set) import qualified Data.Set as Set import Haws.Monads.BackMonad -- Rules -- rab -- a,b rab :: Rule rab = And (Arc (nameIRI "a") (ValueType xsd_string) noActions) (Arc (nameIRI "b") (ValueType xsd_string) noActions) -- a|b raob :: Rule raob = Or (Arc (nameIRI "a") (ValueType xsd_string) noActions) (Arc (nameIRI "b") (ValueType xsd_string) noActions) -- a?b raqb :: Rule raqb = And (optional (Arc (nameIRI "a") (ValueType xsd_string) noActions)) (Arc (nameIRI "b") (ValueType xsd_string) noActions) -- a?b? raqbq :: Rule raqbq = And (optional (Arc (nameIRI "a") (ValueType xsd_string) noActions)) (optional (Arc (nameIRI "b") (ValueType xsd_string) noActions)) a?b+ raqbp :: Rule raqbp = And (optional (Arc (nameIRI "a") (ValueType xsd_string) noActions)) (OneOrMore (Arc (nameIRI "b") (ValueType xsd_string) noActions)) -- (ab)?c+ r_ab_qcp :: Rule r_ab_qcp = And (optional (And (Arc (nameIRI "a") (ValueType xsd_string) noActions) (Arc (nameIRI "b") (ValueType xsd_string) noActions))) (OneOrMore (Arc (nameIRI "c") (ValueType xsd_string) noActions)) -- Some instances iab :: Set RDFTriple iab = Set.fromList [tripleStr ("x","a","_"), tripleStr ("x","b","_") ] iabb :: Set RDFTriple iabb = Set.fromList [tripleStr ("x","a","_"), tripleStr ("x","b","1"), tripleStr ("x","b","2") ] ia :: Set RDFTriple ia = Set.fromList [ tripleStr ("x","a","_") ] ib :: Set RDFTriple ib = Set.fromList [ tripleStr ("x","b","_") ] ic :: Set RDFTriple ic = Set.fromList [ tripleStr ("x","c","_") ] i0 :: Set RDFTriple i0 = Set.fromList [] iabc :: Set RDFTriple iabc = Set.fromList [ tripleStr ("x","a","_") , tripleStr ("x","b","_") , tripleStr ("x","c","_") ] iabcc :: Set RDFTriple iabcc = Set.fromList [ tripleStr ("x","a","_") , tripleStr ("x","b","_") , tripleStr ("x","c","1") , tripleStr ("x","c","2") ] test_iab_rab = Test.TestCase $ Test.assertBool "iab against rab" $ isPassed $ matchRule ctx iab rab test_i0_rab = Test.TestCase $ Test.assertBool "i0 against rab" $ isFailure $ matchRule ctx i0 rab test_ib_rab = Test.TestCase $ Test.assertBool "ib against rab" $ isFailure $ matchRule ctx ib rab test_ia_rab = Test.TestCase $ Test.assertBool "ia against rab" $ isFailure $ matchRule ctx ia rab -- raob test_iab_raob = Test.TestCase $ Test.assertBool "a,b against a|b" $ isFailure $ matchRule ctx iab raob test_i0_raob = Test.TestCase $ Test.assertBool "() against a|b" $ isFailure $ matchRule ctx i0 raob test_ib_raob = Test.TestCase $ Test.assertBool "b against a|b" $ isPassed $ matchRule ctx ib raob test_ia_raob = Test.TestCase $ Test.assertBool "a against a|b" $ isPassed $ matchRule ctx ia raob raqb test_iab_raqb = Test.TestCase $ Test.assertBool "ab against a?b" $ isPassed $ matchRule ctx iab raqb test_i0_raqb = Test.TestCase $ Test.assertBool "() against a?b" $ isFailure $ matchRule ctx i0 raqb test_ib_raqb = Test.TestCase $ Test.assertBool "b against a?b" $ isPassed $ matchRule ctx ib raqb test_ia_raqb = Test.TestCase $ Test.assertBool "a against a?b" $ isFailure $ matchRule ctx ia raqb raqbq test_iab_raqbq = Test.TestCase $ Test.assertBool "ab against a?b?" $ isPassed $ matchRule ctx iab raqbq test_i0_raqbq = Test.TestCase $ Test.assertBool "() against a?b?" $ isPassed $ matchRule ctx i0 raqbq test_ib_raqbq = Test.TestCase $ Test.assertBool "b against a?b?" $ isPassed $ matchRule ctx ib raqbq test_ia_raqbq = Test.TestCase $ Test.assertBool "a against a?b?" $ isPassed $ matchRule ctx ia raqbq raqbp a?b+ test_iab_raqbp = Test.TestCase $ Test.assertBool "ab against a?b+" $ isPassed $ matchRule ctx iab raqbp test_i0_raqbp = Test.TestCase $ Test.assertBool "() against a?b+" $ isFailure $ matchRule ctx i0 raqbp test_ib_raqbp = Test.TestCase $ Test.assertBool "b against a?b+" $ isPassed $ matchRule ctx ib raqbp test_ia_raqbp = Test.TestCase $ Test.assertBool "a against a?b+" $ isFailure $ matchRule ctx ia raqbp test_iabb_raqbp = Test.TestCase $ Test.assertBool "abb against a?b+" $ isPassed $ matchRule ctx iab raqbp -- r_ab_qcp (ab)?c+ test_iab_r_ab_qcp = Test.TestCase $ Test.assertBool "ab against (ab)?c+" $ isFailure $ matchRule ctx iab r_ab_qcp test_i0_r_ab_qcp = Test.TestCase $ Test.assertBool "() against (ab)?c+" $ isFailure $ matchRule ctx i0 r_ab_qcp test_ib_r_ab_qcp = Test.TestCase $ Test.assertBool "b against (ab)?c+" $ isFailure $ matchRule ctx ib r_ab_qcp test_ia_r_ab_qcp = Test.TestCase $ Test.assertBool "a against (ab)?c+" $ isFailure $ matchRule ctx ia r_ab_qcp test_iabb_r_ab_qcp = Test.TestCase $ Test.assertBool "abb against (ab)?c+" $ isFailure $ matchRule ctx iab r_ab_qcp test_ic_r_ab_qcp = Test.TestCase $ Test.assertBool "c against (ab)?c+" $ isPassed $ matchRule ctx ic r_ab_qcp test_iabc_r_ab_qcp = Test.TestCase $ Test.assertBool "abc against (ab)?c+" $ isPassed $ matchRule ctx iabc r_ab_qcp test_iabcc_r_ab_qcp = Test.TestCase $ Test.assertBool "abcc against (ab)?c+" $ isPassed $ matchRule ctx iabcc r_ab_qcp -- Testing references {- l1 { <a> xsd:string, <b> @<l2> } l2 { <c> xsd:string } -} rl1l2 = ShEx { shapes = [shapel1,shapel2], start = Nothing } shapel1 = Shape { label = mkLabel "l1", rule = And (Arc (nameIRI "a") (ValueType xsd_string) noActions) (Arc (nameIRI "b") (ValueReference (mkLabel "l2")) noActions) } shapel2 = Shape { label = mkLabel "l2", rule = Arc (nameIRI "c") (ValueType xsd_string) noActions } g1 = RDFGraph $ Set.fromList [ tripleStr ("x","a","_"), tripleIRIs ("x","b","y"), tripleStr ("y","c","_") ] ctxg1_l1l2 = Context { graph = g1, shEx = rl1l2, typing = emptyTyping } test_x_l1_rl1l2 = Test.TestCase $ Test.assertBool "x against shapel1 in rl1l2 and graph g1" $ isPassed $ matchIRI ctxg1_l1l2 (IRI "x") (shapel1) test_x_l2_rl1l2 = Test.TestCase $ Test.assertBool "x against shapel2 in rl1l2 and graph g1" $ isFailure $ matchIRI ctxg1_l1l2 (IRI "x") (shapel2) test_y_l1_rl1l2 = Test.TestCase $ Test.assertBool "y against shapel1 in rl1l2 and graph g1" $ isFailure $ matchIRI ctxg1_l1l2 (IRI "y") (shapel1) test_y_l2_rl1l2 = Test.TestCase $ Test.assertBool "y against shapel2 in rl1l2 and graph g1" $ isPassed $ matchIRI ctxg1_l1l2 (IRI "y") (shapel2) ---------------------------------------------------- ctx = Context { graph = RDFGraph (Set.fromList []), shEx = ShEx { shapes = [], start = Nothing }, typing = emptyTyping } --- tests = Test.TestList [ test_iab_rab , test_ia_rab , test_ib_rab , test_i0_rab , test_iab_raob , test_ia_raob , test_ib_raob , test_i0_raob , test_iab_raqb , test_ia_raqb , test_ib_raqb , test_i0_raqb , test_iab_raqbq , test_ia_raqbq , test_ib_raqbq , test_i0_raqbq , test_iab_raqbp , test_ia_raqbp , test_ib_raqbp , test_i0_raqbp , test_iabb_raqbp , test_iab_r_ab_qcp , test_ia_r_ab_qcp , test_ib_r_ab_qcp , test_i0_r_ab_qcp , test_iabb_r_ab_qcp , test_ic_r_ab_qcp , test_iabc_r_ab_qcp , test_iabcc_r_ab_qcp , test_x_l1_rl1l2 , test_x_l2_rl1l2 , test_y_l1_rl1l2 , test_y_l2_rl1l2 ] main = Test.runTestTT tests
null
https://raw.githubusercontent.com/labra/Haws/2417adc37522994e2bbb8e9e397481a1f6f4f038/src/Haws/ShEx/TestSemantics.hs
haskell
Rules rab a,b a|b a?b a?b? (ab)?c+ Some instances raob r_ab_qcp (ab)?c+ Testing references l1 { <a> xsd:string, <b> @<l2> } l2 { <c> xsd:string } -------------------------------------------------- -
module Haws.ShEx.TestSemantics where import Haws.ShEx.Shape import Haws.ShEx.Result import Haws.ShEx.Semantics import Haws.ShEx.Context import Haws.ShEx.Typing hiding (main,tests) import Haws.ShEx.RDFModel import qualified Test.HUnit as Test import Data.Set (Set) import qualified Data.Set as Set import Haws.Monads.BackMonad rab :: Rule rab = And (Arc (nameIRI "a") (ValueType xsd_string) noActions) (Arc (nameIRI "b") (ValueType xsd_string) noActions) raob :: Rule raob = Or (Arc (nameIRI "a") (ValueType xsd_string) noActions) (Arc (nameIRI "b") (ValueType xsd_string) noActions) raqb :: Rule raqb = And (optional (Arc (nameIRI "a") (ValueType xsd_string) noActions)) (Arc (nameIRI "b") (ValueType xsd_string) noActions) raqbq :: Rule raqbq = And (optional (Arc (nameIRI "a") (ValueType xsd_string) noActions)) (optional (Arc (nameIRI "b") (ValueType xsd_string) noActions)) a?b+ raqbp :: Rule raqbp = And (optional (Arc (nameIRI "a") (ValueType xsd_string) noActions)) (OneOrMore (Arc (nameIRI "b") (ValueType xsd_string) noActions)) r_ab_qcp :: Rule r_ab_qcp = And (optional (And (Arc (nameIRI "a") (ValueType xsd_string) noActions) (Arc (nameIRI "b") (ValueType xsd_string) noActions))) (OneOrMore (Arc (nameIRI "c") (ValueType xsd_string) noActions)) iab :: Set RDFTriple iab = Set.fromList [tripleStr ("x","a","_"), tripleStr ("x","b","_") ] iabb :: Set RDFTriple iabb = Set.fromList [tripleStr ("x","a","_"), tripleStr ("x","b","1"), tripleStr ("x","b","2") ] ia :: Set RDFTriple ia = Set.fromList [ tripleStr ("x","a","_") ] ib :: Set RDFTriple ib = Set.fromList [ tripleStr ("x","b","_") ] ic :: Set RDFTriple ic = Set.fromList [ tripleStr ("x","c","_") ] i0 :: Set RDFTriple i0 = Set.fromList [] iabc :: Set RDFTriple iabc = Set.fromList [ tripleStr ("x","a","_") , tripleStr ("x","b","_") , tripleStr ("x","c","_") ] iabcc :: Set RDFTriple iabcc = Set.fromList [ tripleStr ("x","a","_") , tripleStr ("x","b","_") , tripleStr ("x","c","1") , tripleStr ("x","c","2") ] test_iab_rab = Test.TestCase $ Test.assertBool "iab against rab" $ isPassed $ matchRule ctx iab rab test_i0_rab = Test.TestCase $ Test.assertBool "i0 against rab" $ isFailure $ matchRule ctx i0 rab test_ib_rab = Test.TestCase $ Test.assertBool "ib against rab" $ isFailure $ matchRule ctx ib rab test_ia_rab = Test.TestCase $ Test.assertBool "ia against rab" $ isFailure $ matchRule ctx ia rab test_iab_raob = Test.TestCase $ Test.assertBool "a,b against a|b" $ isFailure $ matchRule ctx iab raob test_i0_raob = Test.TestCase $ Test.assertBool "() against a|b" $ isFailure $ matchRule ctx i0 raob test_ib_raob = Test.TestCase $ Test.assertBool "b against a|b" $ isPassed $ matchRule ctx ib raob test_ia_raob = Test.TestCase $ Test.assertBool "a against a|b" $ isPassed $ matchRule ctx ia raob raqb test_iab_raqb = Test.TestCase $ Test.assertBool "ab against a?b" $ isPassed $ matchRule ctx iab raqb test_i0_raqb = Test.TestCase $ Test.assertBool "() against a?b" $ isFailure $ matchRule ctx i0 raqb test_ib_raqb = Test.TestCase $ Test.assertBool "b against a?b" $ isPassed $ matchRule ctx ib raqb test_ia_raqb = Test.TestCase $ Test.assertBool "a against a?b" $ isFailure $ matchRule ctx ia raqb raqbq test_iab_raqbq = Test.TestCase $ Test.assertBool "ab against a?b?" $ isPassed $ matchRule ctx iab raqbq test_i0_raqbq = Test.TestCase $ Test.assertBool "() against a?b?" $ isPassed $ matchRule ctx i0 raqbq test_ib_raqbq = Test.TestCase $ Test.assertBool "b against a?b?" $ isPassed $ matchRule ctx ib raqbq test_ia_raqbq = Test.TestCase $ Test.assertBool "a against a?b?" $ isPassed $ matchRule ctx ia raqbq raqbp a?b+ test_iab_raqbp = Test.TestCase $ Test.assertBool "ab against a?b+" $ isPassed $ matchRule ctx iab raqbp test_i0_raqbp = Test.TestCase $ Test.assertBool "() against a?b+" $ isFailure $ matchRule ctx i0 raqbp test_ib_raqbp = Test.TestCase $ Test.assertBool "b against a?b+" $ isPassed $ matchRule ctx ib raqbp test_ia_raqbp = Test.TestCase $ Test.assertBool "a against a?b+" $ isFailure $ matchRule ctx ia raqbp test_iabb_raqbp = Test.TestCase $ Test.assertBool "abb against a?b+" $ isPassed $ matchRule ctx iab raqbp test_iab_r_ab_qcp = Test.TestCase $ Test.assertBool "ab against (ab)?c+" $ isFailure $ matchRule ctx iab r_ab_qcp test_i0_r_ab_qcp = Test.TestCase $ Test.assertBool "() against (ab)?c+" $ isFailure $ matchRule ctx i0 r_ab_qcp test_ib_r_ab_qcp = Test.TestCase $ Test.assertBool "b against (ab)?c+" $ isFailure $ matchRule ctx ib r_ab_qcp test_ia_r_ab_qcp = Test.TestCase $ Test.assertBool "a against (ab)?c+" $ isFailure $ matchRule ctx ia r_ab_qcp test_iabb_r_ab_qcp = Test.TestCase $ Test.assertBool "abb against (ab)?c+" $ isFailure $ matchRule ctx iab r_ab_qcp test_ic_r_ab_qcp = Test.TestCase $ Test.assertBool "c against (ab)?c+" $ isPassed $ matchRule ctx ic r_ab_qcp test_iabc_r_ab_qcp = Test.TestCase $ Test.assertBool "abc against (ab)?c+" $ isPassed $ matchRule ctx iabc r_ab_qcp test_iabcc_r_ab_qcp = Test.TestCase $ Test.assertBool "abcc against (ab)?c+" $ isPassed $ matchRule ctx iabcc r_ab_qcp rl1l2 = ShEx { shapes = [shapel1,shapel2], start = Nothing } shapel1 = Shape { label = mkLabel "l1", rule = And (Arc (nameIRI "a") (ValueType xsd_string) noActions) (Arc (nameIRI "b") (ValueReference (mkLabel "l2")) noActions) } shapel2 = Shape { label = mkLabel "l2", rule = Arc (nameIRI "c") (ValueType xsd_string) noActions } g1 = RDFGraph $ Set.fromList [ tripleStr ("x","a","_"), tripleIRIs ("x","b","y"), tripleStr ("y","c","_") ] ctxg1_l1l2 = Context { graph = g1, shEx = rl1l2, typing = emptyTyping } test_x_l1_rl1l2 = Test.TestCase $ Test.assertBool "x against shapel1 in rl1l2 and graph g1" $ isPassed $ matchIRI ctxg1_l1l2 (IRI "x") (shapel1) test_x_l2_rl1l2 = Test.TestCase $ Test.assertBool "x against shapel2 in rl1l2 and graph g1" $ isFailure $ matchIRI ctxg1_l1l2 (IRI "x") (shapel2) test_y_l1_rl1l2 = Test.TestCase $ Test.assertBool "y against shapel1 in rl1l2 and graph g1" $ isFailure $ matchIRI ctxg1_l1l2 (IRI "y") (shapel1) test_y_l2_rl1l2 = Test.TestCase $ Test.assertBool "y against shapel2 in rl1l2 and graph g1" $ isPassed $ matchIRI ctxg1_l1l2 (IRI "y") (shapel2) ctx = Context { graph = RDFGraph (Set.fromList []), shEx = ShEx { shapes = [], start = Nothing }, typing = emptyTyping } tests = Test.TestList [ test_iab_rab , test_ia_rab , test_ib_rab , test_i0_rab , test_iab_raob , test_ia_raob , test_ib_raob , test_i0_raob , test_iab_raqb , test_ia_raqb , test_ib_raqb , test_i0_raqb , test_iab_raqbq , test_ia_raqbq , test_ib_raqbq , test_i0_raqbq , test_iab_raqbp , test_ia_raqbp , test_ib_raqbp , test_i0_raqbp , test_iabb_raqbp , test_iab_r_ab_qcp , test_ia_r_ab_qcp , test_ib_r_ab_qcp , test_i0_r_ab_qcp , test_iabb_r_ab_qcp , test_ic_r_ab_qcp , test_iabc_r_ab_qcp , test_iabcc_r_ab_qcp , test_x_l1_rl1l2 , test_x_l2_rl1l2 , test_y_l1_rl1l2 , test_y_l2_rl1l2 ] main = Test.runTestTT tests
630988ca44b32b58ad60d8b86fe1515614ab9a1e819820a53232d45c255de9e0
imdea-software/leap
ParamInv.ml
(***********************************************************************) (* *) LEAP (* *) , IMDEA Software Institute (* *) (* *) Copyright 2011 IMDEA Software Institute (* *) 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. *) (* *) (***********************************************************************) open LeapLib module E = Expression module PE = PosExpression module type S = sig exception No_invariant_folder val gen_from_graph : IGraph.t -> Core.proof_obligation_t list val solve_from_graph : IGraph.t -> Core.solved_proof_obligation_t list end module Make (C:Core.S) : S = struct module Eparser = ExprParser module Elexer = ExprLexer exception No_invariant_folder (* General Initialization premise *) let premise_init ?(inv_id="") (inv:E.formula) : Tactics.vc_info = let inv_voc = E.voc inv in let (new_voc, new_inv) = if E.ThreadSet.is_empty inv_voc then let new_t = E.gen_fresh_tid_as_var inv_voc in let new_i = E.param (E.V.Local new_t) inv in (E.ThreadSet.singleton (E.VarTh new_t), new_i) else (inv_voc, inv) in let (initial_cond, voc) = C.theta new_voc in Tactics.create_vc_info [] Tactics.no_tid_constraint initial_cond new_inv voc E.NoTid 0 ~tag:(Tag.new_tag inv_id "") (**********************) (* CONCURRENT SPINV *) (**********************) let gen_vcs ?(inv_id="") (supp:E.formula list) (inv:E.formula) (line:int) (premise:Premise.t) (trans_tid:E.tid) : Tactics.vc_info list = (*********************** TESTING *************************) (* This adds threads identifiers belonging to the support, *) (* which I should not add until instantiating the support *) (* later as part of the tactics. *) (***********************************************************) let voc = E.voc ( Formula.conj_list ( inv::supp ) ) in (*********************** TESTING *************************) let voc = E.voc inv in let rho = C.rho System.Concurrent voc line trans_tid in let tid_constraint = match premise with | Premise.SelfConseq -> Tactics.no_tid_constraint | Premise.OthersConseq -> begin let ineqs = E.ThreadSet.fold (fun t xs -> (trans_tid,t)::xs ) voc [] in Tactics.new_tid_constraint [] ineqs end in List.fold_left (fun rs phi -> Log.print "Create with support" (String.concat "\n" (List.map E.formula_to_str supp)); let new_vc = Tactics.create_vc_info supp tid_constraint phi inv voc trans_tid line ~tag:(Tag.new_tag inv_id "") in new_vc :: rs ) [] rho let spinv_transitions ?(inv_id="") (supp:E.formula list) (inv:E.formula) (cases:IGraph.case_tbl_t) : Tactics.vc_info list = let load_support (line:E.pc_t) (prem:Premise.t) : E.formula list = match IGraph.lookup_case cases line prem with | None -> supp | Some (supp_tags,_) -> C.read_tags_and_group_by_file Core.Inv supp_tags in List.fold_left (fun vcs line -> let self_conseq_supp = load_support line Premise.SelfConseq in let other_conseq_supp = load_support line Premise.OthersConseq in let fresh_k = E.gen_fresh_tid (E.voc (Formula.conj_list (inv::supp@other_conseq_supp))) in let self_conseq_vcs = E.ThreadSet.fold (fun i vcs -> (gen_vcs (inv::self_conseq_supp) inv line Premise.SelfConseq i ~inv_id:inv_id ) @ vcs ) (System.filter_me_tid (E.voc inv)) [] in let other_conseq_vcs = gen_vcs (inv::other_conseq_supp) inv line Premise.OthersConseq fresh_k ~inv_id:inv_id in vcs @ self_conseq_vcs @ other_conseq_vcs ) [] C.lines_to_consider let spinv_with_cases ?(inv_id="") (supp:E.formula list) (inv:E.formula) (cases:IGraph.case_tbl_t) : Tactics.vc_info list = let initiation = if C.requires_theta then [premise_init inv ~inv_id:inv_id] else [] in let transitions = spinv_transitions supp inv cases ~inv_id:inv_id in initiation @ transitions let spinv ?(inv_id="") (supp:E.formula list) (inv:E.formula) : Tactics.vc_info list = spinv_with_cases supp inv (IGraph.empty_case_tbl()) ~inv_id:inv_id (**********************) SEQUENTIAL SPINV (**********************) let seq_gen_vcs ?(inv_id="") (supp:E.formula list) (inv:E.formula) (line:int) (trans_tid:E.tid) : Tactics.vc_info list = let trans_var = E.voc_to_var trans_tid in let voc = E.voc (Formula.conj_list (inv::supp)) in let rho = C.rho System.Sequential voc line trans_tid in let supp = List.map (E.param (E.V.Local trans_var)) supp in let inv = if E.ThreadSet.is_empty (E.voc inv) then E.param (E.V.Local trans_var) inv else inv in List.fold_left (fun rs phi -> let new_vc = Tactics.create_vc_info supp Tactics.no_tid_constraint phi inv voc trans_tid line ~tag:(Tag.new_tag inv_id "") in new_vc :: rs ) [] rho let seq_spinv_transitions ?(inv_id="") (supp:E.formula list) (inv:E.formula) (cases:IGraph.case_tbl_t) : Tactics.vc_info list = let inv_voc = E.voc inv in let trans_tid = if E.ThreadSet.is_empty inv_voc then E.gen_fresh_tid E.ThreadSet.empty else try E.ThreadSet.choose inv_voc with Not_found -> assert false in ALE : More than one thread parametrizing the invariant List.fold_left (fun vcs line -> let specific_supp = match IGraph.lookup_case cases line Premise.SelfConseq with | None -> supp | Some (supp_tags, _) -> C.read_tags_and_group_by_file Core.Inv supp_tags in vcs @ seq_gen_vcs (inv::specific_supp) inv line trans_tid ~inv_id:inv_id ) [] C.lines_to_consider let seq_spinv_with_cases ?(inv_id="") (supp:E.formula list) (inv:E.formula) (cases:IGraph.case_tbl_t) : Tactics.vc_info list = let supp = inv :: supp in let initiation = if C.requires_theta then [premise_init inv ~inv_id:inv_id] else [] in let transitions = seq_spinv_transitions supp inv cases ~inv_id:inv_id in initiation @ transitions let seq_spinv ?(inv_id="") (supp:E.formula list) (inv:E.formula) : Tactics.vc_info list = seq_spinv_with_cases supp inv (IGraph.empty_case_tbl()) ~inv_id:inv_id (***************************************************) (* PROOF GRAPH ANALYSIS *) (***************************************************) let check_well_defined_graph (graph:IGraph.t) : unit = let graph_tags = IGraph.graph_tags graph in let undef_tags = List.filter (fun t -> not (C.is_def_tag t)) graph_tags in if undef_tags <> [] then begin let undef_t = Tag.tag_id (List.hd undef_tags) in Interface.Err.msg "Undefined tag" $ Printf.sprintf "Tag %s was used in the invariant graph \ but it could not be read from the invariant folder." undef_t; raise(Tag.Undefined_tag undef_t) end let generate_obligations (vcs:Tactics.vc_info list) (gral_plan:Tactics.proof_plan) (cases:IGraph.case_tbl_t) : Core.proof_obligation_t list = let vc_count = ref 1 in let show_progress = not ( LeapVerbose.is_verbose_enabled ( ) ) in let show_progress = not (LeapVerbose.is_verbose_enabled()) in *) Progress.init (List.length vcs); List.fold_left (fun res vc -> (* Ale: for lists let vc = Tactics.to_plain_vc_info E.PCVars vc in *) let prem = if Tactics.is_empty_tid_constraint (Tactics.get_tid_constraint_from_info vc) then Premise.SelfConseq else Premise.OthersConseq in let line = Tactics.get_line_from_info vc in let (obligations,cutoff) = match IGraph.lookup_case cases line prem with | None -> (Tactics.apply_tactics_from_proof_plan [vc] gral_plan, Tactics.get_cutoff gral_plan) | Some (_,p) -> let joint_plan = if Tactics.is_empty_proof_plan p then gral_plan else p in (Tactics.apply_tactics_from_proof_plan [vc] joint_plan, Tactics.get_cutoff joint_plan) in let proof_info = C.new_proof_info cutoff in let proof_obligation = C.new_proof_obligation vc obligations proof_info in (* if show_progress then (Progress.current !vc_count; incr vc_count); *) proof_obligation :: res ) [] vcs let gen_from_graph (graph:IGraph.t) : Core.proof_obligation_t list = check_well_defined_graph graph; (* Process the graph *) let graph_info = IGraph.graph_info graph in List.fold_left (fun os (mode, suppTags, invTag, cases, plan) -> let supp_ids = String.concat "," $ List.map Tag.tag_id suppTags in let inv_id = Tag.tag_id invTag in let supp = C.read_tags_and_group_by_file Core.Inv suppTags in let inv = C.read_tag Core.Inv invTag in let vc_info_list = match mode with | IGraph.Concurrent -> if LeapVerbose.is_verbose_enabled() then LeapVerbose.verbstr ("Concurrent problem for invariant " ^inv_id^ " using as support [" ^supp_ids^ "]" ^ " with " ^string_of_int (IGraph.num_of_cases cases)^ " special cases.\n") else print_endline ("Generating verification conditions for " ^ inv_id); spinv_with_cases supp inv cases ~inv_id:inv_id | IGraph.Sequential -> if LeapVerbose.is_verbose_enabled() then LeapVerbose.verbstr ("Sequential problem for invariant " ^inv_id^ " using as support [" ^supp_ids^ "]" ^ " with " ^string_of_int (IGraph.num_of_cases cases)^ " special cases.\n") else print_endline ("Generating verification conditions for " ^ inv_id); seq_spinv_with_cases supp inv cases ~inv_id:inv_id in C.report_vcs vc_info_list; let new_obligations = generate_obligations vc_info_list plan cases in let obligations_num = List.fold_left (fun n po -> n + (List.length (C.obligations po)) ) 0 new_obligations in if (not (LeapVerbose.is_verbose_enabled())) then print_endline ("Generated: " ^ (string_of_int (List.length vc_info_list)) ^ " VC with " ^(string_of_int obligations_num) ^ " proofs obligations\n") else if LeapVerbose.is_verbose_level_enabled(LeapVerbose._SHORT_INFO) then Report.report_generated_vcs vc_info_list obligations_num; os @ new_obligations ) [] graph_info let solve_from_graph (graph:IGraph.t) : Core.solved_proof_obligation_t list = (* gen_from_graph graph; [] *) C.solve_proof_obligations (gen_from_graph graph) end
null
https://raw.githubusercontent.com/imdea-software/leap/5f946163c0f80ff9162db605a75b7ce2e27926ef/src/paraminv/ParamInv.ml
ocaml
********************************************************************* You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, either express or implied. See the License for the specific language governing permissions and limitations under the License. ********************************************************************* General Initialization premise ******************** CONCURRENT SPINV ******************** ********************** TESTING ************************ This adds threads identifiers belonging to the support, which I should not add until instantiating the support later as part of the tactics. ********************************************************* ********************** TESTING ************************ ******************** ******************** ************************************************* PROOF GRAPH ANALYSIS ************************************************* Ale: for lists let vc = Tactics.to_plain_vc_info E.PCVars vc in if show_progress then (Progress.current !vc_count; incr vc_count); Process the graph gen_from_graph graph; []
LEAP , IMDEA Software Institute Copyright 2011 IMDEA Software Institute Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not use this file except in compliance with the License . software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND , open LeapLib module E = Expression module PE = PosExpression module type S = sig exception No_invariant_folder val gen_from_graph : IGraph.t -> Core.proof_obligation_t list val solve_from_graph : IGraph.t -> Core.solved_proof_obligation_t list end module Make (C:Core.S) : S = struct module Eparser = ExprParser module Elexer = ExprLexer exception No_invariant_folder let premise_init ?(inv_id="") (inv:E.formula) : Tactics.vc_info = let inv_voc = E.voc inv in let (new_voc, new_inv) = if E.ThreadSet.is_empty inv_voc then let new_t = E.gen_fresh_tid_as_var inv_voc in let new_i = E.param (E.V.Local new_t) inv in (E.ThreadSet.singleton (E.VarTh new_t), new_i) else (inv_voc, inv) in let (initial_cond, voc) = C.theta new_voc in Tactics.create_vc_info [] Tactics.no_tid_constraint initial_cond new_inv voc E.NoTid 0 ~tag:(Tag.new_tag inv_id "") let gen_vcs ?(inv_id="") (supp:E.formula list) (inv:E.formula) (line:int) (premise:Premise.t) (trans_tid:E.tid) : Tactics.vc_info list = let voc = E.voc ( Formula.conj_list ( inv::supp ) ) in let voc = E.voc inv in let rho = C.rho System.Concurrent voc line trans_tid in let tid_constraint = match premise with | Premise.SelfConseq -> Tactics.no_tid_constraint | Premise.OthersConseq -> begin let ineqs = E.ThreadSet.fold (fun t xs -> (trans_tid,t)::xs ) voc [] in Tactics.new_tid_constraint [] ineqs end in List.fold_left (fun rs phi -> Log.print "Create with support" (String.concat "\n" (List.map E.formula_to_str supp)); let new_vc = Tactics.create_vc_info supp tid_constraint phi inv voc trans_tid line ~tag:(Tag.new_tag inv_id "") in new_vc :: rs ) [] rho let spinv_transitions ?(inv_id="") (supp:E.formula list) (inv:E.formula) (cases:IGraph.case_tbl_t) : Tactics.vc_info list = let load_support (line:E.pc_t) (prem:Premise.t) : E.formula list = match IGraph.lookup_case cases line prem with | None -> supp | Some (supp_tags,_) -> C.read_tags_and_group_by_file Core.Inv supp_tags in List.fold_left (fun vcs line -> let self_conseq_supp = load_support line Premise.SelfConseq in let other_conseq_supp = load_support line Premise.OthersConseq in let fresh_k = E.gen_fresh_tid (E.voc (Formula.conj_list (inv::supp@other_conseq_supp))) in let self_conseq_vcs = E.ThreadSet.fold (fun i vcs -> (gen_vcs (inv::self_conseq_supp) inv line Premise.SelfConseq i ~inv_id:inv_id ) @ vcs ) (System.filter_me_tid (E.voc inv)) [] in let other_conseq_vcs = gen_vcs (inv::other_conseq_supp) inv line Premise.OthersConseq fresh_k ~inv_id:inv_id in vcs @ self_conseq_vcs @ other_conseq_vcs ) [] C.lines_to_consider let spinv_with_cases ?(inv_id="") (supp:E.formula list) (inv:E.formula) (cases:IGraph.case_tbl_t) : Tactics.vc_info list = let initiation = if C.requires_theta then [premise_init inv ~inv_id:inv_id] else [] in let transitions = spinv_transitions supp inv cases ~inv_id:inv_id in initiation @ transitions let spinv ?(inv_id="") (supp:E.formula list) (inv:E.formula) : Tactics.vc_info list = spinv_with_cases supp inv (IGraph.empty_case_tbl()) ~inv_id:inv_id SEQUENTIAL SPINV let seq_gen_vcs ?(inv_id="") (supp:E.formula list) (inv:E.formula) (line:int) (trans_tid:E.tid) : Tactics.vc_info list = let trans_var = E.voc_to_var trans_tid in let voc = E.voc (Formula.conj_list (inv::supp)) in let rho = C.rho System.Sequential voc line trans_tid in let supp = List.map (E.param (E.V.Local trans_var)) supp in let inv = if E.ThreadSet.is_empty (E.voc inv) then E.param (E.V.Local trans_var) inv else inv in List.fold_left (fun rs phi -> let new_vc = Tactics.create_vc_info supp Tactics.no_tid_constraint phi inv voc trans_tid line ~tag:(Tag.new_tag inv_id "") in new_vc :: rs ) [] rho let seq_spinv_transitions ?(inv_id="") (supp:E.formula list) (inv:E.formula) (cases:IGraph.case_tbl_t) : Tactics.vc_info list = let inv_voc = E.voc inv in let trans_tid = if E.ThreadSet.is_empty inv_voc then E.gen_fresh_tid E.ThreadSet.empty else try E.ThreadSet.choose inv_voc with Not_found -> assert false in ALE : More than one thread parametrizing the invariant List.fold_left (fun vcs line -> let specific_supp = match IGraph.lookup_case cases line Premise.SelfConseq with | None -> supp | Some (supp_tags, _) -> C.read_tags_and_group_by_file Core.Inv supp_tags in vcs @ seq_gen_vcs (inv::specific_supp) inv line trans_tid ~inv_id:inv_id ) [] C.lines_to_consider let seq_spinv_with_cases ?(inv_id="") (supp:E.formula list) (inv:E.formula) (cases:IGraph.case_tbl_t) : Tactics.vc_info list = let supp = inv :: supp in let initiation = if C.requires_theta then [premise_init inv ~inv_id:inv_id] else [] in let transitions = seq_spinv_transitions supp inv cases ~inv_id:inv_id in initiation @ transitions let seq_spinv ?(inv_id="") (supp:E.formula list) (inv:E.formula) : Tactics.vc_info list = seq_spinv_with_cases supp inv (IGraph.empty_case_tbl()) ~inv_id:inv_id let check_well_defined_graph (graph:IGraph.t) : unit = let graph_tags = IGraph.graph_tags graph in let undef_tags = List.filter (fun t -> not (C.is_def_tag t)) graph_tags in if undef_tags <> [] then begin let undef_t = Tag.tag_id (List.hd undef_tags) in Interface.Err.msg "Undefined tag" $ Printf.sprintf "Tag %s was used in the invariant graph \ but it could not be read from the invariant folder." undef_t; raise(Tag.Undefined_tag undef_t) end let generate_obligations (vcs:Tactics.vc_info list) (gral_plan:Tactics.proof_plan) (cases:IGraph.case_tbl_t) : Core.proof_obligation_t list = let vc_count = ref 1 in let show_progress = not ( LeapVerbose.is_verbose_enabled ( ) ) in let show_progress = not (LeapVerbose.is_verbose_enabled()) in *) Progress.init (List.length vcs); List.fold_left (fun res vc -> let prem = if Tactics.is_empty_tid_constraint (Tactics.get_tid_constraint_from_info vc) then Premise.SelfConseq else Premise.OthersConseq in let line = Tactics.get_line_from_info vc in let (obligations,cutoff) = match IGraph.lookup_case cases line prem with | None -> (Tactics.apply_tactics_from_proof_plan [vc] gral_plan, Tactics.get_cutoff gral_plan) | Some (_,p) -> let joint_plan = if Tactics.is_empty_proof_plan p then gral_plan else p in (Tactics.apply_tactics_from_proof_plan [vc] joint_plan, Tactics.get_cutoff joint_plan) in let proof_info = C.new_proof_info cutoff in let proof_obligation = C.new_proof_obligation vc obligations proof_info in proof_obligation :: res ) [] vcs let gen_from_graph (graph:IGraph.t) : Core.proof_obligation_t list = check_well_defined_graph graph; let graph_info = IGraph.graph_info graph in List.fold_left (fun os (mode, suppTags, invTag, cases, plan) -> let supp_ids = String.concat "," $ List.map Tag.tag_id suppTags in let inv_id = Tag.tag_id invTag in let supp = C.read_tags_and_group_by_file Core.Inv suppTags in let inv = C.read_tag Core.Inv invTag in let vc_info_list = match mode with | IGraph.Concurrent -> if LeapVerbose.is_verbose_enabled() then LeapVerbose.verbstr ("Concurrent problem for invariant " ^inv_id^ " using as support [" ^supp_ids^ "]" ^ " with " ^string_of_int (IGraph.num_of_cases cases)^ " special cases.\n") else print_endline ("Generating verification conditions for " ^ inv_id); spinv_with_cases supp inv cases ~inv_id:inv_id | IGraph.Sequential -> if LeapVerbose.is_verbose_enabled() then LeapVerbose.verbstr ("Sequential problem for invariant " ^inv_id^ " using as support [" ^supp_ids^ "]" ^ " with " ^string_of_int (IGraph.num_of_cases cases)^ " special cases.\n") else print_endline ("Generating verification conditions for " ^ inv_id); seq_spinv_with_cases supp inv cases ~inv_id:inv_id in C.report_vcs vc_info_list; let new_obligations = generate_obligations vc_info_list plan cases in let obligations_num = List.fold_left (fun n po -> n + (List.length (C.obligations po)) ) 0 new_obligations in if (not (LeapVerbose.is_verbose_enabled())) then print_endline ("Generated: " ^ (string_of_int (List.length vc_info_list)) ^ " VC with " ^(string_of_int obligations_num) ^ " proofs obligations\n") else if LeapVerbose.is_verbose_level_enabled(LeapVerbose._SHORT_INFO) then Report.report_generated_vcs vc_info_list obligations_num; os @ new_obligations ) [] graph_info let solve_from_graph (graph:IGraph.t) : Core.solved_proof_obligation_t list = C.solve_proof_obligations (gen_from_graph graph) end
1c35a47ead435762a6977f40eb84fa6600bc18d9a65be0ebd1925e9b7d419f78
kaznum/programming_in_ocaml_exercise
sample.ml
let rec sum_list = function [] -> 0 | n :: rest -> n + (sum_list rest);; sum_list [1; 2; 3];; sum_list (1::2::3::[]);; let rec length = function [] -> 0 | _ :: rest -> 1 + length rest;; length [1; 2; 3];; let rec append l1 l2 = match l1 with [] -> l2 | v :: l1' -> v :: (append l1' l2);; append [1;2;3] [4;5;6];; [1;2;3] @ [4;5;6];; (* the following definition is not effective *) let rec reverse = function [] -> [] | v :: l' -> reverse l' @ [v];; reverse [];; reverse [1;2;3];; (* the following definition is more effective then reverse above *) let rec revAppend l1 l2 = match l1 with [] -> l2 | v :: l1' -> revAppend l1' (v :: l2) let rev l = revAppend l [];; rev [1;2;3];; let rec map f = function [] -> [] | x :: rest -> f x :: map f rest;; map (fun x -> x * 2) [1;2;3;4];; let rec forall f = function [] -> true | x :: rest -> (f x) && (forall f rest);; forall ( fun x -> x >= 5) [7;10;8];; forall ( fun x -> x >= 5) [9;3;8];; let rec exists f = function [] -> false | x :: rest -> (f x) || (exists f rest);; exists ( fun x -> x >= 5) [9;3;8];; exists ( fun x -> x >= 5) [2;3;4];; let rec fold_right f l e = match l with [] -> e | x :: rest -> f x (fold_right f rest e);; let rec fold_left f e l = match l with [] -> e | x :: rest -> fold_left f (f e x) rest;; fold_right ( fun x y -> x + y ) [ 3; 5; 7] 0;; fold_left (fun x y -> y :: x) [] [1; 2; 3;];; let length_foldr l = fold_right (fun x y -> 1 + y) l 0;; length_foldr [1;2;3;4;5];; let rec nth n l = match (n, l) with (1, a :: _) -> a | (n', _ :: rest) when n' > 0 -> nth (n-1) rest;; nth 3 [1;4;9;16];; let city_phone = [("Kyoto", "075"); ("Tokyo", "03"); ("Sapporo", "011")];; let rec assoc a = function (a', b) :: rest -> if a = a' then b else assoc a rest;; assoc "Tokyo" city_phone;; sample of wrong way let rec assoc_error a = function ( a , b ) : : rest - > b | _ : : rest - > assoc_error a rest ; ; assoc_error " Tokyo " city_phone ; ; let rec assoc_error a = function (a, b) :: rest -> b | _ :: rest -> assoc_error a rest;; assoc_error "Tokyo" city_phone;; *) (* the sorting *) let nextrand seed = let a = 16807.0 and m = 2147483647.0 in let t = a *. seed in t -. m *. floor ( t/. m) let rec randlist n seed tail = if n = 0 then (seed, tail) else randlist (n - 1) (nextrand seed) (seed::tail);; let rec insert x = function [] -> [x] | y :: rest when x < y -> x :: ( y :: rest ) | y :: rest -> y :: (insert x rest );; let rec insertion_sort = function [] -> [] | x :: rest -> insert x ( insertion_sort rest);; insertion_sort ( snd (randlist 10 1.0 []));; let rec quick_sort = function ([] | [_]) as l -> l | pivot :: rest -> let rec partition left right = function [] -> (quick_sort left) @ (pivot :: quick_sort right) | y:: ys -> if pivot < y then partition left ( y :: right) ys else partition (y :: left) right ys in partition [] [] rest;; insertion_sort ( snd (randlist 10000 1.0 []));; quick_sort ( snd (randlist 10000 1.0 []));;
null
https://raw.githubusercontent.com/kaznum/programming_in_ocaml_exercise/6f6a5d62a7a87a1c93561db88f08ae4e445b7d4e/ch5/sample.ml
ocaml
the following definition is not effective the following definition is more effective then reverse above the sorting
let rec sum_list = function [] -> 0 | n :: rest -> n + (sum_list rest);; sum_list [1; 2; 3];; sum_list (1::2::3::[]);; let rec length = function [] -> 0 | _ :: rest -> 1 + length rest;; length [1; 2; 3];; let rec append l1 l2 = match l1 with [] -> l2 | v :: l1' -> v :: (append l1' l2);; append [1;2;3] [4;5;6];; [1;2;3] @ [4;5;6];; let rec reverse = function [] -> [] | v :: l' -> reverse l' @ [v];; reverse [];; reverse [1;2;3];; let rec revAppend l1 l2 = match l1 with [] -> l2 | v :: l1' -> revAppend l1' (v :: l2) let rev l = revAppend l [];; rev [1;2;3];; let rec map f = function [] -> [] | x :: rest -> f x :: map f rest;; map (fun x -> x * 2) [1;2;3;4];; let rec forall f = function [] -> true | x :: rest -> (f x) && (forall f rest);; forall ( fun x -> x >= 5) [7;10;8];; forall ( fun x -> x >= 5) [9;3;8];; let rec exists f = function [] -> false | x :: rest -> (f x) || (exists f rest);; exists ( fun x -> x >= 5) [9;3;8];; exists ( fun x -> x >= 5) [2;3;4];; let rec fold_right f l e = match l with [] -> e | x :: rest -> f x (fold_right f rest e);; let rec fold_left f e l = match l with [] -> e | x :: rest -> fold_left f (f e x) rest;; fold_right ( fun x y -> x + y ) [ 3; 5; 7] 0;; fold_left (fun x y -> y :: x) [] [1; 2; 3;];; let length_foldr l = fold_right (fun x y -> 1 + y) l 0;; length_foldr [1;2;3;4;5];; let rec nth n l = match (n, l) with (1, a :: _) -> a | (n', _ :: rest) when n' > 0 -> nth (n-1) rest;; nth 3 [1;4;9;16];; let city_phone = [("Kyoto", "075"); ("Tokyo", "03"); ("Sapporo", "011")];; let rec assoc a = function (a', b) :: rest -> if a = a' then b else assoc a rest;; assoc "Tokyo" city_phone;; sample of wrong way let rec assoc_error a = function ( a , b ) : : rest - > b | _ : : rest - > assoc_error a rest ; ; assoc_error " Tokyo " city_phone ; ; let rec assoc_error a = function (a, b) :: rest -> b | _ :: rest -> assoc_error a rest;; assoc_error "Tokyo" city_phone;; *) let nextrand seed = let a = 16807.0 and m = 2147483647.0 in let t = a *. seed in t -. m *. floor ( t/. m) let rec randlist n seed tail = if n = 0 then (seed, tail) else randlist (n - 1) (nextrand seed) (seed::tail);; let rec insert x = function [] -> [x] | y :: rest when x < y -> x :: ( y :: rest ) | y :: rest -> y :: (insert x rest );; let rec insertion_sort = function [] -> [] | x :: rest -> insert x ( insertion_sort rest);; insertion_sort ( snd (randlist 10 1.0 []));; let rec quick_sort = function ([] | [_]) as l -> l | pivot :: rest -> let rec partition left right = function [] -> (quick_sort left) @ (pivot :: quick_sort right) | y:: ys -> if pivot < y then partition left ( y :: right) ys else partition (y :: left) right ys in partition [] [] rest;; insertion_sort ( snd (randlist 10000 1.0 []));; quick_sort ( snd (randlist 10000 1.0 []));;
1a55738717c3393c82349b2e8045f18b64f97c10e68930a5b9eee8d6f7b8177a
mbg/hoop
CodeGen.hs
module Language.Hoop.CodeGen ( module Language.Hoop.CodeGen.Decls, module Language.Hoop.CodeGen.New ) where import Language.Hoop.CodeGen.Decls import Language.Hoop.CodeGen.New
null
https://raw.githubusercontent.com/mbg/hoop/98a53bb1db66b06f9b5d3e5242eed336f908ad18/src/Language/Hoop/CodeGen.hs
haskell
module Language.Hoop.CodeGen ( module Language.Hoop.CodeGen.Decls, module Language.Hoop.CodeGen.New ) where import Language.Hoop.CodeGen.Decls import Language.Hoop.CodeGen.New
0e41cf60e15e29c862a48714e21c16110d28d1ee223d7ce81297a710d4446934
lazamar/easy-deploy
Lib.hs
module Lib (main) where import Cli (Arguments (_commands, _ports, _target, _volumes), Port (Port), Volume (Volume)) import qualified Cli import Command (Command, run, safeIO) import Control.Concurrent (threadDelay) import Control.Monad (unless) import Data.Functor (void) import Data.List (intersperse) import Data.Maybe (fromMaybe) import Docker (Container, Image, Tag, isRunning, network, portBinding, volumeBinding) import qualified Docker import Options.Applicative (execParser) -- Constants nginxImage :: Image nginxImage = Docker.officialImage "nginx" nginxTarget :: Docker.Target nginxTarget = Docker.target nginxImage $ Docker.tag "latest" wait :: String -> IO () wait description = do putStrLn $ "Waiting for " ++ show waitTime ++ " seconds " ++ description threadDelay $ waitTime * 1000 * 1000 where waitTime = 3 data Color = Green | Blue deriving (Show) main :: IO () main = do args <- execParser Cli.program let ports = _ports args volumes = _volumes args (image, mTag) = _target args tag = fromMaybe (Docker.tag "latest") mTag commands = _commands args v <- run $ deploy ports volumes image tag commands putStrLn "-------------------" case v of Right _ -> putStrLn "Success" Left stdout -> putStrLn "Failure" >> putStrLn stdout deploy :: [(Port, Port)] -> [(Volume, Volume)] -> Image -> Tag -> [String] -> Command () deploy ports volumes image tag commands = do mRunningColor <- runningColor image let newColor = maybe Blue alternate mRunningColor target = Docker.target image tag net <- network image safeIO $ putStrLn $ "Starting " ++ show newColor ++ " image." Docker.run (Just net) volumeBinds [] target (toContainer image newColor) commands -- This wait allows some time for the server running in the -- new image to kick up and be ready to answer to requests safeIO $ wait "for server to start" {- SMOKE TESTS GO HERE -} safeIO $ putStrLn $ "Switching proxy to " ++ show newColor runProxy image ports newColor case mRunningColor of Just color -> do safeIO $ wait $ "for " ++ show color ++ " server to finish handling its requests" void $ Docker.kill $ toContainer image color safeIO $ putStrLn $ show color ++ " container killed" return () Nothing -> return () safeIO $ putStrLn $ show newColor ++ " is now the main container" where volumeBinds = toVolumeBinding <$> volumes toPortBinding :: (Port, Port) -> Docker.PortBinding toPortBinding (Port a, Port b) = Docker.portBinding a b toVolumeBinding :: (Volume, Volume) -> Docker.VolumeBinding toVolumeBinding (Volume a, Volume b) = Docker.volumeBinding a b runningColor :: Image -> Command (Maybe Color) runningColor img = do blueRunning <- isRunning $ toContainer img Blue greenRunning <- isRunning $ toContainer img Green return $ if blueRunning then Just Blue else if greenRunning then Just Green else Nothing toContainer :: Image -> Color -> Container toContainer img color = Docker.container img $ show color -- ========================== -- PROXY -- ========================== {- This will run the proxy if it isn't running and do nothing if it already is. Creates all folders and files. Will override files if they already exist. The proxy will run an nginx image. The image parameter is used to determine the proxy name and the network it will run in -} runProxy :: Image -> [(Port, Port)] -> Color -> Command () runProxy image ports color = do isContainerRunning <- isRunning proxyContainer unless isContainerRunning $ do net <- network image void $ Docker.run (Just net) volumeBinds portBinds nginxTarget proxyContainer [] setProxyConfig proxyContainer image ports color void $ Docker.exec proxyContainer ["service", "nginx", "reload"] "" where proxyContainer = Docker.container image "PROXY" volumeBinds = [] portBinds = toPortBinding <$> ports {- Will take care of the directory and file -} setProxyConfig :: Docker.Container -> Docker.Image -> [(Port, Port)] -> Color -> Command () setProxyConfig proxyContainer image ports color = void $ Docker.exec proxyContainer ["tee", "/etc/nginx/conf.d/default.conf"] config where config = mconcat $ intersperse "\n" $ proxyConfig color image <$> ports proxyConfig :: Color -> Image -> (Port, Port) -> String proxyConfig color image (_, Port port) = unlines [ "server" , "{" , " listen " ++ show port ++ ";" , " location /" , " {" , " proxy_pass " ++ toUrl color ++ ";" , " }" , " location /stage" , " {" , " proxy_pass " ++ toUrl (alternate color) ++ ";" , " }" , "}" ] where toUrl aColor = "http://"++ show (toContainer image aColor) ++ ":" ++ show port ++ "/" alternate :: Color -> Color alternate Green = Blue alternate Blue = Green
null
https://raw.githubusercontent.com/lazamar/easy-deploy/7750f007be4e609a9fd7165c1011a221b23f486a/src/Lib.hs
haskell
Constants This wait allows some time for the server running in the new image to kick up and be ready to answer to requests SMOKE TESTS GO HERE ========================== PROXY ========================== This will run the proxy if it isn't running and do nothing if it already is. Creates all folders and files. Will override files if they already exist. The proxy will run an nginx image. The image parameter is used to determine the proxy name and the network it will run in Will take care of the directory and file
module Lib (main) where import Cli (Arguments (_commands, _ports, _target, _volumes), Port (Port), Volume (Volume)) import qualified Cli import Command (Command, run, safeIO) import Control.Concurrent (threadDelay) import Control.Monad (unless) import Data.Functor (void) import Data.List (intersperse) import Data.Maybe (fromMaybe) import Docker (Container, Image, Tag, isRunning, network, portBinding, volumeBinding) import qualified Docker import Options.Applicative (execParser) nginxImage :: Image nginxImage = Docker.officialImage "nginx" nginxTarget :: Docker.Target nginxTarget = Docker.target nginxImage $ Docker.tag "latest" wait :: String -> IO () wait description = do putStrLn $ "Waiting for " ++ show waitTime ++ " seconds " ++ description threadDelay $ waitTime * 1000 * 1000 where waitTime = 3 data Color = Green | Blue deriving (Show) main :: IO () main = do args <- execParser Cli.program let ports = _ports args volumes = _volumes args (image, mTag) = _target args tag = fromMaybe (Docker.tag "latest") mTag commands = _commands args v <- run $ deploy ports volumes image tag commands putStrLn "-------------------" case v of Right _ -> putStrLn "Success" Left stdout -> putStrLn "Failure" >> putStrLn stdout deploy :: [(Port, Port)] -> [(Volume, Volume)] -> Image -> Tag -> [String] -> Command () deploy ports volumes image tag commands = do mRunningColor <- runningColor image let newColor = maybe Blue alternate mRunningColor target = Docker.target image tag net <- network image safeIO $ putStrLn $ "Starting " ++ show newColor ++ " image." Docker.run (Just net) volumeBinds [] target (toContainer image newColor) commands safeIO $ wait "for server to start" safeIO $ putStrLn $ "Switching proxy to " ++ show newColor runProxy image ports newColor case mRunningColor of Just color -> do safeIO $ wait $ "for " ++ show color ++ " server to finish handling its requests" void $ Docker.kill $ toContainer image color safeIO $ putStrLn $ show color ++ " container killed" return () Nothing -> return () safeIO $ putStrLn $ show newColor ++ " is now the main container" where volumeBinds = toVolumeBinding <$> volumes toPortBinding :: (Port, Port) -> Docker.PortBinding toPortBinding (Port a, Port b) = Docker.portBinding a b toVolumeBinding :: (Volume, Volume) -> Docker.VolumeBinding toVolumeBinding (Volume a, Volume b) = Docker.volumeBinding a b runningColor :: Image -> Command (Maybe Color) runningColor img = do blueRunning <- isRunning $ toContainer img Blue greenRunning <- isRunning $ toContainer img Green return $ if blueRunning then Just Blue else if greenRunning then Just Green else Nothing toContainer :: Image -> Color -> Container toContainer img color = Docker.container img $ show color runProxy :: Image -> [(Port, Port)] -> Color -> Command () runProxy image ports color = do isContainerRunning <- isRunning proxyContainer unless isContainerRunning $ do net <- network image void $ Docker.run (Just net) volumeBinds portBinds nginxTarget proxyContainer [] setProxyConfig proxyContainer image ports color void $ Docker.exec proxyContainer ["service", "nginx", "reload"] "" where proxyContainer = Docker.container image "PROXY" volumeBinds = [] portBinds = toPortBinding <$> ports setProxyConfig :: Docker.Container -> Docker.Image -> [(Port, Port)] -> Color -> Command () setProxyConfig proxyContainer image ports color = void $ Docker.exec proxyContainer ["tee", "/etc/nginx/conf.d/default.conf"] config where config = mconcat $ intersperse "\n" $ proxyConfig color image <$> ports proxyConfig :: Color -> Image -> (Port, Port) -> String proxyConfig color image (_, Port port) = unlines [ "server" , "{" , " listen " ++ show port ++ ";" , " location /" , " {" , " proxy_pass " ++ toUrl color ++ ";" , " }" , " location /stage" , " {" , " proxy_pass " ++ toUrl (alternate color) ++ ";" , " }" , "}" ] where toUrl aColor = "http://"++ show (toContainer image aColor) ++ ":" ++ show port ++ "/" alternate :: Color -> Color alternate Green = Blue alternate Blue = Green
a19905bf95d993f0c4816b8bea11ea525d29579e76138308eff560eea123527e
ryanpbrewster/haskell
079.hs
079.hs - A common security method used for online banking is to ask the user for - three random characters from a passcode . For example , if the passcode was - 531278 , they may ask for the 2nd , 3rd , and 5th characters ; the expected - reply would be : 317 . - - The text file 079.in contains fifty successful login attempts . - - Given that the three characters are always asked for in order , analyse the - file so as to determine the shortest possible secret passcode of unknown - length . - A common security method used for online banking is to ask the user for - three random characters from a passcode. For example, if the passcode was - 531278, they may ask for the 2nd, 3rd, and 5th characters; the expected - reply would be: 317. - - The text file 079.in contains fifty successful login attempts. - - Given that the three characters are always asked for in order, analyse the - file so as to determine the shortest possible secret passcode of unknown - length. -} {- - In order to solve this, I'm going to assume that the passcode does not - have repeated digits. -} import Data.Char (digitToInt) import Data.Set (fromList, elems) import Data.List (permutations) -- isSubsequence big small isSubsequence _ [] = True isSubsequence [] small = False isSubsequence (b:bs) (s:ss) | b == s = isSubsequence bs ss | otherwise = isSubsequence bs (s:ss) solveProblem logins = let digit_set = elems $ fromList $ concat logins passcodes = permutations digit_set legit pass = all (isSubsequence pass) logins in filter legit passcodes main = do txt <- readFile "079.in" let logins = [ map digitToInt ln | ln <- lines txt ] print $ solveProblem logins
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/project-euler/src/Old/079.hs
haskell
- In order to solve this, I'm going to assume that the passcode does not - have repeated digits. isSubsequence big small
079.hs - A common security method used for online banking is to ask the user for - three random characters from a passcode . For example , if the passcode was - 531278 , they may ask for the 2nd , 3rd , and 5th characters ; the expected - reply would be : 317 . - - The text file 079.in contains fifty successful login attempts . - - Given that the three characters are always asked for in order , analyse the - file so as to determine the shortest possible secret passcode of unknown - length . - A common security method used for online banking is to ask the user for - three random characters from a passcode. For example, if the passcode was - 531278, they may ask for the 2nd, 3rd, and 5th characters; the expected - reply would be: 317. - - The text file 079.in contains fifty successful login attempts. - - Given that the three characters are always asked for in order, analyse the - file so as to determine the shortest possible secret passcode of unknown - length. -} import Data.Char (digitToInt) import Data.Set (fromList, elems) import Data.List (permutations) isSubsequence _ [] = True isSubsequence [] small = False isSubsequence (b:bs) (s:ss) | b == s = isSubsequence bs ss | otherwise = isSubsequence bs (s:ss) solveProblem logins = let digit_set = elems $ fromList $ concat logins passcodes = permutations digit_set legit pass = all (isSubsequence pass) logins in filter legit passcodes main = do txt <- readFile "079.in" let logins = [ map digitToInt ln | ln <- lines txt ] print $ solveProblem logins
7861faf823692ebcbd4e5c3248202c100f04cfe41e85cd4120bc106333300b5b
imrehg/ypsilon
r6rs-aux.scm
Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (define max (lambda args (cond ((null? args) (assertion-violation 'max "required at least 1, but 0 argument given")) ((real-valued? (car args)) (let loop ((value (car args)) (x? (inexact? (car args))) (lst (cdr args))) (cond ((null? lst) (if x? (inexact value) value)) ((real-valued? (car lst)) (loop (if (> (car lst) value) (car lst) value) (or x? (inexact? (car lst))) (cdr lst))) (else (assertion-violation 'max (format "expected real, but got ~s" (car lst)) args))))) (else (assertion-violation 'max (format "expected real, but got ~s" (car args)) args))))) (define min (lambda args (cond ((null? args) (assertion-violation 'min "required at least 1, but 0 argument given")) ((real-valued? (car args)) (let loop ((value (car args)) (x? (inexact? (car args))) (lst (cdr args))) (cond ((null? lst) (if x? (inexact value) value)) ((real-valued? (car lst)) (loop (if (< (car lst) value) (car lst) value) (or x? (inexact? (car lst))) (cdr lst))) (else (assertion-violation 'min (format "expected real, but got ~s" (car lst)) args))))) (else (assertion-violation 'min (format "expected real, but got ~s" (car args)) args))))) (define gcd2 (lambda (a b) (if (= b 0) (abs (if (inexact? b) (inexact a) a)) (gcd2 b (remainder a b))))) (define gcd (lambda args (for-each (lambda (a) (or (integer-valued? a) (assertion-violation 'gcd (format "expected integer, but got ~s" a) args))) args) (let loop ((lst args)) (case (length lst) ((2) (gcd2 (car lst) (cadr lst))) ((1) (abs (car lst))) ((0) 0) (else (loop (cons (gcd2 (car lst) (cadr lst)) (cddr lst)))))))) (define lcm (lambda args (define lcm2 (lambda (a b) (if (or (= a 0) (= b 0)) (if (and (exact? a) (exact? b)) 0 0.0) (abs (* (quotient a (gcd2 a b)) b))))) (for-each (lambda (a) (or (integer-valued? a) (assertion-violation 'lcm (format "expected integer, but got ~s" a) args))) args) (let loop ((lst args)) (case (length lst) ((2) (lcm2 (car lst) (cadr lst))) ((1) (abs (car lst))) ((0) 1) (else (loop (cons (lcm2 (car lst) (cadr lst)) (cddr lst)))))))) (define rationalize (lambda (x e) (or (real? x) (assertion-violation 'rationalize (format "expected real, but got ~s as argument 1" x) (list x e))) (or (real? e) (assertion-violation 'rationalize (format "expected real, but got ~s as argument 2" e) (list x e))) (cond ((infinite? e) (if (infinite? x) +nan.0 0.0)) ((= x 0) x) ((= x e) (- x e)) ((negative? x) (- (rationalize (- x) e))) (else (let ((e (abs e))) (let loop ((bottom (- x e)) (top (+ x e))) (cond ((= bottom top) bottom) (else (let ((x (ceiling bottom))) (cond ((< x top) x) (else (let ((a (- x 1))) (+ a (/ 1 (loop (/ 1 (- top a)) (/ 1 (- bottom a))))))))))))))))) (define string->list (lambda (s) (let ((port (make-string-input-port s))) (let loop ((lst '())) (let ((ch (get-char port))) (if (eof-object? ch) (reverse lst) (loop (cons ch lst)))))))) (define map (lambda (proc lst1 . lst2) (define map-1 (lambda (proc lst) (cond ((null? lst) '()) (else (cons (proc (car lst)) (map-1 proc (cdr lst))))))) (define map-n (lambda (proc lst) (cond ((null? lst) '()) (else (cons (apply proc (car lst)) (map-n proc (cdr lst))))))) (if (null? lst2) (if (list? lst1) (map-1 proc lst1) (assertion-violation 'map (wrong-type-argument-message "proper list" lst1 2) (cons* proc lst1 lst2))) (cond ((apply list-transpose+ lst1 lst2) => (lambda (lst) (map-n proc lst))) (else (assertion-violation 'map "expected same length proper lists" (cons* proc lst1 lst2))))))) (define for-each (lambda (proc lst1 . lst2) (define for-each-1 (lambda (proc lst) (if (null? lst) (unspecified) (begin (proc (car lst)) (for-each-1 proc (cdr lst)))))) (define for-each-n (lambda (proc lst) (cond ((null? lst) (unspecified)) (else (apply proc (car lst)) (for-each-n proc (cdr lst)))))) (if (null? lst2) (if (list? lst1) (for-each-1 proc lst1) (assertion-violation 'for-each (wrong-type-argument-message "proper list" lst1 2) (cons* proc lst1 lst2))) (cond ((apply list-transpose+ lst1 lst2) => (lambda (lst) (for-each-n proc lst))) (else (assertion-violation 'for-each "expected same length proper lists" (cons* proc lst1 lst2))))))) (define vector-map (lambda (proc vec1 . vec2) (list->vector (apply map proc (vector->list vec1) (map vector->list vec2))))) (define vector-for-each (lambda (proc vec1 . vec2) (apply for-each proc (vector->list vec1) (map vector->list vec2)))) (define string-for-each (lambda (proc str1 . str2) (apply for-each proc (string->list str1) (map string->list str2)))) (define call-with-values (lambda (producer consumer) (apply-values consumer (producer)))) (define call-with-port (lambda (port proc) (call-with-values (lambda () (proc port)) (lambda args (close-port port) (apply values args))))) (define mod (lambda (x y) (- x (* (div x y) y)))) (define div-and-mod (lambda (x y) (let ((d (div x y))) (values d (- x (* d y)))))) (define mod0 (lambda (x y) (- x (* (div0 x y) y)))) (define div0-and-mod0 (lambda (x y) (let ((d0 (div0 x y))) (values d0 (- x (* d0 y))))))
null
https://raw.githubusercontent.com/imrehg/ypsilon/e57a06ef5c66c1a88905b2be2fa791fa29848514/heap/boot/r6rs-aux.scm
scheme
Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (define max (lambda args (cond ((null? args) (assertion-violation 'max "required at least 1, but 0 argument given")) ((real-valued? (car args)) (let loop ((value (car args)) (x? (inexact? (car args))) (lst (cdr args))) (cond ((null? lst) (if x? (inexact value) value)) ((real-valued? (car lst)) (loop (if (> (car lst) value) (car lst) value) (or x? (inexact? (car lst))) (cdr lst))) (else (assertion-violation 'max (format "expected real, but got ~s" (car lst)) args))))) (else (assertion-violation 'max (format "expected real, but got ~s" (car args)) args))))) (define min (lambda args (cond ((null? args) (assertion-violation 'min "required at least 1, but 0 argument given")) ((real-valued? (car args)) (let loop ((value (car args)) (x? (inexact? (car args))) (lst (cdr args))) (cond ((null? lst) (if x? (inexact value) value)) ((real-valued? (car lst)) (loop (if (< (car lst) value) (car lst) value) (or x? (inexact? (car lst))) (cdr lst))) (else (assertion-violation 'min (format "expected real, but got ~s" (car lst)) args))))) (else (assertion-violation 'min (format "expected real, but got ~s" (car args)) args))))) (define gcd2 (lambda (a b) (if (= b 0) (abs (if (inexact? b) (inexact a) a)) (gcd2 b (remainder a b))))) (define gcd (lambda args (for-each (lambda (a) (or (integer-valued? a) (assertion-violation 'gcd (format "expected integer, but got ~s" a) args))) args) (let loop ((lst args)) (case (length lst) ((2) (gcd2 (car lst) (cadr lst))) ((1) (abs (car lst))) ((0) 0) (else (loop (cons (gcd2 (car lst) (cadr lst)) (cddr lst)))))))) (define lcm (lambda args (define lcm2 (lambda (a b) (if (or (= a 0) (= b 0)) (if (and (exact? a) (exact? b)) 0 0.0) (abs (* (quotient a (gcd2 a b)) b))))) (for-each (lambda (a) (or (integer-valued? a) (assertion-violation 'lcm (format "expected integer, but got ~s" a) args))) args) (let loop ((lst args)) (case (length lst) ((2) (lcm2 (car lst) (cadr lst))) ((1) (abs (car lst))) ((0) 1) (else (loop (cons (lcm2 (car lst) (cadr lst)) (cddr lst)))))))) (define rationalize (lambda (x e) (or (real? x) (assertion-violation 'rationalize (format "expected real, but got ~s as argument 1" x) (list x e))) (or (real? e) (assertion-violation 'rationalize (format "expected real, but got ~s as argument 2" e) (list x e))) (cond ((infinite? e) (if (infinite? x) +nan.0 0.0)) ((= x 0) x) ((= x e) (- x e)) ((negative? x) (- (rationalize (- x) e))) (else (let ((e (abs e))) (let loop ((bottom (- x e)) (top (+ x e))) (cond ((= bottom top) bottom) (else (let ((x (ceiling bottom))) (cond ((< x top) x) (else (let ((a (- x 1))) (+ a (/ 1 (loop (/ 1 (- top a)) (/ 1 (- bottom a))))))))))))))))) (define string->list (lambda (s) (let ((port (make-string-input-port s))) (let loop ((lst '())) (let ((ch (get-char port))) (if (eof-object? ch) (reverse lst) (loop (cons ch lst)))))))) (define map (lambda (proc lst1 . lst2) (define map-1 (lambda (proc lst) (cond ((null? lst) '()) (else (cons (proc (car lst)) (map-1 proc (cdr lst))))))) (define map-n (lambda (proc lst) (cond ((null? lst) '()) (else (cons (apply proc (car lst)) (map-n proc (cdr lst))))))) (if (null? lst2) (if (list? lst1) (map-1 proc lst1) (assertion-violation 'map (wrong-type-argument-message "proper list" lst1 2) (cons* proc lst1 lst2))) (cond ((apply list-transpose+ lst1 lst2) => (lambda (lst) (map-n proc lst))) (else (assertion-violation 'map "expected same length proper lists" (cons* proc lst1 lst2))))))) (define for-each (lambda (proc lst1 . lst2) (define for-each-1 (lambda (proc lst) (if (null? lst) (unspecified) (begin (proc (car lst)) (for-each-1 proc (cdr lst)))))) (define for-each-n (lambda (proc lst) (cond ((null? lst) (unspecified)) (else (apply proc (car lst)) (for-each-n proc (cdr lst)))))) (if (null? lst2) (if (list? lst1) (for-each-1 proc lst1) (assertion-violation 'for-each (wrong-type-argument-message "proper list" lst1 2) (cons* proc lst1 lst2))) (cond ((apply list-transpose+ lst1 lst2) => (lambda (lst) (for-each-n proc lst))) (else (assertion-violation 'for-each "expected same length proper lists" (cons* proc lst1 lst2))))))) (define vector-map (lambda (proc vec1 . vec2) (list->vector (apply map proc (vector->list vec1) (map vector->list vec2))))) (define vector-for-each (lambda (proc vec1 . vec2) (apply for-each proc (vector->list vec1) (map vector->list vec2)))) (define string-for-each (lambda (proc str1 . str2) (apply for-each proc (string->list str1) (map string->list str2)))) (define call-with-values (lambda (producer consumer) (apply-values consumer (producer)))) (define call-with-port (lambda (port proc) (call-with-values (lambda () (proc port)) (lambda args (close-port port) (apply values args))))) (define mod (lambda (x y) (- x (* (div x y) y)))) (define div-and-mod (lambda (x y) (let ((d (div x y))) (values d (- x (* d y)))))) (define mod0 (lambda (x y) (- x (* (div0 x y) y)))) (define div0-and-mod0 (lambda (x y) (let ((d0 (div0 x y))) (values d0 (- x (* d0 y))))))
63a42a083b221528f5d6e799e3e264ec1948752951c63a85d762d2627cbd6b34
IvanIvanov/fp2013
lab6.scm
(define matr (list (list 1 2 3) (list 4 5 6) (list 7 8 9))) (define E (list (list 1 0 0) (list 0 1 0) (list 0 0 1))) (define (nth l index) (define (nth-iter l index elem-so-far) (cond ( (= index 0) elem-so-far) (else (nth-iter (cdr l) (- index 1) (car l))))) (nth-iter l index (car l))) (define (range a b) (cond ( (> a b) (list)) (else (cons a (range (+ a 1) b))))) (define (first l) (nth l 1)) (define (last l) (nth l (length l))) функцията взима матрица и връща списък с 2 елемента с размерностите на матрицата (define (dimension M) (cons (length M) (cons (length (car M)) (list) ))) предикат , две матрици могат да бъдат умножени MxP * PxN = MxN (define (can-multiply? M1 M2) (= (last (dimension M1)) (first (dimension M2)))) фунция , която връща даден ред ( от индекс 1 ) на матрица (define (get-row M index) (nth M index)) ;;; връща колоната с даден index (define (get-column M index) (map (lambda (row) (nth row index)) M)) ;;; връща главния диагонал на квадратната матрица M (define (diagonal M) (map (lambda (elem index) (nth elem index)) M (range 1 (length M)))) ;;; транспониране на матрица (define (transpose M) (map (lambda (index) (get-column M index)) (range 1 (length (car M))))) функция , две матрици с еднакви размери (define (add-matrices M1 M2) (map (lambda (row1 row2) (map + row1 row2)) M1 M2)) функция , матрица със скалар (define (scalar-mult M scalar) (map (lambda (row) (map (lambda (x) (* x scalar)) row)) M)) проверява дали матрицата е коректна ( не е jagged ) (define (correct? M) (= (* (length M) (length (car M))) (apply + 0 (map (lambda (row) (length row)) M))))
null
https://raw.githubusercontent.com/IvanIvanov/fp2013/2ac1bb1102cb65e0ecbfa8d2fb3ca69953ae4ecf/lab2-and-3/lab6.scm
scheme
връща колоната с даден index връща главния диагонал на квадратната матрица M транспониране на матрица
(define matr (list (list 1 2 3) (list 4 5 6) (list 7 8 9))) (define E (list (list 1 0 0) (list 0 1 0) (list 0 0 1))) (define (nth l index) (define (nth-iter l index elem-so-far) (cond ( (= index 0) elem-so-far) (else (nth-iter (cdr l) (- index 1) (car l))))) (nth-iter l index (car l))) (define (range a b) (cond ( (> a b) (list)) (else (cons a (range (+ a 1) b))))) (define (first l) (nth l 1)) (define (last l) (nth l (length l))) функцията взима матрица и връща списък с 2 елемента с размерностите на матрицата (define (dimension M) (cons (length M) (cons (length (car M)) (list) ))) предикат , две матрици могат да бъдат умножени MxP * PxN = MxN (define (can-multiply? M1 M2) (= (last (dimension M1)) (first (dimension M2)))) фунция , която връща даден ред ( от индекс 1 ) на матрица (define (get-row M index) (nth M index)) (define (get-column M index) (map (lambda (row) (nth row index)) M)) (define (diagonal M) (map (lambda (elem index) (nth elem index)) M (range 1 (length M)))) (define (transpose M) (map (lambda (index) (get-column M index)) (range 1 (length (car M))))) функция , две матрици с еднакви размери (define (add-matrices M1 M2) (map (lambda (row1 row2) (map + row1 row2)) M1 M2)) функция , матрица със скалар (define (scalar-mult M scalar) (map (lambda (row) (map (lambda (x) (* x scalar)) row)) M)) проверява дали матрицата е коректна ( не е jagged ) (define (correct? M) (= (* (length M) (length (car M))) (apply + 0 (map (lambda (row) (length row)) M))))
fcf4d1d2c14dd4d5ff8f683674656922925dce9d67d32bc1b6b3fa4371abf05c
rbkmoney/hellgate
hg_dummy_inspector.erl
-module(hg_dummy_inspector). -behaviour(hg_woody_wrapper). -export([handle_function/3]). -behaviour(hg_test_proxy). -export([get_service_spec/0]). -include_lib("damsel/include/dmsl_proxy_inspector_thrift.hrl"). -include_lib("hellgate/include/invoice_events.hrl"). -spec get_service_spec() -> hg_proto:service_spec(). get_service_spec() -> {"/test/proxy/inspector/dummy", {dmsl_proxy_inspector_thrift, 'InspectorProxy'}}. -spec handle_function(woody:func(), woody:args(), hg_woody_wrapper:handler_opts()) -> term() | no_return(). handle_function( 'InspectPayment', {#proxy_inspector_Context{ payment = _PaymentInfo, options = #{ <<"risk_score">> := RiskScore } }}, _Options ) -> binary_to_atom(RiskScore, utf8); handle_function( 'InspectPayment', {#proxy_inspector_Context{ payment = _PaymentInfo, options = #{ <<"link_state">> := <<"unexpected_failure">> } }}, _Options ) -> erlang:error(test_error); handle_function( 'InspectPayment', {#proxy_inspector_Context{ payment = #proxy_inspector_PaymentInfo{ payment = #proxy_inspector_InvoicePayment{ id = PaymentID }, invoice = #proxy_inspector_Invoice{ id = InvoiceID } }, options = #{ <<"link_state">> := <<"temporary_failure">> } }}, _Options ) -> case is_already_failed(InvoiceID, PaymentID) of false -> ok = set_failed(InvoiceID, PaymentID), erlang:error(test_error); true -> low end; handle_function( 'InspectPayment', {#proxy_inspector_Context{ payment = _PaymentInfo, options = #{ <<"link_state">> := _LinkState } }}, _Options ) -> timer:sleep(10000), high. -define(temp_failure_key(InvoiceID, PaymentID), {temporary_failure_inspector, InvoiceID, PaymentID}). is_already_failed(InvoiceID, PaymentID) -> case hg_kv_store:get(?temp_failure_key(InvoiceID, PaymentID)) of undefined -> false; failed -> true end. set_failed(InvoiceID, PaymentID) -> hg_kv_store:put(?temp_failure_key(InvoiceID, PaymentID), failed).
null
https://raw.githubusercontent.com/rbkmoney/hellgate/c3e7413db06296a72fb64268eca98e63379d2ef5/apps/hellgate/test/hg_dummy_inspector.erl
erlang
-module(hg_dummy_inspector). -behaviour(hg_woody_wrapper). -export([handle_function/3]). -behaviour(hg_test_proxy). -export([get_service_spec/0]). -include_lib("damsel/include/dmsl_proxy_inspector_thrift.hrl"). -include_lib("hellgate/include/invoice_events.hrl"). -spec get_service_spec() -> hg_proto:service_spec(). get_service_spec() -> {"/test/proxy/inspector/dummy", {dmsl_proxy_inspector_thrift, 'InspectorProxy'}}. -spec handle_function(woody:func(), woody:args(), hg_woody_wrapper:handler_opts()) -> term() | no_return(). handle_function( 'InspectPayment', {#proxy_inspector_Context{ payment = _PaymentInfo, options = #{ <<"risk_score">> := RiskScore } }}, _Options ) -> binary_to_atom(RiskScore, utf8); handle_function( 'InspectPayment', {#proxy_inspector_Context{ payment = _PaymentInfo, options = #{ <<"link_state">> := <<"unexpected_failure">> } }}, _Options ) -> erlang:error(test_error); handle_function( 'InspectPayment', {#proxy_inspector_Context{ payment = #proxy_inspector_PaymentInfo{ payment = #proxy_inspector_InvoicePayment{ id = PaymentID }, invoice = #proxy_inspector_Invoice{ id = InvoiceID } }, options = #{ <<"link_state">> := <<"temporary_failure">> } }}, _Options ) -> case is_already_failed(InvoiceID, PaymentID) of false -> ok = set_failed(InvoiceID, PaymentID), erlang:error(test_error); true -> low end; handle_function( 'InspectPayment', {#proxy_inspector_Context{ payment = _PaymentInfo, options = #{ <<"link_state">> := _LinkState } }}, _Options ) -> timer:sleep(10000), high. -define(temp_failure_key(InvoiceID, PaymentID), {temporary_failure_inspector, InvoiceID, PaymentID}). is_already_failed(InvoiceID, PaymentID) -> case hg_kv_store:get(?temp_failure_key(InvoiceID, PaymentID)) of undefined -> false; failed -> true end. set_failed(InvoiceID, PaymentID) -> hg_kv_store:put(?temp_failure_key(InvoiceID, PaymentID), failed).
7878ac5c5dab380a7756abecc97074e9189312e5e447a52edb631272838ca94a
erlang/erlide_kernel
erlide_open.erl
%% Author: jakob Created : Mar 23 , 2006 %% Description: -module(erlide_open). -author(''). %% %% Exported Functions %% -export([open/3, find_first_var/2, get_source_from_module/2, get_external_modules/2, get_external_module/2, get_external_module_tree/1, get_external_include/2, get_external_1/3, get_otp_lib_structure/1, get_lib_files/1, get_includes_in_dir/1 ]). %% TODO (JC) there are some code duplication in external modules (and includes) handling %% %% Include files %% -define(DEBUG , 1 ) . -define(IO_FORMAT_DEBUG , 1 ) . -include_lib("erlide_common/include/erlide_dbglog.hrl"). -include("erlide_open.hrl"). -include_lib("erlide_ide_core/include/erlide_token.hrl"). -define(CACHE_VERSION, 4). %% %% API Functions %% open(Mod, Offset, #open_context{imports=Imports0}=Context) -> ?D({Mod, Offset, Context}), Imports = erlide_util:add_auto_imported(Imports0), try {TokensWComments, BeforeReversed} = erlide_scanner:get_token_window(Mod, Offset, 45, 100), ?D({TokensWComments, BeforeReversed}), try_open(Offset, TokensWComments, BeforeReversed, Context#open_context{imports=Imports}), error catch throw:{open, Res} -> Res; throw:T -> {error, T}; error:E -> {error, E} end. get_external_include(FilePath, #open_context{externalIncludes=ExternalIncludes, pathVars=PathVars}) -> ?D(FilePath), ExtIncPaths = get_external_modules_files(ExternalIncludes, PathVars), get_ext_inc(ExtIncPaths, FilePath). get_otp_lib_structure(StateDir) -> RenewFun = fun(_) -> CodeLibs = code:get_path(), LibDir = code:lib_dir(), Libs = lists:filter(fun(N) -> lists:prefix(LibDir, N) end, CodeLibs), LibDirs = [get_lib_dir(Lib) || Lib <- lists:sort(Libs)], R = lists:map(fun(Dir) -> SubDirs = ["src", "include"], Group = get_app_group(Dir), {Dir, get_dirs(SubDirs, Dir, []), Group} end, LibDirs), ?D(R), R end, VersionFileName = filename:join([code:root_dir()]), CacheName = filename:join(StateDir, "otp.structure"), {_Cached, R} = erlide_cache:check_and_renew_cached(VersionFileName, CacheName, ?CACHE_VERSION, RenewFun, true), ?D(_Cached), {ok, R}. get_app_group(Dir) -> case file:open(filename:join(Dir, "info"), [read]) of {ok, F} -> case file:read_line(F) of {ok, "group:"++Group} -> Val = string:strip(string:strip(Group),right, $\n), case split_at_first_char($\s, Val) of {[], A} -> A; {A, _} -> A end; _ -> "" end; _-> "" end. split_at_first_char(Char, String) -> lists:split(string:chr(String, Char), String). get_dirs([], _, Acc) -> lists:reverse(Acc); get_dirs([Dir | Rest], Base, Acc) -> D = filename:join(Base, Dir), case filelib:is_dir(D) of true -> {ok, Files} = get_lib_files(D), get_dirs(Rest, Base, [{D, Files} | Acc]); false -> get_dirs(Rest, Base, Acc) end. get_lib_files(Dir) -> case file:list_dir(Dir) of {ok, SrcFiles} -> Files = [filename:join(Dir, SrcFile) || SrcFile <- lists:sort(SrcFiles)], {ok, lists:filter(fun(F) -> filelib:is_regular(F) end, Files)}; _ -> {ok, []} end. get_includes_in_dir(Dir) -> case file:list_dir(Dir) of {ok, Files} -> {ok, filter_includes(lists:sort(Files))}; _ -> {ok, []} end. %% %% Local Functions %% filter_includes(Files) -> [File || File <- Files, filename:extension(File) == ".hrl"]. get_lib_dir(Dir) -> case filename:basename(Dir) of "ebin" -> filename:dirname(Dir); _ -> Dir end. try_open(Offset, TokensWComments, BeforeReversedWComments, Context) -> Tokens = erlide_text:strip_comments(TokensWComments), BeforeReversed = erlide_text:strip_comments(BeforeReversedWComments), try_open_aux(Offset, Tokens, BeforeReversed, Context). try_open_aux(Offset, Tokens, BeforeReversed, Context) -> case Tokens of [#token{offset=O} | _] = Tokens when O =< Offset -> ?D(Tokens), o_tokens(Tokens, Offset, Context, BeforeReversed), case BeforeReversed of [] -> not_found; [B | Rest] -> try_open_aux(Offset, [B | Tokens], Rest, Context) end; _ -> ok end. has_prefix(Prefix, FileName) -> lists:prefix(Prefix, filename:basename(FileName)). has_name(Name, FileName) -> Name == filename:rootname(filename:basename(FileName)). get_external_modules(Prefix, #open_context{externalModules=ExternalModulesFiles, pathVars=PathVars}) -> ExternalModules = get_external_modules_files(ExternalModulesFiles, PathVars), {ok, [XM || XM <- ExternalModules, has_prefix(Prefix, XM)]}. get_external_module_tree(#open_context{externalModules=ExternalModulesFiles, pathVars=PathVars}) -> {ok, get_external_module_tree(ExternalModulesFiles, PathVars)}. get_external_module(Name, #open_context{externalModules=ExternalModulesFiles, pathVars=PathVars}) -> ExternalModules = get_external_modules_files(ExternalModulesFiles, PathVars), case [XM || XM <- ExternalModules, has_name(Name, XM)] of [Path | _] -> {ok, Path}; _ -> not_found end. get_external_module_tree(PackedFileNames, PathVars) -> Fun = fun(Parent, FileName, Acc) -> [{Parent, replace_path_var(FileName, PathVars), module} | Acc] end, Fun2 = fun(Parent, FileName, Acc) -> [{Parent, replace_path_var(FileName, PathVars), entry} | Acc] end, FileNames = erlide_util:unpack(PackedFileNames), R = fold_externals(Fun, Fun2, FileNames, PathVars), R. consider_local([]) -> true; consider_local([#token{kind=':'} | _]) -> false; consider_local(_) -> true. consider_macro_def([#token{kind=atom, value=define}, #token{kind='-'} | _]) -> true; consider_macro_def([#token{kind='('} | Rest]) -> consider_macro_def(Rest); consider_macro_def(_) -> false. consider_record_field_ref([#token{kind='{'}, #token{kind=atom, value=Record}, #token{kind='#'} | _]) -> {true, Record}; consider_record_field_ref([_ | Rest]) -> consider_record_field_ref(Rest); consider_record_field_ref(_) -> false. TODO : rewrite this with some kind of table , and make it possible to %% add new items, e.g. gen_server calls o_tokens([#token{kind=atom, value=include} | Rest], _, _, [#token{kind='-'} | _]) -> o_include(Rest); o_tokens([#token{kind=atom, value=include_lib} | Rest], _, _, [#token{kind='-'} | _]) -> o_include_lib(Rest); o_tokens([#token{kind=atom, value=define} | Rest], _, _, _) -> o_macro_def(Rest); o_tokens([#token{kind=atom, value=record} | Rest], Offset, _, [#token{kind='-'} | _]) -> o_record_def(Rest, Offset); o_tokens([#token{kind='#'}, #token{kind=atom, value=Value} | _] = Tokens, Offset, _, _) -> o_record(Tokens, Offset, Value); o_tokens([#token{kind='#'}, #token{kind=macro, value=Value} | _] = Tokens, Offset, _, _) -> o_record(Tokens, Offset, Value); o_tokens([#token{kind=atom, value=Module}, #token{kind=':'}, #token{kind=atom, value=Function}, #token{kind='/'}, #token{kind=integer, value=Arity} | _], _, Context, _) -> o_external(Module, Function, Arity, Context); o_tokens([#token{kind=atom, value=Module}, #token{kind=':'}, #token{kind=atom, value=Function} | Rest], _, Context, _) -> o_external(Module, Function, Rest, Context); o_tokens([#token{kind=macro, value=Module}, #token{kind=':'}, #token{kind=atom, value=Function} | Rest], _, Context, _) -> o_external(Module, Function, Rest, Context); o_tokens([#token{kind=atom, value=Function}, #token{kind='/'}, #token{kind=integer, value=Arity} | _], _, Context, [#token{kind=':'}, #token{kind=atom, value=Module} | _]) -> o_external(Module, Function, Arity, Context); o_tokens([#token{kind=atom, value=Function}, #token{kind='/'}, #token{kind=integer, value=Arity} | _], _, Context, _BeforeReversed) -> o_local(Function, Arity, Context); o_tokens([#token{kind='/'}, #token{kind=integer, value=Arity} | _], _, Context, [#token{kind=atom, value=Function} | _]) -> o_local(Function, Arity, Context); o_tokens([#token{kind=atom, value=Value} | _] = Tokens, Offset, _, [#token{kind='#'} | _]) -> o_record(Tokens, Offset, Value); o_tokens([#token{kind=macro, value=Value} | _] = Tokens, Offset, _, [#token{kind='#'} | _]) -> o_record(Tokens, Offset, Value); o_tokens([#token{kind=macro, value=Value} | _], _, _, _) -> o_macro(Value); o_tokens([#token{kind=atom, value=Function}, #token{kind='('} | Rest], _, Context, BeforeReversed) -> case consider_local(BeforeReversed) of true -> ?D(Rest), o_local(Function, erlide_text:guess_arity(Rest), Context); false -> continue end; o_tokens([#token{kind=atom, value=Value} | _], _Offset, _, BeforeReversed) -> case consider_record_field_ref(BeforeReversed) of {true, Record} -> throw({open, {field, Record, Value}}); false -> no end; o_tokens([#token{kind=var, value=VarName} | _], _, _, BeforeReversed) -> case consider_macro_def(BeforeReversed) of true -> throw({open, {macro_def, VarName}}); false -> throw({open, {variable, VarName}}) end; o_tokens(_, _, _, _) -> no. o_include([#token{kind='('}, #token{kind=string, value=File} | _]) -> throw({open, {include, File}}); o_include(_) -> no. o_include_lib([#token{kind='('}, #token{kind=string, value=Path} | _]) -> ?D(Path), IncludeLib = get_otp_include_lib(Path), throw({open, IncludeLib}); o_include_lib(_) -> no. o_macro(Value) -> throw({open, {macro, Value}}). o_macro_def([#token{kind='('}, #token{kind=var, value=Value} | _]) -> throw({open, {macro, Value}}); o_macro_def([#token{kind='('}, #token{kind=atom, value=Value} | _]) -> throw({open, {macro, Value}}). o_record(Tokens, Offset, Value) -> {State, _Name, Prefix, _Fields} = erlide_content_assist:check_record_tokens(upto_offset(Tokens, Offset)), case State of record_want_field -> throw({open, {field, Value, Prefix}}); record_want_dot_field -> throw({open, {field, Value, Prefix}}); record_dot_field -> throw({open, {field, Value, Prefix}}); record_field -> throw({open, {field, Value, Prefix}}); _ -> throw({open, {record, Value}}) end. upto_offset([#token{offset=O, length=L}=T | Rest], Offset) when Offset>=O+L -> [T | upto_offset(Rest, Offset)]; upto_offset([], _) -> []; upto_offset([T | _], _) -> [T]. o_record_def([#token{kind='('}, #token{value=Value, offset=O, length=L}, #token{kind=','} | _Tokens], Offset) when Offset=<O+L -> throw({open, {record, Value}}); o_record_def([#token{kind='('}, #token{value=Value}, #token{kind=','} | Tokens], Offset) -> Between = erlide_np_util:get_between_outer_pars(Tokens, '{', '}'), o_record_def_aux(Between, Offset, Value, want_field). o_record_def_aux([], _Offset, Record, _) -> throw({open, {record, Record}}); o_record_def_aux([#token{offset=O, length=L, value=Field} | _], Offset, Record, want_field) when Offset<O+L -> throw({open, {field, Record, Field}}); o_record_def_aux([#token{value=V} | _]=Tokens, Offset, Record, _) when V=:='('; V=:='{'; V=:='['; V=:='<<' -> Rest = erlide_text:skip_expr(Tokens), o_record_def_aux(Rest, Offset, Record, want_comma); o_record_def_aux([#token{value=','} | Rest], Offset, Record, want_comma) -> o_record_def_aux(Rest, Offset, Record, want_field); o_record_def_aux([_ | Rest], Offset, Record, W) -> o_record_def_aux(Rest, Offset, Record, W). o_external(Module, Function, [_ | ParameterListTokens], Context) -> ?D({Module, Function, ParameterListTokens}), A = erlide_text:guess_arity(ParameterListTokens), ?D(A), P = get_source_from_module(Module, Context), throw({open, {external, Module, Function, A, P}}); o_external(Module, Function, Arity, Context) when is_integer(Arity) -> ?D({Module, Function, Arity}), P = get_source_from_module(Module, Context), throw({open, {external, Module, Function, Arity, P}}). o_local(Function, Arity, #open_context{imports=Imports}=Context) -> case get_imported(Imports, {Function, Arity}) of false -> throw({open, {local, Function, Arity}}); Module -> P = get_source_from_module(Module, Context), throw({open, {external, Module, Function, Arity, P}}) end. get_imported([], _) -> false; get_imported([{Mod, Funcs} | Rest], Func) -> case lists:member(Func, Funcs) of true -> Mod; false -> get_imported(Rest, Func) end. get_otp_include_lib(Path) -> {Lib, Rest} = find_lib_dir(Path), FileName = filename:basename(Rest), {include_lib, FileName, filename:join([Lib | Rest])}. find_lib_dir(Dir) -> [Lib | Rest] = filename:split(Dir), ?D(Lib), {code:lib_dir(list_to_atom(Lib)), Rest}. get_source_from_module(Mod, Context) -> case catch get_source(Mod) of {'EXIT', _E} -> ?D({get_source, _E}), case catch select_external(get_erl_from_dirs(Context#open_context.extraSourcePaths), atom_to_list(Mod)) of Path when is_list(Path) -> Path; _ -> get_source_from_external_modules(Mod, Context) end; Other -> Other end. get_external_modules_files(PackedFileNames, PathVars) -> ?D(PackedFileNames), Fun = fun(_Parent, FileName, Acc) -> [replace_path_var(FileName, PathVars) | Acc] end, Fun2 = fun(_Parent, _FileName, Acc) -> Acc end, FileNames = erlide_util:unpack(PackedFileNames), R = fold_externals(Fun, Fun2, FileNames, PathVars), %%?D(R), R. replace_path_vars(FileNames, PathVars) -> [replace_path_var(F, PathVars) || F <- FileNames]. replace_path_var(FileName, PathVars) -> case filename:split(FileName) of [Var | Rest] -> filename:join([replace_path_var_aux(Var, PathVars) | Rest]); _ -> FileName end. replace_path_var_aux(Var, PathVars) -> case lists:keysearch(Var, 1, PathVars) of {value, {Var, Value}} -> Value; _ -> Var end. get_external_1(FileName0, PathVars, IsRoot) -> FileName = replace_path_var(FileName0, PathVars), FileNames = case IsRoot orelse filename:extension(FileName) == ".erlidex" of true -> case file:read_file(FileName) of {ok, B} -> erlide_util:split_lines(B); _ -> [FileName] end; false -> [FileName] end, R = replace_path_vars(FileNames, PathVars), {ok, R}. fold_externals(Fun, Fun2, FileNames, PathVars) -> {_Done, Acc} = fx(FileNames, Fun, Fun2, PathVars, "root", [], []), lists:reverse(Acc). fx([], _Fun, _Fun2, _PathVars, _Parent, Done, Acc) -> {Done, Acc}; fx([FN0 | Rest], Fun, Fun2, PathVars, Parent, Done, Acc) -> FN = replace_path_var(FN0, PathVars), case lists:member(FN, Done) of true -> fx(Rest, Fun, Fun2, PathVars, Parent, Done, Acc); false -> case Parent=:="root" orelse filename:extension(FN) == ".erlidex" of true -> {NewDone, NewAcc} = fx2(FN, Fun, Fun2, PathVars, Parent, Done, Acc), fx(Rest, Fun, Fun2, PathVars, Parent, NewDone, NewAcc); false -> fx(Rest, Fun, Fun2, PathVars, Parent, [FN | Done], Fun(Parent, FN, Acc)) end end. fx2(FN, Fun, Fun2, PathVars, Parent, Done, Acc) -> NewAcc = Fun2(Parent, FN, Acc), case file:read_file(FN) of {ok, B} -> Lines = erlide_util:split_lines(B), fx(Lines, Fun, Fun2, PathVars, FN, [FN | Done], NewAcc); _ -> {Done, Acc} end. get_source_from_external_modules(Mod, #open_context{externalModules=ExternalModules, pathVars=PathVars, extraSourcePaths=ExtraSources}=_Context) -> ?D(_Context), L = get_external_modules_files(ExternalModules, PathVars), %%?D(lists:flatten(io_lib:format(">> ~p~n", [L]))), ?D({get_external_modules_files, length(L)}), _Extra = get_erl_from_dirs(ExtraSources), ?D({extra, _Extra}), select_external(L, atom_to_list(Mod)). select_external([], _) -> not_found; select_external([P | Rest], Mod) -> Name = filename:rootname(filename:basename(P)), ? D({select_external , Name , , P } ) , case Name of Mod -> P; _ -> select_external(Rest, Mod) end. get_erl_from_dirs(undefined) -> []; get_erl_from_dirs(L) -> ?D({get_erl_from_dirs, L}), lists:flatmap(fun(X) -> get_erl_from_dir(X) end, L). get_erl_from_dir(D) -> case file:list_dir(D) of {ok, Fs} -> [filename:join(D, F) || F<-Fs, filename:extension(F)==".erl"]; _ -> [] end. get_source(Mod) -> L = Mod:module_info(compile), {value, {source, Path}} = lists:keysearch(source, 1, L), case filelib:is_regular(Path) of true -> ?D(Path), Path; false -> ?D(false), get_source_ebin(Mod) end. find_first_var(Var, S) -> case catch get_var(Var, S) of {'EXIT', _} -> error; Other -> Other end. get_ext_inc([], _) -> ""; get_ext_inc([P | Rest], FilePath) -> S = filename:join(P, FilePath), case filelib:is_regular(S) of true -> {ok, S}; false -> get_ext_inc(Rest, FilePath) end. get_source_ebin(Mod) -> EbinPath = code:which(Mod), BeamF = filename:basename(EbinPath), ErlF = filename:rootname(BeamF) ++ ".erl", SrcPath = filename:join([filename:dirname(filename:dirname(EbinPath)), "src", ErlF]), SrcPath. get_var(Var, S) -> ?D({Var, S}), {ok, T, _} = erlide_scan:string(S), ?D(T), FV = find_var(T, Var), ?D(FV), {var, {{_Line, Offset}, Length}, _Var} = FV, {Offset, Length}. find_var([], _) -> not_found; find_var([{var, _, Var} = T | _], Var) -> T; find_var([_ | Rest], Var) -> find_var(Rest, Var).
null
https://raw.githubusercontent.com/erlang/erlide_kernel/763a7fe47213f374b59862fd5a17d5dcc2811c7b/ide/apps/erlide_ide/src/erlide_open.erl
erlang
Author: jakob Description: Exported Functions TODO (JC) there are some code duplication in external modules (and includes) handling Include files API Functions Local Functions add new items, e.g. gen_server calls ?D(R), ?D(lists:flatten(io_lib:format(">> ~p~n", [L]))),
Created : Mar 23 , 2006 -module(erlide_open). -author(''). -export([open/3, find_first_var/2, get_source_from_module/2, get_external_modules/2, get_external_module/2, get_external_module_tree/1, get_external_include/2, get_external_1/3, get_otp_lib_structure/1, get_lib_files/1, get_includes_in_dir/1 ]). -define(DEBUG , 1 ) . -define(IO_FORMAT_DEBUG , 1 ) . -include_lib("erlide_common/include/erlide_dbglog.hrl"). -include("erlide_open.hrl"). -include_lib("erlide_ide_core/include/erlide_token.hrl"). -define(CACHE_VERSION, 4). open(Mod, Offset, #open_context{imports=Imports0}=Context) -> ?D({Mod, Offset, Context}), Imports = erlide_util:add_auto_imported(Imports0), try {TokensWComments, BeforeReversed} = erlide_scanner:get_token_window(Mod, Offset, 45, 100), ?D({TokensWComments, BeforeReversed}), try_open(Offset, TokensWComments, BeforeReversed, Context#open_context{imports=Imports}), error catch throw:{open, Res} -> Res; throw:T -> {error, T}; error:E -> {error, E} end. get_external_include(FilePath, #open_context{externalIncludes=ExternalIncludes, pathVars=PathVars}) -> ?D(FilePath), ExtIncPaths = get_external_modules_files(ExternalIncludes, PathVars), get_ext_inc(ExtIncPaths, FilePath). get_otp_lib_structure(StateDir) -> RenewFun = fun(_) -> CodeLibs = code:get_path(), LibDir = code:lib_dir(), Libs = lists:filter(fun(N) -> lists:prefix(LibDir, N) end, CodeLibs), LibDirs = [get_lib_dir(Lib) || Lib <- lists:sort(Libs)], R = lists:map(fun(Dir) -> SubDirs = ["src", "include"], Group = get_app_group(Dir), {Dir, get_dirs(SubDirs, Dir, []), Group} end, LibDirs), ?D(R), R end, VersionFileName = filename:join([code:root_dir()]), CacheName = filename:join(StateDir, "otp.structure"), {_Cached, R} = erlide_cache:check_and_renew_cached(VersionFileName, CacheName, ?CACHE_VERSION, RenewFun, true), ?D(_Cached), {ok, R}. get_app_group(Dir) -> case file:open(filename:join(Dir, "info"), [read]) of {ok, F} -> case file:read_line(F) of {ok, "group:"++Group} -> Val = string:strip(string:strip(Group),right, $\n), case split_at_first_char($\s, Val) of {[], A} -> A; {A, _} -> A end; _ -> "" end; _-> "" end. split_at_first_char(Char, String) -> lists:split(string:chr(String, Char), String). get_dirs([], _, Acc) -> lists:reverse(Acc); get_dirs([Dir | Rest], Base, Acc) -> D = filename:join(Base, Dir), case filelib:is_dir(D) of true -> {ok, Files} = get_lib_files(D), get_dirs(Rest, Base, [{D, Files} | Acc]); false -> get_dirs(Rest, Base, Acc) end. get_lib_files(Dir) -> case file:list_dir(Dir) of {ok, SrcFiles} -> Files = [filename:join(Dir, SrcFile) || SrcFile <- lists:sort(SrcFiles)], {ok, lists:filter(fun(F) -> filelib:is_regular(F) end, Files)}; _ -> {ok, []} end. get_includes_in_dir(Dir) -> case file:list_dir(Dir) of {ok, Files} -> {ok, filter_includes(lists:sort(Files))}; _ -> {ok, []} end. filter_includes(Files) -> [File || File <- Files, filename:extension(File) == ".hrl"]. get_lib_dir(Dir) -> case filename:basename(Dir) of "ebin" -> filename:dirname(Dir); _ -> Dir end. try_open(Offset, TokensWComments, BeforeReversedWComments, Context) -> Tokens = erlide_text:strip_comments(TokensWComments), BeforeReversed = erlide_text:strip_comments(BeforeReversedWComments), try_open_aux(Offset, Tokens, BeforeReversed, Context). try_open_aux(Offset, Tokens, BeforeReversed, Context) -> case Tokens of [#token{offset=O} | _] = Tokens when O =< Offset -> ?D(Tokens), o_tokens(Tokens, Offset, Context, BeforeReversed), case BeforeReversed of [] -> not_found; [B | Rest] -> try_open_aux(Offset, [B | Tokens], Rest, Context) end; _ -> ok end. has_prefix(Prefix, FileName) -> lists:prefix(Prefix, filename:basename(FileName)). has_name(Name, FileName) -> Name == filename:rootname(filename:basename(FileName)). get_external_modules(Prefix, #open_context{externalModules=ExternalModulesFiles, pathVars=PathVars}) -> ExternalModules = get_external_modules_files(ExternalModulesFiles, PathVars), {ok, [XM || XM <- ExternalModules, has_prefix(Prefix, XM)]}. get_external_module_tree(#open_context{externalModules=ExternalModulesFiles, pathVars=PathVars}) -> {ok, get_external_module_tree(ExternalModulesFiles, PathVars)}. get_external_module(Name, #open_context{externalModules=ExternalModulesFiles, pathVars=PathVars}) -> ExternalModules = get_external_modules_files(ExternalModulesFiles, PathVars), case [XM || XM <- ExternalModules, has_name(Name, XM)] of [Path | _] -> {ok, Path}; _ -> not_found end. get_external_module_tree(PackedFileNames, PathVars) -> Fun = fun(Parent, FileName, Acc) -> [{Parent, replace_path_var(FileName, PathVars), module} | Acc] end, Fun2 = fun(Parent, FileName, Acc) -> [{Parent, replace_path_var(FileName, PathVars), entry} | Acc] end, FileNames = erlide_util:unpack(PackedFileNames), R = fold_externals(Fun, Fun2, FileNames, PathVars), R. consider_local([]) -> true; consider_local([#token{kind=':'} | _]) -> false; consider_local(_) -> true. consider_macro_def([#token{kind=atom, value=define}, #token{kind='-'} | _]) -> true; consider_macro_def([#token{kind='('} | Rest]) -> consider_macro_def(Rest); consider_macro_def(_) -> false. consider_record_field_ref([#token{kind='{'}, #token{kind=atom, value=Record}, #token{kind='#'} | _]) -> {true, Record}; consider_record_field_ref([_ | Rest]) -> consider_record_field_ref(Rest); consider_record_field_ref(_) -> false. TODO : rewrite this with some kind of table , and make it possible to o_tokens([#token{kind=atom, value=include} | Rest], _, _, [#token{kind='-'} | _]) -> o_include(Rest); o_tokens([#token{kind=atom, value=include_lib} | Rest], _, _, [#token{kind='-'} | _]) -> o_include_lib(Rest); o_tokens([#token{kind=atom, value=define} | Rest], _, _, _) -> o_macro_def(Rest); o_tokens([#token{kind=atom, value=record} | Rest], Offset, _, [#token{kind='-'} | _]) -> o_record_def(Rest, Offset); o_tokens([#token{kind='#'}, #token{kind=atom, value=Value} | _] = Tokens, Offset, _, _) -> o_record(Tokens, Offset, Value); o_tokens([#token{kind='#'}, #token{kind=macro, value=Value} | _] = Tokens, Offset, _, _) -> o_record(Tokens, Offset, Value); o_tokens([#token{kind=atom, value=Module}, #token{kind=':'}, #token{kind=atom, value=Function}, #token{kind='/'}, #token{kind=integer, value=Arity} | _], _, Context, _) -> o_external(Module, Function, Arity, Context); o_tokens([#token{kind=atom, value=Module}, #token{kind=':'}, #token{kind=atom, value=Function} | Rest], _, Context, _) -> o_external(Module, Function, Rest, Context); o_tokens([#token{kind=macro, value=Module}, #token{kind=':'}, #token{kind=atom, value=Function} | Rest], _, Context, _) -> o_external(Module, Function, Rest, Context); o_tokens([#token{kind=atom, value=Function}, #token{kind='/'}, #token{kind=integer, value=Arity} | _], _, Context, [#token{kind=':'}, #token{kind=atom, value=Module} | _]) -> o_external(Module, Function, Arity, Context); o_tokens([#token{kind=atom, value=Function}, #token{kind='/'}, #token{kind=integer, value=Arity} | _], _, Context, _BeforeReversed) -> o_local(Function, Arity, Context); o_tokens([#token{kind='/'}, #token{kind=integer, value=Arity} | _], _, Context, [#token{kind=atom, value=Function} | _]) -> o_local(Function, Arity, Context); o_tokens([#token{kind=atom, value=Value} | _] = Tokens, Offset, _, [#token{kind='#'} | _]) -> o_record(Tokens, Offset, Value); o_tokens([#token{kind=macro, value=Value} | _] = Tokens, Offset, _, [#token{kind='#'} | _]) -> o_record(Tokens, Offset, Value); o_tokens([#token{kind=macro, value=Value} | _], _, _, _) -> o_macro(Value); o_tokens([#token{kind=atom, value=Function}, #token{kind='('} | Rest], _, Context, BeforeReversed) -> case consider_local(BeforeReversed) of true -> ?D(Rest), o_local(Function, erlide_text:guess_arity(Rest), Context); false -> continue end; o_tokens([#token{kind=atom, value=Value} | _], _Offset, _, BeforeReversed) -> case consider_record_field_ref(BeforeReversed) of {true, Record} -> throw({open, {field, Record, Value}}); false -> no end; o_tokens([#token{kind=var, value=VarName} | _], _, _, BeforeReversed) -> case consider_macro_def(BeforeReversed) of true -> throw({open, {macro_def, VarName}}); false -> throw({open, {variable, VarName}}) end; o_tokens(_, _, _, _) -> no. o_include([#token{kind='('}, #token{kind=string, value=File} | _]) -> throw({open, {include, File}}); o_include(_) -> no. o_include_lib([#token{kind='('}, #token{kind=string, value=Path} | _]) -> ?D(Path), IncludeLib = get_otp_include_lib(Path), throw({open, IncludeLib}); o_include_lib(_) -> no. o_macro(Value) -> throw({open, {macro, Value}}). o_macro_def([#token{kind='('}, #token{kind=var, value=Value} | _]) -> throw({open, {macro, Value}}); o_macro_def([#token{kind='('}, #token{kind=atom, value=Value} | _]) -> throw({open, {macro, Value}}). o_record(Tokens, Offset, Value) -> {State, _Name, Prefix, _Fields} = erlide_content_assist:check_record_tokens(upto_offset(Tokens, Offset)), case State of record_want_field -> throw({open, {field, Value, Prefix}}); record_want_dot_field -> throw({open, {field, Value, Prefix}}); record_dot_field -> throw({open, {field, Value, Prefix}}); record_field -> throw({open, {field, Value, Prefix}}); _ -> throw({open, {record, Value}}) end. upto_offset([#token{offset=O, length=L}=T | Rest], Offset) when Offset>=O+L -> [T | upto_offset(Rest, Offset)]; upto_offset([], _) -> []; upto_offset([T | _], _) -> [T]. o_record_def([#token{kind='('}, #token{value=Value, offset=O, length=L}, #token{kind=','} | _Tokens], Offset) when Offset=<O+L -> throw({open, {record, Value}}); o_record_def([#token{kind='('}, #token{value=Value}, #token{kind=','} | Tokens], Offset) -> Between = erlide_np_util:get_between_outer_pars(Tokens, '{', '}'), o_record_def_aux(Between, Offset, Value, want_field). o_record_def_aux([], _Offset, Record, _) -> throw({open, {record, Record}}); o_record_def_aux([#token{offset=O, length=L, value=Field} | _], Offset, Record, want_field) when Offset<O+L -> throw({open, {field, Record, Field}}); o_record_def_aux([#token{value=V} | _]=Tokens, Offset, Record, _) when V=:='('; V=:='{'; V=:='['; V=:='<<' -> Rest = erlide_text:skip_expr(Tokens), o_record_def_aux(Rest, Offset, Record, want_comma); o_record_def_aux([#token{value=','} | Rest], Offset, Record, want_comma) -> o_record_def_aux(Rest, Offset, Record, want_field); o_record_def_aux([_ | Rest], Offset, Record, W) -> o_record_def_aux(Rest, Offset, Record, W). o_external(Module, Function, [_ | ParameterListTokens], Context) -> ?D({Module, Function, ParameterListTokens}), A = erlide_text:guess_arity(ParameterListTokens), ?D(A), P = get_source_from_module(Module, Context), throw({open, {external, Module, Function, A, P}}); o_external(Module, Function, Arity, Context) when is_integer(Arity) -> ?D({Module, Function, Arity}), P = get_source_from_module(Module, Context), throw({open, {external, Module, Function, Arity, P}}). o_local(Function, Arity, #open_context{imports=Imports}=Context) -> case get_imported(Imports, {Function, Arity}) of false -> throw({open, {local, Function, Arity}}); Module -> P = get_source_from_module(Module, Context), throw({open, {external, Module, Function, Arity, P}}) end. get_imported([], _) -> false; get_imported([{Mod, Funcs} | Rest], Func) -> case lists:member(Func, Funcs) of true -> Mod; false -> get_imported(Rest, Func) end. get_otp_include_lib(Path) -> {Lib, Rest} = find_lib_dir(Path), FileName = filename:basename(Rest), {include_lib, FileName, filename:join([Lib | Rest])}. find_lib_dir(Dir) -> [Lib | Rest] = filename:split(Dir), ?D(Lib), {code:lib_dir(list_to_atom(Lib)), Rest}. get_source_from_module(Mod, Context) -> case catch get_source(Mod) of {'EXIT', _E} -> ?D({get_source, _E}), case catch select_external(get_erl_from_dirs(Context#open_context.extraSourcePaths), atom_to_list(Mod)) of Path when is_list(Path) -> Path; _ -> get_source_from_external_modules(Mod, Context) end; Other -> Other end. get_external_modules_files(PackedFileNames, PathVars) -> ?D(PackedFileNames), Fun = fun(_Parent, FileName, Acc) -> [replace_path_var(FileName, PathVars) | Acc] end, Fun2 = fun(_Parent, _FileName, Acc) -> Acc end, FileNames = erlide_util:unpack(PackedFileNames), R = fold_externals(Fun, Fun2, FileNames, PathVars), R. replace_path_vars(FileNames, PathVars) -> [replace_path_var(F, PathVars) || F <- FileNames]. replace_path_var(FileName, PathVars) -> case filename:split(FileName) of [Var | Rest] -> filename:join([replace_path_var_aux(Var, PathVars) | Rest]); _ -> FileName end. replace_path_var_aux(Var, PathVars) -> case lists:keysearch(Var, 1, PathVars) of {value, {Var, Value}} -> Value; _ -> Var end. get_external_1(FileName0, PathVars, IsRoot) -> FileName = replace_path_var(FileName0, PathVars), FileNames = case IsRoot orelse filename:extension(FileName) == ".erlidex" of true -> case file:read_file(FileName) of {ok, B} -> erlide_util:split_lines(B); _ -> [FileName] end; false -> [FileName] end, R = replace_path_vars(FileNames, PathVars), {ok, R}. fold_externals(Fun, Fun2, FileNames, PathVars) -> {_Done, Acc} = fx(FileNames, Fun, Fun2, PathVars, "root", [], []), lists:reverse(Acc). fx([], _Fun, _Fun2, _PathVars, _Parent, Done, Acc) -> {Done, Acc}; fx([FN0 | Rest], Fun, Fun2, PathVars, Parent, Done, Acc) -> FN = replace_path_var(FN0, PathVars), case lists:member(FN, Done) of true -> fx(Rest, Fun, Fun2, PathVars, Parent, Done, Acc); false -> case Parent=:="root" orelse filename:extension(FN) == ".erlidex" of true -> {NewDone, NewAcc} = fx2(FN, Fun, Fun2, PathVars, Parent, Done, Acc), fx(Rest, Fun, Fun2, PathVars, Parent, NewDone, NewAcc); false -> fx(Rest, Fun, Fun2, PathVars, Parent, [FN | Done], Fun(Parent, FN, Acc)) end end. fx2(FN, Fun, Fun2, PathVars, Parent, Done, Acc) -> NewAcc = Fun2(Parent, FN, Acc), case file:read_file(FN) of {ok, B} -> Lines = erlide_util:split_lines(B), fx(Lines, Fun, Fun2, PathVars, FN, [FN | Done], NewAcc); _ -> {Done, Acc} end. get_source_from_external_modules(Mod, #open_context{externalModules=ExternalModules, pathVars=PathVars, extraSourcePaths=ExtraSources}=_Context) -> ?D(_Context), L = get_external_modules_files(ExternalModules, PathVars), ?D({get_external_modules_files, length(L)}), _Extra = get_erl_from_dirs(ExtraSources), ?D({extra, _Extra}), select_external(L, atom_to_list(Mod)). select_external([], _) -> not_found; select_external([P | Rest], Mod) -> Name = filename:rootname(filename:basename(P)), ? D({select_external , Name , , P } ) , case Name of Mod -> P; _ -> select_external(Rest, Mod) end. get_erl_from_dirs(undefined) -> []; get_erl_from_dirs(L) -> ?D({get_erl_from_dirs, L}), lists:flatmap(fun(X) -> get_erl_from_dir(X) end, L). get_erl_from_dir(D) -> case file:list_dir(D) of {ok, Fs} -> [filename:join(D, F) || F<-Fs, filename:extension(F)==".erl"]; _ -> [] end. get_source(Mod) -> L = Mod:module_info(compile), {value, {source, Path}} = lists:keysearch(source, 1, L), case filelib:is_regular(Path) of true -> ?D(Path), Path; false -> ?D(false), get_source_ebin(Mod) end. find_first_var(Var, S) -> case catch get_var(Var, S) of {'EXIT', _} -> error; Other -> Other end. get_ext_inc([], _) -> ""; get_ext_inc([P | Rest], FilePath) -> S = filename:join(P, FilePath), case filelib:is_regular(S) of true -> {ok, S}; false -> get_ext_inc(Rest, FilePath) end. get_source_ebin(Mod) -> EbinPath = code:which(Mod), BeamF = filename:basename(EbinPath), ErlF = filename:rootname(BeamF) ++ ".erl", SrcPath = filename:join([filename:dirname(filename:dirname(EbinPath)), "src", ErlF]), SrcPath. get_var(Var, S) -> ?D({Var, S}), {ok, T, _} = erlide_scan:string(S), ?D(T), FV = find_var(T, Var), ?D(FV), {var, {{_Line, Offset}, Length}, _Var} = FV, {Offset, Length}. find_var([], _) -> not_found; find_var([{var, _, Var} = T | _], Var) -> T; find_var([_ | Rest], Var) -> find_var(Rest, Var).
de32218e13d538c69322296fc1424e6263fe102c427339ed43bc693b9bb7b9c7
Zulu-Inuoe/clution
os.lisp
;;;; --------------------------------------------------------------------------- ;;;; Access to the Operating System (uiop/package:define-package :uiop/os (:use :uiop/common-lisp :uiop/package :uiop/utility) (:export #:featurep #:os-unix-p #:os-macosx-p #:os-windows-p #:os-genera-p #:detect-os ;; features #:os-cond #:getenv #:getenvp ;; environment variables #:implementation-identifier ;; implementation identifier #:implementation-type #:*implementation-type* #:operating-system #:architecture #:lisp-version-string #:hostname #:getcwd #:chdir ;; Windows shortcut support #:read-null-terminated-string #:read-little-endian #:parse-file-location-info #:parse-windows-shortcut)) (in-package :uiop/os) ;;; Features (with-upgradability () (defun featurep (x &optional (*features* *features*)) "Checks whether a feature expression X is true with respect to the *FEATURES* set, as per the CLHS standard for #+ and #-. Beware that just like the CLHS, we assume symbols from the KEYWORD package are used, but that unless you're using #+/#- your reader will not have magically used the KEYWORD package, so you need specify keywords explicitly." (cond ((atom x) (and (member x *features*) t)) ((eq :not (car x)) (assert (null (cddr x))) (not (featurep (cadr x)))) ((eq :or (car x)) (some #'featurep (cdr x))) ((eq :and (car x)) (every #'featurep (cdr x))) (t (parameter-error "~S: malformed feature specification ~S" 'featurep x)))) Starting with UIOP 3.1.5 , these are runtime tests . ;; You may bind *features* with a copy of what your target system offers to test its properties. (defun os-macosx-p () "Is the underlying operating system MacOS X?" ;; OS-MACOSX is not mutually exclusive with OS-UNIX, ;; in fact the former implies the latter. (featurep '(:or :darwin (:and :allegro :macosx) (:and :clisp :macos)))) (defun os-unix-p () "Is the underlying operating system some Unix variant?" (or (featurep '(:or :unix :cygwin)) (os-macosx-p))) (defun os-windows-p () "Is the underlying operating system Microsoft Windows?" (and (not (os-unix-p)) (featurep '(:or :win32 :windows :mswindows :mingw32 :mingw64)))) (defun os-genera-p () "Is the underlying operating system Genera (running on a Symbolics Lisp Machine)?" (featurep :genera)) (defun os-oldmac-p () "Is the underlying operating system an (emulated?) MacOS 9 or earlier?" (featurep :mcl)) (defun os-haiku-p () "Is the underlying operating system Haiku?" (featurep :haiku)) (defun detect-os () "Detects the current operating system. Only needs be run at compile-time, except on ABCL where it might change between FASL compilation and runtime." (loop* :with o :for (feature . detect) :in '((:os-unix . os-unix-p) (:os-macosx . os-macosx-p) (:os-windows . os-windows-p) (:genera . os-genera-p) (:os-oldmac . os-oldmac-p) (:haiku . os-haiku-p)) :when (and (or (not o) (eq feature :os-macosx)) (funcall detect)) :do (setf o feature) (pushnew feature *features*) :else :do (setf *features* (remove feature *features*)) :finally (return (or o (error "Congratulations for trying ASDF on an operating system~%~ that is neither Unix, nor Windows, nor Genera, nor even old MacOS.~%Now you port it."))))) (defmacro os-cond (&rest clauses) #+abcl `(cond ,@clauses) #-abcl (loop* :for (test . body) :in clauses :when (eval test) :return `(progn ,@body))) (detect-os)) ;;;; Environment variables: getting them, and parsing them. (with-upgradability () (defun getenv (x) "Query the environment, as in C getenv. Beware: may return empty string if a variable is present but empty; use getenvp to return NIL in such a case." (declare (ignorable x)) #+(or abcl clasp clisp ecl xcl) (ext:getenv x) #+allegro (sys:getenv x) #+clozure (ccl:getenv x) #+cmucl (unix:unix-getenv x) #+scl (cdr (assoc x ext:*environment-list* :test #'string=)) #+cormanlisp (let* ((buffer (ct:malloc 1)) (cname (ct:lisp-string-to-c-string x)) (needed-size (win:getenvironmentvariable cname buffer 0)) (buffer1 (ct:malloc (1+ needed-size)))) (prog1 (if (zerop (win:getenvironmentvariable cname buffer1 needed-size)) nil (ct:c-string-to-lisp-string buffer1)) (ct:free buffer) (ct:free buffer1))) #+gcl (system:getenv x) #+genera nil #+lispworks (lispworks:environment-variable x) #+mcl (ccl:with-cstrs ((name x)) (let ((value (_getenv name))) (unless (ccl:%null-ptr-p value) (ccl:%get-cstring value)))) #+mkcl (#.(or (find-symbol* 'getenv :si nil) (find-symbol* 'getenv :mk-ext nil)) x) #+sbcl (sb-ext:posix-getenv x) #-(or abcl allegro clasp clisp clozure cmucl cormanlisp ecl gcl genera lispworks mcl mkcl sbcl scl xcl) (not-implemented-error 'getenv)) (defsetf getenv (x) (val) "Set an environment variable." (declare (ignorable x val)) #+allegro `(setf (sys:getenv ,x) ,val) #+clisp `(system::setenv ,x ,val) #+clozure `(ccl:setenv ,x ,val) #+cmucl `(unix:unix-setenv ,x ,val 1) #+ecl `(ext:setenv ,x ,val) #+lispworks `(hcl:setenv ,x ,val) #+mkcl `(mkcl:setenv ,x ,val) #+sbcl `(progn (require :sb-posix) (symbol-call :sb-posix :setenv ,x ,val 1)) #-(or allegro clisp clozure cmucl ecl lispworks mkcl sbcl) '(not-implemented-error '(setf getenv))) (defun getenvp (x) "Predicate that is true if the named variable is present in the libc environment, then returning the non-empty string value of the variable" (let ((g (getenv x))) (and (not (emptyp g)) g)))) ;;;; implementation-identifier ;; ;; produce a string to identify current implementation. Initially stolen from SLIME 's SWANK , completely rewritten since . We 're back to runtime checking , for the sake of e.g. ABCL . (with-upgradability () (defun first-feature (feature-sets) "A helper for various feature detection functions" (dolist (x feature-sets) (multiple-value-bind (short long feature-expr) (if (consp x) (values (first x) (second x) (cons :or (rest x))) (values x x x)) (when (featurep feature-expr) (return (values short long)))))) (defun implementation-type () "The type of Lisp implementation used, as a short UIOP-standardized keyword" (first-feature '(:abcl (:acl :allegro) (:ccl :clozure) :clisp (:corman :cormanlisp) (:cmu :cmucl :cmu) :clasp :ecl :gcl (:lwpe :lispworks-personal-edition) (:lw :lispworks) :mcl :mkcl :sbcl :scl (:smbx :symbolics) :xcl))) (defvar *implementation-type* (implementation-type) "The type of Lisp implementation used, as a short UIOP-standardized keyword") (defun operating-system () "The operating system of the current host" (first-feature '(:cygwin try first ! for GCL at least , must appear before : bsd also before : bsd (:solaris :solaris :sunos) (:bsd :bsd :freebsd :netbsd :openbsd :dragonfly) :unix :genera))) (defun architecture () "The CPU architecture of the current host" (first-feature '((:x64 :x86-64 :x86_64 :x8664-target :amd64 (:and :word-size=64 :pc386)) (:x86 :x86 :i386 :i486 :i586 :i686 :pentium3 :pentium4 :pc386 :iapx386 :x8632-target) (:ppc64 :ppc64 :ppc64-target) (:ppc32 :ppc32 :ppc32-target :ppc :powerpc) :hppa64 :hppa :sparc64 (:sparc32 :sparc32 :sparc) :mipsel :mipseb :mips :alpha (:arm :arm :arm-target) :imach Java comes last : if someone uses C via CFFI or otherwise JNA or JNI , ;; we may have to segregate the code still by architecture. (:java :java :java-1.4 :java-1.5 :java-1.6 :java-1.7)))) #+clozure (defun ccl-fasl-version () the fasl version is target - dependent from CCL 1.8 on . (or (let ((s 'ccl::target-fasl-version)) (and (fboundp s) (funcall s))) (and (boundp 'ccl::fasl-version) (symbol-value 'ccl::fasl-version)) (error "Can't determine fasl version."))) (defun lisp-version-string () "return a string that identifies the current Lisp implementation version" (let ((s (lisp-implementation-version))) (car ; as opposed to OR, this idiom prevents some unreachable code warning (list #+allegro (format nil "~A~@[~A~]~@[~A~]~@[~A~]" excl::*common-lisp-version-number* ;; M means "modern", as opposed to ANSI-compatible mode (which I consider default) (and (eq excl:*current-case-mode* :case-sensitive-lower) "M") Note if not using International ACL ;; see -target-case.htm (excl:ics-target-case (:-ics "8")) (and (member :smp *features*) "S")) #+armedbear (format nil "~a-fasl~a" s system::*fasl-version*) #+clisp (subseq s 0 (position #\space s)) ; strip build information (date, etc.) #+clozure (format nil "~d.~d-f~d" ; shorten for windows ccl::*openmcl-major-version* ccl::*openmcl-minor-version* (logand (ccl-fasl-version) #xFF)) #+cmucl (substitute #\- #\/ s) #+scl (format nil "~A~A" s ;; ANSI upper case vs lower case. (ecase ext:*case-mode* (:upper "") (:lower "l"))) #+ecl (format nil "~A~@[-~A~]" s (let ((vcs-id (ext:lisp-implementation-vcs-id))) (unless (equal vcs-id "UNKNOWN") (subseq vcs-id 0 (min (length vcs-id) 8))))) #+gcl (subseq s (1+ (position #\space s))) #+genera (multiple-value-bind (major minor) (sct:get-system-version "System") (format nil "~D.~D" major minor)) strip the leading " Version " seems like there should be a shorter way to do this , like . #+mkcl (or (let ((fname (find-symbol* '#:git-describe-this-mkcl :mkcl nil))) (when (and fname (fboundp fname)) (funcall fname))) s) s)))) (defun implementation-identifier () "Return a string that identifies the ABI of the current implementation, suitable for use as a directory name to segregate Lisp FASLs, C dynamic libraries, etc." (substitute-if #\_ #'(lambda (x) (find x " /:;&^\\|?<>(){}[]$#`'\"")) (format nil "~(~a~@{~@[-~a~]~}~)" (or (implementation-type) (lisp-implementation-type)) (lisp-version-string) (or (operating-system) (software-type)) (or (architecture) (machine-type)))))) ;;;; Other system information (with-upgradability () (defun hostname () "return the hostname of the current host" #+(or abcl clasp clozure cmucl ecl genera lispworks mcl mkcl sbcl scl xcl) (machine-instance) #+cormanlisp "localhost" ;; is there a better way? Does it matter? #+allegro (symbol-call :excl.osi :gethostname) #+clisp (first (split-string (machine-instance) :separator " ")) #+gcl (system:gethostname))) ;;; Current directory (with-upgradability () #+cmucl (defun parse-unix-namestring* (unix-namestring) "variant of LISP::PARSE-UNIX-NAMESTRING that returns a pathname object" (multiple-value-bind (host device directory name type version) (lisp::parse-unix-namestring unix-namestring 0 (length unix-namestring)) (make-pathname :host (or host lisp::*unix-host*) :device device :directory directory :name name :type type :version version))) (defun getcwd () "Get the current working directory as per POSIX getcwd(3), as a pathname object" (or #+(or abcl genera xcl) (truename *default-pathname-defaults*) ;; d-p-d is canonical! #+allegro (excl::current-directory) #+clisp (ext:default-directory) #+clozure (ccl:current-directory) #+(or cmucl scl) (#+cmucl parse-unix-namestring* #+scl lisp::parse-unix-namestring (strcat (nth-value 1 (unix:unix-current-directory)) "/")) #+cormanlisp (pathname (pl::get-current-directory)) ;; Q: what type does it return? #+(or clasp ecl) (ext:getcwd) #+gcl (let ((*default-pathname-defaults* #p"")) (truename #p"")) #+lispworks (hcl:get-working-directory) #+mkcl (mk-ext:getcwd) #+sbcl (sb-ext:parse-native-namestring (sb-unix:posix-getcwd/)) #+xcl (extensions:current-directory) (not-implemented-error 'getcwd))) (defun chdir (x) "Change current directory, as per POSIX chdir(2), to a given pathname object" (if-let (x (pathname x)) #+(or abcl genera xcl) (setf *default-pathname-defaults* (truename x)) ;; d-p-d is canonical! #+allegro (excl:chdir x) #+clisp (ext:cd x) #+clozure (setf (ccl:current-directory) x) #+(or cmucl scl) (unix:unix-chdir (ext:unix-namestring x)) #+cormanlisp (unless (zerop (win32::_chdir (namestring x))) (error "Could not set current directory to ~A" x)) #+(or clasp ecl) (ext:chdir x) #+gcl (system:chdir x) #+lispworks (hcl:change-directory x) #+mkcl (mk-ext:chdir x) #+sbcl (progn (require :sb-posix) (symbol-call :sb-posix :chdir (sb-ext:native-namestring x))) #-(or abcl allegro clasp clisp clozure cmucl cormanlisp ecl gcl genera lispworks mkcl sbcl scl xcl) (not-implemented-error 'chdir)))) ;;;; ----------------------------------------------------------------- ;;;; Windows shortcut support. Based on: ;;;; : The Windows Shortcut File Format . ;;;; CLISP does n't need it , and READ - SEQUENCE annoys old that does n't need it (with-upgradability () (defparameter *link-initial-dword* 76) (defparameter *link-guid* #(1 20 2 0 0 0 0 0 192 0 0 0 0 0 0 70)) (defun read-null-terminated-string (s) "Read a null-terminated string from an octet stream S" note : does n't play well with UNICODE (with-output-to-string (out) (loop :for code = (read-byte s) :until (zerop code) :do (write-char (code-char code) out)))) (defun read-little-endian (s &optional (bytes 4)) "Read a number in little-endian format from an byte (octet) stream S, the number having BYTES octets (defaulting to 4)." (loop :for i :from 0 :below bytes :sum (ash (read-byte s) (* 8 i)))) (defun parse-file-location-info (s) "helper to parse-windows-shortcut" (let ((start (file-position s)) (total-length (read-little-endian s)) (end-of-header (read-little-endian s)) (fli-flags (read-little-endian s)) (local-volume-offset (read-little-endian s)) (local-offset (read-little-endian s)) (network-volume-offset (read-little-endian s)) (remaining-offset (read-little-endian s))) (declare (ignore total-length end-of-header local-volume-offset)) (unless (zerop fli-flags) (cond ((logbitp 0 fli-flags) (file-position s (+ start local-offset))) ((logbitp 1 fli-flags) (file-position s (+ start network-volume-offset #x14)))) (strcat (read-null-terminated-string s) (progn (file-position s (+ start remaining-offset)) (read-null-terminated-string s)))))) (defun parse-windows-shortcut (pathname) "From a .lnk windows shortcut, extract the pathname linked to" NB : does n't do much checking & does n't look like it will work well with UNICODE . (with-open-file (s pathname :element-type '(unsigned-byte 8)) (handler-case (when (and (= (read-little-endian s) *link-initial-dword*) (let ((header (make-array (length *link-guid*)))) (read-sequence header s) (equalp header *link-guid*))) (let ((flags (read-little-endian s))) (file-position s 76) ;skip rest of header (when (logbitp 0 flags) ;; skip shell item id list (let ((length (read-little-endian s 2))) (file-position s (+ length (file-position s))))) (cond ((logbitp 1 flags) (parse-file-location-info s)) (t (when (logbitp 2 flags) ;; skip description string (let ((length (read-little-endian s 2))) (file-position s (+ length (file-position s))))) (when (logbitp 3 flags) ;; finally, our pathname (let* ((length (read-little-endian s 2)) (buffer (make-array length))) (read-sequence buffer s) (map 'string #'code-char buffer))))))) (end-of-file (c) (declare (ignore c)) nil)))))
null
https://raw.githubusercontent.com/Zulu-Inuoe/clution/b72f7afe5f770ff68a066184a389c23551863f7f/cl-clution/qlfile-libs/uiop-3.3.1/os.lisp
lisp
--------------------------------------------------------------------------- Access to the Operating System features environment variables implementation identifier Windows shortcut support Features You may bind *features* with a copy of what your target system offers to test its properties. OS-MACOSX is not mutually exclusive with OS-UNIX, in fact the former implies the latter. Environment variables: getting them, and parsing them. implementation-identifier produce a string to identify current implementation. we may have to segregate the code still by architecture. as opposed to OR, this idiom prevents some unreachable code warning M means "modern", as opposed to ANSI-compatible mode (which I consider default) see -target-case.htm strip build information (date, etc.) shorten for windows ANSI upper case vs lower case. Other system information is there a better way? Does it matter? Current directory d-p-d is canonical! Q: what type does it return? d-p-d is canonical! ----------------------------------------------------------------- Windows shortcut support. Based on: skip rest of header skip shell item id list skip description string finally, our pathname
(uiop/package:define-package :uiop/os (:use :uiop/common-lisp :uiop/package :uiop/utility) (:export #:os-cond #:implementation-type #:*implementation-type* #:operating-system #:architecture #:lisp-version-string #:hostname #:getcwd #:chdir #:read-null-terminated-string #:read-little-endian #:parse-file-location-info #:parse-windows-shortcut)) (in-package :uiop/os) (with-upgradability () (defun featurep (x &optional (*features* *features*)) "Checks whether a feature expression X is true with respect to the *FEATURES* set, as per the CLHS standard for #+ and #-. Beware that just like the CLHS, we assume symbols from the KEYWORD package are used, but that unless you're using #+/#- your reader will not have magically used the KEYWORD package, so you need specify keywords explicitly." (cond ((atom x) (and (member x *features*) t)) ((eq :not (car x)) (assert (null (cddr x))) (not (featurep (cadr x)))) ((eq :or (car x)) (some #'featurep (cdr x))) ((eq :and (car x)) (every #'featurep (cdr x))) (t (parameter-error "~S: malformed feature specification ~S" 'featurep x)))) Starting with UIOP 3.1.5 , these are runtime tests . (defun os-macosx-p () "Is the underlying operating system MacOS X?" (featurep '(:or :darwin (:and :allegro :macosx) (:and :clisp :macos)))) (defun os-unix-p () "Is the underlying operating system some Unix variant?" (or (featurep '(:or :unix :cygwin)) (os-macosx-p))) (defun os-windows-p () "Is the underlying operating system Microsoft Windows?" (and (not (os-unix-p)) (featurep '(:or :win32 :windows :mswindows :mingw32 :mingw64)))) (defun os-genera-p () "Is the underlying operating system Genera (running on a Symbolics Lisp Machine)?" (featurep :genera)) (defun os-oldmac-p () "Is the underlying operating system an (emulated?) MacOS 9 or earlier?" (featurep :mcl)) (defun os-haiku-p () "Is the underlying operating system Haiku?" (featurep :haiku)) (defun detect-os () "Detects the current operating system. Only needs be run at compile-time, except on ABCL where it might change between FASL compilation and runtime." (loop* :with o :for (feature . detect) :in '((:os-unix . os-unix-p) (:os-macosx . os-macosx-p) (:os-windows . os-windows-p) (:genera . os-genera-p) (:os-oldmac . os-oldmac-p) (:haiku . os-haiku-p)) :when (and (or (not o) (eq feature :os-macosx)) (funcall detect)) :do (setf o feature) (pushnew feature *features*) :else :do (setf *features* (remove feature *features*)) :finally (return (or o (error "Congratulations for trying ASDF on an operating system~%~ that is neither Unix, nor Windows, nor Genera, nor even old MacOS.~%Now you port it."))))) (defmacro os-cond (&rest clauses) #+abcl `(cond ,@clauses) #-abcl (loop* :for (test . body) :in clauses :when (eval test) :return `(progn ,@body))) (detect-os)) (with-upgradability () (defun getenv (x) "Query the environment, as in C getenv. use getenvp to return NIL in such a case." (declare (ignorable x)) #+(or abcl clasp clisp ecl xcl) (ext:getenv x) #+allegro (sys:getenv x) #+clozure (ccl:getenv x) #+cmucl (unix:unix-getenv x) #+scl (cdr (assoc x ext:*environment-list* :test #'string=)) #+cormanlisp (let* ((buffer (ct:malloc 1)) (cname (ct:lisp-string-to-c-string x)) (needed-size (win:getenvironmentvariable cname buffer 0)) (buffer1 (ct:malloc (1+ needed-size)))) (prog1 (if (zerop (win:getenvironmentvariable cname buffer1 needed-size)) nil (ct:c-string-to-lisp-string buffer1)) (ct:free buffer) (ct:free buffer1))) #+gcl (system:getenv x) #+genera nil #+lispworks (lispworks:environment-variable x) #+mcl (ccl:with-cstrs ((name x)) (let ((value (_getenv name))) (unless (ccl:%null-ptr-p value) (ccl:%get-cstring value)))) #+mkcl (#.(or (find-symbol* 'getenv :si nil) (find-symbol* 'getenv :mk-ext nil)) x) #+sbcl (sb-ext:posix-getenv x) #-(or abcl allegro clasp clisp clozure cmucl cormanlisp ecl gcl genera lispworks mcl mkcl sbcl scl xcl) (not-implemented-error 'getenv)) (defsetf getenv (x) (val) "Set an environment variable." (declare (ignorable x val)) #+allegro `(setf (sys:getenv ,x) ,val) #+clisp `(system::setenv ,x ,val) #+clozure `(ccl:setenv ,x ,val) #+cmucl `(unix:unix-setenv ,x ,val 1) #+ecl `(ext:setenv ,x ,val) #+lispworks `(hcl:setenv ,x ,val) #+mkcl `(mkcl:setenv ,x ,val) #+sbcl `(progn (require :sb-posix) (symbol-call :sb-posix :setenv ,x ,val 1)) #-(or allegro clisp clozure cmucl ecl lispworks mkcl sbcl) '(not-implemented-error '(setf getenv))) (defun getenvp (x) "Predicate that is true if the named variable is present in the libc environment, then returning the non-empty string value of the variable" (let ((g (getenv x))) (and (not (emptyp g)) g)))) Initially stolen from SLIME 's SWANK , completely rewritten since . We 're back to runtime checking , for the sake of e.g. ABCL . (with-upgradability () (defun first-feature (feature-sets) "A helper for various feature detection functions" (dolist (x feature-sets) (multiple-value-bind (short long feature-expr) (if (consp x) (values (first x) (second x) (cons :or (rest x))) (values x x x)) (when (featurep feature-expr) (return (values short long)))))) (defun implementation-type () "The type of Lisp implementation used, as a short UIOP-standardized keyword" (first-feature '(:abcl (:acl :allegro) (:ccl :clozure) :clisp (:corman :cormanlisp) (:cmu :cmucl :cmu) :clasp :ecl :gcl (:lwpe :lispworks-personal-edition) (:lw :lispworks) :mcl :mkcl :sbcl :scl (:smbx :symbolics) :xcl))) (defvar *implementation-type* (implementation-type) "The type of Lisp implementation used, as a short UIOP-standardized keyword") (defun operating-system () "The operating system of the current host" (first-feature '(:cygwin try first ! for GCL at least , must appear before : bsd also before : bsd (:solaris :solaris :sunos) (:bsd :bsd :freebsd :netbsd :openbsd :dragonfly) :unix :genera))) (defun architecture () "The CPU architecture of the current host" (first-feature '((:x64 :x86-64 :x86_64 :x8664-target :amd64 (:and :word-size=64 :pc386)) (:x86 :x86 :i386 :i486 :i586 :i686 :pentium3 :pentium4 :pc386 :iapx386 :x8632-target) (:ppc64 :ppc64 :ppc64-target) (:ppc32 :ppc32 :ppc32-target :ppc :powerpc) :hppa64 :hppa :sparc64 (:sparc32 :sparc32 :sparc) :mipsel :mipseb :mips :alpha (:arm :arm :arm-target) :imach Java comes last : if someone uses C via CFFI or otherwise JNA or JNI , (:java :java :java-1.4 :java-1.5 :java-1.6 :java-1.7)))) #+clozure (defun ccl-fasl-version () the fasl version is target - dependent from CCL 1.8 on . (or (let ((s 'ccl::target-fasl-version)) (and (fboundp s) (funcall s))) (and (boundp 'ccl::fasl-version) (symbol-value 'ccl::fasl-version)) (error "Can't determine fasl version."))) (defun lisp-version-string () "return a string that identifies the current Lisp implementation version" (let ((s (lisp-implementation-version))) (list #+allegro (format nil "~A~@[~A~]~@[~A~]~@[~A~]" excl::*common-lisp-version-number* (and (eq excl:*current-case-mode* :case-sensitive-lower) "M") Note if not using International ACL (excl:ics-target-case (:-ics "8")) (and (member :smp *features*) "S")) #+armedbear (format nil "~a-fasl~a" s system::*fasl-version*) #+clisp #+clozure ccl::*openmcl-major-version* ccl::*openmcl-minor-version* (logand (ccl-fasl-version) #xFF)) #+cmucl (substitute #\- #\/ s) #+scl (format nil "~A~A" s (ecase ext:*case-mode* (:upper "") (:lower "l"))) #+ecl (format nil "~A~@[-~A~]" s (let ((vcs-id (ext:lisp-implementation-vcs-id))) (unless (equal vcs-id "UNKNOWN") (subseq vcs-id 0 (min (length vcs-id) 8))))) #+gcl (subseq s (1+ (position #\space s))) #+genera (multiple-value-bind (major minor) (sct:get-system-version "System") (format nil "~D.~D" major minor)) strip the leading " Version " seems like there should be a shorter way to do this , like . #+mkcl (or (let ((fname (find-symbol* '#:git-describe-this-mkcl :mkcl nil))) (when (and fname (fboundp fname)) (funcall fname))) s) s)))) (defun implementation-identifier () "Return a string that identifies the ABI of the current implementation, suitable for use as a directory name to segregate Lisp FASLs, C dynamic libraries, etc." (substitute-if #\_ #'(lambda (x) (find x " /:;&^\\|?<>(){}[]$#`'\"")) (format nil "~(~a~@{~@[-~a~]~}~)" (or (implementation-type) (lisp-implementation-type)) (lisp-version-string) (or (operating-system) (software-type)) (or (architecture) (machine-type)))))) (with-upgradability () (defun hostname () "return the hostname of the current host" #+(or abcl clasp clozure cmucl ecl genera lispworks mcl mkcl sbcl scl xcl) (machine-instance) #+allegro (symbol-call :excl.osi :gethostname) #+clisp (first (split-string (machine-instance) :separator " ")) #+gcl (system:gethostname))) (with-upgradability () #+cmucl (defun parse-unix-namestring* (unix-namestring) "variant of LISP::PARSE-UNIX-NAMESTRING that returns a pathname object" (multiple-value-bind (host device directory name type version) (lisp::parse-unix-namestring unix-namestring 0 (length unix-namestring)) (make-pathname :host (or host lisp::*unix-host*) :device device :directory directory :name name :type type :version version))) (defun getcwd () "Get the current working directory as per POSIX getcwd(3), as a pathname object" #+allegro (excl::current-directory) #+clisp (ext:default-directory) #+clozure (ccl:current-directory) #+(or cmucl scl) (#+cmucl parse-unix-namestring* #+scl lisp::parse-unix-namestring (strcat (nth-value 1 (unix:unix-current-directory)) "/")) #+(or clasp ecl) (ext:getcwd) #+gcl (let ((*default-pathname-defaults* #p"")) (truename #p"")) #+lispworks (hcl:get-working-directory) #+mkcl (mk-ext:getcwd) #+sbcl (sb-ext:parse-native-namestring (sb-unix:posix-getcwd/)) #+xcl (extensions:current-directory) (not-implemented-error 'getcwd))) (defun chdir (x) "Change current directory, as per POSIX chdir(2), to a given pathname object" (if-let (x (pathname x)) #+allegro (excl:chdir x) #+clisp (ext:cd x) #+clozure (setf (ccl:current-directory) x) #+(or cmucl scl) (unix:unix-chdir (ext:unix-namestring x)) #+cormanlisp (unless (zerop (win32::_chdir (namestring x))) (error "Could not set current directory to ~A" x)) #+(or clasp ecl) (ext:chdir x) #+gcl (system:chdir x) #+lispworks (hcl:change-directory x) #+mkcl (mk-ext:chdir x) #+sbcl (progn (require :sb-posix) (symbol-call :sb-posix :chdir (sb-ext:native-namestring x))) #-(or abcl allegro clasp clisp clozure cmucl cormanlisp ecl gcl genera lispworks mkcl sbcl scl xcl) (not-implemented-error 'chdir)))) : The Windows Shortcut File Format . CLISP does n't need it , and READ - SEQUENCE annoys old that does n't need it (with-upgradability () (defparameter *link-initial-dword* 76) (defparameter *link-guid* #(1 20 2 0 0 0 0 0 192 0 0 0 0 0 0 70)) (defun read-null-terminated-string (s) "Read a null-terminated string from an octet stream S" note : does n't play well with UNICODE (with-output-to-string (out) (loop :for code = (read-byte s) :until (zerop code) :do (write-char (code-char code) out)))) (defun read-little-endian (s &optional (bytes 4)) "Read a number in little-endian format from an byte (octet) stream S, the number having BYTES octets (defaulting to 4)." (loop :for i :from 0 :below bytes :sum (ash (read-byte s) (* 8 i)))) (defun parse-file-location-info (s) "helper to parse-windows-shortcut" (let ((start (file-position s)) (total-length (read-little-endian s)) (end-of-header (read-little-endian s)) (fli-flags (read-little-endian s)) (local-volume-offset (read-little-endian s)) (local-offset (read-little-endian s)) (network-volume-offset (read-little-endian s)) (remaining-offset (read-little-endian s))) (declare (ignore total-length end-of-header local-volume-offset)) (unless (zerop fli-flags) (cond ((logbitp 0 fli-flags) (file-position s (+ start local-offset))) ((logbitp 1 fli-flags) (file-position s (+ start network-volume-offset #x14)))) (strcat (read-null-terminated-string s) (progn (file-position s (+ start remaining-offset)) (read-null-terminated-string s)))))) (defun parse-windows-shortcut (pathname) "From a .lnk windows shortcut, extract the pathname linked to" NB : does n't do much checking & does n't look like it will work well with UNICODE . (with-open-file (s pathname :element-type '(unsigned-byte 8)) (handler-case (when (and (= (read-little-endian s) *link-initial-dword*) (let ((header (make-array (length *link-guid*)))) (read-sequence header s) (equalp header *link-guid*))) (let ((flags (read-little-endian s))) (when (logbitp 0 flags) (let ((length (read-little-endian s 2))) (file-position s (+ length (file-position s))))) (cond ((logbitp 1 flags) (parse-file-location-info s)) (t (when (logbitp 2 flags) (let ((length (read-little-endian s 2))) (file-position s (+ length (file-position s))))) (when (logbitp 3 flags) (let* ((length (read-little-endian s 2)) (buffer (make-array length))) (read-sequence buffer s) (map 'string #'code-char buffer))))))) (end-of-file (c) (declare (ignore c)) nil)))))
e87dad4a7ba91bdfe55f50ed4ed390f5b0ee0215baae41c8d43245b44eb26ad5
schemedoc/ffi-cookbook
cpuid-gambit.scm
(define (writeln x) (write x) (newline)) (define %cpuid (c-lambda (int) scheme-object #<<c-lambda-end unsigned int abcd[4]; asm("cpuid;" "mov %%eax, (%0);" "mov %%ebx, 4(%0);" "mov %%ecx, 8(%0);" "mov %%edx, 12(%0);" : : "D"(abcd), "a"(___arg1) : "%ebx", "%ecx", "%edx"); ___SCMOBJ vs = ___make_vector(___PSTATE, 4, ___FAL); i < 4 ; i++ ) { ___SCMOBJ v; ___U32_to_SCMOBJ(___PSTATE, abcd[i], &v, ___RETURN_POS); ___VECTORSET(vs, ___FIX(i), v); } ___return(vs); c-lambda-end )) (define (cpuid which) (let ((vs (%cpuid which))) (values (vector-ref vs 0) (vector-ref vs 1) (vector-ref vs 2) (vector-ref vs 3)))) (define (cpuname b c d) (let ((string (make-string 12 #\space))) (define (unpack-1-char! u32 to i) (let ((char (integer->char (extract-bit-field 8 (* 8 i) u32)))) (string-set! string (+ to i) char))) (define (unpack-4-chars! u32 to) (unpack-1-char! u32 to 0) (unpack-1-char! u32 to 1) (unpack-1-char! u32 to 2) (unpack-1-char! u32 to 3)) (unpack-4-chars! b 0) (unpack-4-chars! d 4) (unpack-4-chars! c 8) string)) (receive (a b c d) (cpuid 0) (writeln a) (writeln (cpuname b c d)))
null
https://raw.githubusercontent.com/schemedoc/ffi-cookbook/75d3594135b5a4c5deea9a064a1aef5a95312f85/assembly/cpuid-gambit.scm
scheme
i++ ) {
(define (writeln x) (write x) (newline)) (define %cpuid (c-lambda (int) scheme-object #<<c-lambda-end asm("cpuid;" "mov %%eax, (%0);" "mov %%ebx, 4(%0);" "mov %%ecx, 8(%0);" "mov %%edx, 12(%0);" : : "D"(abcd), "a"(___arg1) } c-lambda-end )) (define (cpuid which) (let ((vs (%cpuid which))) (values (vector-ref vs 0) (vector-ref vs 1) (vector-ref vs 2) (vector-ref vs 3)))) (define (cpuname b c d) (let ((string (make-string 12 #\space))) (define (unpack-1-char! u32 to i) (let ((char (integer->char (extract-bit-field 8 (* 8 i) u32)))) (string-set! string (+ to i) char))) (define (unpack-4-chars! u32 to) (unpack-1-char! u32 to 0) (unpack-1-char! u32 to 1) (unpack-1-char! u32 to 2) (unpack-1-char! u32 to 3)) (unpack-4-chars! b 0) (unpack-4-chars! d 4) (unpack-4-chars! c 8) string)) (receive (a b c d) (cpuid 0) (writeln a) (writeln (cpuname b c d)))
9259715db3b842961ff83727230855dd162a4f1ca51444949501536a9d64b576
jessealama/laramie
characters.rkt
#lang racket/base (require racket/require (multi-in ".." ("types.rkt" "tokenize.rkt" "tokens.rkt" "characters.rkt"))) (module+ test (require rackunit racket/format syntax/parse/define)) (module+ test (define-simple-macro (check-it test-name subject value) (let ([tokens (tokenize subject #:include-dropped? #t #:include-errors? #t)]) (test-case (format "~a [value]" test-name) (check-equal? tokens value)) (test-case (format "~a [length]" test-name) (check-= (length (enumerate-input-characters tokens)) (string-length subject) 0))))) (module+ test (check-it "Null character in toplevel" (~a #\u0000) (list (unexpected-null-character (location 1 0 1) #f) (character-token (location 1 0 1) (location 1 1 2) '(#\nul . #f)))) (check-it "Character reference EOFs" "&" (list (character-token (location 1 0 1) (location 1 1 2) #\&))) (check-it "Numeric character reference EOFs" "&#" (list (absence-of-digits-in-numeric-character-reference (location 1 0 1) #f) (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#))) (check-it "Decimal character reference EOFs" "&#1" (list (missing-semicolon-after-character-reference (location 1 0 1) #f) (control-character-reference (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\1))))) (check-it "Hexadecimal character reference EOFs" "&#x" (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x))) (check-it "Invalid named character reference" "&screwthis;" (list (unknown-named-character-reference (location 1 11 12) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\s) (character-token (location 1 2 3) (location 1 3 4) #\c) (character-token (location 1 3 4) (location 1 4 5) #\r) (character-token (location 1 4 5) (location 1 5 6) #\e) (character-token (location 1 5 6) (location 1 6 7) #\w) (character-token (location 1 6 7) (location 1 7 8) #\t) (character-token (location 1 7 8) (location 1 8 9) #\h) (character-token (location 1 8 9) (location 1 9 10) #\i) (character-token (location 1 9 10) (location 1 10 11) #\s) (character-token (location 1 10 11) (location 1 11 12) #\;))))) (check-it "Weird character in unknown named character reference" "&screwthis" (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\s) (character-token (location 1 2 3) (location 1 3 4) #\c) (character-token (location 1 3 4) (location 1 4 5) #\r) (character-token (location 1 4 5) (location 1 5 6) #\e) (character-token (location 1 5 6) (location 1 6 7) #\w) (character-token (location 1 6 7) (location 1 7 8) #\t) (character-token (location 1 7 8) (location 1 8 9) #\h) (character-token (location 1 8 9) (location 1 9 10) #\i) (character-token (location 1 9 10) (location 1 10 11) #\s))) (check-it "Decimal character reference out of bounds" "&#99999999999999999999;" (list (character-reference-outside-unicode-range (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\9) (character-token (location 1 3 4) (location 1 4 5) #\9) (character-token (location 1 4 5) (location 1 5 6) #\9) (character-token (location 1 5 6) (location 1 6 7) #\9) (character-token (location 1 6 7) (location 1 7 8) #\9) (character-token (location 1 7 8) (location 1 8 9) #\9) (character-token (location 1 8 9) (location 1 9 10) #\9) (character-token (location 1 9 10) (location 1 10 11) #\9) (character-token (location 1 10 11) (location 1 11 12) #\9) (character-token (location 1 11 12) (location 1 12 13) #\9) (character-token (location 1 12 13) (location 1 13 14) #\9) (character-token (location 1 13 14) (location 1 14 15) #\9) (character-token (location 1 14 15) (location 1 15 16) #\9) (character-token (location 1 15 16) (location 1 16 17) #\9) (character-token (location 1 16 17) (location 1 17 18) #\9) (character-token (location 1 17 18) (location 1 18 19) #\9) (character-token (location 1 18 19) (location 1 19 20) #\9) (character-token (location 1 19 20) (location 1 20 21) #\9) (character-token (location 1 20 21) (location 1 21 22) #\9) (character-token (location 1 21 22) (location 1 22 23) #\9) (character-token (location 1 22 23) (location 1 23 24) #\;))) (character-token (location 1 0 1) (location 1 23 24) '((#\& #\# #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\;) . #\�)))) (check-it "OK decimal reference (P sign)" "&#80;" (list (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\8) (character-token (location 1 3 4) (location 1 4 5) #\0) (character-token (location 1 4 5) (location 1 5 6) #\;)) #\P #f))) (check-it "OK hexadecimal reference (U sign)" "&#x55;" (list (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\5) (character-token (location 1 4 5) (location 1 5 6) #\5) (character-token (location 1 5 6) (location 1 6 7) #\;)) #\U #f))) (check-it "Decimal character reference bails out" "&#123x;" (list (missing-semicolon-after-character-reference (location 1 0 1) #f) (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\1) (character-token (location 1 3 4) (location 1 4 5) #\2) (character-token (location 1 4 5) (location 1 5 6) #\3)) #\{ #f) (character-token (location 1 5 6) (location 1 6 7) #\x) (character-token (location 1 6 7) (location 1 7 8) #\;))) (check-it "Hexadecimal character reference includes non-hexadecimal character" "&#xabcdefg;" (list (missing-semicolon-after-character-reference (location 1 0 1) #f) (character-reference-outside-unicode-range (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\a) (character-token (location 1 4 5) (location 1 5 6) #\b) (character-token (location 1 5 6) (location 1 6 7) #\c) (character-token (location 1 6 7) (location 1 7 8) #\d) (character-token (location 1 7 8) (location 1 8 9) #\e) (character-token (location 1 8 9) (location 1 9 10) #\f))) (character-token (location 1 0 1) (location 1 9 10) '((#\& #\# #\x #\a #\b #\c #\d #\e #\f) . #\�)) (character-token (location 1 9 10) (location 1 10 11) #\g) (character-token (location 1 10 11) (location 1 11 12) #\;))) (check-it "Illegal start to hexadecimal reference" "&#xx;" (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\x) (character-token (location 1 4 5) (location 1 5 6) #\;))) (check-it "EOF in hexadecimal reference" "&#xa" (list (missing-semicolon-after-character-reference (location 1 0 1) #f) (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\a)) #\newline #f))) (check-it "Upgrade hexadecimal character reference to something else (€)" "&#x80;" (list (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\8) (character-token (location 1 4 5) (location 1 5 6) #\0) (character-token (location 1 5 6) (location 1 6 7) #\;)) #\€ #t))) (check-it "Upgrade decimal character reference to something else (…)" "&#133;" (list (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\1) (character-token (location 1 3 4) (location 1 4 5) #\3) (character-token (location 1 4 5) (location 1 5 6) #\3) (character-token (location 1 5 6) (location 1 6 7) #\;)) #\… #t))) (check-it "Surrogate character encoded as a character reference" "&#xd800;" (list (surrogate-character-reference (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\d) (character-token (location 1 4 5) (location 1 5 6) #\8) (character-token (location 1 5 6) (location 1 6 7) #\0) (character-token (location 1 6 7) (location 1 7 8) #\0) (character-token (location 1 7 8) (location 1 8 9) #\;))) (character-token (location 1 0 1) (location 1 8 9) '((#\& #\# #\x #\d #\8 #\0 #\0 #\;) . #\�)))) (check-it "Non-character encoded as a character reference" "&#x6ffff;" (list (noncharacter-character-reference (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\6) (character-token (location 1 4 5) (location 1 5 6) #\f) (character-token (location 1 5 6) (location 1 6 7) #\f) (character-token (location 1 6 7) (location 1 7 8) #\f) (character-token (location 1 7 8) (location 1 8 9) #\f) (character-token (location 1 8 9) (location 1 9 10) #\;))))) (check-it "Control character encoded as a character reference" "&#x000e;" (list (control-character-reference (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\0) (character-token (location 1 4 5) (location 1 5 6) #\0) (character-token (location 1 5 6) (location 1 6 7) #\0) (character-token (location 1 6 7) (location 1 7 8) #\e) (character-token (location 1 7 8) (location 1 8 9) #\;))))) (check-it "Particular control character (explicitly singled out in the HTML5 spec)" "&#x0d;" (list (control-character-reference (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\0) (character-token (location 1 4 5) (location 1 5 6) #\d) (character-token (location 1 5 6) (location 1 6 7) #\;))))) (check-it "Illegal start to decimal character reference" "&#p;" (list (absence-of-digits-in-numeric-character-reference (location 1 0 1) #f) (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\p) (character-token (location 1 3 4) (location 1 4 5) #\;))))
null
https://raw.githubusercontent.com/jessealama/laramie/89dee24f6977d668ee1e1ae958c5644d1d15be2c/laramie-lib/laramie/tokenizer/tests/characters.rkt
racket
))))) ))) ) )) )) ))) ))) ))) )) )) ))) ) . #\�)))) ))))) ))))) ))))) ))))
#lang racket/base (require racket/require (multi-in ".." ("types.rkt" "tokenize.rkt" "tokens.rkt" "characters.rkt"))) (module+ test (require rackunit racket/format syntax/parse/define)) (module+ test (define-simple-macro (check-it test-name subject value) (let ([tokens (tokenize subject #:include-dropped? #t #:include-errors? #t)]) (test-case (format "~a [value]" test-name) (check-equal? tokens value)) (test-case (format "~a [length]" test-name) (check-= (length (enumerate-input-characters tokens)) (string-length subject) 0))))) (module+ test (check-it "Null character in toplevel" (~a #\u0000) (list (unexpected-null-character (location 1 0 1) #f) (character-token (location 1 0 1) (location 1 1 2) '(#\nul . #f)))) (check-it "Character reference EOFs" "&" (list (character-token (location 1 0 1) (location 1 1 2) #\&))) (check-it "Numeric character reference EOFs" "&#" (list (absence-of-digits-in-numeric-character-reference (location 1 0 1) #f) (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#))) (check-it "Decimal character reference EOFs" "&#1" (list (missing-semicolon-after-character-reference (location 1 0 1) #f) (control-character-reference (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\1))))) (check-it "Hexadecimal character reference EOFs" "&#x" (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x))) (check-it "Invalid named character reference" "&screwthis;" (list (unknown-named-character-reference (location 1 11 12) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\s) (character-token (location 1 2 3) (location 1 3 4) #\c) (character-token (location 1 3 4) (location 1 4 5) #\r) (character-token (location 1 4 5) (location 1 5 6) #\e) (character-token (location 1 5 6) (location 1 6 7) #\w) (character-token (location 1 6 7) (location 1 7 8) #\t) (character-token (location 1 7 8) (location 1 8 9) #\h) (character-token (location 1 8 9) (location 1 9 10) #\i) (character-token (location 1 9 10) (location 1 10 11) #\s) (check-it "Weird character in unknown named character reference" "&screwthis" (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\s) (character-token (location 1 2 3) (location 1 3 4) #\c) (character-token (location 1 3 4) (location 1 4 5) #\r) (character-token (location 1 4 5) (location 1 5 6) #\e) (character-token (location 1 5 6) (location 1 6 7) #\w) (character-token (location 1 6 7) (location 1 7 8) #\t) (character-token (location 1 7 8) (location 1 8 9) #\h) (character-token (location 1 8 9) (location 1 9 10) #\i) (character-token (location 1 9 10) (location 1 10 11) #\s))) (check-it "Decimal character reference out of bounds" "&#99999999999999999999;" (list (character-reference-outside-unicode-range (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\9) (character-token (location 1 3 4) (location 1 4 5) #\9) (character-token (location 1 4 5) (location 1 5 6) #\9) (character-token (location 1 5 6) (location 1 6 7) #\9) (character-token (location 1 6 7) (location 1 7 8) #\9) (character-token (location 1 7 8) (location 1 8 9) #\9) (character-token (location 1 8 9) (location 1 9 10) #\9) (character-token (location 1 9 10) (location 1 10 11) #\9) (character-token (location 1 10 11) (location 1 11 12) #\9) (character-token (location 1 11 12) (location 1 12 13) #\9) (character-token (location 1 12 13) (location 1 13 14) #\9) (character-token (location 1 13 14) (location 1 14 15) #\9) (character-token (location 1 14 15) (location 1 15 16) #\9) (character-token (location 1 15 16) (location 1 16 17) #\9) (character-token (location 1 16 17) (location 1 17 18) #\9) (character-token (location 1 17 18) (location 1 18 19) #\9) (character-token (location 1 18 19) (location 1 19 20) #\9) (character-token (location 1 19 20) (location 1 20 21) #\9) (character-token (location 1 20 21) (location 1 21 22) #\9) (character-token (location 1 21 22) (location 1 22 23) #\9) (character-token (location 1 0 1) (location 1 23 24) '((#\& #\# #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 #\9 . #\�)))) (check-it "OK decimal reference (P sign)" "&#80;" (list (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\8) (character-token (location 1 3 4) (location 1 4 5) #\0) #\P #f))) (check-it "OK hexadecimal reference (U sign)" "&#x55;" (list (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\5) (character-token (location 1 4 5) (location 1 5 6) #\5) #\U #f))) (check-it "Decimal character reference bails out" "&#123x;" (list (missing-semicolon-after-character-reference (location 1 0 1) #f) (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\1) (character-token (location 1 3 4) (location 1 4 5) #\2) (character-token (location 1 4 5) (location 1 5 6) #\3)) #\{ #f) (character-token (location 1 5 6) (location 1 6 7) #\x) (check-it "Hexadecimal character reference includes non-hexadecimal character" "&#xabcdefg;" (list (missing-semicolon-after-character-reference (location 1 0 1) #f) (character-reference-outside-unicode-range (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\a) (character-token (location 1 4 5) (location 1 5 6) #\b) (character-token (location 1 5 6) (location 1 6 7) #\c) (character-token (location 1 6 7) (location 1 7 8) #\d) (character-token (location 1 7 8) (location 1 8 9) #\e) (character-token (location 1 8 9) (location 1 9 10) #\f))) (character-token (location 1 0 1) (location 1 9 10) '((#\& #\# #\x #\a #\b #\c #\d #\e #\f) . #\�)) (character-token (location 1 9 10) (location 1 10 11) #\g) (check-it "Illegal start to hexadecimal reference" "&#xx;" (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\x) (check-it "EOF in hexadecimal reference" "&#xa" (list (missing-semicolon-after-character-reference (location 1 0 1) #f) (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\a)) #\newline #f))) (check-it "Upgrade hexadecimal character reference to something else (€)" "&#x80;" (list (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\8) (character-token (location 1 4 5) (location 1 5 6) #\0) #\€ #t))) (check-it "Upgrade decimal character reference to something else (…)" "&#133;" (list (character-reference-token (location 1 0 1) (location 1 0 0) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\1) (character-token (location 1 3 4) (location 1 4 5) #\3) (character-token (location 1 4 5) (location 1 5 6) #\3) #\… #t))) (check-it "Surrogate character encoded as a character reference" "&#xd800;" (list (surrogate-character-reference (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\d) (character-token (location 1 4 5) (location 1 5 6) #\8) (character-token (location 1 5 6) (location 1 6 7) #\0) (character-token (location 1 6 7) (location 1 7 8) #\0) (character-token (location 1 0 1) (location 1 8 9) (check-it "Non-character encoded as a character reference" "&#x6ffff;" (list (noncharacter-character-reference (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\6) (character-token (location 1 4 5) (location 1 5 6) #\f) (character-token (location 1 5 6) (location 1 6 7) #\f) (character-token (location 1 6 7) (location 1 7 8) #\f) (character-token (location 1 7 8) (location 1 8 9) #\f) (check-it "Control character encoded as a character reference" "&#x000e;" (list (control-character-reference (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\0) (character-token (location 1 4 5) (location 1 5 6) #\0) (character-token (location 1 5 6) (location 1 6 7) #\0) (character-token (location 1 6 7) (location 1 7 8) #\e) (check-it "Particular control character (explicitly singled out in the HTML5 spec)" "&#x0d;" (list (control-character-reference (location 1 0 1) (list (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\x) (character-token (location 1 3 4) (location 1 4 5) #\0) (character-token (location 1 4 5) (location 1 5 6) #\d) (check-it "Illegal start to decimal character reference" "&#p;" (list (absence-of-digits-in-numeric-character-reference (location 1 0 1) #f) (character-token (location 1 0 1) (location 1 1 2) #\&) (character-token (location 1 1 2) (location 1 2 3) #\#) (character-token (location 1 2 3) (location 1 3 4) #\p)
9233e60702284dc4bddae3a1da59b515c97b693042786d9f7abf20ed56b393eb
shirok/Gauche
primsyn.scm
;;; ;;; primitive syntax test ;;; (use gauche.test) (test-start "primitive syntax") ;; We use prim-test instead of test, for error-handler is not tested yet. NB : errsyn.scm has tests for invalid syntax . It is run after ;; error-handler and macro tests. ;;---------------------------------------------------------------- (test-section "conditionals") (prim-test "if" 5 (lambda () (if #f 2 5))) (prim-test "if" 2 (lambda () (if (not #f) 2 5))) (prim-test "and" #t (lambda () (and))) (prim-test "and" 5 (lambda () (and 5))) (prim-test "and" #f (lambda () (and 5 #f 2))) (prim-test "and" #f (lambda () (and 5 #f unbound-var))) (prim-test "and" 'a (lambda () (and 3 4 'a))) (prim-test "or" #f (lambda () (or))) (prim-test "or" 3 (lambda () (or 3 9))) (prim-test "or" 3 (lambda () (or #f 3 unbound-var))) (prim-test "when" 4 (lambda () (when 3 5 4))) (prim-test "when" (undefined) (lambda () (when #f 5 4))) (prim-test "when" (undefined) (lambda () (when #f unbound-var))) (prim-test "unless" (undefined) (lambda () (unless 3 5 4))) (prim-test "unless" (undefined) (lambda () (unless #t unbound-var))) (prim-test "unless" 4 (lambda () (unless #f 5 4))) (prim-test "cond" (undefined) (lambda () (cond (#f 2)))) (prim-test "cond" 5 (lambda () (cond (#f 2) (else 5)))) (prim-test "cond" 2 (lambda () (cond (1 2) (else 5)))) (prim-test "cond" 8 (lambda () (cond (#f 2) (1 8) (else 5)))) (prim-test "cond" 3 (lambda () (cond (1 => (lambda (x) (+ x 2))) (else 8)))) (prim-test "cond (SRFI-61)" 1 (lambda () (cond (1 number? => values) (else 8)))) (prim-test "cond (SRFI-61)" 8 (lambda () (cond (1 string? => values) (else 8)))) (prim-test "cond (SRFI-61)" '(1 2) (lambda () (cond ((values 1 2) (lambda (x y) (and (= x 1) (= y 2))) => list)))) (prim-test "case" #t (lambda () (case (+ 2 3) ((1 3 5 7 9) #t) ((0 2 4 6 8) #f)))) (prim-test "case" #t (lambda () (undefined? (case 1 ((2 3) #t))))) (prim-test "case" #t (lambda () (case 1 (() #f) ((1) #t)))) (prim-test "case" #t (lambda () (case 1 (() #f) (else #t)))) (prim-test "case" #t (lambda () (undefined? (case 1 (() #t))))) (prim-test "case (SRFI-87)" 0 (lambda () (case (+ 2 3) ((1 3 5) 0) (else => values)))) (prim-test "case (SRFI-87)" 6 (lambda () (case (+ 2 3) ((1 3 5) => (cut + 1 <>)) (else => values)))) (prim-test "case (SRFI-87)" 5 (lambda () (case (+ 2 3) ((2 4 6) 0) (else => values)))) ;;---------------------------------------------------------------- (test-section "binding") (prim-test "let" 35 (lambda () (let ((x 2) (y 3)) (let ((x 7) (z (+ x y))) (* z x))))) (prim-test "let*" 70 (lambda () (let ((x 2) (y 3)) (let* ((x 7) (z (+ x y))) (* z x))))) (prim-test "let*" 2 (lambda () (let* ((x 1) (x (+ x 1))) x))) (prim-test "named let" -3 (lambda () (let ((f -)) (let f ((a (f 3))) a)))) ;;---------------------------------------------------------------- (test-section "closure and saved env") (prim-test "lambda" 5 (lambda () ((lambda (x) (car x)) '(5 6 7)))) (prim-test "lambda" 12 (lambda () ((lambda (x y) ((lambda (z) (* (car z) (cdr z))) (cons x y))) 3 4))) (define (addN n) (lambda (a) (+ a n))) (prim-test "lambda" 5 (lambda () ((addN 2) 3))) (define add3 (addN 3)) (prim-test "lambda" 9 (lambda () (add3 6))) (define count (let ((c 0)) (lambda () (set! c (+ c 1)) c))) (prim-test "lambda" 1 (lambda () (count))) (prim-test "lambda" 2 (lambda () (count))) ;;---------------------------------------------------------------- (test-section "application") (define Apply apply) ; avoid inline expansion (prim-test "apply" '(1 2 3) (lambda () (Apply list '(1 2 3)))) (prim-test "apply" '(2 3 4) (lambda () (Apply list 2 '(3 4)))) (prim-test "apply" '(3 4 5) (lambda () (Apply list 3 4 '(5)))) (prim-test "apply" '(4 5 6) (lambda () (Apply list 4 5 6 '()))) (prim-test "apply^2" '() (lambda () (Apply Apply list '() '()))) (prim-test "Apply^2" '() (lambda () (Apply Apply list '(())))) (prim-test "apply^2" '(1 . 2) (lambda () (Apply Apply cons '((1 2))))) (prim-test "apply^2" '(3 . 4) (lambda () (Apply Apply cons 3 '((4))))) (prim-test "apply^2" '(5 . 6) (lambda () (Apply Apply (list cons 5 '(6))))) (prim-test "apply" '(6 7 8) (lambda () (Apply Apply (list list 6 7 '(8))))) This tests ' unfolding ' path in ADJUST_ARGUMENT_FRAME . (prim-test "apply, copying args" '(1 2 3) (lambda () (let ((orig (list 1 2 3))) (let ((new (Apply list orig))) (set-car! (cdr new) '100) orig)))) ;; This tests 'folding' path in ADJUST_ARGUMENT_FRAME (prim-test "apply, copying args" '(2 3) (lambda () (let ((orig (list 2 3))) (let ((new (Apply list 1 orig))) (set-car! (cdr new) '100) orig)))) ;; Detect circular list in the argument NB : At this point , we have n't tested # 0= reader notation , ;; and to avoid optimization, these data should be in global space. (define *apply-circular-data-1* (let ((x (list 'a))) (set-cdr! x x) x)) (define *apply-circular-data-2* (let ((x (list 'a 'a))) (set-cdr! (cdr x) x) x)) (prim-test "apply, circular list 1" "improper list not allowed: #0=(a . #0#)" (lambda () (with-error-handler (lambda (e) (slot-ref e 'message)) (lambda () (apply list *apply-circular-data-1*))))) (prim-test "apply, circular list 2" "improper list not allowed: #0=(a . #0#)" (lambda () (with-error-handler (lambda (e) (slot-ref e 'message)) (lambda () (apply list 'a *apply-circular-data-1*))))) (prim-test "apply, circular list 3" "improper list not allowed: #0=(a a . #0#)" (lambda () (with-error-handler (lambda (e) (slot-ref e 'message)) (lambda () (apply list 'a *apply-circular-data-2*))))) (prim-test "apply, circular list 4" "improper list not allowed: #0=(a a . #0#)" (lambda () (with-error-handler (lambda (e) (slot-ref e 'message)) (lambda () ;; This is caught in different place (#<subr apply>), ;; rather than VM APPLY instruction. (Apply list 'a *apply-circular-data-2*))))) This test exhibits the optimizer bug reported by . (define bug-optimizer-local-inliner (lambda (flag) (define (a . args) (receive x args (cons x x) (Apply values x)) (Apply format args)) (define (b bar) (a "~a" bar)) (b 1) (cond (flag (b 1)) (else (a "~a" 1))))) (prim-test "apply local inliner optimizer" "1" (lambda () (bug-optimizer-local-inliner #f)) equal?) (prim-test "apply local inliner optimizer" "1" (lambda () (bug-optimizer-local-inliner #t)) equal?) (prim-test "map" '() (lambda () (map car '()))) (prim-test "map" '(1 2 3) (lambda () (map car '((1) (2) (3))))) (prim-test "map" '(() () ()) (lambda () (map cdr '((1) (2) (3))))) (prim-test "map" '((1 . 4) (2 . 5) (3 . 6)) (lambda () (map cons '(1 2 3) '(4 5 6)))) ;;---------------------------------------------------------------- (test-section "loop") (define (fact-non-tail-rec n) (if (<= n 1) n (* n (fact-non-tail-rec (- n 1))))) (prim-test "loop non-tail-rec" 120 (lambda () (fact-non-tail-rec 5))) (define (fact-tail-rec n r) (if (<= n 1) r (fact-tail-rec (- n 1) (* n r)))) (prim-test "loop tail-rec" 120 (lambda () (fact-tail-rec 5 1))) (define (fact-named-let n) (let loop ((n n) (r 1)) (if (<= n 1) r (loop (- n 1) (* n r))))) (prim-test "loop named-let" 120 (lambda () (fact-named-let 5))) (define (fact-int-define n) (define (rec n r) (if (<= n 1) r (rec (- n 1) (* n r)))) (rec n 1)) (prim-test "loop int-define" 120 (lambda () (fact-int-define 5))) (define (fact-do n) (do ((n n (- n 1)) (r 1 (* n r))) ((<= n 1) r))) (prim-test "loop do" 120 (lambda () (fact-do 5))) ;; tricky case (prim-test "do" #f (lambda () (do () (#t #f) #t))) ;;---------------------------------------------------------------- (test-section "quasiquote") ;; The new compiler generates constant list for much wider range of quasiquoted forms ( e.g. constant numerical expressions ;; and constant variable definitions are folded at the compile time). (define-constant quasi0 99) (define quasi1 101) (define-constant quasi2 '(a b)) (define quasi3 '(c d)) (prim-test "qq" '(1 2 3) (lambda () `(1 2 3))) (prim-test "qq" '() (lambda () `())) (prim-test "qq" 99 (lambda () `,quasi0)) (prim-test "qq" 101 (lambda () `,quasi1)) (prim-test "qq," '((1 . 2)) (lambda () `(,(cons 1 2)))) (prim-test "qq," '((1 . 2) 3) (lambda () `(,(cons 1 2) 3))) (prim-test "qq," '(0 (1 . 2)) (lambda () `(0 ,(cons 1 2)))) (prim-test "qq," '(0 (1 . 2) 3) (lambda () `(0 ,(cons 1 2) 3))) (prim-test "qq," '(((1 . 2))) (lambda () `((,(cons 1 2))))) (prim-test "qq," '(((1 . 2)) 3) (lambda () `((,(cons 1 2)) 3))) (prim-test "qq," '(99 3) (lambda () `(,quasi0 3))) (prim-test "qq," '(3 99) (lambda () `(3 ,quasi0))) (prim-test "qq," '(3 99 3) (lambda () `(3 ,quasi0 3))) (prim-test "qq," '(100 3) (lambda () `(,(+ quasi0 1) 3))) (prim-test "qq," '(3 100) (lambda () `(3 ,(+ quasi0 1)))) (prim-test "qq," '(101 3) (lambda () `(,quasi1 3))) (prim-test "qq," '(3 101) (lambda () `(3 ,quasi1))) (prim-test "qq," '(102 3) (lambda () `(,(+ quasi1 1) 3))) (prim-test "qq," '(3 102) (lambda () `(3 ,(+ quasi1 1)))) (prim-test "qq,(r6rs)" '(98 99 (a b) 100) (lambda () `(98 (unquote quasi0 quasi2) 100))) (prim-test "qq,(r6rs)" '(98 99 101 100) (lambda () `(98 (unquote quasi0 quasi1) 100))) (prim-test "qq,(r6rs)" '(98 99 (a b) 100) (lambda () `(98 (unquote quasi0 quasi2) 100))) (prim-test "qq,(r6rs)" '(98 99 (a b) (1 2) (3 4)) (lambda () `(98 (unquote quasi0 quasi2) (unquote (list 1 2) (list 3 4))))) (prim-test "qq@" '(1 2 3 4) (lambda () `(1 ,@(list 2 3) 4))) (prim-test "qq@" '(1 2 3 4) (lambda () `(1 2 ,@(list 3 4)))) (prim-test "qq@" '(a b c d) (lambda () `(,@quasi2 ,@quasi3))) (prim-test "qq@(r6rs)" '(1 a b a b 2) (lambda () `(1 (unquote-splicing quasi2 quasi2) 2))) (prim-test "qq@(r6rs)" '(1 a b c d 2) (lambda () `(1 (unquote-splicing quasi2 quasi3) 2))) (prim-test "qq@(r6rs)" '(1 a b c d 2) (lambda () `(1 (unquote-splicing (list 'a 'b) '(c d)) ,@(list 2)))) (prim-test "qq." '(1 2 3 4) (lambda () `(1 2 . ,(list 3 4)))) (prim-test "qq." '(a b c d) (lambda () `(,@quasi2 . ,quasi3))) (prim-test "qq#," '#((1 . 2) 3) (lambda () `#(,(cons 1 2) 3))) (prim-test "qq#," '#(99 3) (lambda () `#(,quasi0 3))) (prim-test "qq#," '#(100 3) (lambda () `#(,(+ quasi0 1) 3))) (prim-test "qq#," '#(3 101) (lambda () `#(3 ,quasi1))) (prim-test "qq#," '#(3 102) (lambda () `#(3 ,(+ quasi1 1)))) (prim-test "qq#@" '#(1 2 3 4) (lambda () `#(1 ,@(list 2 3) 4))) (prim-test "qq#@" '#(1 2 3 4) (lambda () `#(1 2 ,@(list 3 4)))) (prim-test "qq#@" '#(a b c d) (lambda () `#(,@quasi2 ,@quasi3))) (prim-test "qq#@" '#(a b (c d)) (lambda () `#(,@quasi2 ,quasi3))) (prim-test "qq#@" '#((a b) c d) (lambda () `#(,quasi2 ,@quasi3))) (prim-test "qq#" '#() (lambda () `#())) (prim-test "qq#@" '#() (lambda () `#(,@(list)))) (prim-test "qq@@" '(1 2 1 2) (lambda () `(,@(list 1 2) ,@(list 1 2)))) (prim-test "qq@@" '(1 2 a 1 2) (lambda () `(,@(list 1 2) a ,@(list 1 2)))) (prim-test "qq@@" '(a 1 2 1 2) (lambda () `(a ,@(list 1 2) ,@(list 1 2)))) (prim-test "qq@@" '(1 2 1 2 a) (lambda () `(,@(list 1 2) ,@(list 1 2) a))) (prim-test "qq@@" '(1 2 1 2 a b) (lambda () `(,@(list 1 2) ,@(list 1 2) a b))) (prim-test "qq@." '(1 2 1 2 . a) (lambda () `(,@(list 1 2) ,@(list 1 2) . a))) (prim-test "qq@." '(1 2 1 2 1 . 2) (lambda () `(,@(list 1 2) ,@(list 1 2) . ,(cons 1 2)))) (prim-test "qq@." '(1 2 1 2 a b) (lambda () `(,@(list 1 2) ,@(list 1 2) . ,quasi2))) (prim-test "qq@." '(1 2 1 2 a 1 . 2) (lambda () `(,@(list 1 2) ,@(list 1 2) a . ,(cons 1 2)))) (prim-test "qq@." '(1 2 1 2 a c d) (lambda () `(,@(list 1 2) ,@(list 1 2) a . ,quasi3))) (prim-test "qq#@@" '#(1 2 1 2) (lambda () `#(,@(list 1 2) ,@(list 1 2)))) (prim-test "qq#@@" '#(1 2 a 1 2) (lambda () `#(,@(list 1 2) a ,@(list 1 2)))) (prim-test "qq#@@" '#(a 1 2 1 2) (lambda () `#(a ,@(list 1 2) ,@(list 1 2)))) (prim-test "qq#@@" '#(1 2 1 2 a) (lambda () `#(,@(list 1 2) ,@(list 1 2) a))) (prim-test "qq#@@" '#(1 2 1 2 a b) (lambda () `#(,@(list 1 2) ,@(list 1 2) a b))) (prim-test "qqq" '(1 `(1 ,2 ,3) 1) (lambda () `(1 `(1 ,2 ,,(+ 1 2)) 1))) (prim-test "qqq" '(1 `(1 ,99 ,101) 1) (lambda () `(1 `(1 ,,quasi0 ,,quasi1) 1))) (prim-test "qqq" '(1 `(1 ,@2 ,@(1 2))) (lambda () `(1 `(1 ,@2 ,@,(list 1 2))))) (prim-test "qqq" '(1 `(1 ,@2 (unquote 1 2))) (lambda () `(1 `(1 ,@2 ,,@(list 1 2))))) (prim-test "qqq" '(1 `(1 ,@2 (unquote-splicing 1 2))) (lambda () `(1 `(1 ,@2 ,@,@(list 1 2))))) (prim-test "qqq" '(1 `(1 ,@(a b) ,@(c d))) (lambda () `(1 `(1 ,@,quasi2 ,@,quasi3)))) (prim-test "qqq" '(1 `(1 ,(a b x) ,(y c d))) (lambda () `(1 `(1 ,(,@quasi2 x) ,(y ,@quasi3))))) (prim-test "qqq#" '#(1 `(1 ,2 ,3) 1) (lambda () `#(1 `(1 ,2 ,,(+ 1 2)) 1))) (prim-test "qqq#" '#(1 `(1 ,99 ,101) 1) (lambda () `#(1 `(1 ,,quasi0 ,,quasi1) 1))) (prim-test "qqq#" '#(1 `(1 ,@2 ,@(1 2))) (lambda () `#(1 `(1 ,@2 ,@,(list 1 2))))) (prim-test "qqq#" '#(1 `(1 ,@(a b) ,@(c d))) (lambda () `#(1 `(1 ,@,quasi2 ,@,quasi3)))) (prim-test "qqq#" '#(1 `(1 ,(a b x) ,(y c d))) (lambda () `#(1 `(1 ,(,@quasi2 x) ,(y ,@quasi3))))) (prim-test "qqq#" '(1 `#(1 ,(a b x) ,(y c d))) (lambda () `(1 `#(1 ,(,@quasi2 x) ,(y ,@quasi3))))) (prim-test "qq-hygiene 0" '(2 1) (lambda () (let ((quasiquote reverse)) `(list 1 2)))) (prim-test "qq-hygiene 1" '(,(+ 1 2)) (lambda () (let ((unquote 3)) `(,(+ 1 2))))) (prim-test "qq-hygiene 2" '(,@(+ 1 2)) (lambda () (let ((unquote-splicing 3)) `(,@(+ 1 2))))) ;;---------------------------------------------------------------- (test-section "multiple values") (prim-test "receive" '(1 2 3) (lambda () (receive (a b c) (values 1 2 3) (list a b c)))) (prim-test "receive" '(1 2 3) (lambda () (receive (a . r) (values 1 2 3) (cons a r)))) (prim-test "receive" '(1 2 3) (lambda () (receive x (values 1 2 3) x))) (prim-test "receive" 1 (lambda () (receive (a) 1 a))) (prim-test "call-with-values" '(1 2 3) (lambda () (call-with-values (lambda () (values 1 2 3)) list))) (prim-test "call-with-values" '() (lambda () (call-with-values (lambda () (values)) list))) This is not ' right ' in R5RS sense --- for now , I just tolerate it by CommonLisp way , i.e. if more than one value is passed to an implicit continuation that expects one value , the second and after ;; values are just discarded. This behavior may be changed later, ;; so do not count on it. The test just make sure it doesn't screw ;; up anything. (prim-test "receive" '((0 0)) (lambda () (receive l (list 0 (values 0 1 2)) l))) ;;---------------------------------------------------------------- (test-section "eval") (prim-test "eval" '(1 . 2) (lambda () (eval '(cons 1 2) (interaction-environment)))) (define (vector-ref x y) 'foo) (prim-test "eval" '(foo foo 3) (lambda () (list (vector-ref '#(3) 0) (eval '(vector-ref '#(3) 0) (interaction-environment)) (eval '(vector-ref '#(3) 0) (scheme-report-environment 5))))) (define vector-ref (with-module scheme vector-ref)) (prim-test "eval" #t (lambda () (with-error-handler (lambda (e) #t) (lambda () (eval '(car '(3 2)) (null-environment 5)))))) ;; check interaction w/ modules (define-module primsyn.test (define foo 'a)) (define foo '(x y)) (prim-test "eval (module)" '(a b (x y)) (lambda () (let* ((m (find-module 'primsyn.test)) (a (eval 'foo m)) (b (eval '(begin (set! foo 'b) foo) m))) (list a b foo)))) (prim-test "eval (module)" '(x y) (lambda () (with-error-handler (lambda (e) foo) (lambda () (eval '(Apply car foo '()) (find-module 'primsyn.test)))))) ;;---------------------------------------------------------------- (test-section "max literal arguments") ;; Fix this after we have separate compile-error condition. (define (test-max-literal-args msg expr) (prim-test (string-append "max literal arguments for " msg) 'caught (lambda () (with-error-handler (lambda (e) 'caught) (lambda () (eval expr (interaction-environment))))))) (test-max-literal-args "inliner" `(list ,@(make-list 10000 #f))) (test-max-literal-args "global proc" `(make ,@(make-list 10000 #f))) (test-max-literal-args "local proc" `(let ((foo (lambda x x))) (foo ,@(make-list 10000 #f)))) ;;---------------------------------------------------------------- (test-section "local procedure optimization") this caused an internal compiler error in 0.8.6 . ( found and fixed by ) (prim-test "internal-define inilining" '(1) (lambda () (with-error-handler (lambda (e) 'ouch!) (lambda () (eval '(let () (define (a x) x) (define (b x) (a x)) (define (c x) (b x)) (list 1)) (interaction-environment)))))) this caused an internal compiler error in 0.8.6 ( found and fixed by ) (prim-test "multiple inlining" 0 (lambda () (let ((f (lambda (i) (set! i 0) i))) (f (f 1))))) this caused an internal compiler error in 0.9.1 (define (zero) 0) (prim-test "pass3 inlining with pass3/$call optimization" #t (lambda () (eval '((letrec ((f (lambda (a b) (do ((x a (+ x 1))) ((>= x b)))))) f) (zero) (zero)) (interaction-environment)))) This caused internal error in 0.9.1 , and infinite loop in dev version ;; after it. (prim-test "pass3/$call inlining problem" #t (lambda () (procedure? (eval '(lambda (n p t) (define (y a r s f) (let loop ([e 0]) (cond [(a n) (unwind-protect (s) (r n))] [(< e 10) (loop (+ 1 e))] [else (f)]))) (define (l0 a r) (y a r (^() (r n)) (^() (error "oo")))) Main locker (define (l1 a r) (y a r p (^() (if (and-let* ([ t ] [m (file-mtime n)]) (< (+ m t) 10)) (begin (l0 a r) (l1 a r)))))) (error "zz")) (interaction-environment))))) ;;---------------------------------------------------------------- (test-section "optimized frames") ;; Empty environment frame is omitted by compiler optimization. ;; The following tests makes sure if it works correctly. (prim-test "lambda (empty env)" 1 (lambda () (let* ((a 1) (b (lambda () ((lambda () a))))) (b)))) (prim-test "let (empty env)" 1 (lambda () (let ((a 1)) (let () (let () a))))) (prim-test "let (empty env)" '(1 . 1) (lambda () (let ((a 1)) (cons (let () (let () a)) (let* () (letrec () a)))))) (prim-test "let (empty env)" '(3 . 1) (lambda () (let ((a 1) (b 0)) (cons (let () (let () (set! b 3)) b) (let () (let () a)))))) (prim-test "named let (empty env)" 1 (lambda () (let ((a -1)) (let loop () (unless (positive? a) (set! a (+ a 1)) (loop))) a))) (prim-test "do (empty env)" 1 (lambda () (let ((a 0)) (do () ((positive? a) a) (set! a (+ a 1)))))) ;;---------------------------------------------------------------- (test-section "hygienity") (prim-test "hygienity (named let)" 4 (lambda () (let ((lambda list)) (let loop ((x 0)) (if (> x 3) x (loop (+ x 1))))))) (prim-test "hygienity (internal defines)" 4 (lambda () (let ((lambda list)) (define (x) 4) (x)))) (prim-test "hygienity (do)" 4 (lambda () (let ((lambda #f) (begin #f) (if #f) (letrec #f)) (do ((x 0 (+ x 1))) ((> x 3) x) #f)))) ;;---------------------------------------------------------------- (test-section "letrec and letrec*") (prim-test "letrec reordering" '((1 3) . (2 3 1)) (lambda () (let ((r '())) (cons (letrec ((a (begin (set! r (cons 1 r)) 1)) (b (begin (set! r (cons 2 r)) 2)) (c (begin (set! r (cons 3 r)) 3))) (list a c)) r)))) (prim-test "letrec* non-reordering" '((1 3) . (3 2 1)) (lambda () (let ((r '())) (cons (letrec* ((a (begin (set! r (cons 1 r)) 1)) (b (begin (set! r (cons 2 r)) 2)) (c (begin (set! r (cons 3 r)) 3))) (list a c)) r)))) (test-end)
null
https://raw.githubusercontent.com/shirok/Gauche/b2fc4010b46d67809cf0e66b25f326ff4a3c92d7/test/primsyn.scm
scheme
primitive syntax test We use prim-test instead of test, for error-handler is not tested yet. error-handler and macro tests. ---------------------------------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------- ---------------------------------------------------------------- avoid inline expansion This tests 'folding' path in ADJUST_ARGUMENT_FRAME Detect circular list in the argument and to avoid optimization, these data should be in global space. This is caught in different place (#<subr apply>), rather than VM APPLY instruction. ---------------------------------------------------------------- tricky case ---------------------------------------------------------------- The new compiler generates constant list for much wider and constant variable definitions are folded at the compile time). ---------------------------------------------------------------- values are just discarded. This behavior may be changed later, so do not count on it. The test just make sure it doesn't screw up anything. ---------------------------------------------------------------- check interaction w/ modules ---------------------------------------------------------------- Fix this after we have separate compile-error condition. ---------------------------------------------------------------- after it. ---------------------------------------------------------------- Empty environment frame is omitted by compiler optimization. The following tests makes sure if it works correctly. ---------------------------------------------------------------- ----------------------------------------------------------------
(use gauche.test) (test-start "primitive syntax") NB : errsyn.scm has tests for invalid syntax . It is run after (test-section "conditionals") (prim-test "if" 5 (lambda () (if #f 2 5))) (prim-test "if" 2 (lambda () (if (not #f) 2 5))) (prim-test "and" #t (lambda () (and))) (prim-test "and" 5 (lambda () (and 5))) (prim-test "and" #f (lambda () (and 5 #f 2))) (prim-test "and" #f (lambda () (and 5 #f unbound-var))) (prim-test "and" 'a (lambda () (and 3 4 'a))) (prim-test "or" #f (lambda () (or))) (prim-test "or" 3 (lambda () (or 3 9))) (prim-test "or" 3 (lambda () (or #f 3 unbound-var))) (prim-test "when" 4 (lambda () (when 3 5 4))) (prim-test "when" (undefined) (lambda () (when #f 5 4))) (prim-test "when" (undefined) (lambda () (when #f unbound-var))) (prim-test "unless" (undefined) (lambda () (unless 3 5 4))) (prim-test "unless" (undefined) (lambda () (unless #t unbound-var))) (prim-test "unless" 4 (lambda () (unless #f 5 4))) (prim-test "cond" (undefined) (lambda () (cond (#f 2)))) (prim-test "cond" 5 (lambda () (cond (#f 2) (else 5)))) (prim-test "cond" 2 (lambda () (cond (1 2) (else 5)))) (prim-test "cond" 8 (lambda () (cond (#f 2) (1 8) (else 5)))) (prim-test "cond" 3 (lambda () (cond (1 => (lambda (x) (+ x 2))) (else 8)))) (prim-test "cond (SRFI-61)" 1 (lambda () (cond (1 number? => values) (else 8)))) (prim-test "cond (SRFI-61)" 8 (lambda () (cond (1 string? => values) (else 8)))) (prim-test "cond (SRFI-61)" '(1 2) (lambda () (cond ((values 1 2) (lambda (x y) (and (= x 1) (= y 2))) => list)))) (prim-test "case" #t (lambda () (case (+ 2 3) ((1 3 5 7 9) #t) ((0 2 4 6 8) #f)))) (prim-test "case" #t (lambda () (undefined? (case 1 ((2 3) #t))))) (prim-test "case" #t (lambda () (case 1 (() #f) ((1) #t)))) (prim-test "case" #t (lambda () (case 1 (() #f) (else #t)))) (prim-test "case" #t (lambda () (undefined? (case 1 (() #t))))) (prim-test "case (SRFI-87)" 0 (lambda () (case (+ 2 3) ((1 3 5) 0) (else => values)))) (prim-test "case (SRFI-87)" 6 (lambda () (case (+ 2 3) ((1 3 5) => (cut + 1 <>)) (else => values)))) (prim-test "case (SRFI-87)" 5 (lambda () (case (+ 2 3) ((2 4 6) 0) (else => values)))) (test-section "binding") (prim-test "let" 35 (lambda () (let ((x 2) (y 3)) (let ((x 7) (z (+ x y))) (* z x))))) (prim-test "let*" 70 (lambda () (let ((x 2) (y 3)) (let* ((x 7) (z (+ x y))) (* z x))))) (prim-test "let*" 2 (lambda () (let* ((x 1) (x (+ x 1))) x))) (prim-test "named let" -3 (lambda () (let ((f -)) (let f ((a (f 3))) a)))) (test-section "closure and saved env") (prim-test "lambda" 5 (lambda () ((lambda (x) (car x)) '(5 6 7)))) (prim-test "lambda" 12 (lambda () ((lambda (x y) ((lambda (z) (* (car z) (cdr z))) (cons x y))) 3 4))) (define (addN n) (lambda (a) (+ a n))) (prim-test "lambda" 5 (lambda () ((addN 2) 3))) (define add3 (addN 3)) (prim-test "lambda" 9 (lambda () (add3 6))) (define count (let ((c 0)) (lambda () (set! c (+ c 1)) c))) (prim-test "lambda" 1 (lambda () (count))) (prim-test "lambda" 2 (lambda () (count))) (test-section "application") (prim-test "apply" '(1 2 3) (lambda () (Apply list '(1 2 3)))) (prim-test "apply" '(2 3 4) (lambda () (Apply list 2 '(3 4)))) (prim-test "apply" '(3 4 5) (lambda () (Apply list 3 4 '(5)))) (prim-test "apply" '(4 5 6) (lambda () (Apply list 4 5 6 '()))) (prim-test "apply^2" '() (lambda () (Apply Apply list '() '()))) (prim-test "Apply^2" '() (lambda () (Apply Apply list '(())))) (prim-test "apply^2" '(1 . 2) (lambda () (Apply Apply cons '((1 2))))) (prim-test "apply^2" '(3 . 4) (lambda () (Apply Apply cons 3 '((4))))) (prim-test "apply^2" '(5 . 6) (lambda () (Apply Apply (list cons 5 '(6))))) (prim-test "apply" '(6 7 8) (lambda () (Apply Apply (list list 6 7 '(8))))) This tests ' unfolding ' path in ADJUST_ARGUMENT_FRAME . (prim-test "apply, copying args" '(1 2 3) (lambda () (let ((orig (list 1 2 3))) (let ((new (Apply list orig))) (set-car! (cdr new) '100) orig)))) (prim-test "apply, copying args" '(2 3) (lambda () (let ((orig (list 2 3))) (let ((new (Apply list 1 orig))) (set-car! (cdr new) '100) orig)))) NB : At this point , we have n't tested # 0= reader notation , (define *apply-circular-data-1* (let ((x (list 'a))) (set-cdr! x x) x)) (define *apply-circular-data-2* (let ((x (list 'a 'a))) (set-cdr! (cdr x) x) x)) (prim-test "apply, circular list 1" "improper list not allowed: #0=(a . #0#)" (lambda () (with-error-handler (lambda (e) (slot-ref e 'message)) (lambda () (apply list *apply-circular-data-1*))))) (prim-test "apply, circular list 2" "improper list not allowed: #0=(a . #0#)" (lambda () (with-error-handler (lambda (e) (slot-ref e 'message)) (lambda () (apply list 'a *apply-circular-data-1*))))) (prim-test "apply, circular list 3" "improper list not allowed: #0=(a a . #0#)" (lambda () (with-error-handler (lambda (e) (slot-ref e 'message)) (lambda () (apply list 'a *apply-circular-data-2*))))) (prim-test "apply, circular list 4" "improper list not allowed: #0=(a a . #0#)" (lambda () (with-error-handler (lambda (e) (slot-ref e 'message)) (lambda () (Apply list 'a *apply-circular-data-2*))))) This test exhibits the optimizer bug reported by . (define bug-optimizer-local-inliner (lambda (flag) (define (a . args) (receive x args (cons x x) (Apply values x)) (Apply format args)) (define (b bar) (a "~a" bar)) (b 1) (cond (flag (b 1)) (else (a "~a" 1))))) (prim-test "apply local inliner optimizer" "1" (lambda () (bug-optimizer-local-inliner #f)) equal?) (prim-test "apply local inliner optimizer" "1" (lambda () (bug-optimizer-local-inliner #t)) equal?) (prim-test "map" '() (lambda () (map car '()))) (prim-test "map" '(1 2 3) (lambda () (map car '((1) (2) (3))))) (prim-test "map" '(() () ()) (lambda () (map cdr '((1) (2) (3))))) (prim-test "map" '((1 . 4) (2 . 5) (3 . 6)) (lambda () (map cons '(1 2 3) '(4 5 6)))) (test-section "loop") (define (fact-non-tail-rec n) (if (<= n 1) n (* n (fact-non-tail-rec (- n 1))))) (prim-test "loop non-tail-rec" 120 (lambda () (fact-non-tail-rec 5))) (define (fact-tail-rec n r) (if (<= n 1) r (fact-tail-rec (- n 1) (* n r)))) (prim-test "loop tail-rec" 120 (lambda () (fact-tail-rec 5 1))) (define (fact-named-let n) (let loop ((n n) (r 1)) (if (<= n 1) r (loop (- n 1) (* n r))))) (prim-test "loop named-let" 120 (lambda () (fact-named-let 5))) (define (fact-int-define n) (define (rec n r) (if (<= n 1) r (rec (- n 1) (* n r)))) (rec n 1)) (prim-test "loop int-define" 120 (lambda () (fact-int-define 5))) (define (fact-do n) (do ((n n (- n 1)) (r 1 (* n r))) ((<= n 1) r))) (prim-test "loop do" 120 (lambda () (fact-do 5))) (prim-test "do" #f (lambda () (do () (#t #f) #t))) (test-section "quasiquote") range of quasiquoted forms ( e.g. constant numerical expressions (define-constant quasi0 99) (define quasi1 101) (define-constant quasi2 '(a b)) (define quasi3 '(c d)) (prim-test "qq" '(1 2 3) (lambda () `(1 2 3))) (prim-test "qq" '() (lambda () `())) (prim-test "qq" 99 (lambda () `,quasi0)) (prim-test "qq" 101 (lambda () `,quasi1)) (prim-test "qq," '((1 . 2)) (lambda () `(,(cons 1 2)))) (prim-test "qq," '((1 . 2) 3) (lambda () `(,(cons 1 2) 3))) (prim-test "qq," '(0 (1 . 2)) (lambda () `(0 ,(cons 1 2)))) (prim-test "qq," '(0 (1 . 2) 3) (lambda () `(0 ,(cons 1 2) 3))) (prim-test "qq," '(((1 . 2))) (lambda () `((,(cons 1 2))))) (prim-test "qq," '(((1 . 2)) 3) (lambda () `((,(cons 1 2)) 3))) (prim-test "qq," '(99 3) (lambda () `(,quasi0 3))) (prim-test "qq," '(3 99) (lambda () `(3 ,quasi0))) (prim-test "qq," '(3 99 3) (lambda () `(3 ,quasi0 3))) (prim-test "qq," '(100 3) (lambda () `(,(+ quasi0 1) 3))) (prim-test "qq," '(3 100) (lambda () `(3 ,(+ quasi0 1)))) (prim-test "qq," '(101 3) (lambda () `(,quasi1 3))) (prim-test "qq," '(3 101) (lambda () `(3 ,quasi1))) (prim-test "qq," '(102 3) (lambda () `(,(+ quasi1 1) 3))) (prim-test "qq," '(3 102) (lambda () `(3 ,(+ quasi1 1)))) (prim-test "qq,(r6rs)" '(98 99 (a b) 100) (lambda () `(98 (unquote quasi0 quasi2) 100))) (prim-test "qq,(r6rs)" '(98 99 101 100) (lambda () `(98 (unquote quasi0 quasi1) 100))) (prim-test "qq,(r6rs)" '(98 99 (a b) 100) (lambda () `(98 (unquote quasi0 quasi2) 100))) (prim-test "qq,(r6rs)" '(98 99 (a b) (1 2) (3 4)) (lambda () `(98 (unquote quasi0 quasi2) (unquote (list 1 2) (list 3 4))))) (prim-test "qq@" '(1 2 3 4) (lambda () `(1 ,@(list 2 3) 4))) (prim-test "qq@" '(1 2 3 4) (lambda () `(1 2 ,@(list 3 4)))) (prim-test "qq@" '(a b c d) (lambda () `(,@quasi2 ,@quasi3))) (prim-test "qq@(r6rs)" '(1 a b a b 2) (lambda () `(1 (unquote-splicing quasi2 quasi2) 2))) (prim-test "qq@(r6rs)" '(1 a b c d 2) (lambda () `(1 (unquote-splicing quasi2 quasi3) 2))) (prim-test "qq@(r6rs)" '(1 a b c d 2) (lambda () `(1 (unquote-splicing (list 'a 'b) '(c d)) ,@(list 2)))) (prim-test "qq." '(1 2 3 4) (lambda () `(1 2 . ,(list 3 4)))) (prim-test "qq." '(a b c d) (lambda () `(,@quasi2 . ,quasi3))) (prim-test "qq#," '#((1 . 2) 3) (lambda () `#(,(cons 1 2) 3))) (prim-test "qq#," '#(99 3) (lambda () `#(,quasi0 3))) (prim-test "qq#," '#(100 3) (lambda () `#(,(+ quasi0 1) 3))) (prim-test "qq#," '#(3 101) (lambda () `#(3 ,quasi1))) (prim-test "qq#," '#(3 102) (lambda () `#(3 ,(+ quasi1 1)))) (prim-test "qq#@" '#(1 2 3 4) (lambda () `#(1 ,@(list 2 3) 4))) (prim-test "qq#@" '#(1 2 3 4) (lambda () `#(1 2 ,@(list 3 4)))) (prim-test "qq#@" '#(a b c d) (lambda () `#(,@quasi2 ,@quasi3))) (prim-test "qq#@" '#(a b (c d)) (lambda () `#(,@quasi2 ,quasi3))) (prim-test "qq#@" '#((a b) c d) (lambda () `#(,quasi2 ,@quasi3))) (prim-test "qq#" '#() (lambda () `#())) (prim-test "qq#@" '#() (lambda () `#(,@(list)))) (prim-test "qq@@" '(1 2 1 2) (lambda () `(,@(list 1 2) ,@(list 1 2)))) (prim-test "qq@@" '(1 2 a 1 2) (lambda () `(,@(list 1 2) a ,@(list 1 2)))) (prim-test "qq@@" '(a 1 2 1 2) (lambda () `(a ,@(list 1 2) ,@(list 1 2)))) (prim-test "qq@@" '(1 2 1 2 a) (lambda () `(,@(list 1 2) ,@(list 1 2) a))) (prim-test "qq@@" '(1 2 1 2 a b) (lambda () `(,@(list 1 2) ,@(list 1 2) a b))) (prim-test "qq@." '(1 2 1 2 . a) (lambda () `(,@(list 1 2) ,@(list 1 2) . a))) (prim-test "qq@." '(1 2 1 2 1 . 2) (lambda () `(,@(list 1 2) ,@(list 1 2) . ,(cons 1 2)))) (prim-test "qq@." '(1 2 1 2 a b) (lambda () `(,@(list 1 2) ,@(list 1 2) . ,quasi2))) (prim-test "qq@." '(1 2 1 2 a 1 . 2) (lambda () `(,@(list 1 2) ,@(list 1 2) a . ,(cons 1 2)))) (prim-test "qq@." '(1 2 1 2 a c d) (lambda () `(,@(list 1 2) ,@(list 1 2) a . ,quasi3))) (prim-test "qq#@@" '#(1 2 1 2) (lambda () `#(,@(list 1 2) ,@(list 1 2)))) (prim-test "qq#@@" '#(1 2 a 1 2) (lambda () `#(,@(list 1 2) a ,@(list 1 2)))) (prim-test "qq#@@" '#(a 1 2 1 2) (lambda () `#(a ,@(list 1 2) ,@(list 1 2)))) (prim-test "qq#@@" '#(1 2 1 2 a) (lambda () `#(,@(list 1 2) ,@(list 1 2) a))) (prim-test "qq#@@" '#(1 2 1 2 a b) (lambda () `#(,@(list 1 2) ,@(list 1 2) a b))) (prim-test "qqq" '(1 `(1 ,2 ,3) 1) (lambda () `(1 `(1 ,2 ,,(+ 1 2)) 1))) (prim-test "qqq" '(1 `(1 ,99 ,101) 1) (lambda () `(1 `(1 ,,quasi0 ,,quasi1) 1))) (prim-test "qqq" '(1 `(1 ,@2 ,@(1 2))) (lambda () `(1 `(1 ,@2 ,@,(list 1 2))))) (prim-test "qqq" '(1 `(1 ,@2 (unquote 1 2))) (lambda () `(1 `(1 ,@2 ,,@(list 1 2))))) (prim-test "qqq" '(1 `(1 ,@2 (unquote-splicing 1 2))) (lambda () `(1 `(1 ,@2 ,@,@(list 1 2))))) (prim-test "qqq" '(1 `(1 ,@(a b) ,@(c d))) (lambda () `(1 `(1 ,@,quasi2 ,@,quasi3)))) (prim-test "qqq" '(1 `(1 ,(a b x) ,(y c d))) (lambda () `(1 `(1 ,(,@quasi2 x) ,(y ,@quasi3))))) (prim-test "qqq#" '#(1 `(1 ,2 ,3) 1) (lambda () `#(1 `(1 ,2 ,,(+ 1 2)) 1))) (prim-test "qqq#" '#(1 `(1 ,99 ,101) 1) (lambda () `#(1 `(1 ,,quasi0 ,,quasi1) 1))) (prim-test "qqq#" '#(1 `(1 ,@2 ,@(1 2))) (lambda () `#(1 `(1 ,@2 ,@,(list 1 2))))) (prim-test "qqq#" '#(1 `(1 ,@(a b) ,@(c d))) (lambda () `#(1 `(1 ,@,quasi2 ,@,quasi3)))) (prim-test "qqq#" '#(1 `(1 ,(a b x) ,(y c d))) (lambda () `#(1 `(1 ,(,@quasi2 x) ,(y ,@quasi3))))) (prim-test "qqq#" '(1 `#(1 ,(a b x) ,(y c d))) (lambda () `(1 `#(1 ,(,@quasi2 x) ,(y ,@quasi3))))) (prim-test "qq-hygiene 0" '(2 1) (lambda () (let ((quasiquote reverse)) `(list 1 2)))) (prim-test "qq-hygiene 1" '(,(+ 1 2)) (lambda () (let ((unquote 3)) `(,(+ 1 2))))) (prim-test "qq-hygiene 2" '(,@(+ 1 2)) (lambda () (let ((unquote-splicing 3)) `(,@(+ 1 2))))) (test-section "multiple values") (prim-test "receive" '(1 2 3) (lambda () (receive (a b c) (values 1 2 3) (list a b c)))) (prim-test "receive" '(1 2 3) (lambda () (receive (a . r) (values 1 2 3) (cons a r)))) (prim-test "receive" '(1 2 3) (lambda () (receive x (values 1 2 3) x))) (prim-test "receive" 1 (lambda () (receive (a) 1 a))) (prim-test "call-with-values" '(1 2 3) (lambda () (call-with-values (lambda () (values 1 2 3)) list))) (prim-test "call-with-values" '() (lambda () (call-with-values (lambda () (values)) list))) This is not ' right ' in R5RS sense --- for now , I just tolerate it by CommonLisp way , i.e. if more than one value is passed to an implicit continuation that expects one value , the second and after (prim-test "receive" '((0 0)) (lambda () (receive l (list 0 (values 0 1 2)) l))) (test-section "eval") (prim-test "eval" '(1 . 2) (lambda () (eval '(cons 1 2) (interaction-environment)))) (define (vector-ref x y) 'foo) (prim-test "eval" '(foo foo 3) (lambda () (list (vector-ref '#(3) 0) (eval '(vector-ref '#(3) 0) (interaction-environment)) (eval '(vector-ref '#(3) 0) (scheme-report-environment 5))))) (define vector-ref (with-module scheme vector-ref)) (prim-test "eval" #t (lambda () (with-error-handler (lambda (e) #t) (lambda () (eval '(car '(3 2)) (null-environment 5)))))) (define-module primsyn.test (define foo 'a)) (define foo '(x y)) (prim-test "eval (module)" '(a b (x y)) (lambda () (let* ((m (find-module 'primsyn.test)) (a (eval 'foo m)) (b (eval '(begin (set! foo 'b) foo) m))) (list a b foo)))) (prim-test "eval (module)" '(x y) (lambda () (with-error-handler (lambda (e) foo) (lambda () (eval '(Apply car foo '()) (find-module 'primsyn.test)))))) (test-section "max literal arguments") (define (test-max-literal-args msg expr) (prim-test (string-append "max literal arguments for " msg) 'caught (lambda () (with-error-handler (lambda (e) 'caught) (lambda () (eval expr (interaction-environment))))))) (test-max-literal-args "inliner" `(list ,@(make-list 10000 #f))) (test-max-literal-args "global proc" `(make ,@(make-list 10000 #f))) (test-max-literal-args "local proc" `(let ((foo (lambda x x))) (foo ,@(make-list 10000 #f)))) (test-section "local procedure optimization") this caused an internal compiler error in 0.8.6 . ( found and fixed by ) (prim-test "internal-define inilining" '(1) (lambda () (with-error-handler (lambda (e) 'ouch!) (lambda () (eval '(let () (define (a x) x) (define (b x) (a x)) (define (c x) (b x)) (list 1)) (interaction-environment)))))) this caused an internal compiler error in 0.8.6 ( found and fixed by ) (prim-test "multiple inlining" 0 (lambda () (let ((f (lambda (i) (set! i 0) i))) (f (f 1))))) this caused an internal compiler error in 0.9.1 (define (zero) 0) (prim-test "pass3 inlining with pass3/$call optimization" #t (lambda () (eval '((letrec ((f (lambda (a b) (do ((x a (+ x 1))) ((>= x b)))))) f) (zero) (zero)) (interaction-environment)))) This caused internal error in 0.9.1 , and infinite loop in dev version (prim-test "pass3/$call inlining problem" #t (lambda () (procedure? (eval '(lambda (n p t) (define (y a r s f) (let loop ([e 0]) (cond [(a n) (unwind-protect (s) (r n))] [(< e 10) (loop (+ 1 e))] [else (f)]))) (define (l0 a r) (y a r (^() (r n)) (^() (error "oo")))) Main locker (define (l1 a r) (y a r p (^() (if (and-let* ([ t ] [m (file-mtime n)]) (< (+ m t) 10)) (begin (l0 a r) (l1 a r)))))) (error "zz")) (interaction-environment))))) (test-section "optimized frames") (prim-test "lambda (empty env)" 1 (lambda () (let* ((a 1) (b (lambda () ((lambda () a))))) (b)))) (prim-test "let (empty env)" 1 (lambda () (let ((a 1)) (let () (let () a))))) (prim-test "let (empty env)" '(1 . 1) (lambda () (let ((a 1)) (cons (let () (let () a)) (let* () (letrec () a)))))) (prim-test "let (empty env)" '(3 . 1) (lambda () (let ((a 1) (b 0)) (cons (let () (let () (set! b 3)) b) (let () (let () a)))))) (prim-test "named let (empty env)" 1 (lambda () (let ((a -1)) (let loop () (unless (positive? a) (set! a (+ a 1)) (loop))) a))) (prim-test "do (empty env)" 1 (lambda () (let ((a 0)) (do () ((positive? a) a) (set! a (+ a 1)))))) (test-section "hygienity") (prim-test "hygienity (named let)" 4 (lambda () (let ((lambda list)) (let loop ((x 0)) (if (> x 3) x (loop (+ x 1))))))) (prim-test "hygienity (internal defines)" 4 (lambda () (let ((lambda list)) (define (x) 4) (x)))) (prim-test "hygienity (do)" 4 (lambda () (let ((lambda #f) (begin #f) (if #f) (letrec #f)) (do ((x 0 (+ x 1))) ((> x 3) x) #f)))) (test-section "letrec and letrec*") (prim-test "letrec reordering" '((1 3) . (2 3 1)) (lambda () (let ((r '())) (cons (letrec ((a (begin (set! r (cons 1 r)) 1)) (b (begin (set! r (cons 2 r)) 2)) (c (begin (set! r (cons 3 r)) 3))) (list a c)) r)))) (prim-test "letrec* non-reordering" '((1 3) . (3 2 1)) (lambda () (let ((r '())) (cons (letrec* ((a (begin (set! r (cons 1 r)) 1)) (b (begin (set! r (cons 2 r)) 2)) (c (begin (set! r (cons 3 r)) 3))) (list a c)) r)))) (test-end)
0aac1a30cf9d25aa214086ba06ab1853874742b53a360e5a17aca8534ac41f4b
Risto-Stevcev/bastet
Test_JsDefault.ml
open BsMocha.Mocha module TestDefault = Test.Default (MochaI.Test) (JsVerifyI.Quickcheck) ;; describe "Default" (fun () -> MochaI.run TestDefault.suites)
null
https://raw.githubusercontent.com/Risto-Stevcev/bastet/030db286f57d2e316897f0600d40b34777eabba6/bastet_js/test/Test_JsDefault.ml
ocaml
open BsMocha.Mocha module TestDefault = Test.Default (MochaI.Test) (JsVerifyI.Quickcheck) ;; describe "Default" (fun () -> MochaI.run TestDefault.suites)
8ecb2dc42e4a21b345c5460e08254b68d71c7ac61d9f8c62d140b96910a0d167
flavioc/cl-hurd
file-exec.lisp
(in-package :hurd-translator) (defcfun ("do_exec_exec" %do-exec-exec) pid-t (execserver port) (file port) (file-type msg-type-name) (oldtask task) (flags exec-flags) (argv :pointer) (argvlen msg-type-number) (envp :pointer) (envplen msg-type-number) (dtable :pointer) (dtable-type msg-type-name) (dtablelen msg-type-number) (portarray :pointer) (portarray-type msg-type-name) (portarraylen msg-type-number) (intarray :pointer) (intarraylen msg-type-number) (deallocnames :pointer) (deallocnameslen msg-type-number) (destroynames :pointer) (destroynameslen msg-type-number)) (defcfun ("exec_finished" %exec-finished) :boolean (pid pid-t) (status :pointer)) (def-fs-interface :file-exec ((file port) (task task) (flags exec-flags) (argv :pointer) (argvlen :unsigned-int) (envp :pointer) (envplen :unsigned-int) (fds :pointer) (fdslen :unsigned-int) (portarray :pointer) (portarraylen :unsigned-int) (intarray :pointer) (intarray-len :unsigned-int) (deallocnames :pointer) (deallocnameslen :unsigned-int) (destroynames :pointer) (destroynameslen :unsigned-int)) (with-lookup protid file (block file-exec (let ((node (get-node protid)) (open (open-node protid)) (user (get-user protid))) (unless (flag-is-p (flags open) :exec) (return-from file-exec :bad-fd)) (unless (has-access-p node user :exec) (return-from file-exec :permission-denied)) (when (is-dir-p (stat node)) (return-from file-exec :permission-denied)) (let ((use-uid-p (is-uid-p (stat node))) (use-gid-p (is-gid-p (stat node)))) (when (or use-uid-p use-gid-p) (warn "suid/sgid executables not supported."))) (let* ((new-user (make-iouser :old user)) (new-open (make-open-node node '(:read) :copy open)) (new-protid (new-protid *translator* new-user new-open))) (with-port-deallocate (right (get-send-right new-protid)) (let ((pid (%do-exec-exec +exec-server+ right :copy-send task (enable-flags flags :newtask) argv argvlen envp envplen fds :copy-send fdslen portarray :copy-send portarraylen intarray intarray-len deallocnames deallocnameslen destroynames destroynameslen))) (when (zerop pid) (return-from file-exec :gratuitous-error)) (with-foreign-pointer (status (foreign-type-size :int)) (loop for ret = (%exec-finished pid status) when ret return (mem-ref status 'err) do (wait :miliseconds 200))))))))))
null
https://raw.githubusercontent.com/flavioc/cl-hurd/982232f47d1a0ff4df5fde2edad03b9df871470a/translator/interfaces/file-exec.lisp
lisp
(in-package :hurd-translator) (defcfun ("do_exec_exec" %do-exec-exec) pid-t (execserver port) (file port) (file-type msg-type-name) (oldtask task) (flags exec-flags) (argv :pointer) (argvlen msg-type-number) (envp :pointer) (envplen msg-type-number) (dtable :pointer) (dtable-type msg-type-name) (dtablelen msg-type-number) (portarray :pointer) (portarray-type msg-type-name) (portarraylen msg-type-number) (intarray :pointer) (intarraylen msg-type-number) (deallocnames :pointer) (deallocnameslen msg-type-number) (destroynames :pointer) (destroynameslen msg-type-number)) (defcfun ("exec_finished" %exec-finished) :boolean (pid pid-t) (status :pointer)) (def-fs-interface :file-exec ((file port) (task task) (flags exec-flags) (argv :pointer) (argvlen :unsigned-int) (envp :pointer) (envplen :unsigned-int) (fds :pointer) (fdslen :unsigned-int) (portarray :pointer) (portarraylen :unsigned-int) (intarray :pointer) (intarray-len :unsigned-int) (deallocnames :pointer) (deallocnameslen :unsigned-int) (destroynames :pointer) (destroynameslen :unsigned-int)) (with-lookup protid file (block file-exec (let ((node (get-node protid)) (open (open-node protid)) (user (get-user protid))) (unless (flag-is-p (flags open) :exec) (return-from file-exec :bad-fd)) (unless (has-access-p node user :exec) (return-from file-exec :permission-denied)) (when (is-dir-p (stat node)) (return-from file-exec :permission-denied)) (let ((use-uid-p (is-uid-p (stat node))) (use-gid-p (is-gid-p (stat node)))) (when (or use-uid-p use-gid-p) (warn "suid/sgid executables not supported."))) (let* ((new-user (make-iouser :old user)) (new-open (make-open-node node '(:read) :copy open)) (new-protid (new-protid *translator* new-user new-open))) (with-port-deallocate (right (get-send-right new-protid)) (let ((pid (%do-exec-exec +exec-server+ right :copy-send task (enable-flags flags :newtask) argv argvlen envp envplen fds :copy-send fdslen portarray :copy-send portarraylen intarray intarray-len deallocnames deallocnameslen destroynames destroynameslen))) (when (zerop pid) (return-from file-exec :gratuitous-error)) (with-foreign-pointer (status (foreign-type-size :int)) (loop for ret = (%exec-finished pid status) when ret return (mem-ref status 'err) do (wait :miliseconds 200))))))))))
a903a526234a392e66dac76377aa20cb310db8aba2738c42db3edac87975928c
ocaml-multicore/parafuzz
predef.mli
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Predefined type constructors (with special typing rules in typecore) *) open Types val type_int: type_expr val type_char: type_expr val type_string: type_expr val type_bytes: type_expr val type_float: type_expr val type_bool: type_expr val type_unit: type_expr val type_exn: type_expr val type_eff: type_expr -> type_expr val type_continuation: type_expr -> type_expr -> type_expr val type_array: type_expr -> type_expr val type_list: type_expr -> type_expr val type_option: type_expr -> type_expr val type_nativeint: type_expr val type_int32: type_expr val type_int64: type_expr val type_lazy_t: type_expr -> type_expr val type_extension_constructor:type_expr val type_floatarray:type_expr val path_int: Path.t val path_char: Path.t val path_string: Path.t val path_bytes: Path.t val path_float: Path.t val path_bool: Path.t val path_unit: Path.t val path_exn: Path.t val path_eff: Path.t val path_continuation: Path.t val path_array: Path.t val path_list: Path.t val path_option: Path.t val path_nativeint: Path.t val path_int32: Path.t val path_int64: Path.t val path_lazy_t: Path.t val path_extension_constructor: Path.t val path_floatarray: Path.t val path_match_failure: Path.t val path_assert_failure : Path.t val path_undefined_recursive_module : Path.t val ident_false : Ident.t val ident_true : Ident.t val ident_void : Ident.t val ident_nil : Ident.t val ident_cons : Ident.t val ident_none : Ident.t val ident_some : Ident.t To build the initial environment . Since there is a nasty mutual recursion between predef and env , we break it by parameterizing over , Env.add_type and Env.add_extension . recursion between predef and env, we break it by parameterizing over Env.t, Env.add_type and Env.add_extension. *) val build_initial_env: (Ident.t -> type_declaration -> 'a -> 'a) -> (Ident.t -> extension_constructor -> 'a -> 'a) -> 'a -> 'a * 'a (* To initialize linker tables *) val builtin_values: (string * Ident.t) list val builtin_idents: (string * Ident.t) list * All predefined exceptions , exposed as [ Ident.t ] for flambda ( for building value approximations ) . The [ Ident.t ] for division by zero is also exported explicitly so flambda can generate code to raise it . building value approximations). The [Ident.t] for division by zero is also exported explicitly so flambda can generate code to raise it. *) val ident_division_by_zero: Ident.t val all_predef_exns : Ident.t list
null
https://raw.githubusercontent.com/ocaml-multicore/parafuzz/6a92906f1ba03287ffcb433063bded831a644fd5/typing/predef.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Predefined type constructors (with special typing rules in typecore) To initialize linker tables
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Types val type_int: type_expr val type_char: type_expr val type_string: type_expr val type_bytes: type_expr val type_float: type_expr val type_bool: type_expr val type_unit: type_expr val type_exn: type_expr val type_eff: type_expr -> type_expr val type_continuation: type_expr -> type_expr -> type_expr val type_array: type_expr -> type_expr val type_list: type_expr -> type_expr val type_option: type_expr -> type_expr val type_nativeint: type_expr val type_int32: type_expr val type_int64: type_expr val type_lazy_t: type_expr -> type_expr val type_extension_constructor:type_expr val type_floatarray:type_expr val path_int: Path.t val path_char: Path.t val path_string: Path.t val path_bytes: Path.t val path_float: Path.t val path_bool: Path.t val path_unit: Path.t val path_exn: Path.t val path_eff: Path.t val path_continuation: Path.t val path_array: Path.t val path_list: Path.t val path_option: Path.t val path_nativeint: Path.t val path_int32: Path.t val path_int64: Path.t val path_lazy_t: Path.t val path_extension_constructor: Path.t val path_floatarray: Path.t val path_match_failure: Path.t val path_assert_failure : Path.t val path_undefined_recursive_module : Path.t val ident_false : Ident.t val ident_true : Ident.t val ident_void : Ident.t val ident_nil : Ident.t val ident_cons : Ident.t val ident_none : Ident.t val ident_some : Ident.t To build the initial environment . Since there is a nasty mutual recursion between predef and env , we break it by parameterizing over , Env.add_type and Env.add_extension . recursion between predef and env, we break it by parameterizing over Env.t, Env.add_type and Env.add_extension. *) val build_initial_env: (Ident.t -> type_declaration -> 'a -> 'a) -> (Ident.t -> extension_constructor -> 'a -> 'a) -> 'a -> 'a * 'a val builtin_values: (string * Ident.t) list val builtin_idents: (string * Ident.t) list * All predefined exceptions , exposed as [ Ident.t ] for flambda ( for building value approximations ) . The [ Ident.t ] for division by zero is also exported explicitly so flambda can generate code to raise it . building value approximations). The [Ident.t] for division by zero is also exported explicitly so flambda can generate code to raise it. *) val ident_division_by_zero: Ident.t val all_predef_exns : Ident.t list
3da6720057616704ca5b7c3f693613c8e598d2638f8c993baa6a4f9eea3ba353
theodormoroianu/SecondYearCourses
LambdaChurch_20210415164352.hs
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) -- alpha-equivalence aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) -- subst u x t defines [u/x]t, i.e., substituting u for x in t for example [ 3 / x](x + x ) = = 3 + 3 -- This substitution avoids variable captures so it is safe to be used when -- reducing terms with free variables (e.g., if evaluating inside lambda abstractions) subst :: Term -- ^ substitution term -> Variable -- ^ variable to be substitutes -> Term -- ^ term in which the substitution occurs -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV -- Normal order reduction -- - like call by name -- - but also reduce under lambda abstractions if no application is possible -- - guarantees reaching a normal form if it exists normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce -- alpha-beta equivalence (for strongly normalizing terms) is obtained by -- fully evaluating the terms using beta-reduction, then checking their -- alpha-equivalence. abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s -- Church Encodings in Lambda churchTrue :: Term churchTrue = lams ["t", "f"] (v "t") churchFalse :: Term churchFalse = lams ["t", "f"] (v "f") churchIf :: Term churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") churchNot :: Term churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue) churchAnd :: Term churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse) churchOr :: Term churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2") church0 :: Term church0 = lams ["s", "z"] (v "z") -- note that it's the same as churchFalse church1 :: Term church1 = lams ["s", "z"] (v "s" $$ v "z") church2 :: Term church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) churchS :: Term churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) churchNat :: Integer -> Term churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z")) churchPlus :: Term churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) churchPlus' :: Term churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m") churchMul :: Term churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) churchMul' :: Term churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0) churchPow :: Term churchPow = lams ["m", "n"] (v "n" $$ v "m") churchPow' :: Term churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1) churchIs0 :: Term churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue) churchS' :: Term churchS' = lam "n" (v "n" $$ churchS $$ church1) churchS'Rev0 :: Term churchS'Rev0 = lams ["s","z"] church0 churchPred :: Term churchPred = lam "n" (churchIf $$ (churchIs0 $$ v "n") $$ church0 $$ (v "n" $$ churchS' $$ churchS'Rev0)) churchSub :: Term churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m") churchLte :: Term churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n")) churchGte :: Term churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m") churchLt :: Term churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n")) churchGt :: Term churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m") churchEq :: Term churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m")) churchPair :: Term churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") churchFst :: Term churchFst = lam "pair" (v "pair" $$ churchTrue) churchSnd :: Term churchSnd = lam "pair" (v "pair" $$ churchFalse) churchPred' :: Term churchPred' = lam "n" (churchFst $$ (v "n" $$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ church0 $$ church0) )) cPred :: CNat -> CNat cPred = \n -> cFst $ cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0) churchFactorial :: Term churchFactorial = lam "n" (churchSnd $$ (v "n" $$ lam "p" (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church1 $$ church1) )) cFactorial :: CNat -> CNat cFactorial = \n -> cSnd $ cFor n (\p -> cPair (cFst p) (cFst p * cSnd p)) (cPair 1 1) churchFibonacci :: Term churchFibonacci = lam "n" (churchFst $$ (v "n" $$ lam "p" (churchPair $$ (churchSnd $$ v "p") $$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church0 $$ church1) )) cFibonacci :: CNat -> CNat cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1) churchDivMod :: Term churchDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (churchIf $$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair")) $$ (churchPair $$ (churchS $$ (churchFst $$ v "pair")) $$ (churchSub $$ (churchSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (churchPair $$ church0 $$ v "m") ) cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m) newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } instance Foldable CList where foldr agg init xs = cFoldR xs agg init churchNil :: Term churchNil = lams ["agg", "init"] (v "init") cNil :: CList a cNil = CList $ \agg init -> init churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) (.:) :: a -> CList a -> CList a (.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415164352.hs
haskell
alpha-equivalence subst u x t defines [u/x]t, i.e., substituting u for x in t This substitution avoids variable captures so it is safe to be used when reducing terms with free variables (e.g., if evaluating inside lambda abstractions) ^ substitution term ^ variable to be substitutes ^ term in which the substitution occurs Normal order reduction - like call by name - but also reduce under lambda abstractions if no application is possible - guarantees reaching a normal form if it exists alpha-beta equivalence (for strongly normalizing terms) is obtained by fully evaluating the terms using beta-reduction, then checking their alpha-equivalence. Church Encodings in Lambda note that it's the same as churchFalse
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) for example [ 3 / x](x + x ) = = 3 + 3 subst -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s churchTrue :: Term churchTrue = lams ["t", "f"] (v "t") churchFalse :: Term churchFalse = lams ["t", "f"] (v "f") churchIf :: Term churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") churchNot :: Term churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue) churchAnd :: Term churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse) churchOr :: Term churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2") church0 :: Term church1 :: Term church1 = lams ["s", "z"] (v "s" $$ v "z") church2 :: Term church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) churchS :: Term churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) churchNat :: Integer -> Term churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z")) churchPlus :: Term churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) churchPlus' :: Term churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m") churchMul :: Term churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) churchMul' :: Term churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0) churchPow :: Term churchPow = lams ["m", "n"] (v "n" $$ v "m") churchPow' :: Term churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1) churchIs0 :: Term churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue) churchS' :: Term churchS' = lam "n" (v "n" $$ churchS $$ church1) churchS'Rev0 :: Term churchS'Rev0 = lams ["s","z"] church0 churchPred :: Term churchPred = lam "n" (churchIf $$ (churchIs0 $$ v "n") $$ church0 $$ (v "n" $$ churchS' $$ churchS'Rev0)) churchSub :: Term churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m") churchLte :: Term churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n")) churchGte :: Term churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m") churchLt :: Term churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n")) churchGt :: Term churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m") churchEq :: Term churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m")) churchPair :: Term churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") churchFst :: Term churchFst = lam "pair" (v "pair" $$ churchTrue) churchSnd :: Term churchSnd = lam "pair" (v "pair" $$ churchFalse) churchPred' :: Term churchPred' = lam "n" (churchFst $$ (v "n" $$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ church0 $$ church0) )) cPred :: CNat -> CNat cPred = \n -> cFst $ cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0) churchFactorial :: Term churchFactorial = lam "n" (churchSnd $$ (v "n" $$ lam "p" (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church1 $$ church1) )) cFactorial :: CNat -> CNat cFactorial = \n -> cSnd $ cFor n (\p -> cPair (cFst p) (cFst p * cSnd p)) (cPair 1 1) churchFibonacci :: Term churchFibonacci = lam "n" (churchFst $$ (v "n" $$ lam "p" (churchPair $$ (churchSnd $$ v "p") $$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church0 $$ church1) )) cFibonacci :: CNat -> CNat cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1) churchDivMod :: Term churchDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (churchIf $$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair")) $$ (churchPair $$ (churchS $$ (churchFst $$ v "pair")) $$ (churchSub $$ (churchSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (churchPair $$ church0 $$ v "m") ) cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m) newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } instance Foldable CList where foldr agg init xs = cFoldR xs agg init churchNil :: Term churchNil = lams ["agg", "init"] (v "init") cNil :: CList a cNil = CList $ \agg init -> init churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) (.:) :: a -> CList a -> CList a (.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
2e96f2b67a067f2d0cad7ca7af9f180b5d6c6783cfe4521ed3803f34e2a2180f
resttime/cl-liballegro
fullscreen-modes.lisp
(in-package #:cl-liballegro) Fullscreen modes (defcfun ("al_get_display_mode" get-display-mode) :pointer (index :int) (mode :pointer)) (defcfun ("al_get_num_display_modes" get-num-display-modes) :int)
null
https://raw.githubusercontent.com/resttime/cl-liballegro/0f8a3a77d5c81fe14352d9a799cba20e1a3a90b4/src/ffi-functions/fullscreen-modes.lisp
lisp
(in-package #:cl-liballegro) Fullscreen modes (defcfun ("al_get_display_mode" get-display-mode) :pointer (index :int) (mode :pointer)) (defcfun ("al_get_num_display_modes" get-num-display-modes) :int)
2fea79b74409f79c84c5deeb6c59e16a9e36cc0d65c531a2e24abaca950cb6bb
kiranshila/Doplarr
state.clj
(ns doplarr.state (:require [clojure.core.cache.wrapped :as cache])) (def cache (cache/ttl-cache-factory {} :ttl 900000)) (def discord (atom nil)) (def config (atom nil))
null
https://raw.githubusercontent.com/kiranshila/Doplarr/6e8da5dde51ce8d92d18b7971383ec0b588ff426/src/doplarr/state.clj
clojure
(ns doplarr.state (:require [clojure.core.cache.wrapped :as cache])) (def cache (cache/ttl-cache-factory {} :ttl 900000)) (def discord (atom nil)) (def config (atom nil))
495014e437286cd554cb6df1fe48f0e6490b07a6b56f9f2e337b8262d4de32c1
racket/typed-racket
json-hash.rkt
#lang typed/racket/base (require typed/json) (: jsx JSExpr) (define jsx #hasheq((a . "val1") (b . "val2") (c . "val3")))
null
https://raw.githubusercontent.com/racket/typed-racket/0236151e3b95d6d39276353cb5005197843e16e4/typed-racket-test/succeed/json-hash.rkt
racket
#lang typed/racket/base (require typed/json) (: jsx JSExpr) (define jsx #hasheq((a . "val1") (b . "val2") (c . "val3")))
d88d753d6a4521f860373bdc10abc1920c4a22261f0b89936a22d9376a815765
awslabs/s2n-bignum
bignum_sqr_4_8.ml
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) (* ========================================================================= *) MULX - based 4x4->8 squaring . (* ========================================================================= *) (**** print_literal_from_elf "x86/fastmul/bignum_sqr_4_8.o";; ****) let bignum_sqr_4_8_mc = define_assert_from_elf "bignum_sqr_4_8_mc" "x86/fastmul/bignum_sqr_4_8.o" [ 0x55; (* PUSH (% rbp) *) 0x41; 0x54; (* PUSH (% r12) *) 0x41; 0x55; (* PUSH (% r13) *) MOV ( % rdx ) ( ( % % ( rsi,0 ) ) ) 0xc4; 0x62; 0xbb; 0xf6; 0x4e; 0x08; MULX4 ( % r9,% r8 ) ( % rdx , ( % % ( rsi,8 ) ) ) 0xc4; 0x62; 0xab; 0xf6; 0x5e; 0x18; MULX4 ( % r11,% r10 ) ( % rdx , ( % % ( rsi,24 ) ) ) MOV ( % rdx ) ( ( % % ( rsi,16 ) ) ) 0xc4; 0x62; 0x9b; 0xf6; 0x6e; 0x18; MULX4 ( % r13,% r12 ) ( % rdx , ( % % ( rsi,24 ) ) ) XOR ( % ebp ) ( % ebp ) 0xc4; 0xe2; 0xfb; 0xf6; 0x0e; MULX4 ( % rcx,% rax ) ( % rdx , ( % % ( rsi,0 ) ) ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xc8; (* ADCX (% r9) (% rax) *) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xd1; ADOX ( % r10 ) ( % rcx ) 0xc4; 0xe2; 0xfb; 0xf6; 0x4e; 0x08; MULX4 ( % rcx,% rax ) ( % rdx , ( % % ( rsi,8 ) ) ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xd0; (* ADCX (% r10) (% rax) *) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xd9; ADOX ( % r11 ) ( % rcx ) MOV ( % rdx ) ( ( % % ( rsi,24 ) ) ) 0xc4; 0xe2; 0xfb; 0xf6; 0x4e; 0x08; MULX4 ( % rcx,% rax ) ( % rdx , ( % % ( rsi,8 ) ) ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xd8; (* ADCX (% r11) (% rax) *) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xe1; ADOX ( % r12 ) ( % rcx ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xe5; (* ADCX (% r12) (% rbp) *) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xed; ADOX ( % r13 ) ( % rbp ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xed; (* ADCX (% r13) (% rbp) *) XOR ( % ebp ) ( % ebp ) MOV ( % rdx ) ( ( % % ( rsi,0 ) ) ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd2; MULX4 ( % rdx,% rax ) ( % rdx,% rdx ) MOV ( ( % % ( rdi,0 ) ) ) ( % rax ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xc0; (* ADCX (% r8) (% r8) *) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xc2; ADOX ( % r8 ) ( % rdx ) MOV ( % rdx ) ( ( % % ( rsi,8 ) ) ) MOV ( ( % % ( rdi,8 ) ) ) ( % r8 ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd2; MULX4 ( % rdx,% rax ) ( % rdx,% rdx ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xc9; (* ADCX (% r9) (% r9) *) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xc8; ADOX ( % r9 ) ( % rax ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xd2; (* ADCX (% r10) (% r10) *) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xd2; ADOX ( % r10 ) ( % rdx ) MOV ( % rdx ) ( ( % % ( rsi,16 ) ) ) MOV ( ( % % ( rdi,16 ) ) ) ( % r9 ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd2; MULX4 ( % rdx,% rax ) ( % rdx,% rdx ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xdb; (* ADCX (% r11) (% r11) *) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xd8; ADOX ( % r11 ) ( % rax ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xe4; (* ADCX (% r12) (% r12) *) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xe2; ADOX ( % r12 ) ( % rdx ) MOV ( % rdx ) ( ( % % ( rsi,24 ) ) ) MOV ( ( % % ( ) ) ) ( % r10 ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd2; MULX4 ( % rdx,% rax ) ( % rdx,% rdx ) MOV ( ( % % ( rdi,32 ) ) ) ( % r11 ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xed; (* ADCX (% r13) (% r13) *) MOV ( ( % % ( rdi,40 ) ) ) ( % r12 ) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xe8; ADOX ( % r13 ) ( % rax ) MOV ( ( % % ( rdi,48 ) ) ) ( % r13 ) 0x66; 0x48; 0x0f; 0x38; 0xf6; 0xd5; ADCX ( % rdx ) ( % rbp ) 0xf3; 0x48; 0x0f; 0x38; 0xf6; 0xd5; ADOX ( % rdx ) ( % rbp ) MOV ( ( % % ( ) ) ) ( % rdx ) 0x41; 0x5d; (* POP (% r13) *) 0x41; 0x5c; (* POP (% r12) *) 0x5d; (* POP (% rbp) *) RET ];; let BIGNUM_SQR_4_8_EXEC = X86_MK_CORE_EXEC_RULE bignum_sqr_4_8_mc;; (* ------------------------------------------------------------------------- *) (* Proof. *) (* ------------------------------------------------------------------------- *) let BIGNUM_SQR_4_8_CORRECT = time prove (`!z x a pc. nonoverlapping (word pc,0x109) (z,8 * 8) /\ (x = z \/ nonoverlapping (x,8 * 4) (z,8 * 8)) ==> ensures x86 (\s. bytes_loaded s (word pc) (BUTLAST bignum_sqr_4_8_mc) /\ read RIP s = word(pc + 0x05) /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = word (pc + 0x103) /\ bignum_from_memory (z,8) s = a EXP 2) (MAYCHANGE [RIP; RAX; RBP; RCX; RDX; R8; R9; R10; R11; R12; R13] ,, MAYCHANGE [memory :> bytes(z,8 * 8)] ,, MAYCHANGE SOME_FLAGS)`, MAP_EVERY X_GEN_TAC [`z:int64`; `x:int64`; `a:num`; `pc:num`] THEN REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN ENSURES_INIT_TAC "s0" THEN BIGNUM_DIGITIZE_TAC "x_" `bignum_from_memory (x,4) s0` THEN X86_ACCSTEPS_TAC BIGNUM_SQR_4_8_EXEC (1--50) (1--50) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN EXPAND_TAC "a" THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_ARITH_TAC);; let BIGNUM_SQR_4_8_SUBROUTINE_CORRECT = time prove (`!z x a pc stackpointer returnaddress. nonoverlapping (word_sub stackpointer (word 24),32) (z,8 * 8) /\ ALL (nonoverlapping (word_sub stackpointer (word 24),24)) [(word pc,0x109); (x,8 * 4)] /\ nonoverlapping (word pc,0x109) (z,8 * 8) /\ (x = z \/ nonoverlapping (x,8 * 4) (z,8 * 8)) ==> ensures x86 (\s. bytes_loaded s (word pc) bignum_sqr_4_8_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,8) s = a EXP 2) (MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,, MAYCHANGE [memory :> bytes(z,8 * 8); memory :> bytes(word_sub stackpointer (word 24),24)] ,, MAYCHANGE SOME_FLAGS)`, X86_PROMOTE_RETURN_STACK_TAC bignum_sqr_4_8_mc BIGNUM_SQR_4_8_CORRECT `[RBP; R12; R13]` 24);; (* ------------------------------------------------------------------------- *) (* Correctness of Windows ABI version. *) (* ------------------------------------------------------------------------- *) let windows_bignum_sqr_4_8_mc = define_from_elf "windows_bignum_sqr_4_8_mc" "x86/fastmul/bignum_sqr_4_8.obj";; let WINDOWS_BIGNUM_SQR_4_8_SUBROUTINE_CORRECT = time prove (`!z x a pc stackpointer returnaddress. nonoverlapping (word_sub stackpointer (word 40),48) (z,8 * 8) /\ ALL (nonoverlapping (word_sub stackpointer (word 40),40)) [(word pc,0x113); (x,8 * 4)] /\ nonoverlapping (word pc,0x113) (z,8 * 8) /\ (x = z \/ nonoverlapping (x,8 * 4) (z,8 * 8)) ==> ensures x86 (\s. bytes_loaded s (word pc) windows_bignum_sqr_4_8_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ WINDOWS_C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,8) s = a EXP 2) (MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,, MAYCHANGE [memory :> bytes(z,8 * 8); memory :> bytes(word_sub stackpointer (word 40),40)] ,, MAYCHANGE SOME_FLAGS)`, WINDOWS_X86_WRAP_STACK_TAC windows_bignum_sqr_4_8_mc bignum_sqr_4_8_mc BIGNUM_SQR_4_8_CORRECT `[RBP; R12; R13]` 24);;
null
https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/x86/proofs/bignum_sqr_4_8.ml
ocaml
========================================================================= ========================================================================= *** print_literal_from_elf "x86/fastmul/bignum_sqr_4_8.o";; *** PUSH (% rbp) PUSH (% r12) PUSH (% r13) ADCX (% r9) (% rax) ADCX (% r10) (% rax) ADCX (% r11) (% rax) ADCX (% r12) (% rbp) ADCX (% r13) (% rbp) ADCX (% r8) (% r8) ADCX (% r9) (% r9) ADCX (% r10) (% r10) ADCX (% r11) (% r11) ADCX (% r12) (% r12) ADCX (% r13) (% r13) POP (% r13) POP (% r12) POP (% rbp) ------------------------------------------------------------------------- Proof. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Correctness of Windows ABI version. -------------------------------------------------------------------------
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) MULX - based 4x4->8 squaring . let bignum_sqr_4_8_mc = define_assert_from_elf "bignum_sqr_4_8_mc" "x86/fastmul/bignum_sqr_4_8.o" [ MOV ( % rdx ) ( ( % % ( rsi,0 ) ) ) 0xc4; 0x62; 0xbb; 0xf6; 0x4e; 0x08; MULX4 ( % r9,% r8 ) ( % rdx , ( % % ( rsi,8 ) ) ) 0xc4; 0x62; 0xab; 0xf6; 0x5e; 0x18; MULX4 ( % r11,% r10 ) ( % rdx , ( % % ( rsi,24 ) ) ) MOV ( % rdx ) ( ( % % ( rsi,16 ) ) ) 0xc4; 0x62; 0x9b; 0xf6; 0x6e; 0x18; MULX4 ( % r13,% r12 ) ( % rdx , ( % % ( rsi,24 ) ) ) XOR ( % ebp ) ( % ebp ) 0xc4; 0xe2; 0xfb; 0xf6; 0x0e; MULX4 ( % rcx,% rax ) ( % rdx , ( % % ( rsi,0 ) ) ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xc8; 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xd1; ADOX ( % r10 ) ( % rcx ) 0xc4; 0xe2; 0xfb; 0xf6; 0x4e; 0x08; MULX4 ( % rcx,% rax ) ( % rdx , ( % % ( rsi,8 ) ) ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xd0; 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xd9; ADOX ( % r11 ) ( % rcx ) MOV ( % rdx ) ( ( % % ( rsi,24 ) ) ) 0xc4; 0xe2; 0xfb; 0xf6; 0x4e; 0x08; MULX4 ( % rcx,% rax ) ( % rdx , ( % % ( rsi,8 ) ) ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xd8; 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xe1; ADOX ( % r12 ) ( % rcx ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xe5; 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xed; ADOX ( % r13 ) ( % rbp ) 0x66; 0x4c; 0x0f; 0x38; 0xf6; 0xed; XOR ( % ebp ) ( % ebp ) MOV ( % rdx ) ( ( % % ( rsi,0 ) ) ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd2; MULX4 ( % rdx,% rax ) ( % rdx,% rdx ) MOV ( ( % % ( rdi,0 ) ) ) ( % rax ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xc0; 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xc2; ADOX ( % r8 ) ( % rdx ) MOV ( % rdx ) ( ( % % ( rsi,8 ) ) ) MOV ( ( % % ( rdi,8 ) ) ) ( % r8 ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd2; MULX4 ( % rdx,% rax ) ( % rdx,% rdx ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xc9; 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xc8; ADOX ( % r9 ) ( % rax ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xd2; 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xd2; ADOX ( % r10 ) ( % rdx ) MOV ( % rdx ) ( ( % % ( rsi,16 ) ) ) MOV ( ( % % ( rdi,16 ) ) ) ( % r9 ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd2; MULX4 ( % rdx,% rax ) ( % rdx,% rdx ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xdb; 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xd8; ADOX ( % r11 ) ( % rax ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xe4; 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xe2; ADOX ( % r12 ) ( % rdx ) MOV ( % rdx ) ( ( % % ( rsi,24 ) ) ) MOV ( ( % % ( ) ) ) ( % r10 ) 0xc4; 0xe2; 0xfb; 0xf6; 0xd2; MULX4 ( % rdx,% rax ) ( % rdx,% rdx ) MOV ( ( % % ( rdi,32 ) ) ) ( % r11 ) 0x66; 0x4d; 0x0f; 0x38; 0xf6; 0xed; MOV ( ( % % ( rdi,40 ) ) ) ( % r12 ) 0xf3; 0x4c; 0x0f; 0x38; 0xf6; 0xe8; ADOX ( % r13 ) ( % rax ) MOV ( ( % % ( rdi,48 ) ) ) ( % r13 ) 0x66; 0x48; 0x0f; 0x38; 0xf6; 0xd5; ADCX ( % rdx ) ( % rbp ) 0xf3; 0x48; 0x0f; 0x38; 0xf6; 0xd5; ADOX ( % rdx ) ( % rbp ) MOV ( ( % % ( ) ) ) ( % rdx ) RET ];; let BIGNUM_SQR_4_8_EXEC = X86_MK_CORE_EXEC_RULE bignum_sqr_4_8_mc;; let BIGNUM_SQR_4_8_CORRECT = time prove (`!z x a pc. nonoverlapping (word pc,0x109) (z,8 * 8) /\ (x = z \/ nonoverlapping (x,8 * 4) (z,8 * 8)) ==> ensures x86 (\s. bytes_loaded s (word pc) (BUTLAST bignum_sqr_4_8_mc) /\ read RIP s = word(pc + 0x05) /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = word (pc + 0x103) /\ bignum_from_memory (z,8) s = a EXP 2) (MAYCHANGE [RIP; RAX; RBP; RCX; RDX; R8; R9; R10; R11; R12; R13] ,, MAYCHANGE [memory :> bytes(z,8 * 8)] ,, MAYCHANGE SOME_FLAGS)`, MAP_EVERY X_GEN_TAC [`z:int64`; `x:int64`; `a:num`; `pc:num`] THEN REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN ENSURES_INIT_TAC "s0" THEN BIGNUM_DIGITIZE_TAC "x_" `bignum_from_memory (x,4) s0` THEN X86_ACCSTEPS_TAC BIGNUM_SQR_4_8_EXEC (1--50) (1--50) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN EXPAND_TAC "a" THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_ARITH_TAC);; let BIGNUM_SQR_4_8_SUBROUTINE_CORRECT = time prove (`!z x a pc stackpointer returnaddress. nonoverlapping (word_sub stackpointer (word 24),32) (z,8 * 8) /\ ALL (nonoverlapping (word_sub stackpointer (word 24),24)) [(word pc,0x109); (x,8 * 4)] /\ nonoverlapping (word pc,0x109) (z,8 * 8) /\ (x = z \/ nonoverlapping (x,8 * 4) (z,8 * 8)) ==> ensures x86 (\s. bytes_loaded s (word pc) bignum_sqr_4_8_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,8) s = a EXP 2) (MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,, MAYCHANGE [memory :> bytes(z,8 * 8); memory :> bytes(word_sub stackpointer (word 24),24)] ,, MAYCHANGE SOME_FLAGS)`, X86_PROMOTE_RETURN_STACK_TAC bignum_sqr_4_8_mc BIGNUM_SQR_4_8_CORRECT `[RBP; R12; R13]` 24);; let windows_bignum_sqr_4_8_mc = define_from_elf "windows_bignum_sqr_4_8_mc" "x86/fastmul/bignum_sqr_4_8.obj";; let WINDOWS_BIGNUM_SQR_4_8_SUBROUTINE_CORRECT = time prove (`!z x a pc stackpointer returnaddress. nonoverlapping (word_sub stackpointer (word 40),48) (z,8 * 8) /\ ALL (nonoverlapping (word_sub stackpointer (word 40),40)) [(word pc,0x113); (x,8 * 4)] /\ nonoverlapping (word pc,0x113) (z,8 * 8) /\ (x = z \/ nonoverlapping (x,8 * 4) (z,8 * 8)) ==> ensures x86 (\s. bytes_loaded s (word pc) windows_bignum_sqr_4_8_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ WINDOWS_C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,8) s = a EXP 2) (MAYCHANGE [RIP; RSP; RAX; RCX; RDX; R8; R9; R10; R11] ,, MAYCHANGE [memory :> bytes(z,8 * 8); memory :> bytes(word_sub stackpointer (word 40),40)] ,, MAYCHANGE SOME_FLAGS)`, WINDOWS_X86_WRAP_STACK_TAC windows_bignum_sqr_4_8_mc bignum_sqr_4_8_mc BIGNUM_SQR_4_8_CORRECT `[RBP; R12; R13]` 24);;
cced512b4de08820ce9ecd1ce0b970d82b5e4a147dfa1b47eb669aff6cba683e
McCLIM/McCLIM
creating-assoc.lisp
(in-package #:creating-assoc) (defmacro creating-assoc (item alist &environment env) "assoc that creates the requested alist item on-the-fly if not yet existing" (multiple-value-bind (dummies vals new setter getter) (get-setf-expansion alist env) (let ((object (gensym "object-"))) `(let* ((,object ,item) ,@(mapcar #'list dummies vals) (,(car new) ,getter)) (prog1 (or (assoc ,object ,(car new)) (first (setq ,(car new) (cons (list ,object) ,(car new))))) ,setter))))) ;;; Example: ;;; ( let * ( ( list ' ( ( foo 1 ) ) ) ) ;;; (list (assoc 'foo list) ;;; (assoc 'baz list) ;;; (creating-assoc 'baz list) ;;; (assoc 'baz list) ;;; list)) = > ( ( FOO 1 ) ;;; NIL ( BAZ ) ( BAZ ) ( ( BAZ ) ( FOO 1 ) ) ) ;;; ;;; (creating-assoc 'baz list) ;;; ;;; expands to: ;;; ( LET * ( ( # : |object-15058| ' BAZ ) ( # : G15057 LIST ) ) ( PROG1 ;;; (OR (ASSOC #:|object-15058| #:G15057) ;;; (FIRST (SETQ #:G15057 (CONS (LIST #:|object-15058|) #:G15057)))) ;;; (SETQ LIST #:G15057))) ;;; Have a look at #2 if you want to.
null
https://raw.githubusercontent.com/McCLIM/McCLIM/c079691b0913f8306ceff2620b045b6e24e2f745/Extensions/conditional-commands/creating-assoc.lisp
lisp
Example: (list (assoc 'foo list) (assoc 'baz list) (creating-assoc 'baz list) (assoc 'baz list) list)) NIL (creating-assoc 'baz list) expands to: (OR (ASSOC #:|object-15058| #:G15057) (FIRST (SETQ #:G15057 (CONS (LIST #:|object-15058|) #:G15057)))) (SETQ LIST #:G15057))) Have a look at #2 if you want to.
(in-package #:creating-assoc) (defmacro creating-assoc (item alist &environment env) "assoc that creates the requested alist item on-the-fly if not yet existing" (multiple-value-bind (dummies vals new setter getter) (get-setf-expansion alist env) (let ((object (gensym "object-"))) `(let* ((,object ,item) ,@(mapcar #'list dummies vals) (,(car new) ,getter)) (prog1 (or (assoc ,object ,(car new)) (first (setq ,(car new) (cons (list ,object) ,(car new))))) ,setter))))) ( let * ( ( list ' ( ( foo 1 ) ) ) ) = > ( ( FOO 1 ) ( BAZ ) ( BAZ ) ( ( BAZ ) ( FOO 1 ) ) ) ( LET * ( ( # : |object-15058| ' BAZ ) ( # : G15057 LIST ) ) ( PROG1
9079a3b41d2a413312500554273a521839834adbb399c9b3089e5e1fea0058a3
manuel-serrano/bigloo
gstobject.scm
;*=====================================================================*/ ;* .../prgm/project/bigloo/api/gstreamer/src/Llib/gstobject.scm */ ;* ------------------------------------------------------------- */ * Author : * / * Creation : Sun Dec 30 16:06:35 2007 * / * Last change : Sun Nov 18 15:02:12 2012 ( serrano ) * / * Copyright : 2007 - 12 * / ;* ------------------------------------------------------------- */ * GstObject wrapper * / ;*=====================================================================*/ ;*---------------------------------------------------------------------*/ ;* The module */ ;*---------------------------------------------------------------------*/ (module __gstreamer_gstobject (library pthread) (include "gst.sch") (import __gstreamer_gsterror) (export (abstract-class gst-object (%gst-object-init) ($builtin::$gst-object (default (%$gst-object-nil))) ($finalizer::obj read-only (default #f)) (%closures::pair-nil (default '()))) (inline gst-object?::bool ::obj) (%$gst-object-nil::$gst-object) (generic %gst-object-init ::gst-object) (%gst-object->gobject::$gst-object ::gst-object) (%gst-object-ref! ::gst-object) (%gst-object-unref! ::gst-object) (%gst-object-init-debug ::obj) (%gst-object-finalize-debug ::obj) (%gst-object-finalize-closures! ::gst-object) (%gst-object-finalize! ::gst-object) (gst-object-property-list::pair-nil ::gst-object) (gst-object-property ::gst-object ::keyword) (gst-object-property-set! ::gst-object ::keyword ::obj) (gst-object-connect! ::gst-object ::bstring ::procedure) (closure-gcmark! ::procedure) (closure-gcunmark! ::procedure)) (extern (export gst-object? "bgl_gst_objectp") (export %gst-object->gobject "bgl_gst_object_to_gstobject") (export closure-gcmark! "bgl_closure_gcmark") (export closure-gcunmark! "bgl_closure_gcunmark"))) ;*---------------------------------------------------------------------*/ ;* gst-object? ... */ ;*---------------------------------------------------------------------*/ (define-inline (gst-object?::bool o) (isa? o gst-object)) ;*---------------------------------------------------------------------*/ ;* %$gst-object-nil ... */ ;*---------------------------------------------------------------------*/ (define (%$gst-object-nil::$gst-object) ($gst-object-nil)) ;*---------------------------------------------------------------------*/ ;* %gst-object->gobject ... */ ;*---------------------------------------------------------------------*/ (define (%gst-object->gobject o::gst-object) (with-access::gst-object o ($builtin) $builtin)) ;*---------------------------------------------------------------------*/ ;* *gst-object-debug-mutex* ... */ ;*---------------------------------------------------------------------*/ (define *gst-object-debug-mutex* (make-mutex)) (define *gst-object-debug-count* 0) ;*---------------------------------------------------------------------*/ ;* %gst-object-init-debug ... */ ;*---------------------------------------------------------------------*/ (define (%gst-object-init-debug o) (synchronize *gst-object-debug-mutex* (set! *gst-object-debug-count* (+fx 1 *gst-object-debug-count*)) (display "gst-object-init (" (current-error-port)) (display *gst-object-debug-count* (current-error-port)) (display "): " (current-error-port))) (display (find-runtime-type o) (current-error-port)) (pragma "fprintf( stderr, \" o=%p builtin=%p refcount=%d\", $1, ((BgL_gstzd2objectzd2_bglt)$1)->BgL_z42builtinz42, ((GObject *)(((BgL_gstzd2objectzd2_bglt)$1)->BgL_z42builtinz42))->ref_count )" o) (newline (current-error-port))) ;*---------------------------------------------------------------------*/ ;* %gst-object-finalize-debug ... */ ;*---------------------------------------------------------------------*/ (define (%gst-object-finalize-debug o) (when (> (bigloo-debug) (gst-debug-level)) (synchronize *gst-object-debug-mutex* (set! *gst-object-debug-count* (+fx -1 *gst-object-debug-count*)) (display "gst-object-unref! (" (current-error-port)) (display *gst-object-debug-count* (current-error-port)) (display "): " (current-error-port))) (display (find-runtime-type o) (current-error-port)) (pragma "fprintf( stderr, \" o=%p builtin=%p refcount=%d -> %d\", $1, ((BgL_gstzd2objectzd2_bglt)$1)->BgL_z42builtinz42, ((GObject *)((BgL_gstzd2objectzd2_bglt)$1)->BgL_z42builtinz42)->ref_count, ((GObject *)((BgL_gstzd2objectzd2_bglt)$1)->BgL_z42builtinz42)->ref_count -1 ), puts( \"\" )" o) #unspecified)) ;*---------------------------------------------------------------------*/ ;* %gst-object-init ::gst-object ... */ ;*---------------------------------------------------------------------*/ (define-generic (%gst-object-init o::gst-object) (with-access::gst-object o ($builtin $finalizer) (when ($gst-object-null? $builtin) (raise (instantiate::&gst-create-error (proc '%gst-object-init) (msg "Illegal gst-object") (obj o)))) (when (> (bigloo-debug) (gst-debug-level)) (%gst-object-init-debug o)) (cond ((procedure? $finalizer) ;; user finalizer ($gst-add-finalizer! o $finalizer)) ($finalizer ;; regular unref finalizer ($gst-add-finalizer! o %gst-object-finalize!))) o)) ;*---------------------------------------------------------------------*/ ;* object-display ... */ ;*---------------------------------------------------------------------*/ (define-method (object-display o::gst-object . port) (let ((p (if (pair? port) (car port) (current-output-port)))) (display "<" p) (display (find-runtime-type o) p) (display " refcount=" p) (with-access::gst-object o ($builtin) (display ($gst-object-refcount $builtin) p)) (display ">" p))) ;*---------------------------------------------------------------------*/ ;* %gst-object-unref! ... */ ;*---------------------------------------------------------------------*/ (define (%gst-object-unref! o) (with-access::gst-object o ($builtin) ($gst-object-unref! $builtin))) ;*---------------------------------------------------------------------*/ ;* %gst-object-ref! ... */ ;*---------------------------------------------------------------------*/ (define (%gst-object-ref! o) (with-access::gst-object o ($builtin) ($gst-object-ref! $builtin))) ;*---------------------------------------------------------------------*/ ;* %gst-object-finalize-closures! ... */ ;*---------------------------------------------------------------------*/ (define (%gst-object-finalize-closures! o) (with-access::gst-object o (%closures) (for-each closure-gcunmark! %closures))) ;*---------------------------------------------------------------------*/ ;* %gst-object-finalize! ... */ ;*---------------------------------------------------------------------*/ (define (%gst-object-finalize! o) (when (> (bigloo-debug) (gst-debug-level)) (%gst-object-finalize-debug o)) (%gst-object-finalize-closures! o) (%gst-object-unref! o)) ;*---------------------------------------------------------------------*/ ;* gst-object-property-list ... */ ;*---------------------------------------------------------------------*/ (define (gst-object-property-list o::gst-object) (with-access::gst-object o ($builtin) ($gst-object-property-list $builtin))) ;*---------------------------------------------------------------------*/ ;* gst-object-property ... */ ;*---------------------------------------------------------------------*/ (define (gst-object-property o::gst-object prop) (with-access::gst-object o ($builtin) ($gst-object-get-property $builtin (keyword->string! prop)))) ;*---------------------------------------------------------------------*/ ;* gst-object-property-set! ... */ ;*---------------------------------------------------------------------*/ (define (gst-object-property-set! o::gst-object prop val) (with-access::gst-object o ($builtin) ($gst-object-set-property! $builtin (keyword->string! prop) val))) ;*---------------------------------------------------------------------*/ ;* gst-object-connect! ... */ ;*---------------------------------------------------------------------*/ (define (gst-object-connect! el name proc) (with-access::gst-object el (%closures $builtin) (set! %closures (cons proc %closures)) (closure-gcmark! proc) ($gst-object-connect! $builtin name proc))) ;*---------------------------------------------------------------------*/ ;* *gcmark-mutex* ... */ ;*---------------------------------------------------------------------*/ (define *gcmark-mutex* (make-mutex)) ;*---------------------------------------------------------------------*/ ;* *gcmark-closure* ... */ ;*---------------------------------------------------------------------*/ (define *gcmark-closure* '()) ;*---------------------------------------------------------------------*/ ;* closure-gcmark! ... */ ;*---------------------------------------------------------------------*/ (define (closure-gcmark! proc) (synchronize *gcmark-mutex* (set! *gcmark-closure* (cons proc *gcmark-closure*)) (when (> (bigloo-debug) (gst-debug-level)) (synchronize *gst-object-debug-mutex* (tprint "closure-gcmark: " (length *gcmark-closure*)))))) ;*---------------------------------------------------------------------*/ ;* closure-gcunmark! ... */ ;*---------------------------------------------------------------------*/ (define (closure-gcunmark! proc) (synchronize *gcmark-mutex* (set! *gcmark-closure* (remq! proc *gcmark-closure*)) (when (> (bigloo-debug) (gst-debug-level)) (synchronize *gst-object-debug-mutex* (tprint "closure-gcunmark: " (length *gcmark-closure*))))))
null
https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/api/gstreamer/src/Llib/gstobject.scm
scheme
*=====================================================================*/ * .../prgm/project/bigloo/api/gstreamer/src/Llib/gstobject.scm */ * ------------------------------------------------------------- */ * ------------------------------------------------------------- */ *=====================================================================*/ *---------------------------------------------------------------------*/ * The module */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * gst-object? ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * %$gst-object-nil ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * %gst-object->gobject ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * *gst-object-debug-mutex* ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * %gst-object-init-debug ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * %gst-object-finalize-debug ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * %gst-object-init ::gst-object ... */ *---------------------------------------------------------------------*/ user finalizer regular unref finalizer *---------------------------------------------------------------------*/ * object-display ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * %gst-object-unref! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * %gst-object-ref! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * %gst-object-finalize-closures! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * %gst-object-finalize! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * gst-object-property-list ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * gst-object-property ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * gst-object-property-set! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * gst-object-connect! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * *gcmark-mutex* ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * *gcmark-closure* ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * closure-gcmark! ... */ *---------------------------------------------------------------------*/ *---------------------------------------------------------------------*/ * closure-gcunmark! ... */ *---------------------------------------------------------------------*/
* Author : * / * Creation : Sun Dec 30 16:06:35 2007 * / * Last change : Sun Nov 18 15:02:12 2012 ( serrano ) * / * Copyright : 2007 - 12 * / * GstObject wrapper * / (module __gstreamer_gstobject (library pthread) (include "gst.sch") (import __gstreamer_gsterror) (export (abstract-class gst-object (%gst-object-init) ($builtin::$gst-object (default (%$gst-object-nil))) ($finalizer::obj read-only (default #f)) (%closures::pair-nil (default '()))) (inline gst-object?::bool ::obj) (%$gst-object-nil::$gst-object) (generic %gst-object-init ::gst-object) (%gst-object->gobject::$gst-object ::gst-object) (%gst-object-ref! ::gst-object) (%gst-object-unref! ::gst-object) (%gst-object-init-debug ::obj) (%gst-object-finalize-debug ::obj) (%gst-object-finalize-closures! ::gst-object) (%gst-object-finalize! ::gst-object) (gst-object-property-list::pair-nil ::gst-object) (gst-object-property ::gst-object ::keyword) (gst-object-property-set! ::gst-object ::keyword ::obj) (gst-object-connect! ::gst-object ::bstring ::procedure) (closure-gcmark! ::procedure) (closure-gcunmark! ::procedure)) (extern (export gst-object? "bgl_gst_objectp") (export %gst-object->gobject "bgl_gst_object_to_gstobject") (export closure-gcmark! "bgl_closure_gcmark") (export closure-gcunmark! "bgl_closure_gcunmark"))) (define-inline (gst-object?::bool o) (isa? o gst-object)) (define (%$gst-object-nil::$gst-object) ($gst-object-nil)) (define (%gst-object->gobject o::gst-object) (with-access::gst-object o ($builtin) $builtin)) (define *gst-object-debug-mutex* (make-mutex)) (define *gst-object-debug-count* 0) (define (%gst-object-init-debug o) (synchronize *gst-object-debug-mutex* (set! *gst-object-debug-count* (+fx 1 *gst-object-debug-count*)) (display "gst-object-init (" (current-error-port)) (display *gst-object-debug-count* (current-error-port)) (display "): " (current-error-port))) (display (find-runtime-type o) (current-error-port)) (pragma "fprintf( stderr, \" o=%p builtin=%p refcount=%d\", $1, ((BgL_gstzd2objectzd2_bglt)$1)->BgL_z42builtinz42, ((GObject *)(((BgL_gstzd2objectzd2_bglt)$1)->BgL_z42builtinz42))->ref_count )" o) (newline (current-error-port))) (define (%gst-object-finalize-debug o) (when (> (bigloo-debug) (gst-debug-level)) (synchronize *gst-object-debug-mutex* (set! *gst-object-debug-count* (+fx -1 *gst-object-debug-count*)) (display "gst-object-unref! (" (current-error-port)) (display *gst-object-debug-count* (current-error-port)) (display "): " (current-error-port))) (display (find-runtime-type o) (current-error-port)) (pragma "fprintf( stderr, \" o=%p builtin=%p refcount=%d -> %d\", $1, ((BgL_gstzd2objectzd2_bglt)$1)->BgL_z42builtinz42, ((GObject *)((BgL_gstzd2objectzd2_bglt)$1)->BgL_z42builtinz42)->ref_count, ((GObject *)((BgL_gstzd2objectzd2_bglt)$1)->BgL_z42builtinz42)->ref_count -1 ), puts( \"\" )" o) #unspecified)) (define-generic (%gst-object-init o::gst-object) (with-access::gst-object o ($builtin $finalizer) (when ($gst-object-null? $builtin) (raise (instantiate::&gst-create-error (proc '%gst-object-init) (msg "Illegal gst-object") (obj o)))) (when (> (bigloo-debug) (gst-debug-level)) (%gst-object-init-debug o)) (cond ((procedure? $finalizer) ($gst-add-finalizer! o $finalizer)) ($finalizer ($gst-add-finalizer! o %gst-object-finalize!))) o)) (define-method (object-display o::gst-object . port) (let ((p (if (pair? port) (car port) (current-output-port)))) (display "<" p) (display (find-runtime-type o) p) (display " refcount=" p) (with-access::gst-object o ($builtin) (display ($gst-object-refcount $builtin) p)) (display ">" p))) (define (%gst-object-unref! o) (with-access::gst-object o ($builtin) ($gst-object-unref! $builtin))) (define (%gst-object-ref! o) (with-access::gst-object o ($builtin) ($gst-object-ref! $builtin))) (define (%gst-object-finalize-closures! o) (with-access::gst-object o (%closures) (for-each closure-gcunmark! %closures))) (define (%gst-object-finalize! o) (when (> (bigloo-debug) (gst-debug-level)) (%gst-object-finalize-debug o)) (%gst-object-finalize-closures! o) (%gst-object-unref! o)) (define (gst-object-property-list o::gst-object) (with-access::gst-object o ($builtin) ($gst-object-property-list $builtin))) (define (gst-object-property o::gst-object prop) (with-access::gst-object o ($builtin) ($gst-object-get-property $builtin (keyword->string! prop)))) (define (gst-object-property-set! o::gst-object prop val) (with-access::gst-object o ($builtin) ($gst-object-set-property! $builtin (keyword->string! prop) val))) (define (gst-object-connect! el name proc) (with-access::gst-object el (%closures $builtin) (set! %closures (cons proc %closures)) (closure-gcmark! proc) ($gst-object-connect! $builtin name proc))) (define *gcmark-mutex* (make-mutex)) (define *gcmark-closure* '()) (define (closure-gcmark! proc) (synchronize *gcmark-mutex* (set! *gcmark-closure* (cons proc *gcmark-closure*)) (when (> (bigloo-debug) (gst-debug-level)) (synchronize *gst-object-debug-mutex* (tprint "closure-gcmark: " (length *gcmark-closure*)))))) (define (closure-gcunmark! proc) (synchronize *gcmark-mutex* (set! *gcmark-closure* (remq! proc *gcmark-closure*)) (when (> (bigloo-debug) (gst-debug-level)) (synchronize *gst-object-debug-mutex* (tprint "closure-gcunmark: " (length *gcmark-closure*))))))
ba36836a2ee3ebd6f4b39d082471f7c071bdeb24995c59546f7e23b9b271f2d5
FlowForwarding/lincx
linc_max_table_features.erl
%%------------------------------------------------------------------------------ Copyright 2012 FlowForwarding.org %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%----------------------------------------------------------------------------- @author Erlang Solutions Ltd. < > @author Cloudozer LLP < > 2012 FlowForwarding.org %% @doc Userspace implementation of the OpenFlow Switch logic. -module(linc_max_table_features). -export([handle_req/2]). -include_lib("of_protocol/include/ofp_v4.hrl"). -include_lib("linc_max/include/linc_max.hrl"). -define(REQUIRED_PROPERTIES, [instructions, next_tables, write_actions, apply_actions, match, wildcards, write_setfield, apply_setfield]). -define(OPTIONAL_PROPERTIES, [instructions_miss, next_tables_miss, write_actions_miss, apply_actions_miss, write_setfield_miss, apply_setfield_miss]). handle_req(_SwitchId, #ofp_table_features_request{body=[]}) -> %% Read request #ofp_table_features_reply{body = get_all_features()}; handle_req(SwitchId, #ofp_table_features_request{body=[_TF|_]=TableFeaturesList}) -> SetRequest case validate_config(TableFeaturesList) of ok -> %% When a table is "deleted" by not being present in the %% list of tables in the request, we should remove all %% flow entries. DeletedTables = lists:seq(0, ?OFPTT_MAX) -- [TableId || #ofp_table_features{table_id = TableId} <- TableFeaturesList], [linc_max_flow:clear_table_flows(SwitchId, TableId) || TableId <- DeletedTables], %% Currently we have no concept of deleted tables, though, %% so we report them all as existing. #ofp_table_features_reply{body = get_all_features()}; {error,Reason} -> #ofp_error_msg{type=table_features_failed, code=Reason} end. get_all_features() -> [get_table_features(TableId) || TableId <- lists:seq(0, ?OFPTT_MAX)]. get_table_features(TableId) -> #ofp_table_features{ table_id = TableId, name = list_to_binary(io_lib:format("Flow Table 0x~2.16.0b", [TableId])), metadata_match = ?SUPPORTED_METADATA_MATCH, metadata_write = ?SUPPORTED_METADATA_WRITE, max_entries = ?MAX_FLOW_TABLE_ENTRIES, The # ofp_table_feature_prop_*_miss properties do not need to be %% included if they are equal to the #ofp_table_feature_prop_* property properties = [#ofp_table_feature_prop_instructions{ instruction_ids = ?SUPPORTED_INSTRUCTIONS} , #ofp_table_feature_prop_next_tables{ next_table_ids = lists:seq(TableId+1,?OFPTT_MAX)} , #ofp_table_feature_prop_write_actions{ action_ids = ?SUPPORTED_ACTIONS} , #ofp_table_feature_prop_apply_actions{ action_ids = ?SUPPORTED_ACTIONS} , #ofp_table_feature_prop_match{ oxm_ids = ?SUPPORTED_MATCH_FIELDS} , #ofp_table_feature_prop_wildcards{ oxm_ids = ?SUPPORTED_WILDCARDS} , #ofp_table_feature_prop_write_setfield{ oxm_ids = ?SUPPORTED_WRITE_SETFIELDS} , #ofp_table_feature_prop_apply_setfield{ oxm_ids = ?SUPPORTED_WRITE_SETFIELDS} ]}. validate_config(TableFeaturesList) -> validate_configs(TableFeaturesList, []). validate_configs([#ofp_table_features{table_id = TableId, properties = Properties}|TableFeaturesList], TableIds) when TableId =< ?OFPTT_MAX -> case lists:member(TableId,TableIds) of true -> {error, bad_table}; false -> case validate_feature_properties(TableId, Properties) of ok -> validate_configs(TableFeaturesList, [TableId|TableIds]); Error -> Error end end; validate_configs([#ofp_table_features{table_id = all}|_TableFeaturesList], _TableIds) -> {error, bad_table}; validate_configs([], _TableIds) -> ok. There are three classes of features %% - mandatory, must appear just once - optional , may appear 0 or 1 time %% - experimenters, it is probably up to the experimenter to define the rules. %% Currently we do not support any experimenters features so we do not care. validate_feature_properties(TableId, Properties) -> case validate_feature_properties(TableId, Properties, [], []) of {ok, {MandatoryFound, _Optional}} -> case all_mandatory_present(MandatoryFound, ?REQUIRED_PROPERTIES) of true -> ok; false -> {error, bad_argument} end; Error -> Error end. %% In version 1.3.1 of the OpenFlow specification, there is no error code defined %% for duplicate feature properties, so we use bad_argument instead. validate_feature_properties(TableId, [#ofp_table_feature_prop_instructions{ instruction_ids = Instructions } | Properties], Mandatory, Optional) -> case lists:member(instructions, Mandatory) of true -> {error,bad_argument}; false -> case lists:all(fun (I) -> lists:member(I, ?SUPPORTED_INSTRUCTIONS) end, Instructions) of true-> validate_feature_properties(TableId, Properties, [instructions|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_instructions_miss{ instruction_ids = Instructions } | Properties], Mandatory, Optional) -> case lists:member(instructions_miss, Optional) of true -> {error,bad_argument}; false -> case all_supported(Instructions, ?SUPPORTED_INSTRUCTIONS) of true-> validate_feature_properties(TableId, Properties, Mandatory, [instructions_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_next_tables{ next_table_ids = TableIds } | Properties], Mandatory, Optional) -> case lists:member(next_tables, Mandatory) of true -> {error,bad_argument}; false -> case lists:all(fun (Id) -> Id > TableId end, TableIds) of true-> validate_feature_properties(TableId, Properties, [next_tables|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_next_tables_miss{ next_table_ids = TableIds } | Properties], Mandatory, Optional) -> case lists:member(next_tables_miss, Optional) of true -> {error,bad_argument}; false -> case lists:all(fun (Id) -> Id > TableId end, TableIds) of true-> validate_feature_properties(TableId, Properties, Mandatory, [next_tables_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_write_actions{ action_ids = ActionIds } | Properties], Mandatory, Optional) -> case lists:member(write_actions, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(ActionIds, ?SUPPORTED_WRITE_ACTIONS) of true-> validate_feature_properties(TableId, Properties, [write_actions|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_write_actions_miss{ action_ids = ActionIds } | Properties], Mandatory, Optional) -> case lists:member(write_actions_miss, Optional) of true -> {error,bad_argument}; false -> case all_supported(ActionIds, ?SUPPORTED_WRITE_ACTIONS) of true-> validate_feature_properties(TableId, Properties, Mandatory, [write_actions_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_apply_actions{ action_ids = ActionIds } | Properties], Mandatory, Optional) -> case lists:member(apply_actions, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(ActionIds, ?SUPPORTED_APPLY_ACTIONS) of true-> validate_feature_properties(TableId, Properties, [apply_actions|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_apply_actions_miss{ action_ids = ActionIds } | Properties], Mandatory, Optional) -> case lists:member(apply_actions_miss, Optional) of true -> {error,bad_argument}; false -> case all_supported(ActionIds, ?SUPPORTED_APPLY_ACTIONS) of true-> validate_feature_properties(TableId, Properties, Mandatory, [apply_actions_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_match{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(match, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_MATCH_FIELDS) of true-> validate_feature_properties(TableId, Properties, [match|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_wildcards{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(wildcards, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_WILDCARDS) of true-> validate_feature_properties(TableId, Properties, [wildcards|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_write_setfield{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(write_setfield, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_WRITE_SETFIELDS) of true-> validate_feature_properties(TableId, Properties, [write_setfield|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_write_setfield_miss{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(write_setfield_miss, Optional) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_WRITE_SETFIELDS) of true-> validate_feature_properties(TableId, Properties, Mandatory, [write_setfield_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_apply_setfield{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(apply_setfield, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_APPLY_SETFIELDS) of true-> validate_feature_properties(TableId, Properties, [apply_setfield|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_apply_setfield_miss{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(apply_setfield_miss, Optional) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_APPLY_SETFIELDS) of true-> validate_feature_properties(TableId, Properties, Mandatory, [apply_setfield_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(_TableId, [#ofp_table_feature_prop_experimenter{} | _Properties], _Mandatory, _Optional) -> %% No experimeters properties are currently supported {error,bad_type}; validate_feature_properties(_TableId, [#ofp_table_feature_prop_experimenter_miss{} | _Properties], _Mandatory, _Optional) -> %% No experimeters properties are currently supported {error,bad_type}; validate_feature_properties(_TableId, [], Mandatory, Optional) -> {ok, {Mandatory, Optional}}. all_supported(Items, SupportedItems) -> lists:all(fun (I) -> lists:member(I, SupportedItems) end, Items). all_mandatory_present(Found, Required) -> lists:sort(Found) == lists:sort(Required).
null
https://raw.githubusercontent.com/FlowForwarding/lincx/7795923b51fa1e680511669f4a27404b2ed1f1dc/apps/linc_max/src/linc_max_table_features.erl
erlang
------------------------------------------------------------------------------ you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------------------------------- @doc Userspace implementation of the OpenFlow Switch logic. Read request When a table is "deleted" by not being present in the list of tables in the request, we should remove all flow entries. Currently we have no concept of deleted tables, though, so we report them all as existing. included if they are equal to the #ofp_table_feature_prop_* property - mandatory, must appear just once - experimenters, it is probably up to the experimenter to define the rules. Currently we do not support any experimenters features so we do not care. In version 1.3.1 of the OpenFlow specification, there is no error code defined for duplicate feature properties, so we use bad_argument instead. No experimeters properties are currently supported No experimeters properties are currently supported
Copyright 2012 FlowForwarding.org Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author Erlang Solutions Ltd. < > @author Cloudozer LLP < > 2012 FlowForwarding.org -module(linc_max_table_features). -export([handle_req/2]). -include_lib("of_protocol/include/ofp_v4.hrl"). -include_lib("linc_max/include/linc_max.hrl"). -define(REQUIRED_PROPERTIES, [instructions, next_tables, write_actions, apply_actions, match, wildcards, write_setfield, apply_setfield]). -define(OPTIONAL_PROPERTIES, [instructions_miss, next_tables_miss, write_actions_miss, apply_actions_miss, write_setfield_miss, apply_setfield_miss]). handle_req(_SwitchId, #ofp_table_features_request{body=[]}) -> #ofp_table_features_reply{body = get_all_features()}; handle_req(SwitchId, #ofp_table_features_request{body=[_TF|_]=TableFeaturesList}) -> SetRequest case validate_config(TableFeaturesList) of ok -> DeletedTables = lists:seq(0, ?OFPTT_MAX) -- [TableId || #ofp_table_features{table_id = TableId} <- TableFeaturesList], [linc_max_flow:clear_table_flows(SwitchId, TableId) || TableId <- DeletedTables], #ofp_table_features_reply{body = get_all_features()}; {error,Reason} -> #ofp_error_msg{type=table_features_failed, code=Reason} end. get_all_features() -> [get_table_features(TableId) || TableId <- lists:seq(0, ?OFPTT_MAX)]. get_table_features(TableId) -> #ofp_table_features{ table_id = TableId, name = list_to_binary(io_lib:format("Flow Table 0x~2.16.0b", [TableId])), metadata_match = ?SUPPORTED_METADATA_MATCH, metadata_write = ?SUPPORTED_METADATA_WRITE, max_entries = ?MAX_FLOW_TABLE_ENTRIES, The # ofp_table_feature_prop_*_miss properties do not need to be properties = [#ofp_table_feature_prop_instructions{ instruction_ids = ?SUPPORTED_INSTRUCTIONS} , #ofp_table_feature_prop_next_tables{ next_table_ids = lists:seq(TableId+1,?OFPTT_MAX)} , #ofp_table_feature_prop_write_actions{ action_ids = ?SUPPORTED_ACTIONS} , #ofp_table_feature_prop_apply_actions{ action_ids = ?SUPPORTED_ACTIONS} , #ofp_table_feature_prop_match{ oxm_ids = ?SUPPORTED_MATCH_FIELDS} , #ofp_table_feature_prop_wildcards{ oxm_ids = ?SUPPORTED_WILDCARDS} , #ofp_table_feature_prop_write_setfield{ oxm_ids = ?SUPPORTED_WRITE_SETFIELDS} , #ofp_table_feature_prop_apply_setfield{ oxm_ids = ?SUPPORTED_WRITE_SETFIELDS} ]}. validate_config(TableFeaturesList) -> validate_configs(TableFeaturesList, []). validate_configs([#ofp_table_features{table_id = TableId, properties = Properties}|TableFeaturesList], TableIds) when TableId =< ?OFPTT_MAX -> case lists:member(TableId,TableIds) of true -> {error, bad_table}; false -> case validate_feature_properties(TableId, Properties) of ok -> validate_configs(TableFeaturesList, [TableId|TableIds]); Error -> Error end end; validate_configs([#ofp_table_features{table_id = all}|_TableFeaturesList], _TableIds) -> {error, bad_table}; validate_configs([], _TableIds) -> ok. There are three classes of features - optional , may appear 0 or 1 time validate_feature_properties(TableId, Properties) -> case validate_feature_properties(TableId, Properties, [], []) of {ok, {MandatoryFound, _Optional}} -> case all_mandatory_present(MandatoryFound, ?REQUIRED_PROPERTIES) of true -> ok; false -> {error, bad_argument} end; Error -> Error end. validate_feature_properties(TableId, [#ofp_table_feature_prop_instructions{ instruction_ids = Instructions } | Properties], Mandatory, Optional) -> case lists:member(instructions, Mandatory) of true -> {error,bad_argument}; false -> case lists:all(fun (I) -> lists:member(I, ?SUPPORTED_INSTRUCTIONS) end, Instructions) of true-> validate_feature_properties(TableId, Properties, [instructions|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_instructions_miss{ instruction_ids = Instructions } | Properties], Mandatory, Optional) -> case lists:member(instructions_miss, Optional) of true -> {error,bad_argument}; false -> case all_supported(Instructions, ?SUPPORTED_INSTRUCTIONS) of true-> validate_feature_properties(TableId, Properties, Mandatory, [instructions_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_next_tables{ next_table_ids = TableIds } | Properties], Mandatory, Optional) -> case lists:member(next_tables, Mandatory) of true -> {error,bad_argument}; false -> case lists:all(fun (Id) -> Id > TableId end, TableIds) of true-> validate_feature_properties(TableId, Properties, [next_tables|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_next_tables_miss{ next_table_ids = TableIds } | Properties], Mandatory, Optional) -> case lists:member(next_tables_miss, Optional) of true -> {error,bad_argument}; false -> case lists:all(fun (Id) -> Id > TableId end, TableIds) of true-> validate_feature_properties(TableId, Properties, Mandatory, [next_tables_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_write_actions{ action_ids = ActionIds } | Properties], Mandatory, Optional) -> case lists:member(write_actions, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(ActionIds, ?SUPPORTED_WRITE_ACTIONS) of true-> validate_feature_properties(TableId, Properties, [write_actions|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_write_actions_miss{ action_ids = ActionIds } | Properties], Mandatory, Optional) -> case lists:member(write_actions_miss, Optional) of true -> {error,bad_argument}; false -> case all_supported(ActionIds, ?SUPPORTED_WRITE_ACTIONS) of true-> validate_feature_properties(TableId, Properties, Mandatory, [write_actions_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_apply_actions{ action_ids = ActionIds } | Properties], Mandatory, Optional) -> case lists:member(apply_actions, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(ActionIds, ?SUPPORTED_APPLY_ACTIONS) of true-> validate_feature_properties(TableId, Properties, [apply_actions|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_apply_actions_miss{ action_ids = ActionIds } | Properties], Mandatory, Optional) -> case lists:member(apply_actions_miss, Optional) of true -> {error,bad_argument}; false -> case all_supported(ActionIds, ?SUPPORTED_APPLY_ACTIONS) of true-> validate_feature_properties(TableId, Properties, Mandatory, [apply_actions_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_match{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(match, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_MATCH_FIELDS) of true-> validate_feature_properties(TableId, Properties, [match|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_wildcards{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(wildcards, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_WILDCARDS) of true-> validate_feature_properties(TableId, Properties, [wildcards|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_write_setfield{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(write_setfield, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_WRITE_SETFIELDS) of true-> validate_feature_properties(TableId, Properties, [write_setfield|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_write_setfield_miss{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(write_setfield_miss, Optional) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_WRITE_SETFIELDS) of true-> validate_feature_properties(TableId, Properties, Mandatory, [write_setfield_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_apply_setfield{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(apply_setfield, Mandatory) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_APPLY_SETFIELDS) of true-> validate_feature_properties(TableId, Properties, [apply_setfield|Mandatory], Optional); false -> {error,bad_argument} end end; validate_feature_properties(TableId, [#ofp_table_feature_prop_apply_setfield_miss{ oxm_ids = FieldIds } | Properties], Mandatory, Optional) -> case lists:member(apply_setfield_miss, Optional) of true -> {error,bad_argument}; false -> case all_supported(FieldIds, ?SUPPORTED_APPLY_SETFIELDS) of true-> validate_feature_properties(TableId, Properties, Mandatory, [apply_setfield_miss|Optional]); false -> {error,bad_argument} end end; validate_feature_properties(_TableId, [#ofp_table_feature_prop_experimenter{} | _Properties], _Mandatory, _Optional) -> {error,bad_type}; validate_feature_properties(_TableId, [#ofp_table_feature_prop_experimenter_miss{} | _Properties], _Mandatory, _Optional) -> {error,bad_type}; validate_feature_properties(_TableId, [], Mandatory, Optional) -> {ok, {Mandatory, Optional}}. all_supported(Items, SupportedItems) -> lists:all(fun (I) -> lists:member(I, SupportedItems) end, Items). all_mandatory_present(Found, Required) -> lists:sort(Found) == lists:sort(Required).
a2f90f8683efc7d553d0e671c2553a01819baea17a5c7c09a9d71e4087908220
cl21/cl21
cons.lisp
(in-package :cl-user) (defpackage cl21.core.cons (:use :cl) (:shadow :member :member-if :nth :nthcdr) (:import-from :cl21.core.sequence :abstract-sequence :abstract-list :drop-while :make-sequence-like :method-unimplemented-error :abstract-length :abstract-elt :abstract-first :abstract-second :abstract-third :abstract-fourth :abstract-fifth :abstract-sixth :abstract-seventh :abstract-eighth :abstract-ninth :abstract-tenth :abstract-rest :adjust-sequence :abstract-replace :abstract-copy-seq :abstract-subseq :abstract-take :abstract-drop :abstract-take-while :abstract-drop-while :abstract-last :abstract-find-if :abstract-position-if :abstract-search :abstract-delete-if :abstract-count-if :abstract-nreverse :abstract-nsubstitute-if :abstract-delete-duplicates :abstract-mismatch :abstract-fill :make-sequence-iterator :iterator-endp :iterator-next :iterator-pointer :with-sequence-iterator :do-abstract-sequence :take :drop) (:shadowing-import-from :cl21.core.sequence :first :rest :length :subseq :nreverse :replace :copy-seq) (:shadowing-import-from :cl21.core.generic :emptyp :getf :coerce) (:shadowing-import-from :cl21.core.array :vector) (:import-from :cl21.internal.util :define-typecase-compiler-macro) (:import-from :alexandria :iota :remove-from-plist :delete-from-plist :ensure-list :ensure-cons :ensure-car #+nil :flatten :mappend :with-gensyms) (:export :list :null :cons :atom :consp :rplaca :rplacd :nth :nthcdr :car :cdr :caar :cadr :cdar :cddr :caaar :caadr :cadar :caddr :cdaar :cdadr :cddar :cdddr :caaaar :caaadr :caadar :caaddr :cadaar :cadadr :caddar :cadddr :cdaaar :cdaadr :cdadar :cdaddr :cddaar :cddadr :cdddar :cddddr :copy-tree :sublis :nsublis :subst :subst-if :nsubst :nsubst-if :tree-equal :copy-list :list* :listp :make-list :endp :null :nconc :nappend :revappend :nreconc :ldiff :tailp :mapcan :maplist :mapcon :acons :assoc :assoc-if :copy-alist :pairlis :rassoc :rassoc-if :get-properties :intersection :nintersection :adjoin :set-difference :nset-difference :set-exclusive-or :nset-exclusive-or :subsetp :union :nunion :list-length :iota :remove-from-plist :delete-from-plist :ensure-list :ensure-cons :ensure-car :list-push :list-pushnew :list-pop Alexandria :mappend :maptree :1.. :0.. ;; Abstract List :member :member-if :abstract-member :abstract-member-if :flatten :abstract-flatten :last-cons :abstract-last-cons)) (in-package :cl21.core.cons) (setf (symbol-function 'nappend) #'nconc) (defmacro list-push (value place) `(cl:push ,value ,place)) (defmacro list-pushnew (value place &rest keys) `(cl:pushnew ,value ,place ,@keys)) (defmacro list-pop (place) `(cl:pop ,place)) (defun maptree (fn tree) (labels ((rec (tree) (etypecase tree (atom (funcall fn tree)) (cons (cons (rec (car tree)) (if (cdr tree) (rec (cdr tree)) nil)))))) (if (null tree) nil (rec tree)))) (defun 1.. (n) (iota n :start 1)) (defun 0.. (n) (iota (1+ n))) ;; ;; Abstract List (defmethod emptyp ((sequence abstract-list)) (method-unimplemented-error 'emptyp sequence)) (defmethod getf ((place abstract-list) key &optional default) (let ((rest (nthcdr place key))) (if (emptyp rest) (values default nil) (values (abstract-first rest) t)))) (defmethod (setf getf) (newval (place abstract-list) key) (setf (abstract-elt place key) newval)) (defmethod abstract-length ((sequence abstract-list)) (do-abstract-sequence (nil sequence i) (i))) (defmethod abstract-elt ((sequence abstract-list) index) (abstract-first (drop index sequence))) (defmethod (setf abstract-elt) (newval (sequence abstract-list) index) (setf (abstract-first (nthcdr sequence index)) newval)) (defmethod abstract-first ((sequence abstract-list)) (method-unimplemented-error 'abstract-first sequence)) (defmethod (setf abstract-first) (newval (sequence abstract-list)) (declare (ignore newval)) (method-unimplemented-error '(setf abstract-first) sequence)) #.`(progn ,@(loop for (function . n) in '((second . 1) (third . 2) (fourth . 3) (fifth . 4) (sixth . 5) (seventh . 6) (eighth . 7) (ninth . 8) (tenth . 9)) for abstract-fun = (intern (format nil "~A-~A" :abstract function)) append `((defmethod ,abstract-fun ((sequence abstract-list)) (dotimes (n ,n (abstract-first sequence)) (setq sequence (abstract-rest sequence)))) (defmethod (setf ,abstract-fun) (newval (sequence abstract-list)) (dotimes (n ,n) (setq sequence (abstract-rest sequence))) (setf (abstract-first sequence) newval))))) (defun nth (list n) (etypecase list (cl:list (cl:nth n list)) (abstract-list (dotimes (i n (abstract-first list)) (setq list (abstract-rest list)))))) (define-typecase-compiler-macro nth (list n) (typecase list (cl:list `(cl:nth ,n ,list)))) (defun (setf nth) (newval list n) (etypecase list (cl:list (setf (cl:nth n list) newval)) (abstract-list (dotimes (i n) (setq list (abstract-rest list))) (setf (abstract-first list) newval)))) (define-typecase-compiler-macro (setf nth) (newval list n) (typecase list (cl:list `(setf (cl:nth ,n ,list) ,newval)))) (defmethod abstract-rest ((sequence abstract-list)) (method-unimplemented-error 'abstract-rest sequence)) (defmethod (setf abstract-rest) (newval (sequence abstract-list)) (declare (ignore newval)) (method-unimplemented-error '(setf abstract-rest) sequence)) (defun nthcdr (list n) (etypecase list (cl:list (cl:nthcdr n list)) (abstract-list (dotimes (i n list) (setq list (abstract-rest list)))))) (define-typecase-compiler-macro nthcdr (list n) (typecase list (cl:list `(cl:nthcdr ,n ,list)))) (defun (setf nthcdr) (newval list n) (etypecase list (cl:list (setf (cdr (cl:nthcdr (1- n) list)) newval)) (abstract-list (when (> n 1) (dotimes (i (1- n)) (setq list (abstract-rest list)))) (setf (abstract-rest list) newval)))) (define-typecase-compiler-macro (setf nthcdr) (newval list n) (typecase list (cl:list `(setf (cl:nthcdr ,n ,list) ,newval)))) (defmethod adjust-sequence ((seq abstract-list) length &key initial-element (initial-contents nil icp)) (if (eql length 0) (make-sequence-like seq 0) (let ((olength (abstract-length seq))) (cond ((eql length olength) (if icp (abstract-replace seq initial-contents) seq)) ((< length olength) (setf (nthcdr seq length) (make-sequence-like seq 0)) (if icp (abstract-replace seq initial-contents) seq)) ((zerop olength) (let ((result (make-sequence-like seq length :initial-element initial-element))) (if icp (abstract-replace result initial-contents) result))) (t (setf (nthcdr seq olength) (make-sequence-like seq (- length olength) :initial-element initial-element)) (if icp (abstract-replace seq initial-contents) seq)))))) (defmethod coerce ((object abstract-list) type) (ecase type (list (let ((results '())) (do-abstract-sequence (x object (cl:nreverse results)) () (cl:push x results)))) ((vector simple-vector) (apply #'vector (coerce object 'list))) (string (cl:coerce (coerce object 'list) 'string)))) (eval-when (:compile-toplevel :load-toplevel :execute) (defstruct (list-iterator (:constructor %make-list-iterator (sequence &key pointer limit step next-fn))) (pointer 0 :type integer) (limit nil :type (or integer null)) (step +1 :type integer) (sequence nil :type (or cl:list abstract-list)) (next-fn #'first :type function)) (defmethod make-sequence-iterator ((sequence abstract-list) &key (start 0) end from-end) (if from-end (let ((end (or end (abstract-length sequence)))) (%make-list-iterator (abstract-nreverse (abstract-subseq sequence start end)) :pointer (1- end) :step -1 :limit (1- start))) (%make-list-iterator (nthcdr sequence start) :pointer start :step +1 :limit end))) (defmethod make-sequence-iterator ((sequence cl:list) &key (start 0) end from-end) (if from-end (let ((seq (cl:nreverse (cl:subseq sequence start end)))) (%make-list-iterator seq :pointer (1- (or end (cl:length seq))) :step -1 :limit (1- start))) (%make-list-iterator (cl:nthcdr start sequence) :pointer start :step +1 :limit end))) (defmethod iterator-pointer ((iterator list-iterator)) (list-iterator-pointer iterator)) (defmethod iterator-endp ((iterator list-iterator)) (or (eql (list-iterator-limit iterator) (list-iterator-pointer iterator)) (emptyp (list-iterator-sequence iterator)))) (defmethod iterator-next ((iterator list-iterator)) (prog1 (funcall (list-iterator-next-fn iterator) (list-iterator-sequence iterator)) (setf (list-iterator-sequence iterator) (rest (list-iterator-sequence iterator))) (incf (list-iterator-pointer iterator) (list-iterator-step iterator)))) (defun make-cons-iterator (sequence &key (start 0) end from-end) (if from-end (let ((end (or end (length sequence))) (buf '())) (dotimes (i start) (setq sequence (rest sequence))) (do ((i start (1+ i))) ((= i end)) (cl:push sequence buf) (setq sequence (rest sequence))) (%make-list-iterator buf :pointer (1- end) :step -1 :limit (1- start))) (%make-list-iterator (nthcdr sequence start) :pointer start :step +1 :limit end :next-fn #'identity)))) (defmacro do-abstract-cons ((var sequence &rest result-form) (&optional (i (gensym "I")) (start 0) end from-end) &body body) (with-gensyms (iterator) `(let ((,iterator (make-cons-iterator ,sequence :start ,start :end ,end :from-end ,from-end))) (with-sequence-iterator (,var ,iterator ,@result-form) (,i) ,@body)))) (defmethod abstract-copy-seq ((sequence abstract-list)) (cond ((emptyp sequence) (make-sequence-like sequence 0)) ((emptyp (abstract-rest sequence)) (make-sequence-like sequence 1 :initial-contents (list (abstract-first sequence)))) (T (let ((new (make-sequence-like sequence 1))) (setf (abstract-first new) (abstract-first sequence) (abstract-rest new) (copy-seq (abstract-rest sequence))) new)))) (defmethod abstract-subseq ((sequence abstract-list) start &optional end) (let ((results '())) (do-abstract-sequence (x sequence (make-sequence-like sequence (- i start) :initial-contents (cl:nreverse results))) (i start end) (cl:push x results)))) (defmethod abstract-fill ((sequence abstract-list) item &key (start 0) end) (do-abstract-cons (x sequence sequence) (i start end) (setf (abstract-first x) item))) (defmethod abstract-drop (n (sequence abstract-list)) (copy-seq (nthcdr sequence n))) (defmethod abstract-take-while (pred (sequence abstract-list)) (let ((results '())) (flet ((final (length) (make-sequence-like sequence length :initial-contents (cl:nreverse results)))) (do-abstract-sequence (x sequence (final i)) (i) (unless (funcall pred x) (return (final i))) (cl:push x results))))) (defmethod abstract-drop-while (pred (sequence abstract-list)) (do-abstract-cons (x sequence) (i 0) (unless (funcall pred (abstract-first x)) (return x)))) (defmethod abstract-last ((sequence abstract-list)) (do-abstract-cons (x sequence) () (when (emptyp (abstract-rest x)) (return (abstract-first x))))) (defmethod abstract-search (sequence1 (sequence2 abstract-list) &key from-end (test #'eql) (start1 0) end1 (start2 0) end2 (key #'identity)) (when (typep sequence1 'abstract-sequence) (setq sequence1 (coerce sequence1 'list))) (setq sequence1 (cl:subseq sequence1 start1 end1)) (let ((length (cl:length sequence1)) (first-el (funcall key (car sequence1)))) (do-abstract-cons (x sequence2) (i start2 end2 from-end) (when (and (funcall test (funcall key (abstract-first x)) first-el) (every (lambda (x y) (funcall test (funcall key x) (funcall key y))) (cdr sequence1) (coerce (take (1- length) (abstract-rest x)) 'list))) (return i))))) (defmethod abstract-delete-if (pred (sequence abstract-list) &key from-end (start 0) end count (key #'identity)) (let ((removed-count 0)) (unless from-end (loop while (and (not (eql removed-count count)) (funcall pred (funcall key (abstract-first sequence)))) do (setq sequence (abstract-rest sequence)) (incf removed-count))) (do-abstract-cons (x sequence sequence) (i start end from-end) (when (eql removed-count count) (return sequence)) (let ((rest (abstract-rest x))) (when (and (not (emptyp rest)) (funcall pred (funcall key (abstract-first rest)))) (incf removed-count) (setf (abstract-rest x) (abstract-rest rest))))))) (defmethod abstract-mismatch (sequence1 (sequence2 abstract-list) &key from-end (test #'eql) (start1 0) end1 (start2 0) end2 (key #'identity)) (let ((end1 (and from-end (or end1 (length sequence1)))) (current (if from-end (nreverse (subseq sequence2 start2 end2)) (drop start2 sequence2)))) (do-abstract-sequence (x sequence1 (cond ((emptyp current) nil) ((and end2 (= (- end2 start2) (- i start1))) nil) (from-end (- end1 i)) (t i))) (i start1 end1 from-end) (when (emptyp current) (return (if from-end (1+ i) (1- i)))) (unless (funcall test (funcall key x) (funcall key (first current))) (return (if from-end (- end1 i) i))) (setq current (rest current))))) (defmethod abstract-nreverse ((sequence abstract-list)) (if (emptyp sequence) sequence (let ((current (make-sequence-like sequence 0))) (do () ((emptyp sequence) current) (let ((next-rest (abstract-rest sequence))) (setf (abstract-rest sequence) current) (setq current sequence) (setq sequence next-rest)))))) (defmethod abstract-nsubstitute-if (new pred (sequence abstract-list) &key from-end (start 0) end count (key #'identity)) (let ((subst-count 0)) (if (and count (zerop count)) sequence (do-abstract-cons (x sequence sequence) (i start end from-end) (when (eql count subst-count) (return sequence)) (when (funcall pred (funcall key (abstract-first x))) (incf subst-count) (setf (abstract-first x) new)))))) (defmethod abstract-delete-duplicates ((sequence abstract-list) &key from-end (test #'eql) (start 0) end (key #'identity)) (if from-end (let ((buf '()) (length 0)) (do-abstract-sequence (x sequence) (i start end nil) (incf length) (cl:push x buf)) (setq buf (cl:nreverse (cl:delete-duplicates buf :test test :key key))) (replace sequence buf :start1 start :end1 end) (if end (progn (setf (nthcdr sequence (+ start length -1)) (nthcdr sequence end)) sequence) (adjust-sequence sequence (+ start (cl:length buf))))) (flet ((find-dup (x seq &key (start 0) end) (do-abstract-sequence (y seq) (i start end nil) (when (funcall test (funcall key x) (funcall key y)) (return t))))) (let ((seq (nthcdr sequence start))) (loop while (find-dup (abstract-first seq) (abstract-rest seq) :start 0 :end (and end (1- end))) do (setq seq (abstract-rest seq))) (do-abstract-cons (x seq) (i start end nil) (let ((rest (abstract-rest x))) (when (emptyp rest) (return)) (when (find-dup (abstract-first rest) (abstract-rest rest) :start 0 :end (and end (- end i 1))) (setf (abstract-rest x) (abstract-rest rest)) (return)))) (cond ((zerop start) (setq sequence seq)) ((= start 1) (setf (abstract-rest sequence) seq)) (t (setf (nthcdr start sequence) seq))) sequence)))) ;; ;; Function: member, member-if ;; Generic Function: abstract-member, abstract-member-if (defun member (item list &rest args &key key test) (declare (ignore key test)) (etypecase list (cl:list (apply #'cl:member item list args)) (abstract-list (apply #'abstract-member item list args)))) (define-typecase-compiler-macro member (&whole form item list &rest args) (typecase list (cl:list `(cl:member ,@(cdr form))))) (defgeneric abstract-member (item list &key key test) (:method (item (list abstract-list) &key (key #'identity) (test #'eql)) (drop-while (lambda (x) (not (funcall test (funcall key x) item))) list))) (defun member-if (test list &rest args &key key) (declare (ignore key)) (etypecase list (cl:list (apply #'cl:member-if test list args)) (abstract-list (apply #'abstract-member-if test list args)))) (define-typecase-compiler-macro member-if (&whole form test list &rest args) (typecase list (cl:list `(cl:member-if ,@(cdr form))))) (defgeneric abstract-member-if (test list &key key) (:method (test (list abstract-list) &key key) (drop-while (if key (lambda (x) (not (funcall test (funcall key x)))) (complement test)) list))) ;; ;; Function: flatten ;; Generic Function: abstract-flatten (defun flatten (tree) (typecase tree (cl:list (alexandria:flatten tree)) (abstract-list (abstract-flatten tree)) (otherwise (list tree)))) (defgeneric abstract-flatten (tree) (:method ((tree abstract-list)) (let ((buf '()) (length 0)) (do-abstract-sequence (x tree) () (incf length) (cl:push (flatten x) buf)) (make-sequence-like tree length :initial-contents (nreverse buf))))) ;; ;; Function: last-cons ;; Generic Function: abstract-last-cons (defun last-cons (list &optional (n 1)) (etypecase list (cl:list (cl:last list n)) (abstract-list (abstract-last-cons list n)))) (defgeneric abstract-last-cons (list &optional n) (:method ((list abstract-list) &optional (n 1)) (do ((current list (abstract-rest current))) ((emptyp (nthcdr current n)) current))))
null
https://raw.githubusercontent.com/cl21/cl21/c36644f3b6ea4975174c8ce72de43a4524dd0696/src/core/cons.lisp
lisp
Abstract List Abstract List Function: member, member-if Generic Function: abstract-member, abstract-member-if Function: flatten Generic Function: abstract-flatten Function: last-cons Generic Function: abstract-last-cons
(in-package :cl-user) (defpackage cl21.core.cons (:use :cl) (:shadow :member :member-if :nth :nthcdr) (:import-from :cl21.core.sequence :abstract-sequence :abstract-list :drop-while :make-sequence-like :method-unimplemented-error :abstract-length :abstract-elt :abstract-first :abstract-second :abstract-third :abstract-fourth :abstract-fifth :abstract-sixth :abstract-seventh :abstract-eighth :abstract-ninth :abstract-tenth :abstract-rest :adjust-sequence :abstract-replace :abstract-copy-seq :abstract-subseq :abstract-take :abstract-drop :abstract-take-while :abstract-drop-while :abstract-last :abstract-find-if :abstract-position-if :abstract-search :abstract-delete-if :abstract-count-if :abstract-nreverse :abstract-nsubstitute-if :abstract-delete-duplicates :abstract-mismatch :abstract-fill :make-sequence-iterator :iterator-endp :iterator-next :iterator-pointer :with-sequence-iterator :do-abstract-sequence :take :drop) (:shadowing-import-from :cl21.core.sequence :first :rest :length :subseq :nreverse :replace :copy-seq) (:shadowing-import-from :cl21.core.generic :emptyp :getf :coerce) (:shadowing-import-from :cl21.core.array :vector) (:import-from :cl21.internal.util :define-typecase-compiler-macro) (:import-from :alexandria :iota :remove-from-plist :delete-from-plist :ensure-list :ensure-cons :ensure-car #+nil :flatten :mappend :with-gensyms) (:export :list :null :cons :atom :consp :rplaca :rplacd :nth :nthcdr :car :cdr :caar :cadr :cdar :cddr :caaar :caadr :cadar :caddr :cdaar :cdadr :cddar :cdddr :caaaar :caaadr :caadar :caaddr :cadaar :cadadr :caddar :cadddr :cdaaar :cdaadr :cdadar :cdaddr :cddaar :cddadr :cdddar :cddddr :copy-tree :sublis :nsublis :subst :subst-if :nsubst :nsubst-if :tree-equal :copy-list :list* :listp :make-list :endp :null :nconc :nappend :revappend :nreconc :ldiff :tailp :mapcan :maplist :mapcon :acons :assoc :assoc-if :copy-alist :pairlis :rassoc :rassoc-if :get-properties :intersection :nintersection :adjoin :set-difference :nset-difference :set-exclusive-or :nset-exclusive-or :subsetp :union :nunion :list-length :iota :remove-from-plist :delete-from-plist :ensure-list :ensure-cons :ensure-car :list-push :list-pushnew :list-pop Alexandria :mappend :maptree :1.. :0.. :member :member-if :abstract-member :abstract-member-if :flatten :abstract-flatten :last-cons :abstract-last-cons)) (in-package :cl21.core.cons) (setf (symbol-function 'nappend) #'nconc) (defmacro list-push (value place) `(cl:push ,value ,place)) (defmacro list-pushnew (value place &rest keys) `(cl:pushnew ,value ,place ,@keys)) (defmacro list-pop (place) `(cl:pop ,place)) (defun maptree (fn tree) (labels ((rec (tree) (etypecase tree (atom (funcall fn tree)) (cons (cons (rec (car tree)) (if (cdr tree) (rec (cdr tree)) nil)))))) (if (null tree) nil (rec tree)))) (defun 1.. (n) (iota n :start 1)) (defun 0.. (n) (iota (1+ n))) (defmethod emptyp ((sequence abstract-list)) (method-unimplemented-error 'emptyp sequence)) (defmethod getf ((place abstract-list) key &optional default) (let ((rest (nthcdr place key))) (if (emptyp rest) (values default nil) (values (abstract-first rest) t)))) (defmethod (setf getf) (newval (place abstract-list) key) (setf (abstract-elt place key) newval)) (defmethod abstract-length ((sequence abstract-list)) (do-abstract-sequence (nil sequence i) (i))) (defmethod abstract-elt ((sequence abstract-list) index) (abstract-first (drop index sequence))) (defmethod (setf abstract-elt) (newval (sequence abstract-list) index) (setf (abstract-first (nthcdr sequence index)) newval)) (defmethod abstract-first ((sequence abstract-list)) (method-unimplemented-error 'abstract-first sequence)) (defmethod (setf abstract-first) (newval (sequence abstract-list)) (declare (ignore newval)) (method-unimplemented-error '(setf abstract-first) sequence)) #.`(progn ,@(loop for (function . n) in '((second . 1) (third . 2) (fourth . 3) (fifth . 4) (sixth . 5) (seventh . 6) (eighth . 7) (ninth . 8) (tenth . 9)) for abstract-fun = (intern (format nil "~A-~A" :abstract function)) append `((defmethod ,abstract-fun ((sequence abstract-list)) (dotimes (n ,n (abstract-first sequence)) (setq sequence (abstract-rest sequence)))) (defmethod (setf ,abstract-fun) (newval (sequence abstract-list)) (dotimes (n ,n) (setq sequence (abstract-rest sequence))) (setf (abstract-first sequence) newval))))) (defun nth (list n) (etypecase list (cl:list (cl:nth n list)) (abstract-list (dotimes (i n (abstract-first list)) (setq list (abstract-rest list)))))) (define-typecase-compiler-macro nth (list n) (typecase list (cl:list `(cl:nth ,n ,list)))) (defun (setf nth) (newval list n) (etypecase list (cl:list (setf (cl:nth n list) newval)) (abstract-list (dotimes (i n) (setq list (abstract-rest list))) (setf (abstract-first list) newval)))) (define-typecase-compiler-macro (setf nth) (newval list n) (typecase list (cl:list `(setf (cl:nth ,n ,list) ,newval)))) (defmethod abstract-rest ((sequence abstract-list)) (method-unimplemented-error 'abstract-rest sequence)) (defmethod (setf abstract-rest) (newval (sequence abstract-list)) (declare (ignore newval)) (method-unimplemented-error '(setf abstract-rest) sequence)) (defun nthcdr (list n) (etypecase list (cl:list (cl:nthcdr n list)) (abstract-list (dotimes (i n list) (setq list (abstract-rest list)))))) (define-typecase-compiler-macro nthcdr (list n) (typecase list (cl:list `(cl:nthcdr ,n ,list)))) (defun (setf nthcdr) (newval list n) (etypecase list (cl:list (setf (cdr (cl:nthcdr (1- n) list)) newval)) (abstract-list (when (> n 1) (dotimes (i (1- n)) (setq list (abstract-rest list)))) (setf (abstract-rest list) newval)))) (define-typecase-compiler-macro (setf nthcdr) (newval list n) (typecase list (cl:list `(setf (cl:nthcdr ,n ,list) ,newval)))) (defmethod adjust-sequence ((seq abstract-list) length &key initial-element (initial-contents nil icp)) (if (eql length 0) (make-sequence-like seq 0) (let ((olength (abstract-length seq))) (cond ((eql length olength) (if icp (abstract-replace seq initial-contents) seq)) ((< length olength) (setf (nthcdr seq length) (make-sequence-like seq 0)) (if icp (abstract-replace seq initial-contents) seq)) ((zerop olength) (let ((result (make-sequence-like seq length :initial-element initial-element))) (if icp (abstract-replace result initial-contents) result))) (t (setf (nthcdr seq olength) (make-sequence-like seq (- length olength) :initial-element initial-element)) (if icp (abstract-replace seq initial-contents) seq)))))) (defmethod coerce ((object abstract-list) type) (ecase type (list (let ((results '())) (do-abstract-sequence (x object (cl:nreverse results)) () (cl:push x results)))) ((vector simple-vector) (apply #'vector (coerce object 'list))) (string (cl:coerce (coerce object 'list) 'string)))) (eval-when (:compile-toplevel :load-toplevel :execute) (defstruct (list-iterator (:constructor %make-list-iterator (sequence &key pointer limit step next-fn))) (pointer 0 :type integer) (limit nil :type (or integer null)) (step +1 :type integer) (sequence nil :type (or cl:list abstract-list)) (next-fn #'first :type function)) (defmethod make-sequence-iterator ((sequence abstract-list) &key (start 0) end from-end) (if from-end (let ((end (or end (abstract-length sequence)))) (%make-list-iterator (abstract-nreverse (abstract-subseq sequence start end)) :pointer (1- end) :step -1 :limit (1- start))) (%make-list-iterator (nthcdr sequence start) :pointer start :step +1 :limit end))) (defmethod make-sequence-iterator ((sequence cl:list) &key (start 0) end from-end) (if from-end (let ((seq (cl:nreverse (cl:subseq sequence start end)))) (%make-list-iterator seq :pointer (1- (or end (cl:length seq))) :step -1 :limit (1- start))) (%make-list-iterator (cl:nthcdr start sequence) :pointer start :step +1 :limit end))) (defmethod iterator-pointer ((iterator list-iterator)) (list-iterator-pointer iterator)) (defmethod iterator-endp ((iterator list-iterator)) (or (eql (list-iterator-limit iterator) (list-iterator-pointer iterator)) (emptyp (list-iterator-sequence iterator)))) (defmethod iterator-next ((iterator list-iterator)) (prog1 (funcall (list-iterator-next-fn iterator) (list-iterator-sequence iterator)) (setf (list-iterator-sequence iterator) (rest (list-iterator-sequence iterator))) (incf (list-iterator-pointer iterator) (list-iterator-step iterator)))) (defun make-cons-iterator (sequence &key (start 0) end from-end) (if from-end (let ((end (or end (length sequence))) (buf '())) (dotimes (i start) (setq sequence (rest sequence))) (do ((i start (1+ i))) ((= i end)) (cl:push sequence buf) (setq sequence (rest sequence))) (%make-list-iterator buf :pointer (1- end) :step -1 :limit (1- start))) (%make-list-iterator (nthcdr sequence start) :pointer start :step +1 :limit end :next-fn #'identity)))) (defmacro do-abstract-cons ((var sequence &rest result-form) (&optional (i (gensym "I")) (start 0) end from-end) &body body) (with-gensyms (iterator) `(let ((,iterator (make-cons-iterator ,sequence :start ,start :end ,end :from-end ,from-end))) (with-sequence-iterator (,var ,iterator ,@result-form) (,i) ,@body)))) (defmethod abstract-copy-seq ((sequence abstract-list)) (cond ((emptyp sequence) (make-sequence-like sequence 0)) ((emptyp (abstract-rest sequence)) (make-sequence-like sequence 1 :initial-contents (list (abstract-first sequence)))) (T (let ((new (make-sequence-like sequence 1))) (setf (abstract-first new) (abstract-first sequence) (abstract-rest new) (copy-seq (abstract-rest sequence))) new)))) (defmethod abstract-subseq ((sequence abstract-list) start &optional end) (let ((results '())) (do-abstract-sequence (x sequence (make-sequence-like sequence (- i start) :initial-contents (cl:nreverse results))) (i start end) (cl:push x results)))) (defmethod abstract-fill ((sequence abstract-list) item &key (start 0) end) (do-abstract-cons (x sequence sequence) (i start end) (setf (abstract-first x) item))) (defmethod abstract-drop (n (sequence abstract-list)) (copy-seq (nthcdr sequence n))) (defmethod abstract-take-while (pred (sequence abstract-list)) (let ((results '())) (flet ((final (length) (make-sequence-like sequence length :initial-contents (cl:nreverse results)))) (do-abstract-sequence (x sequence (final i)) (i) (unless (funcall pred x) (return (final i))) (cl:push x results))))) (defmethod abstract-drop-while (pred (sequence abstract-list)) (do-abstract-cons (x sequence) (i 0) (unless (funcall pred (abstract-first x)) (return x)))) (defmethod abstract-last ((sequence abstract-list)) (do-abstract-cons (x sequence) () (when (emptyp (abstract-rest x)) (return (abstract-first x))))) (defmethod abstract-search (sequence1 (sequence2 abstract-list) &key from-end (test #'eql) (start1 0) end1 (start2 0) end2 (key #'identity)) (when (typep sequence1 'abstract-sequence) (setq sequence1 (coerce sequence1 'list))) (setq sequence1 (cl:subseq sequence1 start1 end1)) (let ((length (cl:length sequence1)) (first-el (funcall key (car sequence1)))) (do-abstract-cons (x sequence2) (i start2 end2 from-end) (when (and (funcall test (funcall key (abstract-first x)) first-el) (every (lambda (x y) (funcall test (funcall key x) (funcall key y))) (cdr sequence1) (coerce (take (1- length) (abstract-rest x)) 'list))) (return i))))) (defmethod abstract-delete-if (pred (sequence abstract-list) &key from-end (start 0) end count (key #'identity)) (let ((removed-count 0)) (unless from-end (loop while (and (not (eql removed-count count)) (funcall pred (funcall key (abstract-first sequence)))) do (setq sequence (abstract-rest sequence)) (incf removed-count))) (do-abstract-cons (x sequence sequence) (i start end from-end) (when (eql removed-count count) (return sequence)) (let ((rest (abstract-rest x))) (when (and (not (emptyp rest)) (funcall pred (funcall key (abstract-first rest)))) (incf removed-count) (setf (abstract-rest x) (abstract-rest rest))))))) (defmethod abstract-mismatch (sequence1 (sequence2 abstract-list) &key from-end (test #'eql) (start1 0) end1 (start2 0) end2 (key #'identity)) (let ((end1 (and from-end (or end1 (length sequence1)))) (current (if from-end (nreverse (subseq sequence2 start2 end2)) (drop start2 sequence2)))) (do-abstract-sequence (x sequence1 (cond ((emptyp current) nil) ((and end2 (= (- end2 start2) (- i start1))) nil) (from-end (- end1 i)) (t i))) (i start1 end1 from-end) (when (emptyp current) (return (if from-end (1+ i) (1- i)))) (unless (funcall test (funcall key x) (funcall key (first current))) (return (if from-end (- end1 i) i))) (setq current (rest current))))) (defmethod abstract-nreverse ((sequence abstract-list)) (if (emptyp sequence) sequence (let ((current (make-sequence-like sequence 0))) (do () ((emptyp sequence) current) (let ((next-rest (abstract-rest sequence))) (setf (abstract-rest sequence) current) (setq current sequence) (setq sequence next-rest)))))) (defmethod abstract-nsubstitute-if (new pred (sequence abstract-list) &key from-end (start 0) end count (key #'identity)) (let ((subst-count 0)) (if (and count (zerop count)) sequence (do-abstract-cons (x sequence sequence) (i start end from-end) (when (eql count subst-count) (return sequence)) (when (funcall pred (funcall key (abstract-first x))) (incf subst-count) (setf (abstract-first x) new)))))) (defmethod abstract-delete-duplicates ((sequence abstract-list) &key from-end (test #'eql) (start 0) end (key #'identity)) (if from-end (let ((buf '()) (length 0)) (do-abstract-sequence (x sequence) (i start end nil) (incf length) (cl:push x buf)) (setq buf (cl:nreverse (cl:delete-duplicates buf :test test :key key))) (replace sequence buf :start1 start :end1 end) (if end (progn (setf (nthcdr sequence (+ start length -1)) (nthcdr sequence end)) sequence) (adjust-sequence sequence (+ start (cl:length buf))))) (flet ((find-dup (x seq &key (start 0) end) (do-abstract-sequence (y seq) (i start end nil) (when (funcall test (funcall key x) (funcall key y)) (return t))))) (let ((seq (nthcdr sequence start))) (loop while (find-dup (abstract-first seq) (abstract-rest seq) :start 0 :end (and end (1- end))) do (setq seq (abstract-rest seq))) (do-abstract-cons (x seq) (i start end nil) (let ((rest (abstract-rest x))) (when (emptyp rest) (return)) (when (find-dup (abstract-first rest) (abstract-rest rest) :start 0 :end (and end (- end i 1))) (setf (abstract-rest x) (abstract-rest rest)) (return)))) (cond ((zerop start) (setq sequence seq)) ((= start 1) (setf (abstract-rest sequence) seq)) (t (setf (nthcdr start sequence) seq))) sequence)))) (defun member (item list &rest args &key key test) (declare (ignore key test)) (etypecase list (cl:list (apply #'cl:member item list args)) (abstract-list (apply #'abstract-member item list args)))) (define-typecase-compiler-macro member (&whole form item list &rest args) (typecase list (cl:list `(cl:member ,@(cdr form))))) (defgeneric abstract-member (item list &key key test) (:method (item (list abstract-list) &key (key #'identity) (test #'eql)) (drop-while (lambda (x) (not (funcall test (funcall key x) item))) list))) (defun member-if (test list &rest args &key key) (declare (ignore key)) (etypecase list (cl:list (apply #'cl:member-if test list args)) (abstract-list (apply #'abstract-member-if test list args)))) (define-typecase-compiler-macro member-if (&whole form test list &rest args) (typecase list (cl:list `(cl:member-if ,@(cdr form))))) (defgeneric abstract-member-if (test list &key key) (:method (test (list abstract-list) &key key) (drop-while (if key (lambda (x) (not (funcall test (funcall key x)))) (complement test)) list))) (defun flatten (tree) (typecase tree (cl:list (alexandria:flatten tree)) (abstract-list (abstract-flatten tree)) (otherwise (list tree)))) (defgeneric abstract-flatten (tree) (:method ((tree abstract-list)) (let ((buf '()) (length 0)) (do-abstract-sequence (x tree) () (incf length) (cl:push (flatten x) buf)) (make-sequence-like tree length :initial-contents (nreverse buf))))) (defun last-cons (list &optional (n 1)) (etypecase list (cl:list (cl:last list n)) (abstract-list (abstract-last-cons list n)))) (defgeneric abstract-last-cons (list &optional n) (:method ((list abstract-list) &optional (n 1)) (do ((current list (abstract-rest current))) ((emptyp (nthcdr current n)) current))))
90f61b5a34eb37a7a2a1f03243f66be06f6bf6e367c4ba425ffa75fa11cf0d44
Tyruiop/syncretism
time.clj
(ns syncretism.time (:require [java-time :as jt]) (:import [java.sql Timestamp] [java.time ZoneId])) (defn cur-ny-time "Utility function to get the current time in NYC." [] (-> (System/currentTimeMillis) (Timestamp.) .toLocalDateTime (.atZone (ZoneId/systemDefault)) (jt/with-zone-same-instant "America/New_York") jt/as-map)) (defn cur-local-time "Utility function to get the current time in NYC." [] (-> (System/currentTimeMillis) (Timestamp.) .toLocalDateTime (.atZone (ZoneId/systemDefault)) jt/as-map)) (defn market-time "Input ts, in milliseconds Returns ts if it is a valid market time, otherwise the next possible market time" ([ts] (market-time (ZoneId/systemDefault) ts)) ([zone ts] (let [d (-> ts (Timestamp.) .toLocalDateTime (.atZone zone) (jt/with-zone-same-instant "America/New_York") jt/as-map) {:keys [day-of-week hour-of-day minute-of-hour second-of-day]} d mins (+ minute-of-hour (* hour-of-day 60))] Saturday "CLOSED" Sunday "CLOSED" Pre - market open ( 4h ) "CLOSED" End market open ( 20h ) "CLOSED" (and (< hour-of-day 20) (>= hour-of-day 16)) "POST" (and (>= hour-of-day 4) (or (< hour-of-day 9) (and (= hour-of-day 9) (< minute-of-hour 30)))) "PRE" (and (<= hour-of-day 16) (or (>= hour-of-day 10) (and (= hour-of-day 9) (>= minute-of-hour 30)))) "OPEN")))) (defn ts-start-of-day "Takes a timestamp, returns the timestamp of the start of that day, NY time. Note that ZoneId/systemDefault is used, but the data is crawled in a Europe/Berlin timezone server." [ts] (let [t-map (-> ts (Timestamp.) .toLocalDateTime (.atZone (ZoneId/systemDefault)) (jt/with-zone-same-instant "America/New_York") jt/as-map)] (- (int (/ ts 1000)) (:second-of-day t-map)))) (defn get-day-of-week "Takes a timestamp in seconds and returns the day of the week, assuming NY time." [ts] (-> ts (* 1000) (Timestamp.) .toLocalDateTime (.atZone (ZoneId/of "America/New_York")) (jt/with-zone-same-instant "America/New_York") jt/as-map :day-of-week))
null
https://raw.githubusercontent.com/Tyruiop/syncretism/805961af501121d3f79cd5395ae31811757f7cbf/syncretism/src/syncretism/time.clj
clojure
(ns syncretism.time (:require [java-time :as jt]) (:import [java.sql Timestamp] [java.time ZoneId])) (defn cur-ny-time "Utility function to get the current time in NYC." [] (-> (System/currentTimeMillis) (Timestamp.) .toLocalDateTime (.atZone (ZoneId/systemDefault)) (jt/with-zone-same-instant "America/New_York") jt/as-map)) (defn cur-local-time "Utility function to get the current time in NYC." [] (-> (System/currentTimeMillis) (Timestamp.) .toLocalDateTime (.atZone (ZoneId/systemDefault)) jt/as-map)) (defn market-time "Input ts, in milliseconds Returns ts if it is a valid market time, otherwise the next possible market time" ([ts] (market-time (ZoneId/systemDefault) ts)) ([zone ts] (let [d (-> ts (Timestamp.) .toLocalDateTime (.atZone zone) (jt/with-zone-same-instant "America/New_York") jt/as-map) {:keys [day-of-week hour-of-day minute-of-hour second-of-day]} d mins (+ minute-of-hour (* hour-of-day 60))] Saturday "CLOSED" Sunday "CLOSED" Pre - market open ( 4h ) "CLOSED" End market open ( 20h ) "CLOSED" (and (< hour-of-day 20) (>= hour-of-day 16)) "POST" (and (>= hour-of-day 4) (or (< hour-of-day 9) (and (= hour-of-day 9) (< minute-of-hour 30)))) "PRE" (and (<= hour-of-day 16) (or (>= hour-of-day 10) (and (= hour-of-day 9) (>= minute-of-hour 30)))) "OPEN")))) (defn ts-start-of-day "Takes a timestamp, returns the timestamp of the start of that day, NY time. Note that ZoneId/systemDefault is used, but the data is crawled in a Europe/Berlin timezone server." [ts] (let [t-map (-> ts (Timestamp.) .toLocalDateTime (.atZone (ZoneId/systemDefault)) (jt/with-zone-same-instant "America/New_York") jt/as-map)] (- (int (/ ts 1000)) (:second-of-day t-map)))) (defn get-day-of-week "Takes a timestamp in seconds and returns the day of the week, assuming NY time." [ts] (-> ts (* 1000) (Timestamp.) .toLocalDateTime (.atZone (ZoneId/of "America/New_York")) (jt/with-zone-same-instant "America/New_York") jt/as-map :day-of-week))