_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
|
---|---|---|---|---|---|---|---|---|
cdd95da455f16080260037a24337118c0f742466a35a084888f53f5f71522c0b | binaryage/clearcut | utils.clj | (ns clearcut.circus.utils
(:require [clojure.java.io :as io]
[clojure.string :as string]
[cuerdas.core :as cuerdas]
[clansi]
[clojure.java.shell :as shell]
[clojure.tools.logging :as log]
[clojure.pprint :refer [pprint]]
[clearcut.tools :as tools])
(:import (java.util.regex Matcher Pattern)))
(defn produce-diff [path1 path2]
(let [options-args ["-U" "5"]
paths-args [path1 path2]]
(try
(let [result (apply shell/sh "colordiff" (concat options-args paths-args))]
(if-not (empty? (:err result))
(clansi/style (str "! " (:err result)) :red)
(cuerdas/rtrim (:out result))))
(catch Throwable e
(clansi/style (str "! " (.getMessage e)) :red)))))
(defn js-beautify-version []
(let [options-args ["--version"]]
(try
(let [result (apply shell/sh "js-beautify" options-args)]
(if-not (empty? (:err result))
(clansi/style (str "! " (:err result)) :red)
(cuerdas/rtrim (:out result))))
(catch Throwable e
(clansi/style (str "! " (.getMessage e)) :red)))))
(defn dim-text [text]
(clansi/style text :black)) ; black on black background should be displayed as gray
(defn get-canonical-line [line]
(string/trimr line))
(defn append-nl [text]
(str text "\n"))
(defn get-canonical-transcript [transcript]
(let [s (->> transcript
(cuerdas/lines)
(map get-canonical-line)
(cuerdas/unlines)
(append-nl))] ; we want to be compatible with "copy transcript!" button which copies to clipboard with extra new-line
(string/replace s #"\n\n+" "\n\n")))
(defn extract-relevant-output [content]
(let [separator (tools/get-arena-separator)]
(if-let [separator-index (string/last-index-of content separator)]
(let [semicolon-index (or (string/index-of content ";" separator-index) separator-index)
relevant-content (.substring content (+ semicolon-index 1))]
relevant-content))))
(defn make-empty-normalizer-state []
{:counter 1
:counters {}
:identifiers {}
:mappings {}})
(defn get-counter [normalizer-state]
(:counter normalizer-state))
(defn get-mapping [normalizer-state name]
(get-in normalizer-state [:mappings name]))
(defn get-counter-for-name [normalizer-state name]
(get-in normalizer-state [:counters name]))
(defn register-mapping [normalizer-state name replacement]
(-> normalizer-state
(update :counter inc)
(update :mappings assoc name replacement)))
(defn register-counter [normalizer-state name identifier]
(let [x (fn [state]
(let [assigned-number (get-in state [:identifiers identifier])]
(assoc-in state [:counters name] assigned-number)))]
(-> normalizer-state
(update-in [:identifiers identifier] (fn [c] (inc (or c 0))))
(x))))
(defn register-mapping-if-needed [normalizer-state name replacement]
(if (get-mapping normalizer-state name)
normalizer-state
(register-mapping normalizer-state name replacement)))
(defn register-counter-if-needed [normalizer-state name identifier]
(if (get-counter-for-name normalizer-state name)
normalizer-state
(register-counter normalizer-state name identifier)))
(defn normalize-identifiers [[content normalizer-state]]
"The goal here is to rename all generated $<number>$ identifiers with stable numbering."
(let [* (fn [[content normalizer-state] match]
(let [needle (first match)
replacement (str (get-counter normalizer-state) (nth match 2))
new-normalizer-state (register-mapping-if-needed normalizer-state needle replacement)
new-content (string/replace content needle (get-mapping new-normalizer-state needle))]
[new-content new-normalizer-state]))]
(reduce * [content normalizer-state] (re-seq #"(\d+)(\$|__)" content))))
(defn normalize-gensyms [[content normalizer-state]]
"The goal here is to rename all generated name<NUM> identifiers with stable numbering."
(let [* (fn [[content normalizer-state] match]
(if (> (Long/parseLong (first match)) 1000)
(let [needle (first match)
replacement (str (get-counter normalizer-state))
new-normalizer-state (register-mapping-if-needed normalizer-state needle replacement)
new-content (string/replace content needle (get-mapping new-normalizer-state needle))]
[new-content new-normalizer-state])
[content normalizer-state]))]
(reduce * [content normalizer-state] (re-seq #"(\d+)" content))))
(defn normalize-twins [[content normalizer-state]]
"The goal here is to rename all generated <NUM>_<NUM> identifiers with stable numbering."
(let [* (fn [[content normalizer-state] needle]
(let [replacement (str (get-counter normalizer-state))
new-normalizer-state (register-mapping-if-needed normalizer-state needle replacement)
new-content (string/replace content needle (get-mapping new-normalizer-state needle))]
[new-content new-normalizer-state]))]
(reduce * [content normalizer-state] (re-seq #"\d+_\d+" content))))
(defn normalize-inlines [[content normalizer-state]]
"The goal here is to rename all generated <NUM>$$inline_<NUM> identifiers with stable numbering."
(let [* (fn [[content normalizer-state] needle]
(let [replacement (str (get-counter normalizer-state))
new-normalizer-state (register-mapping-if-needed normalizer-state needle replacement)
new-content (string/replace content needle (get-mapping new-normalizer-state needle))]
[new-content new-normalizer-state]))]
(reduce * [content normalizer-state] (re-seq #"\d+\$\$inline_\d+" content))))
(defn linearize-numbering [[content normalizer-state]]
"The goal here is to rename all generated <IDENTIFIER>_<NUM> to linear numbering for each distinct identifier."
(let [names (distinct (re-seq #"[a-zA-Z0-9_$]+_\d+" content))
* (fn [[content normalizer-state] name]
(let [group (re-matches #"([a-zA-Z0-9_$]+_)(\d+)" name)
identifier (nth group 1)
new-normalizer-state (register-counter-if-needed normalizer-state name identifier)
$ $ $ is a marker so we do n't conflict with name candidates for future replacement
we want to prevent replacing partial matches , eg . to mess with id_100
replacement (str (Matcher/quoteReplacement massaged-name) "$1")
new-content (string/replace content pattern replacement)]
[new-content new-normalizer-state]))
+ (fn [[content normalizer-state] name]
(let [group (re-matches #"([a-zA-Z0-9_$]+_)(\d+)" name)
identifier (nth group 1)
new-content (string/replace content (str identifier "$$$") identifier)]
[new-content normalizer-state]))]
(reduce + (reduce * [content normalizer-state] names) names)))
(defn drop-multi-dollars [[content normalizer-state]]
[(string/replace content #"\$\$+" "") normalizer-state])
(defn drop-leading-dollars [[content normalizer-state]]
[(string/replace content #"([^0-9a-zA-Z_])\$" "$1") normalizer-state])
(defn humanize-clearcut-ns [[content normalizer-state]]
[(string/replace content #"clearcut\$(.*?)\$" "clearcut.$1.") normalizer-state])
(defn humanize-cljs-core-ns [[content normalizer-state]]
[(string/replace content #"cljs\$core\$" "cljs.core.") normalizer-state])
(defn humanize-goog-ns [[content normalizer-state]]
[(string/replace content #"goog\$(.*?)\$" "goog.$1.") normalizer-state])
(defn safe-spit [path content]
(io/make-parents path)
(spit path content))
(defn pprint-str [v & [length level]]
(with-out-str
(binding [*print-level* (or level 10)
*print-length* (or length 10)]
(pprint v))))
(defn beautify-js! [path]
(log/debug (str "Beautify JS at '" path "'"))
(let [options-args ["-n" "-s" "2"]
paths-args ["-f" path "-o" path]]
(try
(let [result (apply shell/sh "js-beautify" (concat options-args paths-args))]
(if-not (empty? (:err result))
(log/error (str "! " (:err result)))))
(catch Throwable e
(log/error (str "! " (.getMessage e)))))))
(defn comment-out-text [s & [stuffer]]
(->> s
(cuerdas/lines)
(map #(str "// " stuffer %))
(cuerdas/unlines)))
; taken from: -tools/blob/dcc9853514756f2f4fc3bfdfdba45abffd94c5dd/src/clojure/tools/file_utils.clj#L83
(defn recursive-delete [directory]
(if (.isDirectory directory)
(when (reduce #(and %1 (recursive-delete %2)) true (.listFiles directory))
(.delete directory))
(.delete directory)))
(defn unwrap-snippets [content]
(let [counter (volatile! 0)
* (fn [match]
(vswap! counter inc)
(let [raw (string/replace (tools/decode (second match)) "\\n" "\n")
commented (comment-out-text raw " ")]
(str "\n"
"\n"
"// SNIPPET #" @counter ":\n"
commented "\n"
"// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
"\n"
"\n")))]
(string/replace content #"console\.log\(['\"]-12345-SNIPPET:(.*?)-54321-['\"]\);" *)))
(defn replace-tagged-literals [content]
(let [counter (volatile! 0)
* (fn [match]
(vswap! counter inc)
(let [name (nth match 1)]
(str "<" name "#" @counter ">")))]
(string/replace content #"#object\[cljs\.tagged_literals\.(.*?) 0x(.*?) \"cljs\.tagged_literals\.(.*?)@(.*?)\"]" *)))
(defn post-process-code [code]
(let [unwrapped-code (-> code
(unwrap-snippets)
(replace-tagged-literals))
[stabilized-code normalizer-state] (-> [unwrapped-code (make-empty-normalizer-state)]
(normalize-identifiers)
(normalize-gensyms)
(normalize-twins)
(normalize-inlines)
(linearize-numbering)
(drop-multi-dollars)
(drop-leading-dollars)
(humanize-clearcut-ns)
(humanize-goog-ns)
(humanize-cljs-core-ns))]
(log/debug "normalizer state:\n" (pprint-str normalizer-state 10000))
stabilized-code))
(defn silent-slurp [path]
(try
(slurp path)
(catch Throwable _
"")))
(defn make-build-filter [filter]
(if (empty? filter)
(constantly false)
(fn [name]
(let [parts (string/split filter #"\s")
* (fn [part]
(re-find (re-pattern part) name))]
(not (some * parts))))))
(def get-build-filter (memoize make-build-filter))
(defn print-cause-chain [tr]
(clojure.stacktrace/print-throwable tr)
(println)
(when-let [cause (.getCause tr)]
(print "Caused by: ")
(recur cause)))
(defn replace-absolute-paths [text]
(-> text
(string/replace #"(\s)/.*?/test/src/" "$1<absolute-path>/test/src/")
(string/replace #"(\s)/.*?/src/lib/" "$1<absolute-path>/src/lib/")))
(defn post-process-compiler-output [text]
(-> text
(replace-absolute-paths)))
| null | https://raw.githubusercontent.com/binaryage/clearcut/7f44705cd8743f8679199cb78a215487eb411ed4/test/src/circus/clearcut/circus/utils.clj | clojure | black on black background should be displayed as gray
we want to be compatible with "copy transcript!" button which copies to clipboard with extra new-line
taken from: -tools/blob/dcc9853514756f2f4fc3bfdfdba45abffd94c5dd/src/clojure/tools/file_utils.clj#L83 | (ns clearcut.circus.utils
(:require [clojure.java.io :as io]
[clojure.string :as string]
[cuerdas.core :as cuerdas]
[clansi]
[clojure.java.shell :as shell]
[clojure.tools.logging :as log]
[clojure.pprint :refer [pprint]]
[clearcut.tools :as tools])
(:import (java.util.regex Matcher Pattern)))
(defn produce-diff [path1 path2]
(let [options-args ["-U" "5"]
paths-args [path1 path2]]
(try
(let [result (apply shell/sh "colordiff" (concat options-args paths-args))]
(if-not (empty? (:err result))
(clansi/style (str "! " (:err result)) :red)
(cuerdas/rtrim (:out result))))
(catch Throwable e
(clansi/style (str "! " (.getMessage e)) :red)))))
(defn js-beautify-version []
(let [options-args ["--version"]]
(try
(let [result (apply shell/sh "js-beautify" options-args)]
(if-not (empty? (:err result))
(clansi/style (str "! " (:err result)) :red)
(cuerdas/rtrim (:out result))))
(catch Throwable e
(clansi/style (str "! " (.getMessage e)) :red)))))
(defn dim-text [text]
(defn get-canonical-line [line]
(string/trimr line))
(defn append-nl [text]
(str text "\n"))
(defn get-canonical-transcript [transcript]
(let [s (->> transcript
(cuerdas/lines)
(map get-canonical-line)
(cuerdas/unlines)
(string/replace s #"\n\n+" "\n\n")))
(defn extract-relevant-output [content]
(let [separator (tools/get-arena-separator)]
(if-let [separator-index (string/last-index-of content separator)]
(let [semicolon-index (or (string/index-of content ";" separator-index) separator-index)
relevant-content (.substring content (+ semicolon-index 1))]
relevant-content))))
(defn make-empty-normalizer-state []
{:counter 1
:counters {}
:identifiers {}
:mappings {}})
(defn get-counter [normalizer-state]
(:counter normalizer-state))
(defn get-mapping [normalizer-state name]
(get-in normalizer-state [:mappings name]))
(defn get-counter-for-name [normalizer-state name]
(get-in normalizer-state [:counters name]))
(defn register-mapping [normalizer-state name replacement]
(-> normalizer-state
(update :counter inc)
(update :mappings assoc name replacement)))
(defn register-counter [normalizer-state name identifier]
(let [x (fn [state]
(let [assigned-number (get-in state [:identifiers identifier])]
(assoc-in state [:counters name] assigned-number)))]
(-> normalizer-state
(update-in [:identifiers identifier] (fn [c] (inc (or c 0))))
(x))))
(defn register-mapping-if-needed [normalizer-state name replacement]
(if (get-mapping normalizer-state name)
normalizer-state
(register-mapping normalizer-state name replacement)))
(defn register-counter-if-needed [normalizer-state name identifier]
(if (get-counter-for-name normalizer-state name)
normalizer-state
(register-counter normalizer-state name identifier)))
(defn normalize-identifiers [[content normalizer-state]]
"The goal here is to rename all generated $<number>$ identifiers with stable numbering."
(let [* (fn [[content normalizer-state] match]
(let [needle (first match)
replacement (str (get-counter normalizer-state) (nth match 2))
new-normalizer-state (register-mapping-if-needed normalizer-state needle replacement)
new-content (string/replace content needle (get-mapping new-normalizer-state needle))]
[new-content new-normalizer-state]))]
(reduce * [content normalizer-state] (re-seq #"(\d+)(\$|__)" content))))
(defn normalize-gensyms [[content normalizer-state]]
"The goal here is to rename all generated name<NUM> identifiers with stable numbering."
(let [* (fn [[content normalizer-state] match]
(if (> (Long/parseLong (first match)) 1000)
(let [needle (first match)
replacement (str (get-counter normalizer-state))
new-normalizer-state (register-mapping-if-needed normalizer-state needle replacement)
new-content (string/replace content needle (get-mapping new-normalizer-state needle))]
[new-content new-normalizer-state])
[content normalizer-state]))]
(reduce * [content normalizer-state] (re-seq #"(\d+)" content))))
(defn normalize-twins [[content normalizer-state]]
"The goal here is to rename all generated <NUM>_<NUM> identifiers with stable numbering."
(let [* (fn [[content normalizer-state] needle]
(let [replacement (str (get-counter normalizer-state))
new-normalizer-state (register-mapping-if-needed normalizer-state needle replacement)
new-content (string/replace content needle (get-mapping new-normalizer-state needle))]
[new-content new-normalizer-state]))]
(reduce * [content normalizer-state] (re-seq #"\d+_\d+" content))))
(defn normalize-inlines [[content normalizer-state]]
"The goal here is to rename all generated <NUM>$$inline_<NUM> identifiers with stable numbering."
(let [* (fn [[content normalizer-state] needle]
(let [replacement (str (get-counter normalizer-state))
new-normalizer-state (register-mapping-if-needed normalizer-state needle replacement)
new-content (string/replace content needle (get-mapping new-normalizer-state needle))]
[new-content new-normalizer-state]))]
(reduce * [content normalizer-state] (re-seq #"\d+\$\$inline_\d+" content))))
(defn linearize-numbering [[content normalizer-state]]
"The goal here is to rename all generated <IDENTIFIER>_<NUM> to linear numbering for each distinct identifier."
(let [names (distinct (re-seq #"[a-zA-Z0-9_$]+_\d+" content))
* (fn [[content normalizer-state] name]
(let [group (re-matches #"([a-zA-Z0-9_$]+_)(\d+)" name)
identifier (nth group 1)
new-normalizer-state (register-counter-if-needed normalizer-state name identifier)
$ $ $ is a marker so we do n't conflict with name candidates for future replacement
we want to prevent replacing partial matches , eg . to mess with id_100
replacement (str (Matcher/quoteReplacement massaged-name) "$1")
new-content (string/replace content pattern replacement)]
[new-content new-normalizer-state]))
+ (fn [[content normalizer-state] name]
(let [group (re-matches #"([a-zA-Z0-9_$]+_)(\d+)" name)
identifier (nth group 1)
new-content (string/replace content (str identifier "$$$") identifier)]
[new-content normalizer-state]))]
(reduce + (reduce * [content normalizer-state] names) names)))
(defn drop-multi-dollars [[content normalizer-state]]
[(string/replace content #"\$\$+" "") normalizer-state])
(defn drop-leading-dollars [[content normalizer-state]]
[(string/replace content #"([^0-9a-zA-Z_])\$" "$1") normalizer-state])
(defn humanize-clearcut-ns [[content normalizer-state]]
[(string/replace content #"clearcut\$(.*?)\$" "clearcut.$1.") normalizer-state])
(defn humanize-cljs-core-ns [[content normalizer-state]]
[(string/replace content #"cljs\$core\$" "cljs.core.") normalizer-state])
(defn humanize-goog-ns [[content normalizer-state]]
[(string/replace content #"goog\$(.*?)\$" "goog.$1.") normalizer-state])
(defn safe-spit [path content]
(io/make-parents path)
(spit path content))
(defn pprint-str [v & [length level]]
(with-out-str
(binding [*print-level* (or level 10)
*print-length* (or length 10)]
(pprint v))))
(defn beautify-js! [path]
(log/debug (str "Beautify JS at '" path "'"))
(let [options-args ["-n" "-s" "2"]
paths-args ["-f" path "-o" path]]
(try
(let [result (apply shell/sh "js-beautify" (concat options-args paths-args))]
(if-not (empty? (:err result))
(log/error (str "! " (:err result)))))
(catch Throwable e
(log/error (str "! " (.getMessage e)))))))
(defn comment-out-text [s & [stuffer]]
(->> s
(cuerdas/lines)
(map #(str "// " stuffer %))
(cuerdas/unlines)))
(defn recursive-delete [directory]
(if (.isDirectory directory)
(when (reduce #(and %1 (recursive-delete %2)) true (.listFiles directory))
(.delete directory))
(.delete directory)))
(defn unwrap-snippets [content]
(let [counter (volatile! 0)
* (fn [match]
(vswap! counter inc)
(let [raw (string/replace (tools/decode (second match)) "\\n" "\n")
commented (comment-out-text raw " ")]
(str "\n"
"\n"
"// SNIPPET #" @counter ":\n"
commented "\n"
"// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
"\n"
"\n")))]
(string/replace content #"console\.log\(['\"]-12345-SNIPPET:(.*?)-54321-['\"]\);" *)))
(defn replace-tagged-literals [content]
(let [counter (volatile! 0)
* (fn [match]
(vswap! counter inc)
(let [name (nth match 1)]
(str "<" name "#" @counter ">")))]
(string/replace content #"#object\[cljs\.tagged_literals\.(.*?) 0x(.*?) \"cljs\.tagged_literals\.(.*?)@(.*?)\"]" *)))
(defn post-process-code [code]
(let [unwrapped-code (-> code
(unwrap-snippets)
(replace-tagged-literals))
[stabilized-code normalizer-state] (-> [unwrapped-code (make-empty-normalizer-state)]
(normalize-identifiers)
(normalize-gensyms)
(normalize-twins)
(normalize-inlines)
(linearize-numbering)
(drop-multi-dollars)
(drop-leading-dollars)
(humanize-clearcut-ns)
(humanize-goog-ns)
(humanize-cljs-core-ns))]
(log/debug "normalizer state:\n" (pprint-str normalizer-state 10000))
stabilized-code))
(defn silent-slurp [path]
(try
(slurp path)
(catch Throwable _
"")))
(defn make-build-filter [filter]
(if (empty? filter)
(constantly false)
(fn [name]
(let [parts (string/split filter #"\s")
* (fn [part]
(re-find (re-pattern part) name))]
(not (some * parts))))))
(def get-build-filter (memoize make-build-filter))
(defn print-cause-chain [tr]
(clojure.stacktrace/print-throwable tr)
(println)
(when-let [cause (.getCause tr)]
(print "Caused by: ")
(recur cause)))
(defn replace-absolute-paths [text]
(-> text
(string/replace #"(\s)/.*?/test/src/" "$1<absolute-path>/test/src/")
(string/replace #"(\s)/.*?/src/lib/" "$1<absolute-path>/src/lib/")))
(defn post-process-compiler-output [text]
(-> text
(replace-absolute-paths)))
|
504266b400bea9cae69259e8112c3c81bc2aaa406804d17993733c9c8317195f | mpickering/apply-refact | Naming3.hs | data Yes = Foo {bar_cap :: Int} | null | https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Naming3.hs | haskell | data Yes = Foo {bar_cap :: Int} |
|
0589e6addd9ee7524d3aff9f5bfdc2bb02e52bdc894e768460658dd4d745607f | shmookey/solpb | StructsSpec.hs | {-# LANGUAGE OverloadedStrings #-}
module Spec.Proto.StructsSpec where
import Prelude hiding (fail)
import Data.Text (Text, pack, unpack)
import Data.Semigroup ((<>))
import Data.Foldable (toList)
import Data.Sequence (fromList)
import Text.ProtocolBuffers.Basic (uFromString, uToString)
import qualified Data.Sequence as Seq
import qualified Data.ByteString.Lazy.Char8 as BL8
import qualified Data.Text as T
import Control.Monad.Resultant
import qualified Generator
import Util.ReSpec
import Util.Protobuf
import Util.Solidity
import Util.TestGen
import Gen.Structs.Structs
import Gen.Structs.Structs.In1
import Gen.Structs.Structs.In1.In1_1
import Gen.Structs.Structs.In1.In1_2
import Gen.Structs.Structs.In2
import Gen.Structs.Ext
tests :: Spec ()
tests = spec "StructsSpec" 2 $
let
msg = Structs
{ listA = fromList
[ In2
{ uints = fromList
[ In1_1 { x = 94, y = 38 }
, In1_1 { x = 72, y = 21 }
]
, strings = fromList
[ In1_2 { s = uFromString "foo" }
, In1_2 { s = uFromString "bar" }
]
}
, In2
{ uints = fromList
[ In1_1 { x = 37, y = 15 }
, In1_1 { x = 99, y = 71 }
]
, strings = fromList
[ In1_2 { s = uFromString "abc" }
, In1_2 { s = uFromString "xyz" }
]
}
]
, listB = fromList
[ Ext { z = 56 }
, Ext { z = 43 }
]
}
testContractSrc = pack
$ "contract StructsSpec { \n"
++ " function testDecode(bytes bs) returns (bool) { \n"
++ " StructsCodec.Structs memory x = StructsCodec.decode(bs); \n"
++ " string memory foo = 'foo'; \n"
++ " string memory bar = 'bar'; \n"
++ " string memory abc = 'abc'; \n"
++ " string memory xyz = 'xyz'; \n"
++ " if(x.listA.length != 2) throw; \n"
++ " if(x.listA[0].uints.length != 2) throw; \n"
++ " if(x.listA[0].strings.length != 2) throw; \n"
++ " if(x.listA[1].uints.length != 2) throw; \n"
++ " if(x.listA[1].strings.length != 2) throw; \n"
++ " if(x.listB.length != 2) throw; \n"
++ " if(x.listA[0].uints[0].x != 94) throw; \n"
++ " if(x.listA[0].uints[0].y != 38) throw; \n"
++ " if(x.listA[0].uints[1].x != 72) throw; \n"
++ " if(x.listA[0].uints[1].y != 21) throw; \n"
++ " if(!strcmp(x.listA[0].strings[0].s, foo)) throw; \n"
++ " if(!strcmp(x.listA[0].strings[1].s, bar)) throw; \n"
++ " if(x.listA[1].uints[0].x != 37) throw; \n"
++ " if(x.listA[1].uints[0].y != 15) throw; \n"
++ " if(x.listA[1].uints[1].x != 99) throw; \n"
++ " if(x.listA[1].uints[1].y != 71) throw; \n"
++ " if(!strcmp(x.listA[1].strings[0].s, abc)) throw; \n"
++ " if(!strcmp(x.listA[1].strings[1].s, xyz)) throw; \n"
++ " if(x.listB[0].z != 56) throw; \n"
++ " if(x.listB[1].z != 43) throw; \n"
++ " return true; \n"
++ " } \n"
++ " function testEncode() returns (bytes) { \n"
++ " StructsCodec.Structs memory x; \n"
++ " x.listA = new Structs_In2Codec.Structs_In2[](2); \n"
++ " x.listA[0].uints = new Structs_In1_In1_1Codec.Structs_In1_In1_1[](2); \n"
++ " x.listA[0].strings = new Structs_In1_In1_2Codec.Structs_In1_In1_2[](2); \n"
++ " x.listA[1].uints = new Structs_In1_In1_1Codec.Structs_In1_In1_1[](2); \n"
++ " x.listA[1].strings = new Structs_In1_In1_2Codec.Structs_In1_In1_2[](2); \n"
++ " x.listB = new ExtCodec.Ext[](2); \n"
++ " x.listA[0].uints[0].x = 94; \n"
++ " x.listA[0].uints[0].y = 38; \n"
++ " x.listA[0].uints[1].x = 72; \n"
++ " x.listA[0].uints[1].y = 21; \n"
++ " x.listA[0].strings[0].s = 'foo'; \n"
++ " x.listA[0].strings[1].s = 'bar'; \n"
++ " x.listA[1].uints[0].x = 37; \n"
++ " x.listA[1].uints[0].y = 15; \n"
++ " x.listA[1].uints[1].x = 99; \n"
++ " x.listA[1].uints[1].y = 71; \n"
++ " x.listA[1].strings[0].s = 'abc'; \n"
++ " x.listA[1].strings[1].s = 'xyz'; \n"
++ " x.listB[0].z = 56; \n"
++ " x.listB[1].z = 43; \n"
++ " bytes memory bs = StructsCodec.encode(x); \n"
++ " return bs; \n"
++ " } \n"
++ " function strcmp(string a, string b) returns (bool) { \n"
++ " bytes memory aa = bytes(a); \n"
++ " bytes memory bb = bytes(b); \n"
++ " for(uint i=0; i<aa.length; i++) \n"
++ " if(aa[i] != bb[i]) return false; \n"
++ " return true; \n"
++ " } \n"
++ "} \n"
encoded = hexEncode msg
in do
(struct, structs) <- loadStruct "Structs.proto" "Structs"
libSrc <- solpb $ Generator.generate structs
contract <- compile "StructsSpec" $ testContractSrc <> libSrc
test "Decode a message with a complex nested structure" $ do
runEVM contract $ callDataWithBytes "testDecode" encoded
return ()
test "Encode a message with a complex nested structure" $ do
encodeOutput <- runEVM contract $ callDataNoArgs "testEncode"
let result = extractReturnedBytes encodeOutput
if result /= encoded
then fail . unpack $ "Encoding error. Expected " <> encoded <> " but got " <> result
else return ()
| null | https://raw.githubusercontent.com/shmookey/solpb/4263050f9436e0a1d541ac99ab52970e9c2132c6/test/Spec/Proto/StructsSpec.hs | haskell | # LANGUAGE OverloadedStrings # |
module Spec.Proto.StructsSpec where
import Prelude hiding (fail)
import Data.Text (Text, pack, unpack)
import Data.Semigroup ((<>))
import Data.Foldable (toList)
import Data.Sequence (fromList)
import Text.ProtocolBuffers.Basic (uFromString, uToString)
import qualified Data.Sequence as Seq
import qualified Data.ByteString.Lazy.Char8 as BL8
import qualified Data.Text as T
import Control.Monad.Resultant
import qualified Generator
import Util.ReSpec
import Util.Protobuf
import Util.Solidity
import Util.TestGen
import Gen.Structs.Structs
import Gen.Structs.Structs.In1
import Gen.Structs.Structs.In1.In1_1
import Gen.Structs.Structs.In1.In1_2
import Gen.Structs.Structs.In2
import Gen.Structs.Ext
tests :: Spec ()
tests = spec "StructsSpec" 2 $
let
msg = Structs
{ listA = fromList
[ In2
{ uints = fromList
[ In1_1 { x = 94, y = 38 }
, In1_1 { x = 72, y = 21 }
]
, strings = fromList
[ In1_2 { s = uFromString "foo" }
, In1_2 { s = uFromString "bar" }
]
}
, In2
{ uints = fromList
[ In1_1 { x = 37, y = 15 }
, In1_1 { x = 99, y = 71 }
]
, strings = fromList
[ In1_2 { s = uFromString "abc" }
, In1_2 { s = uFromString "xyz" }
]
}
]
, listB = fromList
[ Ext { z = 56 }
, Ext { z = 43 }
]
}
testContractSrc = pack
$ "contract StructsSpec { \n"
++ " function testDecode(bytes bs) returns (bool) { \n"
++ " StructsCodec.Structs memory x = StructsCodec.decode(bs); \n"
++ " string memory foo = 'foo'; \n"
++ " string memory bar = 'bar'; \n"
++ " string memory abc = 'abc'; \n"
++ " string memory xyz = 'xyz'; \n"
++ " if(x.listA.length != 2) throw; \n"
++ " if(x.listA[0].uints.length != 2) throw; \n"
++ " if(x.listA[0].strings.length != 2) throw; \n"
++ " if(x.listA[1].uints.length != 2) throw; \n"
++ " if(x.listA[1].strings.length != 2) throw; \n"
++ " if(x.listB.length != 2) throw; \n"
++ " if(x.listA[0].uints[0].x != 94) throw; \n"
++ " if(x.listA[0].uints[0].y != 38) throw; \n"
++ " if(x.listA[0].uints[1].x != 72) throw; \n"
++ " if(x.listA[0].uints[1].y != 21) throw; \n"
++ " if(!strcmp(x.listA[0].strings[0].s, foo)) throw; \n"
++ " if(!strcmp(x.listA[0].strings[1].s, bar)) throw; \n"
++ " if(x.listA[1].uints[0].x != 37) throw; \n"
++ " if(x.listA[1].uints[0].y != 15) throw; \n"
++ " if(x.listA[1].uints[1].x != 99) throw; \n"
++ " if(x.listA[1].uints[1].y != 71) throw; \n"
++ " if(!strcmp(x.listA[1].strings[0].s, abc)) throw; \n"
++ " if(!strcmp(x.listA[1].strings[1].s, xyz)) throw; \n"
++ " if(x.listB[0].z != 56) throw; \n"
++ " if(x.listB[1].z != 43) throw; \n"
++ " return true; \n"
++ " } \n"
++ " function testEncode() returns (bytes) { \n"
++ " StructsCodec.Structs memory x; \n"
++ " x.listA = new Structs_In2Codec.Structs_In2[](2); \n"
++ " x.listA[0].uints = new Structs_In1_In1_1Codec.Structs_In1_In1_1[](2); \n"
++ " x.listA[0].strings = new Structs_In1_In1_2Codec.Structs_In1_In1_2[](2); \n"
++ " x.listA[1].uints = new Structs_In1_In1_1Codec.Structs_In1_In1_1[](2); \n"
++ " x.listA[1].strings = new Structs_In1_In1_2Codec.Structs_In1_In1_2[](2); \n"
++ " x.listB = new ExtCodec.Ext[](2); \n"
++ " x.listA[0].uints[0].x = 94; \n"
++ " x.listA[0].uints[0].y = 38; \n"
++ " x.listA[0].uints[1].x = 72; \n"
++ " x.listA[0].uints[1].y = 21; \n"
++ " x.listA[0].strings[0].s = 'foo'; \n"
++ " x.listA[0].strings[1].s = 'bar'; \n"
++ " x.listA[1].uints[0].x = 37; \n"
++ " x.listA[1].uints[0].y = 15; \n"
++ " x.listA[1].uints[1].x = 99; \n"
++ " x.listA[1].uints[1].y = 71; \n"
++ " x.listA[1].strings[0].s = 'abc'; \n"
++ " x.listA[1].strings[1].s = 'xyz'; \n"
++ " x.listB[0].z = 56; \n"
++ " x.listB[1].z = 43; \n"
++ " bytes memory bs = StructsCodec.encode(x); \n"
++ " return bs; \n"
++ " } \n"
++ " function strcmp(string a, string b) returns (bool) { \n"
++ " bytes memory aa = bytes(a); \n"
++ " bytes memory bb = bytes(b); \n"
++ " for(uint i=0; i<aa.length; i++) \n"
++ " if(aa[i] != bb[i]) return false; \n"
++ " return true; \n"
++ " } \n"
++ "} \n"
encoded = hexEncode msg
in do
(struct, structs) <- loadStruct "Structs.proto" "Structs"
libSrc <- solpb $ Generator.generate structs
contract <- compile "StructsSpec" $ testContractSrc <> libSrc
test "Decode a message with a complex nested structure" $ do
runEVM contract $ callDataWithBytes "testDecode" encoded
return ()
test "Encode a message with a complex nested structure" $ do
encodeOutput <- runEVM contract $ callDataNoArgs "testEncode"
let result = extractReturnedBytes encodeOutput
if result /= encoded
then fail . unpack $ "Encoding error. Expected " <> encoded <> " but got " <> result
else return ()
|
2735069fc27bdfacba9995f3d213199bc008d91a3785e0a40ddf472417e39bbb | MinaProtocol/mina | persistent_frontier.ml | open Async_kernel
open Core
open Mina_base
open Mina_state
open Mina_block
open Frontier_base
module Database = Database
module type CONTEXT = sig
val logger : Logger.t
val precomputed_values : Precomputed_values.t
val constraint_constants : Genesis_constants.Constraint_constants.t
val consensus_constants : Consensus.Constants.t
end
exception Invalid_genesis_state_hash of Mina_block.Validated.t
let construct_staged_ledger_at_root ~(precomputed_values : Precomputed_values.t)
~root_ledger ~root_transition ~root ~protocol_states ~logger =
let open Deferred.Or_error.Let_syntax in
let open Root_data.Minimal in
let blockchain_state =
root_transition |> Mina_block.Validated.forget |> With_hash.data
|> Mina_block.header |> Mina_block.Header.protocol_state
|> Protocol_state.blockchain_state
in
let pending_coinbases = pending_coinbase root in
let scan_state = scan_state root in
let protocol_states_map =
List.fold protocol_states ~init:State_hash.Map.empty
~f:(fun acc protocol_state ->
Map.add_exn acc ~key:(Protocol_state.hashes protocol_state).state_hash
~data:protocol_state )
in
let get_state hash =
match Map.find protocol_states_map hash with
| None ->
[%log error]
~metadata:[ ("state_hash", State_hash.to_yojson hash) ]
"Protocol state (for scan state transactions) for $state_hash not \
found when loading persisted transition frontier" ;
Or_error.errorf
!"Protocol state (for scan state transactions) for \
%{sexp:State_hash.t} not found when loading persisted transition \
frontier"
hash
| Some protocol_state ->
Ok protocol_state
in
let mask = Mina_ledger.Ledger.of_database root_ledger in
let local_state = Blockchain_state.snarked_local_state blockchain_state in
let staged_ledger_hash =
Blockchain_state.staged_ledger_hash blockchain_state
in
let%bind staged_ledger =
Staged_ledger.of_scan_state_pending_coinbases_and_snarked_ledger_unchecked
~snarked_local_state:local_state ~snarked_ledger:mask ~scan_state
~constraint_constants:precomputed_values.constraint_constants
~pending_coinbases
~expected_merkle_root:(Staged_ledger_hash.ledger_hash staged_ledger_hash)
~get_state
in
let is_genesis =
Mina_block.Validated.header root_transition
|> Header.protocol_state |> Protocol_state.consensus_state
|> Consensus.Data.Consensus_state.is_genesis_state
in
let constructed_staged_ledger_hash = Staged_ledger.hash staged_ledger in
if
is_genesis
|| Staged_ledger_hash.equal staged_ledger_hash
constructed_staged_ledger_hash
then Deferred.return (Ok staged_ledger)
else
Deferred.return
(Or_error.errorf
!"Constructed staged ledger %{sexp: Staged_ledger_hash.t} did not \
match the staged ledger hash in the protocol state %{sexp: \
Staged_ledger_hash.t}"
constructed_staged_ledger_hash staged_ledger_hash )
module rec Instance_type : sig
type t =
{ db : Database.t; mutable sync : Sync.t option; factory : Factory_type.t }
end =
Instance_type
and Factory_type : sig
type t =
{ logger : Logger.t
; directory : string
; verifier : Verifier.t
; time_controller : Block_time.Controller.t
; mutable instance : Instance_type.t option
}
end =
Factory_type
open Instance_type
open Factory_type
module Instance = struct
type t = Instance_type.t
let create factory =
let db =
Database.create ~logger:factory.logger ~directory:factory.directory
in
{ db; sync = None; factory }
let assert_no_sync t =
if Option.is_some t.sync then Error `Sync_cannot_be_running else Ok ()
let assert_sync t ~f =
match t.sync with
| None ->
return (Error `Sync_must_be_running)
| Some sync ->
f sync
let start_sync ~constraint_constants t ~persistent_root_instance =
let open Result.Let_syntax in
let%map () = assert_no_sync t in
t.sync <-
Some
(Sync.create ~constraint_constants ~logger:t.factory.logger
~time_controller:t.factory.time_controller ~db:t.db
~persistent_root_instance )
let stop_sync t =
let open Deferred.Let_syntax in
assert_sync t ~f:(fun sync ->
let%map () = Sync.close sync in
t.sync <- None ;
Ok () )
let notify_sync t ~diffs =
assert_sync t ~f:(fun sync ->
Sync.notify sync ~diffs ; Deferred.Result.return () )
let destroy t =
let open Deferred.Let_syntax in
[%log' trace t.factory.logger]
"Destroying transition frontier persistence instance" ;
let%map () =
if Option.is_some t.sync then
stop_sync t
>>| Fn.compose Result.ok_or_failwith
(Result.map_error ~f:(Fn.const "impossible"))
else return ()
in
Database.close t.db ;
t.factory.instance <- None
let factory { factory; _ } = factory
let check_database t = Database.check t.db
let get_root_transition t =
let open Result.Let_syntax in
Database.get_root_hash t.db
>>= Database.get_transition t.db
|> Result.map_error ~f:Database.Error.message
let fast_forward t target_root :
(unit, [> `Failure of string | `Bootstrap_required ]) Result.t =
let open Root_identifier.Stable.Latest in
let open Result.Let_syntax in
let%bind () = assert_no_sync t in
let lift_error r msg = Result.map_error r ~f:(Fn.const (`Failure msg)) in
let%bind root =
lift_error (Database.get_root t.db) "failed to get root hash"
in
let root_hash = Root_data.Minimal.hash root in
if State_hash.equal root_hash target_root.state_hash then
(* If the target hash is already the root hash, no fast forward required, but we should check the frontier hash. *)
Ok ()
else (
[%log' warn t.factory.logger]
~metadata:
[ ("current_root", State_hash.to_yojson root_hash)
; ("target_root", State_hash.to_yojson target_root.state_hash)
]
"Cannot fast forward persistent frontier's root: bootstrap is required \
($current_root --> $target_root)" ;
Error `Bootstrap_required )
let load_full_frontier t ~context:(module Context : CONTEXT) ~root_ledger
~consensus_local_state ~max_length ~ignore_consensus_local_state
~persistent_root_instance =
let open Context in
let open Deferred.Result.Let_syntax in
let downgrade_transition transition genesis_state_hash :
( Mina_block.almost_valid_block
, [ `Invalid_genesis_protocol_state ] )
Result.t =
(* we explicitly re-validate the genesis protocol state here to prevent X-version bugs *)
transition |> Mina_block.Validated.remember
|> Validation.reset_staged_ledger_diff_validation
|> Validation.reset_genesis_protocol_state_validation
|> Validation.validate_genesis_protocol_state ~genesis_state_hash
in
let%bind () = Deferred.return (assert_no_sync t) in
(* read basic information from the database *)
let%bind root, root_transition, best_tip, protocol_states, root_hash =
(let open Result.Let_syntax in
let%bind root = Database.get_root t.db in
let root_hash = Root_data.Minimal.hash root in
let%bind root_transition = Database.get_transition t.db root_hash in
let%bind best_tip = Database.get_best_tip t.db in
let%map protocol_states =
Database.get_protocol_states_for_root_scan_state t.db
in
(root, root_transition, best_tip, protocol_states, root_hash))
|> Result.map_error ~f:(fun err ->
`Failure (Database.Error.not_found_message err) )
|> Deferred.return
in
let root_genesis_state_hash =
root_transition |> Mina_block.Validated.forget |> With_hash.data
|> Mina_block.header |> Mina_block.Header.protocol_state
|> Protocol_state.genesis_state_hash
in
(* construct the root staged ledger in memory *)
let%bind root_staged_ledger =
let open Deferred.Let_syntax in
match%map
construct_staged_ledger_at_root ~precomputed_values ~root_ledger
~root_transition ~root ~protocol_states ~logger:t.factory.logger
with
| Error err ->
Error (`Failure (Error.to_string_hum err))
| Ok staged_ledger ->
Ok staged_ledger
in
(* initialize the new in memory frontier and extensions *)
let frontier =
Full_frontier.create
~context:(module Context)
~time_controller:t.factory.time_controller
~root_data:
{ transition = root_transition
; staged_ledger = root_staged_ledger
; protocol_states =
List.map protocol_states
~f:(With_hash.of_data ~hash_data:Protocol_state.hashes)
}
~root_ledger:
(Mina_ledger.Ledger.Any_ledger.cast
(module Mina_ledger.Ledger.Db)
root_ledger )
~consensus_local_state ~max_length ~persistent_root_instance
in
let%bind extensions =
Deferred.map
(Extensions.create ~logger:t.factory.logger frontier)
~f:Result.return
in
let apply_diff diff =
let (`New_root_and_diffs_with_mutants (_, diffs_with_mutants)) =
Full_frontier.apply_diffs frontier [ diff ] ~has_long_catchup_job:false
~enable_epoch_ledger_sync:
( if ignore_consensus_local_state then `Disabled
else `Enabled root_ledger )
in
Extensions.notify extensions ~frontier ~diffs_with_mutants
|> Deferred.map ~f:Result.return
in
(* crawl through persistent frontier and load transitions into in memory frontier *)
let%bind () =
Deferred.map
(Database.crawl_successors t.db root_hash
~init:(Full_frontier.root frontier) ~f:(fun parent transition ->
let%bind transition =
match
downgrade_transition transition root_genesis_state_hash
with
| Ok t ->
Deferred.Result.return t
| Error `Invalid_genesis_protocol_state ->
Error (`Fatal_error (Invalid_genesis_state_hash transition))
|> Deferred.return
in
(* we're loading transitions from persistent storage,
don't assign a timestamp
*)
let transition_receipt_time = None in
let%bind breadcrumb =
Breadcrumb.build ~skip_staged_ledger_verification:`All
~logger:t.factory.logger ~precomputed_values
~verifier:t.factory.verifier
~trust_system:(Trust_system.null ()) ~parent ~transition
~sender:None ~transition_receipt_time ()
in
let%map () = apply_diff Diff.(E (New_node (Full breadcrumb))) in
breadcrumb ) )
~f:
(Result.map_error ~f:(function
| `Crawl_error err ->
let msg =
match err with
| `Fatal_error exn ->
"fatal error -- " ^ Exn.to_string exn
| `Invalid_staged_ledger_diff err
| `Invalid_staged_ledger_hash err ->
"staged ledger diff application failed -- "
^ Error.to_string_hum err
in
`Failure
( "error rebuilding transition frontier from persistence: "
^ msg )
| `Not_found _ as err ->
`Failure (Database.Error.not_found_message err) ) )
in
let%map () = apply_diff Diff.(E (Best_tip_changed best_tip)) in
(frontier, extensions)
end
type t = Factory_type.t
let create ~logger ~verifier ~time_controller ~directory =
{ logger; verifier; time_controller; directory; instance = None }
let destroy_database_exn t =
assert (Option.is_none t.instance) ;
File_system.remove_dir t.directory
let create_instance_exn t =
assert (Option.is_none t.instance) ;
let instance = Instance.create t in
t.instance <- Some instance ;
instance
let with_instance_exn t ~f =
let instance = create_instance_exn t in
let x = f instance in
let%map () = Instance.destroy instance in
x
let reset_database_exn t ~root_data ~genesis_state_hash =
let open Root_data.Limited in
let open Deferred.Let_syntax in
let root_transition = transition root_data in
[%log' info t.logger]
~metadata:
[ ( "state_hash"
, State_hash.to_yojson
@@ Mina_block.Validated.state_hash root_transition )
]
"Resetting transition frontier database to new root" ;
let%bind () = destroy_database_exn t in
with_instance_exn t ~f:(fun instance ->
Database.initialize instance.db ~root_data ;
(* sanity check database after initialization on debug builds *)
Debug_assert.debug_assert (fun () ->
ignore
( Database.check instance.db ~genesis_state_hash
|> Result.map_error ~f:(function
| `Invalid_version ->
"invalid version"
| `Not_initialized ->
"not initialized"
| `Genesis_state_mismatch _ ->
"genesis state mismatch"
| `Corrupt err ->
Database.Error.message err )
|> Result.ok_or_failwith
: Frozen_ledger_hash.t ) ) )
| null | https://raw.githubusercontent.com/MinaProtocol/mina/57e2ea1b87fe1a24517e1c62f51cc59fe9bc87cd/src/lib/transition_frontier/persistent_frontier/persistent_frontier.ml | ocaml | If the target hash is already the root hash, no fast forward required, but we should check the frontier hash.
we explicitly re-validate the genesis protocol state here to prevent X-version bugs
read basic information from the database
construct the root staged ledger in memory
initialize the new in memory frontier and extensions
crawl through persistent frontier and load transitions into in memory frontier
we're loading transitions from persistent storage,
don't assign a timestamp
sanity check database after initialization on debug builds | open Async_kernel
open Core
open Mina_base
open Mina_state
open Mina_block
open Frontier_base
module Database = Database
module type CONTEXT = sig
val logger : Logger.t
val precomputed_values : Precomputed_values.t
val constraint_constants : Genesis_constants.Constraint_constants.t
val consensus_constants : Consensus.Constants.t
end
exception Invalid_genesis_state_hash of Mina_block.Validated.t
let construct_staged_ledger_at_root ~(precomputed_values : Precomputed_values.t)
~root_ledger ~root_transition ~root ~protocol_states ~logger =
let open Deferred.Or_error.Let_syntax in
let open Root_data.Minimal in
let blockchain_state =
root_transition |> Mina_block.Validated.forget |> With_hash.data
|> Mina_block.header |> Mina_block.Header.protocol_state
|> Protocol_state.blockchain_state
in
let pending_coinbases = pending_coinbase root in
let scan_state = scan_state root in
let protocol_states_map =
List.fold protocol_states ~init:State_hash.Map.empty
~f:(fun acc protocol_state ->
Map.add_exn acc ~key:(Protocol_state.hashes protocol_state).state_hash
~data:protocol_state )
in
let get_state hash =
match Map.find protocol_states_map hash with
| None ->
[%log error]
~metadata:[ ("state_hash", State_hash.to_yojson hash) ]
"Protocol state (for scan state transactions) for $state_hash not \
found when loading persisted transition frontier" ;
Or_error.errorf
!"Protocol state (for scan state transactions) for \
%{sexp:State_hash.t} not found when loading persisted transition \
frontier"
hash
| Some protocol_state ->
Ok protocol_state
in
let mask = Mina_ledger.Ledger.of_database root_ledger in
let local_state = Blockchain_state.snarked_local_state blockchain_state in
let staged_ledger_hash =
Blockchain_state.staged_ledger_hash blockchain_state
in
let%bind staged_ledger =
Staged_ledger.of_scan_state_pending_coinbases_and_snarked_ledger_unchecked
~snarked_local_state:local_state ~snarked_ledger:mask ~scan_state
~constraint_constants:precomputed_values.constraint_constants
~pending_coinbases
~expected_merkle_root:(Staged_ledger_hash.ledger_hash staged_ledger_hash)
~get_state
in
let is_genesis =
Mina_block.Validated.header root_transition
|> Header.protocol_state |> Protocol_state.consensus_state
|> Consensus.Data.Consensus_state.is_genesis_state
in
let constructed_staged_ledger_hash = Staged_ledger.hash staged_ledger in
if
is_genesis
|| Staged_ledger_hash.equal staged_ledger_hash
constructed_staged_ledger_hash
then Deferred.return (Ok staged_ledger)
else
Deferred.return
(Or_error.errorf
!"Constructed staged ledger %{sexp: Staged_ledger_hash.t} did not \
match the staged ledger hash in the protocol state %{sexp: \
Staged_ledger_hash.t}"
constructed_staged_ledger_hash staged_ledger_hash )
module rec Instance_type : sig
type t =
{ db : Database.t; mutable sync : Sync.t option; factory : Factory_type.t }
end =
Instance_type
and Factory_type : sig
type t =
{ logger : Logger.t
; directory : string
; verifier : Verifier.t
; time_controller : Block_time.Controller.t
; mutable instance : Instance_type.t option
}
end =
Factory_type
open Instance_type
open Factory_type
module Instance = struct
type t = Instance_type.t
let create factory =
let db =
Database.create ~logger:factory.logger ~directory:factory.directory
in
{ db; sync = None; factory }
let assert_no_sync t =
if Option.is_some t.sync then Error `Sync_cannot_be_running else Ok ()
let assert_sync t ~f =
match t.sync with
| None ->
return (Error `Sync_must_be_running)
| Some sync ->
f sync
let start_sync ~constraint_constants t ~persistent_root_instance =
let open Result.Let_syntax in
let%map () = assert_no_sync t in
t.sync <-
Some
(Sync.create ~constraint_constants ~logger:t.factory.logger
~time_controller:t.factory.time_controller ~db:t.db
~persistent_root_instance )
let stop_sync t =
let open Deferred.Let_syntax in
assert_sync t ~f:(fun sync ->
let%map () = Sync.close sync in
t.sync <- None ;
Ok () )
let notify_sync t ~diffs =
assert_sync t ~f:(fun sync ->
Sync.notify sync ~diffs ; Deferred.Result.return () )
let destroy t =
let open Deferred.Let_syntax in
[%log' trace t.factory.logger]
"Destroying transition frontier persistence instance" ;
let%map () =
if Option.is_some t.sync then
stop_sync t
>>| Fn.compose Result.ok_or_failwith
(Result.map_error ~f:(Fn.const "impossible"))
else return ()
in
Database.close t.db ;
t.factory.instance <- None
let factory { factory; _ } = factory
let check_database t = Database.check t.db
let get_root_transition t =
let open Result.Let_syntax in
Database.get_root_hash t.db
>>= Database.get_transition t.db
|> Result.map_error ~f:Database.Error.message
let fast_forward t target_root :
(unit, [> `Failure of string | `Bootstrap_required ]) Result.t =
let open Root_identifier.Stable.Latest in
let open Result.Let_syntax in
let%bind () = assert_no_sync t in
let lift_error r msg = Result.map_error r ~f:(Fn.const (`Failure msg)) in
let%bind root =
lift_error (Database.get_root t.db) "failed to get root hash"
in
let root_hash = Root_data.Minimal.hash root in
if State_hash.equal root_hash target_root.state_hash then
Ok ()
else (
[%log' warn t.factory.logger]
~metadata:
[ ("current_root", State_hash.to_yojson root_hash)
; ("target_root", State_hash.to_yojson target_root.state_hash)
]
"Cannot fast forward persistent frontier's root: bootstrap is required \
($current_root --> $target_root)" ;
Error `Bootstrap_required )
let load_full_frontier t ~context:(module Context : CONTEXT) ~root_ledger
~consensus_local_state ~max_length ~ignore_consensus_local_state
~persistent_root_instance =
let open Context in
let open Deferred.Result.Let_syntax in
let downgrade_transition transition genesis_state_hash :
( Mina_block.almost_valid_block
, [ `Invalid_genesis_protocol_state ] )
Result.t =
transition |> Mina_block.Validated.remember
|> Validation.reset_staged_ledger_diff_validation
|> Validation.reset_genesis_protocol_state_validation
|> Validation.validate_genesis_protocol_state ~genesis_state_hash
in
let%bind () = Deferred.return (assert_no_sync t) in
let%bind root, root_transition, best_tip, protocol_states, root_hash =
(let open Result.Let_syntax in
let%bind root = Database.get_root t.db in
let root_hash = Root_data.Minimal.hash root in
let%bind root_transition = Database.get_transition t.db root_hash in
let%bind best_tip = Database.get_best_tip t.db in
let%map protocol_states =
Database.get_protocol_states_for_root_scan_state t.db
in
(root, root_transition, best_tip, protocol_states, root_hash))
|> Result.map_error ~f:(fun err ->
`Failure (Database.Error.not_found_message err) )
|> Deferred.return
in
let root_genesis_state_hash =
root_transition |> Mina_block.Validated.forget |> With_hash.data
|> Mina_block.header |> Mina_block.Header.protocol_state
|> Protocol_state.genesis_state_hash
in
let%bind root_staged_ledger =
let open Deferred.Let_syntax in
match%map
construct_staged_ledger_at_root ~precomputed_values ~root_ledger
~root_transition ~root ~protocol_states ~logger:t.factory.logger
with
| Error err ->
Error (`Failure (Error.to_string_hum err))
| Ok staged_ledger ->
Ok staged_ledger
in
let frontier =
Full_frontier.create
~context:(module Context)
~time_controller:t.factory.time_controller
~root_data:
{ transition = root_transition
; staged_ledger = root_staged_ledger
; protocol_states =
List.map protocol_states
~f:(With_hash.of_data ~hash_data:Protocol_state.hashes)
}
~root_ledger:
(Mina_ledger.Ledger.Any_ledger.cast
(module Mina_ledger.Ledger.Db)
root_ledger )
~consensus_local_state ~max_length ~persistent_root_instance
in
let%bind extensions =
Deferred.map
(Extensions.create ~logger:t.factory.logger frontier)
~f:Result.return
in
let apply_diff diff =
let (`New_root_and_diffs_with_mutants (_, diffs_with_mutants)) =
Full_frontier.apply_diffs frontier [ diff ] ~has_long_catchup_job:false
~enable_epoch_ledger_sync:
( if ignore_consensus_local_state then `Disabled
else `Enabled root_ledger )
in
Extensions.notify extensions ~frontier ~diffs_with_mutants
|> Deferred.map ~f:Result.return
in
let%bind () =
Deferred.map
(Database.crawl_successors t.db root_hash
~init:(Full_frontier.root frontier) ~f:(fun parent transition ->
let%bind transition =
match
downgrade_transition transition root_genesis_state_hash
with
| Ok t ->
Deferred.Result.return t
| Error `Invalid_genesis_protocol_state ->
Error (`Fatal_error (Invalid_genesis_state_hash transition))
|> Deferred.return
in
let transition_receipt_time = None in
let%bind breadcrumb =
Breadcrumb.build ~skip_staged_ledger_verification:`All
~logger:t.factory.logger ~precomputed_values
~verifier:t.factory.verifier
~trust_system:(Trust_system.null ()) ~parent ~transition
~sender:None ~transition_receipt_time ()
in
let%map () = apply_diff Diff.(E (New_node (Full breadcrumb))) in
breadcrumb ) )
~f:
(Result.map_error ~f:(function
| `Crawl_error err ->
let msg =
match err with
| `Fatal_error exn ->
"fatal error -- " ^ Exn.to_string exn
| `Invalid_staged_ledger_diff err
| `Invalid_staged_ledger_hash err ->
"staged ledger diff application failed -- "
^ Error.to_string_hum err
in
`Failure
( "error rebuilding transition frontier from persistence: "
^ msg )
| `Not_found _ as err ->
`Failure (Database.Error.not_found_message err) ) )
in
let%map () = apply_diff Diff.(E (Best_tip_changed best_tip)) in
(frontier, extensions)
end
type t = Factory_type.t
let create ~logger ~verifier ~time_controller ~directory =
{ logger; verifier; time_controller; directory; instance = None }
let destroy_database_exn t =
assert (Option.is_none t.instance) ;
File_system.remove_dir t.directory
let create_instance_exn t =
assert (Option.is_none t.instance) ;
let instance = Instance.create t in
t.instance <- Some instance ;
instance
let with_instance_exn t ~f =
let instance = create_instance_exn t in
let x = f instance in
let%map () = Instance.destroy instance in
x
let reset_database_exn t ~root_data ~genesis_state_hash =
let open Root_data.Limited in
let open Deferred.Let_syntax in
let root_transition = transition root_data in
[%log' info t.logger]
~metadata:
[ ( "state_hash"
, State_hash.to_yojson
@@ Mina_block.Validated.state_hash root_transition )
]
"Resetting transition frontier database to new root" ;
let%bind () = destroy_database_exn t in
with_instance_exn t ~f:(fun instance ->
Database.initialize instance.db ~root_data ;
Debug_assert.debug_assert (fun () ->
ignore
( Database.check instance.db ~genesis_state_hash
|> Result.map_error ~f:(function
| `Invalid_version ->
"invalid version"
| `Not_initialized ->
"not initialized"
| `Genesis_state_mismatch _ ->
"genesis state mismatch"
| `Corrupt err ->
Database.Error.message err )
|> Result.ok_or_failwith
: Frozen_ledger_hash.t ) ) )
|
f5a7281953c94ae91636774b0996173770f72fc8bf2101a29d1f65d151c7c083 | scicloj/notespace | nrepl.clj | (ns scicloj.notespace.v4.nrepl
(:require [nrepl.core :as nrepl]
[nrepl.middleware :as middleware]
[nrepl.middleware.print :as print]
[nrepl.transport :as transport]
[clojure.core.async :as async]
[scicloj.notespace.v4.events.pipeline :as v4.pipeline]
[scicloj.notespace.v4.log :as v4.log]
[scicloj.notespace.v4.path :as v4.path]
[scicloj.notespace.v4.state :as v4.state]
[scicloj.notespace.v4.config :as v4.config]))
(defn get-path-when-eval-buffer
[{:keys [op file-path code] :as request}]
(cond ;;
(= op "load-file")
file-path
;;
(and (= op "eval")
(re-matches #".*clojure.lang.Compiler/load.*" code))
(-> code
read-string
second
second
second
second
second
first)
;;
:else
nil))
(defn request->event [{:keys [id op file code] :as request}]
(when (#{"eval" "load-file"} op)
(let [path-when-eval-buffer (get-path-when-eval-buffer request)]
(when-not (some->> file
(re-matches #"\*cider-repl.*\*"))
(let [event-type (if path-when-eval-buffer
:scicloj.notespace.v4.events.handle/buffer-update
:scicloj.notespace.v4.events.handle/eval)
path (some-> (-> path-when-eval-buffer
(or file))
v4.path/real-path)]
(merge {:request-id id
:event/type event-type
:path path}
(when (= event-type :scicloj.notespace.v4.events.handle/eval)
{:code code})))))))
(defn handle-request [request]
(when-not (:ignore-nrepl? @v4.config/*config)
(some-> request
request->event
v4.pipeline/process-event)))
(defn handle-message [{:keys [id op] :as request}
{:keys [value err] :as message}]
(when-not (:ignore-nrepl? @v4.config/*config)
(when (= "eval" op)
(cond
;;
(contains? message :value)
(let [request-event (request->event request)]
(when (-> request-event :event/type (= :scicloj.notespace.v4.events.handle/eval))
(v4.pipeline/process-event
{:request-id id
:value value
:event/type :scicloj.notespace.v4.events.handle/value})))
;;
err
(let [request-event (request->event request)]
(when (-> request-event :event/type (= :scicloj.notespace.v4.events.handle/eval))
(v4.pipeline/process-event
{:request-id id
:err err
:event/type :scicloj.notespace.v4.events.handle/error})))
;;
(-> message :status :done)
(let [request-event (request->event request)]
(when (-> request-event :event/type (= :scicloj.notespace.v4.events.handle/eval))
(v4.pipeline/process-event
{:request-id id
:event/type :scicloj.notespace.v4.events.handle/done})))))))
(defn middleware [f]
(fn [request]
(handle-request request)
(-> request
(update :transport (fn [t]
(reify transport/Transport
(recv [req]
(transport/recv t))
(recv [req timeout]
(transport/recv t timeout))
(send [this message]
(handle-message request message)
(transport/send t message)
this))))
(f))))
(middleware/set-descriptor! #'middleware
{:requires #{#'print/wrap-print}
:expects #{"eval"}
:handles {}})
| null | https://raw.githubusercontent.com/scicloj/notespace/e8e583eb064412da32683bc8d18f97a43bdc9184/src/scicloj/notespace/v4/nrepl.clj | clojure | (ns scicloj.notespace.v4.nrepl
(:require [nrepl.core :as nrepl]
[nrepl.middleware :as middleware]
[nrepl.middleware.print :as print]
[nrepl.transport :as transport]
[clojure.core.async :as async]
[scicloj.notespace.v4.events.pipeline :as v4.pipeline]
[scicloj.notespace.v4.log :as v4.log]
[scicloj.notespace.v4.path :as v4.path]
[scicloj.notespace.v4.state :as v4.state]
[scicloj.notespace.v4.config :as v4.config]))
(defn get-path-when-eval-buffer
[{:keys [op file-path code] :as request}]
(= op "load-file")
file-path
(and (= op "eval")
(re-matches #".*clojure.lang.Compiler/load.*" code))
(-> code
read-string
second
second
second
second
second
first)
:else
nil))
(defn request->event [{:keys [id op file code] :as request}]
(when (#{"eval" "load-file"} op)
(let [path-when-eval-buffer (get-path-when-eval-buffer request)]
(when-not (some->> file
(re-matches #"\*cider-repl.*\*"))
(let [event-type (if path-when-eval-buffer
:scicloj.notespace.v4.events.handle/buffer-update
:scicloj.notespace.v4.events.handle/eval)
path (some-> (-> path-when-eval-buffer
(or file))
v4.path/real-path)]
(merge {:request-id id
:event/type event-type
:path path}
(when (= event-type :scicloj.notespace.v4.events.handle/eval)
{:code code})))))))
(defn handle-request [request]
(when-not (:ignore-nrepl? @v4.config/*config)
(some-> request
request->event
v4.pipeline/process-event)))
(defn handle-message [{:keys [id op] :as request}
{:keys [value err] :as message}]
(when-not (:ignore-nrepl? @v4.config/*config)
(when (= "eval" op)
(cond
(contains? message :value)
(let [request-event (request->event request)]
(when (-> request-event :event/type (= :scicloj.notespace.v4.events.handle/eval))
(v4.pipeline/process-event
{:request-id id
:value value
:event/type :scicloj.notespace.v4.events.handle/value})))
err
(let [request-event (request->event request)]
(when (-> request-event :event/type (= :scicloj.notespace.v4.events.handle/eval))
(v4.pipeline/process-event
{:request-id id
:err err
:event/type :scicloj.notespace.v4.events.handle/error})))
(-> message :status :done)
(let [request-event (request->event request)]
(when (-> request-event :event/type (= :scicloj.notespace.v4.events.handle/eval))
(v4.pipeline/process-event
{:request-id id
:event/type :scicloj.notespace.v4.events.handle/done})))))))
(defn middleware [f]
(fn [request]
(handle-request request)
(-> request
(update :transport (fn [t]
(reify transport/Transport
(recv [req]
(transport/recv t))
(recv [req timeout]
(transport/recv t timeout))
(send [this message]
(handle-message request message)
(transport/send t message)
this))))
(f))))
(middleware/set-descriptor! #'middleware
{:requires #{#'print/wrap-print}
:expects #{"eval"}
:handles {}})
|
|
0c5aa8133af37a470af3f0d1e57406ed1052e4ac4ecf41c020b9d7873aa37551 | oakes/Lightmod | dev.clj | (require
'[nightlight.core :as nightlight]
'[figwheel.main :as figwheel]
'[[[name]].server :refer [-main]])
(let [server (-main)
port (-> server meta :local-port)
url (str ":" port "/index.html")]
(println "Started app on" url)
(nightlight/start {:port 4000 :url url})
(figwheel/-main "--build" "dev"))
| null | https://raw.githubusercontent.com/oakes/Lightmod/141d1671d485326ef1f37b057c4116a2618dd948/resources/templates/export/dev.clj | clojure | (require
'[nightlight.core :as nightlight]
'[figwheel.main :as figwheel]
'[[[name]].server :refer [-main]])
(let [server (-main)
port (-> server meta :local-port)
url (str ":" port "/index.html")]
(println "Started app on" url)
(nightlight/start {:port 4000 :url url})
(figwheel/-main "--build" "dev"))
|
|
1eafe11bb641d86bf5972e3d063d503727d375b316084053dd1d1960fb5ab2f1 | ygrek/mldonkey | commonServer.ml | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This server is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This server is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Printf2
open CommonOptions
open CommonNetwork
open Options
open CommonUser
open CommonTypes
let log_prefix = "[cSe]"
let lprintf_nl fmt =
lprintf_nl2 log_prefix fmt
let lprintf_n fmt =
lprintf2 log_prefix fmt
module G = GuiTypes
type 'a server_impl = {
mutable impl_server_update : int;
mutable impl_server_state : CommonTypes.host_state;
mutable impl_server_num : int;
mutable impl_server_sort : int;
mutable impl_server_val : 'a;
mutable impl_server_ops : 'a server_ops;
}
and 'a server_ops = {
mutable op_server_network : network;
mutable op_server_to_option : ('a -> (string * option_value) list);
mutable op_server_remove : ('a -> unit);
mutable op_server_info : ('a -> GuiTypes.server_info);
mutable op_server_sort : ('a -> int);
mutable op_server_connect : ('a -> unit);
mutable op_server_disconnect : ('a -> unit);
mutable op_server_users : ('a -> user list);
mutable op_server_published : ('a -> file list);
mutable op_server_query_users : ('a -> unit);
mutable op_server_find_user : ('a -> string -> unit);
mutable op_server_cid : ('a -> Ip.t);
mutable op_server_low_id : ('a -> bool);
mutable op_server_set_preferred : ('a -> bool -> unit);
mutable op_server_rename : ('a -> string -> unit);
}
let ni n m =
let s = Printf.sprintf "Server.%s not implemented by %s"
m n.network_name in
lprintf_nl "%s" s;
s
let fni n m = failwith (ni n m)
let ni_ok n m = ignore (ni n m)
let as_server (server : 'a server_impl) =
let (server : server) = Obj.magic server in
server
let as_server_impl (server : server) =
let (server : 'a server_impl) = Obj.magic server in
server
let dummy_server_impl = {
impl_server_update = 1;
impl_server_state = NewHost;
impl_server_num = 0;
impl_server_sort = 0;
impl_server_val = 0;
impl_server_ops = Obj.magic None;
}
let dummy_server = as_server dummy_server_impl
let impl_server_info impl =
let module T = GuiTypes in
{
T.server_num = impl.impl_server_num;
T.server_state = impl.impl_server_state;
T.server_network = 0;
T.server_addr = Ip.addr_of_ip Ip.null;
T.server_port = 0;
T.server_realport = 0;
T.server_country_code = None;
T.server_score = 0;
T.server_tags = [];
T.server_nusers = 0L;
T.server_nfiles = 0L;
T.server_name = "";
T.server_description = "";
T.server_users = None;
T.server_banner = "";
T.server_preferred = false;
T.server_master = false;
T.server_version = "";
T.server_max_users = 0L;
T.server_soft_limit = 0L;
T.server_hard_limit = 0L;
T.server_lowid_users = 0L;
T.server_ping = 0;
T.server_published_files = 0;
T.server_features = None;
}
let server_num s =
let s = as_server_impl s in
s.impl_server_num
module H = Weak.Make(struct
type t = server
let hash s = Hashtbl.hash (server_num s)
let equal x y =
(server_num x) = (server_num y)
end)
let server_counter = ref 0
let servers_by_num = H.create 1027
let _ =
Heap.add_memstat "CommonServer" (fun level buf ->
let counter = ref 0 in
H.iter (fun _ -> incr counter) servers_by_num;
Printf.bprintf buf " servers: %d\n" !counter;
)
let server_must_update s =
let impl = as_server_impl s in
if impl.impl_server_update <> 0 then
CommonEvent.add_event (Server_info_event s);
impl.impl_server_update <- 0
let server_must_update_state s =
let impl = as_server_impl s in
if impl.impl_server_update > 0 then
begin
impl.impl_server_update <- - impl.impl_server_update;
CommonEvent.add_event (Server_info_event s);
end
let server_update_num impl =
let server = as_server impl in
incr server_counter;
impl.impl_server_num <- !server_counter;
server_must_update server;
H.add servers_by_num server
let server_to_option (server : server) =
let server = as_server_impl server in
server.impl_server_ops.op_server_to_option server.impl_server_val
let server_network (server : server) =
let server = as_server_impl server in
server.impl_server_ops.op_server_network
let server_info (server : server) =
let server = as_server_impl server in
server.impl_server_ops.op_server_info server.impl_server_val
let server_find_user s u =
let s = as_server_impl s in
s.impl_server_ops.op_server_find_user s.impl_server_val u
let server_query_users s =
let s = as_server_impl s in
s.impl_server_ops.op_server_query_users s.impl_server_val
let server_users s =
let s = as_server_impl s in
s.impl_server_ops.op_server_users s.impl_server_val
let server_published s =
let s = as_server_impl s in
s.impl_server_ops.op_server_published s.impl_server_val
let server_cid s =
let s = as_server_impl s in
s.impl_server_ops.op_server_cid s.impl_server_val
let server_low_id s =
let s = as_server_impl s in
s.impl_server_ops.op_server_low_id s.impl_server_val
let server_set_preferred s b =
let s = as_server_impl s in
s.impl_server_ops.op_server_set_preferred s.impl_server_val b
let server_rename s name =
let s = as_server_impl s in
s.impl_server_ops.op_server_rename s.impl_server_val name
let servers_ops = ref []
let new_server_ops network =
let s = {
op_server_network = network;
op_server_remove = (fun _ -> ni_ok network "server_remove");
(* op_server_print = (fun _ _ -> ni_ok network "server_print"); *)
op_server_to_option = (fun _ -> fni network "server_to_option");
op_server_info = (fun _ -> fni network "server_info");
op_server_sort = (fun _ -> ni_ok network "server_sort"; 0);
op_server_connect = (fun _ -> ni_ok network "server_connect");
op_server_disconnect = (fun _ -> ni_ok network "server_disconnect");
op_server_find_user = (fun _ -> fni network "find_user");
op_server_query_users = (fun _ -> ni_ok network "query_users");
op_server_published = (fun _ -> fni network "published");
op_server_users = (fun _ -> fni network "users");
op_server_cid = (fun _ -> fni network "cid");
op_server_low_id = (fun _ -> fni network "low_id");
op_server_set_preferred = (fun _ _ -> fni network "server_set_preferred");
op_server_rename = (fun _ _ -> fni network "server_rename");
} in
let ss = (Obj.magic s : int server_ops) in
servers_ops := (ss, { ss with op_server_network = s.op_server_network })
:: ! servers_ops;
s
let check_server_implementations () =
lprintf_nl "----- Methods not implemented for CommonServer ----";
List.iter (fun (c, cc) ->
let n = c.op_server_network.network_name in
lprintf_nl " Network %s" n;
if c.op_server_remove == cc.op_server_remove then
lprintf_nl "op_server_remove";
if c.op_server_to_option == cc.op_server_to_option then
lprintf_nl "op_server_to_option";
if c.op_server_info == cc.op_server_info then
lprintf_nl "op_server_info";
if c.op_server_sort == cc.op_server_sort then
lprintf_nl "op_server_sort";
if c.op_server_connect == cc.op_server_connect then
lprintf_nl "op_server_connect";
if c.op_server_disconnect == cc.op_server_disconnect then
lprintf_nl "op_server_disconnect";
if c.op_server_find_user == cc.op_server_find_user then
lprintf_nl "op_server_find_user";
if c.op_server_query_users == cc.op_server_query_users then
lprintf_nl "op_server_query_users";
if c.op_server_users == cc.op_server_users then
lprintf_nl "op_server_users";
if c.op_server_cid == cc.op_server_cid then
lprintf_nl "op_server_cid";
if c.op_server_low_id == cc.op_server_low_id then
lprintf_nl "op_server_low_id";
if c.op_server_rename == cc.op_server_rename then
lprintf_nl "op_server_rename";
if c.op_server_set_preferred == cc.op_server_set_preferred then
lprintf_nl "op_server_set_preferred";
) !servers_ops;
lprint_newline ()
let server_find (num : int) =
H.find servers_by_num (as_server { dummy_server_impl with
impl_server_num = num })
let server_blocked s =
let info = server_info s in
!Ip.banned (Ip.ip_of_addr info.G.server_addr, info.G.server_country_code) <> None
let server_connect s =
if not (server_blocked s) then
let server = as_server_impl s in
server.impl_server_ops.op_server_connect server.impl_server_val
let server_disconnect s =
let server = as_server_impl s in
server.impl_server_ops.op_server_disconnect server.impl_server_val
let server_state c =
let impl = as_server_impl c in
impl.impl_server_state
let set_server_state c state =
let impl = as_server_impl c in
if impl.impl_server_state <> state then begin
impl.impl_server_state <- state;
server_must_update_state c
end
let server_sort () =
let list = ref [] in
H.iter (fun s ->
let impl = as_server_impl s in
match impl.impl_server_state with
RemovedHost -> ()
| _ ->
list := s :: !list;
impl.impl_server_sort <-
(try impl.impl_server_ops.op_server_sort impl.impl_server_val
with _ -> 0);
) servers_by_num;
List.sort (fun s1 s2 ->
compare (as_server_impl s2).impl_server_sort (as_server_impl s1).impl_server_sort
) !list
let server_iter f =
H.iter f servers_by_num
let com_servers_by_num = servers_by_num
let server_new_user server user =
user_must_update user;
CommonEvent.add_event (Server_new_user_event (server, user))
let servers_get_all () =
let list = ref [] in
H.iter (fun c ->
list := (server_num c) :: !list) servers_by_num;
!list
let servers_by_num = ()
let check_blocked_servers () =
try
server_iter (fun s ->
if server_blocked s then
begin
let impl = as_server_impl s in
let info = server_info s in
(match impl.impl_server_state with
NotConnected _ -> ()
| _ -> server_disconnect s;
lprintf_nl "Disconnected server %s (%s:%d), IP is now blocked"
info.G.server_name
(Ip.string_of_addr info.G.server_addr)
info.G.server_port);
end;
server_must_update s)
with
Not_found -> ()
| e -> lprintf_nl "Exception in check_blocked_servers: %s" (Printexc2.to_string e)
let disconnect_all_servers () =
try
server_iter (fun s ->
(match (as_server_impl s).impl_server_state with
NotConnected _ -> ()
| _ -> server_disconnect s; server_must_update s))
with
Not_found -> ()
| e -> lprintf_nl "Exception in disconnect_all_servers: %s" (Printexc2.to_string e)
let server_must_update_all () =
try
server_iter (fun s ->
server_must_update s)
with e ->
lprintf_nl "Exception in server_must_update_all: %s" (Printexc2.to_string e)
let server_banner s o =
let buf = o.conn_buf in
let info = server_info s in
Printf.bprintf buf "%s"
info.G.server_banner
let server_print_html_header buf ext =
if !!html_mods_use_js_tooltips then Printf.bprintf buf
"\\<div id=\\\"object1\\\" style=\\\"position:absolute; background-color:#FFFFDD;color:black;border-color:black;border-width:20px;font-size:8pt; visibility:visible; left:25px; top:
-100px; z-index:+1\\\" onmouseover=\\\"overdiv=1;\\\" onmouseout=\\\"overdiv=0; setTimeout(\\\'hideLayer()\\\',1000)\\\"\\>\\ \\</div\\>";
html_mods_table_header buf "serversTable" (Printf.sprintf "servers%s" ext) ([
( Num, "srh", "Server number", "#" ) ;
( Str, "srh", "Connect|Disconnect", "C/D" ) ;
( Str, "srh", "Remove", "Rem" ) ;
( Str, "srh", "Preferred", "P" ) ;
( Str, "srh", "Master servers", "M" ) ;
( Str, "srh", "[Hi]gh or [Lo]w ID", "ID" ) ;
( Str, "srh", "Network name", "Network" ) ;
( Str, "srh", "Connection status", "Status" ) ;
( Str, "srh br", "IP address", "IP address" ) ;
] @ (if Geoip.active () then [( Str, "srh br", "Country Code/Name", "CC" )] else []) @ [
( Num, "srh ar", "Number of connected users", "Users" ) ;
( Num, "srh ar br", "Max number of users", "MaxUsers" ) ;
( Num, "srh ar br", "LowID users", "LowID" ) ;
( Num, "srh ar", "Number of files indexed on server", "Files" );
( Num, "srh ar br", "Number of published files on server", "Publ" );
( Num, "srh ar", "Soft file limit", "Soft" ) ;
( Num, "srh ar br", "Hard file limit", "Hard" ) ;
( Num, "srh ar br", "Ping (ms)", "Ping" ) ;
( Str, "srh br", "Server version", "Version" ) ;
( Str, "srh", "Server name", "Name" ) ;
( Str, "srh", "Server details", "Details" ) ])
let server_print s o =
let impl = as_server_impl s in
let n = impl.impl_server_ops.op_server_network in
if network_is_enabled n then
try
let info =
try server_info s with e ->
lprintf_nl "Exception %s in server_info (%s)\n"
(Printexc2.to_string e) n.network_name;
raise e in
let cc,cn = Geoip.get_country_code_name info.G.server_country_code in
let buf = o.conn_buf in
if use_html_mods o then begin
let snum = (server_num s) in
let ip_port_string =
Printf.sprintf "%s:%s%s"
(Ip.string_of_addr info.G.server_addr)
(string_of_int info.G.server_port)
(if info.G.server_realport <> 0
then "(" ^ (string_of_int info.G.server_realport) ^ ")"
else ""
)
in
Printf.bprintf buf "\\<tr class=\\\"dl-%d\\\""
(html_mods_cntr ());
if !!html_mods_use_js_tooltips then
Printf.bprintf buf " onMouseOver=\\\"mOvr(this);setTimeout('popLayer(\\\\\'%s %s<br>%s\\\\\')',%d);setTimeout('hideLayer()',%d);return true;\\\" onMouseOut=\\\"mOut(this);hideLayer();setTimeout('hideLayer()',%d)\\\"\\>"
info.G.server_name ip_port_string
(match info.G.server_features with
| None -> ""
| Some f -> "server features: " ^ f)
!!html_mods_js_tooltips_wait
!!html_mods_js_tooltips_timeout
!!html_mods_js_tooltips_wait
else Printf.bprintf buf "\\>";
Printf.bprintf buf " \\<td class=\\\"srb\\\" %s \\>%d\\</td\\> %s %s %s"
(match impl.impl_server_state with
Connected _ ->
Printf.sprintf "title=\\\"Server Banner\\\"
onClick=\\\"location.href='submit?q=server_banner+%d'\\\""
snum
| _ -> "")
snum
(
let not_connected =
match impl.impl_server_state with
| ServerFull
| NotConnected _ -> true
| _ -> false
in
if server_blocked s && not_connected
then "\\<td class=\\\"srb\\\"\\>blk\\</td\\>"
else Printf.sprintf
"\\<td class=\\\"srb\\\" title=\\\"Connect|Disconnect\\\"
onClick=\\\"parent.fstatus.location.href='submit?q=%s+%d'\\\"\\>%s\\</td\\>"
(if not_connected then "c" else "x")
snum
(if not_connected then "Conn" else "Disc")
)
(
Printf.sprintf
"\\<td class=\\\"srb\\\" title=\\\"Remove server\\\"
onClick=\\\"parent.fstatus.location.href='submit?q=rem+%d'\\\"\\>Rem\\</td\\>"
snum
)
(
if info.G.server_preferred then begin
Printf.sprintf
"\\<td class=\\\"srb\\\" title=\\\"Unset preferred\\\"
onClick=\\\"parent.fstatus.location.href='submit?q=preferred+false+%s'\\\"\\>P\\</td\\>"
(Ip.string_of_addr info.G.server_addr)
end else begin
Printf.sprintf
"\\<td class=\\\"srb\\\" title=\\\"Set preferred\\\"
onClick=\\\"parent.fstatus.location.href='submit?q=preferred+true+%s'\\\"\\>-\\</td\\>"
(Ip.string_of_addr info.G.server_addr)
end
);
let id_title, id_text =
match n.network_name with
"Donkey" -> begin
match impl.impl_server_state with
Connected _ -> begin
let cid = (server_cid s) in
let (label,shortlabel,our_ip) =
if not (server_low_id s) then
("HighID","Hi",
(if !!set_client_ip <> cid then
Printf.sprintf "(clientIP: %s)"
(Ip.to_string !!set_client_ip)
else ""))
else ("LowID","Lo","")
in
Printf.sprintf "%s: %s = %s %s"
label
(Int64.to_string (Ip.to_int64 (Ip.rev cid)))
(Ip.to_string cid)
our_ip
,shortlabel
end
| _ -> "",""
end
| _ -> "",""
in
let server_state_string =
match impl.impl_server_state with
NotConnected _ when server_blocked s -> "IP blocked"
| _ -> string_of_connection_state impl.impl_server_state
in
html_mods_td buf ([
("", "srb", if info.G.server_master then "M" else "-");
(id_title, "sr", id_text);
("", "sr", n.network_name);
("", "sr", server_state_string);
("", "sr br", ip_port_string);
] @ (if Geoip.active () then [(cn, "sr br", CommonPictures.flag_html cc)] else []) @ [
("", "sr ar", if info.G.server_nusers = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_nusers);
("", "sr ar br", if info.G.server_max_users = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_max_users);
("", "sr ar br", if info.G.server_lowid_users = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_lowid_users);
("", "sr ar", if info.G.server_nfiles = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_nfiles)]);
if info.G.server_published_files = 0 then
html_mods_td buf ([("", "sr br", "")])
else
Printf.bprintf buf
"\\<TD class=\\\"sr br\\\" title=\\\"Show published files\\\"
onClick=\\\"location.href='submit?q=server_shares+%d'\\\"\\>%d\\</TD\\>"
snum info.G.server_published_files;
html_mods_td buf ([
("", "sr ar", if info.G.server_soft_limit = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_soft_limit);
("", "sr ar br", if info.G.server_hard_limit = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_hard_limit);
("", "sr ar br", if info.G.server_ping = 0 then "" else Printf.sprintf "%d" info.G.server_ping);
("", "sr br", info.G.server_version);
("", "sr", info.G.server_name);
]);
Printf.bprintf buf "\\<td width=\\\"100%%\\\" class=\\\"sr\\\"\\>%s\\</td\\>\\</tr\\>\n"
info.G.server_description;
end
else
begin
Printf.bprintf buf "[%-10s%5d] %15s:%-10s %s\n%45sUsers:%-8Ld Files:%-8Ld State:%s\n"
(n.network_name)
(server_num s)
(Ip.string_of_addr info.G.server_addr)
(Printf.sprintf "%s%s"
(string_of_int info.G.server_port)
(if info.G.server_realport <> 0
then "(" ^ (string_of_int info.G.server_realport) ^ ")"
else ""))
(info.G.server_name)
(if Geoip.active () then Printf.sprintf "%33s/%-2s%9s" cn cc "" else "")
(info.G.server_nusers)
(info.G.server_nfiles)
(if server_blocked s
then "IP blocked"
else (string_of_connection_state impl.impl_server_state));
end;
with e ->
lprintf_nl "Exception %s in CommonServer.server_print"
(Printexc2.to_string e)
| null | https://raw.githubusercontent.com/ygrek/mldonkey/333868a12bb6cd25fed49391dd2c3a767741cb51/src/daemon/common/commonServer.ml | ocaml | op_server_print = (fun _ _ -> ni_ok network "server_print"); | Copyright 2001 , 2002 b8_bavard , b8_fee_carabine ,
This server is part of mldonkey .
mldonkey is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
mldonkey 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 mldonkey ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
This server is part of mldonkey.
mldonkey is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
mldonkey 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 mldonkey; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
open Printf2
open CommonOptions
open CommonNetwork
open Options
open CommonUser
open CommonTypes
let log_prefix = "[cSe]"
let lprintf_nl fmt =
lprintf_nl2 log_prefix fmt
let lprintf_n fmt =
lprintf2 log_prefix fmt
module G = GuiTypes
type 'a server_impl = {
mutable impl_server_update : int;
mutable impl_server_state : CommonTypes.host_state;
mutable impl_server_num : int;
mutable impl_server_sort : int;
mutable impl_server_val : 'a;
mutable impl_server_ops : 'a server_ops;
}
and 'a server_ops = {
mutable op_server_network : network;
mutable op_server_to_option : ('a -> (string * option_value) list);
mutable op_server_remove : ('a -> unit);
mutable op_server_info : ('a -> GuiTypes.server_info);
mutable op_server_sort : ('a -> int);
mutable op_server_connect : ('a -> unit);
mutable op_server_disconnect : ('a -> unit);
mutable op_server_users : ('a -> user list);
mutable op_server_published : ('a -> file list);
mutable op_server_query_users : ('a -> unit);
mutable op_server_find_user : ('a -> string -> unit);
mutable op_server_cid : ('a -> Ip.t);
mutable op_server_low_id : ('a -> bool);
mutable op_server_set_preferred : ('a -> bool -> unit);
mutable op_server_rename : ('a -> string -> unit);
}
let ni n m =
let s = Printf.sprintf "Server.%s not implemented by %s"
m n.network_name in
lprintf_nl "%s" s;
s
let fni n m = failwith (ni n m)
let ni_ok n m = ignore (ni n m)
let as_server (server : 'a server_impl) =
let (server : server) = Obj.magic server in
server
let as_server_impl (server : server) =
let (server : 'a server_impl) = Obj.magic server in
server
let dummy_server_impl = {
impl_server_update = 1;
impl_server_state = NewHost;
impl_server_num = 0;
impl_server_sort = 0;
impl_server_val = 0;
impl_server_ops = Obj.magic None;
}
let dummy_server = as_server dummy_server_impl
let impl_server_info impl =
let module T = GuiTypes in
{
T.server_num = impl.impl_server_num;
T.server_state = impl.impl_server_state;
T.server_network = 0;
T.server_addr = Ip.addr_of_ip Ip.null;
T.server_port = 0;
T.server_realport = 0;
T.server_country_code = None;
T.server_score = 0;
T.server_tags = [];
T.server_nusers = 0L;
T.server_nfiles = 0L;
T.server_name = "";
T.server_description = "";
T.server_users = None;
T.server_banner = "";
T.server_preferred = false;
T.server_master = false;
T.server_version = "";
T.server_max_users = 0L;
T.server_soft_limit = 0L;
T.server_hard_limit = 0L;
T.server_lowid_users = 0L;
T.server_ping = 0;
T.server_published_files = 0;
T.server_features = None;
}
let server_num s =
let s = as_server_impl s in
s.impl_server_num
module H = Weak.Make(struct
type t = server
let hash s = Hashtbl.hash (server_num s)
let equal x y =
(server_num x) = (server_num y)
end)
let server_counter = ref 0
let servers_by_num = H.create 1027
let _ =
Heap.add_memstat "CommonServer" (fun level buf ->
let counter = ref 0 in
H.iter (fun _ -> incr counter) servers_by_num;
Printf.bprintf buf " servers: %d\n" !counter;
)
let server_must_update s =
let impl = as_server_impl s in
if impl.impl_server_update <> 0 then
CommonEvent.add_event (Server_info_event s);
impl.impl_server_update <- 0
let server_must_update_state s =
let impl = as_server_impl s in
if impl.impl_server_update > 0 then
begin
impl.impl_server_update <- - impl.impl_server_update;
CommonEvent.add_event (Server_info_event s);
end
let server_update_num impl =
let server = as_server impl in
incr server_counter;
impl.impl_server_num <- !server_counter;
server_must_update server;
H.add servers_by_num server
let server_to_option (server : server) =
let server = as_server_impl server in
server.impl_server_ops.op_server_to_option server.impl_server_val
let server_network (server : server) =
let server = as_server_impl server in
server.impl_server_ops.op_server_network
let server_info (server : server) =
let server = as_server_impl server in
server.impl_server_ops.op_server_info server.impl_server_val
let server_find_user s u =
let s = as_server_impl s in
s.impl_server_ops.op_server_find_user s.impl_server_val u
let server_query_users s =
let s = as_server_impl s in
s.impl_server_ops.op_server_query_users s.impl_server_val
let server_users s =
let s = as_server_impl s in
s.impl_server_ops.op_server_users s.impl_server_val
let server_published s =
let s = as_server_impl s in
s.impl_server_ops.op_server_published s.impl_server_val
let server_cid s =
let s = as_server_impl s in
s.impl_server_ops.op_server_cid s.impl_server_val
let server_low_id s =
let s = as_server_impl s in
s.impl_server_ops.op_server_low_id s.impl_server_val
let server_set_preferred s b =
let s = as_server_impl s in
s.impl_server_ops.op_server_set_preferred s.impl_server_val b
let server_rename s name =
let s = as_server_impl s in
s.impl_server_ops.op_server_rename s.impl_server_val name
let servers_ops = ref []
let new_server_ops network =
let s = {
op_server_network = network;
op_server_remove = (fun _ -> ni_ok network "server_remove");
op_server_to_option = (fun _ -> fni network "server_to_option");
op_server_info = (fun _ -> fni network "server_info");
op_server_sort = (fun _ -> ni_ok network "server_sort"; 0);
op_server_connect = (fun _ -> ni_ok network "server_connect");
op_server_disconnect = (fun _ -> ni_ok network "server_disconnect");
op_server_find_user = (fun _ -> fni network "find_user");
op_server_query_users = (fun _ -> ni_ok network "query_users");
op_server_published = (fun _ -> fni network "published");
op_server_users = (fun _ -> fni network "users");
op_server_cid = (fun _ -> fni network "cid");
op_server_low_id = (fun _ -> fni network "low_id");
op_server_set_preferred = (fun _ _ -> fni network "server_set_preferred");
op_server_rename = (fun _ _ -> fni network "server_rename");
} in
let ss = (Obj.magic s : int server_ops) in
servers_ops := (ss, { ss with op_server_network = s.op_server_network })
:: ! servers_ops;
s
let check_server_implementations () =
lprintf_nl "----- Methods not implemented for CommonServer ----";
List.iter (fun (c, cc) ->
let n = c.op_server_network.network_name in
lprintf_nl " Network %s" n;
if c.op_server_remove == cc.op_server_remove then
lprintf_nl "op_server_remove";
if c.op_server_to_option == cc.op_server_to_option then
lprintf_nl "op_server_to_option";
if c.op_server_info == cc.op_server_info then
lprintf_nl "op_server_info";
if c.op_server_sort == cc.op_server_sort then
lprintf_nl "op_server_sort";
if c.op_server_connect == cc.op_server_connect then
lprintf_nl "op_server_connect";
if c.op_server_disconnect == cc.op_server_disconnect then
lprintf_nl "op_server_disconnect";
if c.op_server_find_user == cc.op_server_find_user then
lprintf_nl "op_server_find_user";
if c.op_server_query_users == cc.op_server_query_users then
lprintf_nl "op_server_query_users";
if c.op_server_users == cc.op_server_users then
lprintf_nl "op_server_users";
if c.op_server_cid == cc.op_server_cid then
lprintf_nl "op_server_cid";
if c.op_server_low_id == cc.op_server_low_id then
lprintf_nl "op_server_low_id";
if c.op_server_rename == cc.op_server_rename then
lprintf_nl "op_server_rename";
if c.op_server_set_preferred == cc.op_server_set_preferred then
lprintf_nl "op_server_set_preferred";
) !servers_ops;
lprint_newline ()
let server_find (num : int) =
H.find servers_by_num (as_server { dummy_server_impl with
impl_server_num = num })
let server_blocked s =
let info = server_info s in
!Ip.banned (Ip.ip_of_addr info.G.server_addr, info.G.server_country_code) <> None
let server_connect s =
if not (server_blocked s) then
let server = as_server_impl s in
server.impl_server_ops.op_server_connect server.impl_server_val
let server_disconnect s =
let server = as_server_impl s in
server.impl_server_ops.op_server_disconnect server.impl_server_val
let server_state c =
let impl = as_server_impl c in
impl.impl_server_state
let set_server_state c state =
let impl = as_server_impl c in
if impl.impl_server_state <> state then begin
impl.impl_server_state <- state;
server_must_update_state c
end
let server_sort () =
let list = ref [] in
H.iter (fun s ->
let impl = as_server_impl s in
match impl.impl_server_state with
RemovedHost -> ()
| _ ->
list := s :: !list;
impl.impl_server_sort <-
(try impl.impl_server_ops.op_server_sort impl.impl_server_val
with _ -> 0);
) servers_by_num;
List.sort (fun s1 s2 ->
compare (as_server_impl s2).impl_server_sort (as_server_impl s1).impl_server_sort
) !list
let server_iter f =
H.iter f servers_by_num
let com_servers_by_num = servers_by_num
let server_new_user server user =
user_must_update user;
CommonEvent.add_event (Server_new_user_event (server, user))
let servers_get_all () =
let list = ref [] in
H.iter (fun c ->
list := (server_num c) :: !list) servers_by_num;
!list
let servers_by_num = ()
let check_blocked_servers () =
try
server_iter (fun s ->
if server_blocked s then
begin
let impl = as_server_impl s in
let info = server_info s in
(match impl.impl_server_state with
NotConnected _ -> ()
| _ -> server_disconnect s;
lprintf_nl "Disconnected server %s (%s:%d), IP is now blocked"
info.G.server_name
(Ip.string_of_addr info.G.server_addr)
info.G.server_port);
end;
server_must_update s)
with
Not_found -> ()
| e -> lprintf_nl "Exception in check_blocked_servers: %s" (Printexc2.to_string e)
let disconnect_all_servers () =
try
server_iter (fun s ->
(match (as_server_impl s).impl_server_state with
NotConnected _ -> ()
| _ -> server_disconnect s; server_must_update s))
with
Not_found -> ()
| e -> lprintf_nl "Exception in disconnect_all_servers: %s" (Printexc2.to_string e)
let server_must_update_all () =
try
server_iter (fun s ->
server_must_update s)
with e ->
lprintf_nl "Exception in server_must_update_all: %s" (Printexc2.to_string e)
let server_banner s o =
let buf = o.conn_buf in
let info = server_info s in
Printf.bprintf buf "%s"
info.G.server_banner
let server_print_html_header buf ext =
if !!html_mods_use_js_tooltips then Printf.bprintf buf
"\\<div id=\\\"object1\\\" style=\\\"position:absolute; background-color:#FFFFDD;color:black;border-color:black;border-width:20px;font-size:8pt; visibility:visible; left:25px; top:
-100px; z-index:+1\\\" onmouseover=\\\"overdiv=1;\\\" onmouseout=\\\"overdiv=0; setTimeout(\\\'hideLayer()\\\',1000)\\\"\\>\\ \\</div\\>";
html_mods_table_header buf "serversTable" (Printf.sprintf "servers%s" ext) ([
( Num, "srh", "Server number", "#" ) ;
( Str, "srh", "Connect|Disconnect", "C/D" ) ;
( Str, "srh", "Remove", "Rem" ) ;
( Str, "srh", "Preferred", "P" ) ;
( Str, "srh", "Master servers", "M" ) ;
( Str, "srh", "[Hi]gh or [Lo]w ID", "ID" ) ;
( Str, "srh", "Network name", "Network" ) ;
( Str, "srh", "Connection status", "Status" ) ;
( Str, "srh br", "IP address", "IP address" ) ;
] @ (if Geoip.active () then [( Str, "srh br", "Country Code/Name", "CC" )] else []) @ [
( Num, "srh ar", "Number of connected users", "Users" ) ;
( Num, "srh ar br", "Max number of users", "MaxUsers" ) ;
( Num, "srh ar br", "LowID users", "LowID" ) ;
( Num, "srh ar", "Number of files indexed on server", "Files" );
( Num, "srh ar br", "Number of published files on server", "Publ" );
( Num, "srh ar", "Soft file limit", "Soft" ) ;
( Num, "srh ar br", "Hard file limit", "Hard" ) ;
( Num, "srh ar br", "Ping (ms)", "Ping" ) ;
( Str, "srh br", "Server version", "Version" ) ;
( Str, "srh", "Server name", "Name" ) ;
( Str, "srh", "Server details", "Details" ) ])
let server_print s o =
let impl = as_server_impl s in
let n = impl.impl_server_ops.op_server_network in
if network_is_enabled n then
try
let info =
try server_info s with e ->
lprintf_nl "Exception %s in server_info (%s)\n"
(Printexc2.to_string e) n.network_name;
raise e in
let cc,cn = Geoip.get_country_code_name info.G.server_country_code in
let buf = o.conn_buf in
if use_html_mods o then begin
let snum = (server_num s) in
let ip_port_string =
Printf.sprintf "%s:%s%s"
(Ip.string_of_addr info.G.server_addr)
(string_of_int info.G.server_port)
(if info.G.server_realport <> 0
then "(" ^ (string_of_int info.G.server_realport) ^ ")"
else ""
)
in
Printf.bprintf buf "\\<tr class=\\\"dl-%d\\\""
(html_mods_cntr ());
if !!html_mods_use_js_tooltips then
Printf.bprintf buf " onMouseOver=\\\"mOvr(this);setTimeout('popLayer(\\\\\'%s %s<br>%s\\\\\')',%d);setTimeout('hideLayer()',%d);return true;\\\" onMouseOut=\\\"mOut(this);hideLayer();setTimeout('hideLayer()',%d)\\\"\\>"
info.G.server_name ip_port_string
(match info.G.server_features with
| None -> ""
| Some f -> "server features: " ^ f)
!!html_mods_js_tooltips_wait
!!html_mods_js_tooltips_timeout
!!html_mods_js_tooltips_wait
else Printf.bprintf buf "\\>";
Printf.bprintf buf " \\<td class=\\\"srb\\\" %s \\>%d\\</td\\> %s %s %s"
(match impl.impl_server_state with
Connected _ ->
Printf.sprintf "title=\\\"Server Banner\\\"
onClick=\\\"location.href='submit?q=server_banner+%d'\\\""
snum
| _ -> "")
snum
(
let not_connected =
match impl.impl_server_state with
| ServerFull
| NotConnected _ -> true
| _ -> false
in
if server_blocked s && not_connected
then "\\<td class=\\\"srb\\\"\\>blk\\</td\\>"
else Printf.sprintf
"\\<td class=\\\"srb\\\" title=\\\"Connect|Disconnect\\\"
onClick=\\\"parent.fstatus.location.href='submit?q=%s+%d'\\\"\\>%s\\</td\\>"
(if not_connected then "c" else "x")
snum
(if not_connected then "Conn" else "Disc")
)
(
Printf.sprintf
"\\<td class=\\\"srb\\\" title=\\\"Remove server\\\"
onClick=\\\"parent.fstatus.location.href='submit?q=rem+%d'\\\"\\>Rem\\</td\\>"
snum
)
(
if info.G.server_preferred then begin
Printf.sprintf
"\\<td class=\\\"srb\\\" title=\\\"Unset preferred\\\"
onClick=\\\"parent.fstatus.location.href='submit?q=preferred+false+%s'\\\"\\>P\\</td\\>"
(Ip.string_of_addr info.G.server_addr)
end else begin
Printf.sprintf
"\\<td class=\\\"srb\\\" title=\\\"Set preferred\\\"
onClick=\\\"parent.fstatus.location.href='submit?q=preferred+true+%s'\\\"\\>-\\</td\\>"
(Ip.string_of_addr info.G.server_addr)
end
);
let id_title, id_text =
match n.network_name with
"Donkey" -> begin
match impl.impl_server_state with
Connected _ -> begin
let cid = (server_cid s) in
let (label,shortlabel,our_ip) =
if not (server_low_id s) then
("HighID","Hi",
(if !!set_client_ip <> cid then
Printf.sprintf "(clientIP: %s)"
(Ip.to_string !!set_client_ip)
else ""))
else ("LowID","Lo","")
in
Printf.sprintf "%s: %s = %s %s"
label
(Int64.to_string (Ip.to_int64 (Ip.rev cid)))
(Ip.to_string cid)
our_ip
,shortlabel
end
| _ -> "",""
end
| _ -> "",""
in
let server_state_string =
match impl.impl_server_state with
NotConnected _ when server_blocked s -> "IP blocked"
| _ -> string_of_connection_state impl.impl_server_state
in
html_mods_td buf ([
("", "srb", if info.G.server_master then "M" else "-");
(id_title, "sr", id_text);
("", "sr", n.network_name);
("", "sr", server_state_string);
("", "sr br", ip_port_string);
] @ (if Geoip.active () then [(cn, "sr br", CommonPictures.flag_html cc)] else []) @ [
("", "sr ar", if info.G.server_nusers = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_nusers);
("", "sr ar br", if info.G.server_max_users = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_max_users);
("", "sr ar br", if info.G.server_lowid_users = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_lowid_users);
("", "sr ar", if info.G.server_nfiles = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_nfiles)]);
if info.G.server_published_files = 0 then
html_mods_td buf ([("", "sr br", "")])
else
Printf.bprintf buf
"\\<TD class=\\\"sr br\\\" title=\\\"Show published files\\\"
onClick=\\\"location.href='submit?q=server_shares+%d'\\\"\\>%d\\</TD\\>"
snum info.G.server_published_files;
html_mods_td buf ([
("", "sr ar", if info.G.server_soft_limit = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_soft_limit);
("", "sr ar br", if info.G.server_hard_limit = Int64.zero then "" else Printf.sprintf "%Ld" info.G.server_hard_limit);
("", "sr ar br", if info.G.server_ping = 0 then "" else Printf.sprintf "%d" info.G.server_ping);
("", "sr br", info.G.server_version);
("", "sr", info.G.server_name);
]);
Printf.bprintf buf "\\<td width=\\\"100%%\\\" class=\\\"sr\\\"\\>%s\\</td\\>\\</tr\\>\n"
info.G.server_description;
end
else
begin
Printf.bprintf buf "[%-10s%5d] %15s:%-10s %s\n%45sUsers:%-8Ld Files:%-8Ld State:%s\n"
(n.network_name)
(server_num s)
(Ip.string_of_addr info.G.server_addr)
(Printf.sprintf "%s%s"
(string_of_int info.G.server_port)
(if info.G.server_realport <> 0
then "(" ^ (string_of_int info.G.server_realport) ^ ")"
else ""))
(info.G.server_name)
(if Geoip.active () then Printf.sprintf "%33s/%-2s%9s" cn cc "" else "")
(info.G.server_nusers)
(info.G.server_nfiles)
(if server_blocked s
then "IP blocked"
else (string_of_connection_state impl.impl_server_state));
end;
with e ->
lprintf_nl "Exception %s in CommonServer.server_print"
(Printexc2.to_string e)
|
7026fa165e387c2869d61ccee46750e624d97928d20a7ef7b9f09416811c2bc2 | ucsd-progsys/elsa | Eval.hs | # LANGUAGE OverloadedStrings , BangPatterns #
module Language.Elsa.Eval (elsa, elsaOn) where
import qualified Data.HashMap.Strict as M
import qualified Data.HashMap.Lazy as ML
import qualified Data.HashSet as S
import qualified Data.List as L
import Control.Monad.State
import qualified Data.Maybe as Mb -- (isJust, maybeToList)
import Language.Elsa.Types
import Language.Elsa.Utils (qPushes, qInit, qPop, fromEither)
--------------------------------------------------------------------------------
elsa :: Elsa a -> [Result a]
--------------------------------------------------------------------------------
elsa = elsaOn (const True)
--------------------------------------------------------------------------------
elsaOn :: (Id -> Bool) -> Elsa a -> [Result a]
--------------------------------------------------------------------------------
elsaOn cond p =
case mkEnv (defns p) of
Left err -> [err]
Right g -> case checkDupEval (evals p) of
Left err -> [err]
Right _ -> [result g e | e <- evals p, check e ]
where
check = cond . bindId . evName
checkDupEval :: [Eval a] -> CheckM a (S.HashSet Id)
checkDupEval = foldM addEvalId S.empty
addEvalId :: S.HashSet Id -> Eval a -> CheckM a (S.HashSet Id)
addEvalId s e =
if S.member (bindId b) s
then Left (errDupEval b)
else Right (S.insert (bindId b) s)
where
b = evName e
result :: Env a -> Eval a -> Result a
result g e = fromEither (eval g e)
mkEnv :: [Defn a] -> CheckM a (Env a)
mkEnv = foldM expand M.empty
expand :: Env a -> Defn a -> CheckM a (Env a)
expand g (Defn b e) =
if dupId
then Left (errDupDefn b)
else case zs of
(x,l) : _ -> Left (Unbound b x l)
[] -> Right (M.insert (bindId b) e' g)
where
dupId = M.member (bindId b) g
e' = subst e g
zs = M.toList (freeVars' e')
--------------------------------------------------------------------------------
type CheckM a b = Either (Result a) b
type Env a = M.HashMap Id (Expr a)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
eval :: Env a -> Eval a -> CheckM a (Result a)
--------------------------------------------------------------------------------
eval g (Eval n e steps) = go e steps
where
go e []
| isNormal g e = return (OK n)
| otherwise = Left (errPartial n e)
go e (s:steps) = step g n e s >>= (`go` steps)
step :: Env a -> Bind a -> Expr a -> Step a -> CheckM a (Expr a)
step g n e (Step k e')
| isEq k g e e' = return e'
| otherwise = Left (errInvalid n e k e')
isEq :: Eqn a -> Env a -> Expr a -> Expr a -> Bool
isEq (AlphEq _) = isAlphEq
isEq (BetaEq _) = isBetaEq
isEq (UnBeta _) = isUnBeta
isEq (DefnEq _) = isDefnEq
isEq (TrnsEq _) = isTrnsEq
isEq (UnTrEq _) = isUnTrEq
isEq (NormEq _) = isNormEq
--------------------------------------------------------------------------------
-- | Transitive Reachability
--------------------------------------------------------------------------------
isTrnsEq :: Env a -> Expr a -> Expr a -> Bool
isTrnsEq g e1 e2 = Mb.isJust (findTrans (isEquiv g e2) (canon g e1))
isUnTrEq :: Env a -> Expr a -> Expr a -> Bool
isUnTrEq g e1 e2 = isTrnsEq g e2 e1
findTrans :: (Expr a -> Bool) -> Expr a -> Maybe (Expr a)
findTrans p e = go S.empty (qInit e)
where
go seen q = do
(e, q') <- qPop q
if S.member e seen
then go seen q'
else if p e
then return e
else go (S.insert e seen) (qPushes q (betas e))
--------------------------------------------------------------------------------
-- | Definition Equivalence
--------------------------------------------------------------------------------
isDefnEq :: Env a -> Expr a -> Expr a -> Bool
isDefnEq g e1 e2 = subst e1 g == subst e2 g
--------------------------------------------------------------------------------
-- | Alpha Equivalence
--------------------------------------------------------------------------------
isAlphEq :: Env a -> Expr a -> Expr a -> Bool
isAlphEq _ e1 e2 = alphaNormal e1 == alphaNormal e2
alphaNormal :: Expr a -> Expr a
alphaNormal = alphaShift 0
alphaShift :: Int -> Expr a -> Expr a
alphaShift n e = evalState (normalize M.empty e) n
type AlphaM a = State Int a
normalize :: M.HashMap Id Id -> Expr a -> AlphaM (Expr a)
normalize g (EVar x z) =
return (EVar (rename g x) z)
normalize g (EApp e1 e2 z) = do
e1' <- normalize g e1
e2' <- normalize g e2
return (EApp e1' e2' z)
normalize g (ELam (Bind x z1) e z2) = do
y <- fresh
let g' = M.insert x y g
e' <- normalize g' e
return (ELam (Bind y z1) e' z2)
rename :: M.HashMap Id Id -> Id -> Id
rename g x = M.lookupDefault x x g
fresh :: AlphaM Id
fresh = do
n <- get
put (n + 1)
return (newAId n)
newAId :: Int -> Id
newAId n = aId ++ show n
_isAId :: Id -> Maybe Int
_isAId x
| L.isPrefixOf aId x = Just . read . drop 2 $ x
| otherwise = Nothing
aId :: String
aId = "$x"
--------------------------------------------------------------------------------
-- | Beta Reduction
--------------------------------------------------------------------------------
isBetaEq :: Env a -> Expr a -> Expr a -> Bool
isBetaEq _ e1 e2 = or [ e1' == e2 | e1' <- betas e1 ]
isUnBeta :: Env a -> Expr a -> Expr a -> Bool
isUnBeta g e1 e2 = isBetaEq g e2 e1
isNormal :: Env a -> Expr a -> Bool
isNormal g = null . betas . (`subst` g)
-- | `betas e` returns the list [e1,...en] of terms obtainable via a single-step
-- beta reduction from `e`.
betas :: Expr a -> [Expr a]
betas (EVar _ _) = []
betas (ELam b e z) = [ ELam b e' z | e' <- betas e ]
betas (EApp e1 e2 z) = [ EApp e1' e2 z | e1' <- betas e1 ]
++ [ EApp e1 e2' z | e2' <- betas e2 ]
++ Mb.maybeToList (beta e1 e2)
beta :: Expr a -> Expr a -> Maybe (Expr a)
beta (ELam (Bind x _) e _) e' = substCA e x e'
beta _ _ = Nothing
substCA :: Expr a -> Id -> Expr a -> Maybe (Expr a)
substCA e x e' = go [] e
where
zs = freeVars e'
bnd bs zs = or [ b `isIn` zs | b <- bs ]
go bs e@(EVar y _)
| y /= x = Just e -- different var, no subst
| bnd bs zs = Nothing -- same var, but free-var-captured
| otherwise = Just e' -- same var, but no capture
go bs (EApp e1 e2 l) = do e1' <- go bs e1
e2' <- go bs e2
Just (EApp e1' e2' l)
go bs e@(ELam b e1 l)
| x == bindId b = Just e -- subst-var has been rebound
| otherwise = do e1' <- go (b:bs) e1
Just (ELam b e1' l)
isIn :: Bind a -> S.HashSet Id -> Bool
isIn = S.member . bindId
--------------------------------------------------------------------------------
-- | Evaluation to Normal Form
--------------------------------------------------------------------------------
isNormEq :: Env a -> Expr a -> Expr a -> Bool
isNormEq g e1 e2 = eqVal (subst e2 g) $ evalNbE ML.empty (subst e1 g)
where
evalNbE !env e = case e of
EVar x _ -> Mb.fromMaybe (Neutral x []) $ ML.lookup x env
ELam (Bind x _) b _ -> Fun $ \val -> evalNbE (ML.insert x val env) b
EApp f arg _ -> case evalNbE env f of
Fun f' -> f' (evalNbE env arg)
Neutral x args -> Neutral x (evalNbE env arg:args)
eqVal (EVar x _) (Neutral x' [])
= x == x'
eqVal (ELam (Bind x _) b _) (Fun f)
= eqVal b (f (Neutral x []))
eqVal (EApp f a _) (Neutral x (a':args))
= eqVal a a' && eqVal f (Neutral x args)
eqVal _ _ = False
-- | NbE semantic domain
data Value = Fun !(Value -> Value) | Neutral !Id ![Value]
--------------------------------------------------------------------------------
-- | General Helpers
--------------------------------------------------------------------------------
freeVars :: Expr a -> S.HashSet Id
freeVars = S.fromList . M.keys . freeVars'
freeVars' :: Expr a -> M.HashMap Id a
freeVars' (EVar x l) = M.singleton x l
freeVars' (ELam b e _) = M.delete (bindId b) (freeVars' e)
freeVars' (EApp e e' _) = M.union (freeVars' e) (freeVars' e')
subst :: Expr a -> Env a -> Expr a
subst e@(EVar v _) su = M.lookupDefault e v su
subst (EApp e1 e2 z) su = EApp (subst e1 su) (subst e2 su) z
subst (ELam b e z) su = ELam b (subst e su') z
where
su' = M.delete (bindId b) su
canon :: Env a -> Expr a -> Expr a
canon g = alphaNormal . (`subst` g)
isEquiv :: Env a -> Expr a -> Expr a -> Bool
isEquiv g e1 e2 = isAlphEq g (subst e1 g) (subst e2 g)
--------------------------------------------------------------------------------
-- | Error Cases
--------------------------------------------------------------------------------
errInvalid :: Bind a -> Expr a -> Eqn a -> Expr a -> Result a
errInvalid b _ eqn _ = Invalid b (tag eqn)
errPartial :: Bind a -> Expr a -> Result a
errPartial b e = Partial b (tag e)
errDupDefn :: Bind a -> Result a
errDupDefn b = DupDefn b (tag b)
errDupEval :: Bind a -> Result a
errDupEval b = DupEval b (tag b) | null | https://raw.githubusercontent.com/ucsd-progsys/elsa/040aa85d4c63ae837d839fd7e5a2b85bd90c1289/src/Language/Elsa/Eval.hs | haskell | (isJust, maybeToList)
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Transitive Reachability
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Definition Equivalence
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Alpha Equivalence
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Beta Reduction
------------------------------------------------------------------------------
| `betas e` returns the list [e1,...en] of terms obtainable via a single-step
beta reduction from `e`.
different var, no subst
same var, but free-var-captured
same var, but no capture
subst-var has been rebound
------------------------------------------------------------------------------
| Evaluation to Normal Form
------------------------------------------------------------------------------
| NbE semantic domain
------------------------------------------------------------------------------
| General Helpers
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Error Cases
------------------------------------------------------------------------------ | # LANGUAGE OverloadedStrings , BangPatterns #
module Language.Elsa.Eval (elsa, elsaOn) where
import qualified Data.HashMap.Strict as M
import qualified Data.HashMap.Lazy as ML
import qualified Data.HashSet as S
import qualified Data.List as L
import Control.Monad.State
import Language.Elsa.Types
import Language.Elsa.Utils (qPushes, qInit, qPop, fromEither)
elsa :: Elsa a -> [Result a]
elsa = elsaOn (const True)
elsaOn :: (Id -> Bool) -> Elsa a -> [Result a]
elsaOn cond p =
case mkEnv (defns p) of
Left err -> [err]
Right g -> case checkDupEval (evals p) of
Left err -> [err]
Right _ -> [result g e | e <- evals p, check e ]
where
check = cond . bindId . evName
checkDupEval :: [Eval a] -> CheckM a (S.HashSet Id)
checkDupEval = foldM addEvalId S.empty
addEvalId :: S.HashSet Id -> Eval a -> CheckM a (S.HashSet Id)
addEvalId s e =
if S.member (bindId b) s
then Left (errDupEval b)
else Right (S.insert (bindId b) s)
where
b = evName e
result :: Env a -> Eval a -> Result a
result g e = fromEither (eval g e)
mkEnv :: [Defn a] -> CheckM a (Env a)
mkEnv = foldM expand M.empty
expand :: Env a -> Defn a -> CheckM a (Env a)
expand g (Defn b e) =
if dupId
then Left (errDupDefn b)
else case zs of
(x,l) : _ -> Left (Unbound b x l)
[] -> Right (M.insert (bindId b) e' g)
where
dupId = M.member (bindId b) g
e' = subst e g
zs = M.toList (freeVars' e')
type CheckM a b = Either (Result a) b
type Env a = M.HashMap Id (Expr a)
eval :: Env a -> Eval a -> CheckM a (Result a)
eval g (Eval n e steps) = go e steps
where
go e []
| isNormal g e = return (OK n)
| otherwise = Left (errPartial n e)
go e (s:steps) = step g n e s >>= (`go` steps)
step :: Env a -> Bind a -> Expr a -> Step a -> CheckM a (Expr a)
step g n e (Step k e')
| isEq k g e e' = return e'
| otherwise = Left (errInvalid n e k e')
isEq :: Eqn a -> Env a -> Expr a -> Expr a -> Bool
isEq (AlphEq _) = isAlphEq
isEq (BetaEq _) = isBetaEq
isEq (UnBeta _) = isUnBeta
isEq (DefnEq _) = isDefnEq
isEq (TrnsEq _) = isTrnsEq
isEq (UnTrEq _) = isUnTrEq
isEq (NormEq _) = isNormEq
isTrnsEq :: Env a -> Expr a -> Expr a -> Bool
isTrnsEq g e1 e2 = Mb.isJust (findTrans (isEquiv g e2) (canon g e1))
isUnTrEq :: Env a -> Expr a -> Expr a -> Bool
isUnTrEq g e1 e2 = isTrnsEq g e2 e1
findTrans :: (Expr a -> Bool) -> Expr a -> Maybe (Expr a)
findTrans p e = go S.empty (qInit e)
where
go seen q = do
(e, q') <- qPop q
if S.member e seen
then go seen q'
else if p e
then return e
else go (S.insert e seen) (qPushes q (betas e))
isDefnEq :: Env a -> Expr a -> Expr a -> Bool
isDefnEq g e1 e2 = subst e1 g == subst e2 g
isAlphEq :: Env a -> Expr a -> Expr a -> Bool
isAlphEq _ e1 e2 = alphaNormal e1 == alphaNormal e2
alphaNormal :: Expr a -> Expr a
alphaNormal = alphaShift 0
alphaShift :: Int -> Expr a -> Expr a
alphaShift n e = evalState (normalize M.empty e) n
type AlphaM a = State Int a
normalize :: M.HashMap Id Id -> Expr a -> AlphaM (Expr a)
normalize g (EVar x z) =
return (EVar (rename g x) z)
normalize g (EApp e1 e2 z) = do
e1' <- normalize g e1
e2' <- normalize g e2
return (EApp e1' e2' z)
normalize g (ELam (Bind x z1) e z2) = do
y <- fresh
let g' = M.insert x y g
e' <- normalize g' e
return (ELam (Bind y z1) e' z2)
rename :: M.HashMap Id Id -> Id -> Id
rename g x = M.lookupDefault x x g
fresh :: AlphaM Id
fresh = do
n <- get
put (n + 1)
return (newAId n)
newAId :: Int -> Id
newAId n = aId ++ show n
_isAId :: Id -> Maybe Int
_isAId x
| L.isPrefixOf aId x = Just . read . drop 2 $ x
| otherwise = Nothing
aId :: String
aId = "$x"
isBetaEq :: Env a -> Expr a -> Expr a -> Bool
isBetaEq _ e1 e2 = or [ e1' == e2 | e1' <- betas e1 ]
isUnBeta :: Env a -> Expr a -> Expr a -> Bool
isUnBeta g e1 e2 = isBetaEq g e2 e1
isNormal :: Env a -> Expr a -> Bool
isNormal g = null . betas . (`subst` g)
betas :: Expr a -> [Expr a]
betas (EVar _ _) = []
betas (ELam b e z) = [ ELam b e' z | e' <- betas e ]
betas (EApp e1 e2 z) = [ EApp e1' e2 z | e1' <- betas e1 ]
++ [ EApp e1 e2' z | e2' <- betas e2 ]
++ Mb.maybeToList (beta e1 e2)
beta :: Expr a -> Expr a -> Maybe (Expr a)
beta (ELam (Bind x _) e _) e' = substCA e x e'
beta _ _ = Nothing
substCA :: Expr a -> Id -> Expr a -> Maybe (Expr a)
substCA e x e' = go [] e
where
zs = freeVars e'
bnd bs zs = or [ b `isIn` zs | b <- bs ]
go bs e@(EVar y _)
go bs (EApp e1 e2 l) = do e1' <- go bs e1
e2' <- go bs e2
Just (EApp e1' e2' l)
go bs e@(ELam b e1 l)
| otherwise = do e1' <- go (b:bs) e1
Just (ELam b e1' l)
isIn :: Bind a -> S.HashSet Id -> Bool
isIn = S.member . bindId
isNormEq :: Env a -> Expr a -> Expr a -> Bool
isNormEq g e1 e2 = eqVal (subst e2 g) $ evalNbE ML.empty (subst e1 g)
where
evalNbE !env e = case e of
EVar x _ -> Mb.fromMaybe (Neutral x []) $ ML.lookup x env
ELam (Bind x _) b _ -> Fun $ \val -> evalNbE (ML.insert x val env) b
EApp f arg _ -> case evalNbE env f of
Fun f' -> f' (evalNbE env arg)
Neutral x args -> Neutral x (evalNbE env arg:args)
eqVal (EVar x _) (Neutral x' [])
= x == x'
eqVal (ELam (Bind x _) b _) (Fun f)
= eqVal b (f (Neutral x []))
eqVal (EApp f a _) (Neutral x (a':args))
= eqVal a a' && eqVal f (Neutral x args)
eqVal _ _ = False
data Value = Fun !(Value -> Value) | Neutral !Id ![Value]
freeVars :: Expr a -> S.HashSet Id
freeVars = S.fromList . M.keys . freeVars'
freeVars' :: Expr a -> M.HashMap Id a
freeVars' (EVar x l) = M.singleton x l
freeVars' (ELam b e _) = M.delete (bindId b) (freeVars' e)
freeVars' (EApp e e' _) = M.union (freeVars' e) (freeVars' e')
subst :: Expr a -> Env a -> Expr a
subst e@(EVar v _) su = M.lookupDefault e v su
subst (EApp e1 e2 z) su = EApp (subst e1 su) (subst e2 su) z
subst (ELam b e z) su = ELam b (subst e su') z
where
su' = M.delete (bindId b) su
canon :: Env a -> Expr a -> Expr a
canon g = alphaNormal . (`subst` g)
isEquiv :: Env a -> Expr a -> Expr a -> Bool
isEquiv g e1 e2 = isAlphEq g (subst e1 g) (subst e2 g)
errInvalid :: Bind a -> Expr a -> Eqn a -> Expr a -> Result a
errInvalid b _ eqn _ = Invalid b (tag eqn)
errPartial :: Bind a -> Expr a -> Result a
errPartial b e = Partial b (tag e)
errDupDefn :: Bind a -> Result a
errDupDefn b = DupDefn b (tag b)
errDupEval :: Bind a -> Result a
errDupEval b = DupEval b (tag b) |
3dfaeaefe86c11160d73884c5f4c889c4c55d38f42a2c6e7b49fa9f504d035c3 | lortabac/ariel | Types.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE TemplateHaskell #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
module Ariel.Core.Types where
import Ariel.Common.Types
import Ariel.Prelude
import Control.Lens (Plated, children, transformM, makeLenses)
import GHC.Generics
import Language.Sexp.Located (Position, dummyPos)
import Logic.Unify
data Decl
= Decl Position QName Expr
deriving (Eq, Show, Generic)
data Ty
= TCon Name
| TApp Ty Ty
| TVar TyVar
| Forall [TyVar] Ty
| Metavar UVar
deriving (Eq, Show, Ord, Generic, Data)
pattern TArr :: Ty -> Ty -> Ty
pattern TArr t1 t2 = TApp (TApp (TCon "->") t1) t2
pattern TInt :: Ty
pattern TInt = TCon "Int"
pattern TString :: Ty
pattern TString = TCon "String"
pattern TBool :: Ty
pattern TBool = TCon "Bool"
pattern TIO :: Ty -> Ty
pattern TIO t = TApp (TCon "IO") t
instance Plated Ty
instance Unifiable Ty where
getVar (Metavar v) = Just v
getVar _ = Nothing
transformTermM = transformM
termChildren = children
data Kind
= Star
| KArr Kind Kind
deriving (Eq, Show, Ord, Data)
data Expr
= Int Int
| String Text
| Bool Bool
| Con QName Tag
| Global Position QName
| Lam Position Name Expr
| Let Position Name Expr Expr
| Prim Position Text [Expr]
| IOPrim Position Text [Expr]
| Case Expr (Map Tag Expr)
| Var Position Name
| App Position Expr Expr
| If Position Expr Expr Expr
| BindIO Position Expr Expr
| Ann Position Expr Ty
| Fix Position Expr
deriving (Eq, Show, Generic)
-- | Convenience constructor for vars
var :: Name -> Expr
var = Var dummyPos
-- | Convenience operator for lambdas
(==>) :: Name -> Expr -> Expr
(==>) = Lam dummyPos
infixr 1 ==>
-- | Convenience operator for applications
(@@) :: Expr -> Expr -> Expr
(@@) = App dummyPos
infixl 9 @@
data Defs = Defs
{ _globals :: Map QName Expr,
_sumTypes :: Map QName (Map Tag [Ty])
}
deriving (Eq, Show)
instance Semigroup Defs where
Defs gs1 st1 <> Defs gs2 st2 = Defs (gs1 <> gs2) (st1 <> st2)
instance Monoid Defs where
mempty = Defs mempty mempty
makeLenses ''Defs
| null | https://raw.githubusercontent.com/lortabac/ariel/80b89d52e089bb2589a6c3272300fa4897f6072d/src/Ariel/Core/Types.hs | haskell | # LANGUAGE DeriveDataTypeable #
# LANGUAGE OverloadedStrings #
| Convenience constructor for vars
| Convenience operator for lambdas
| Convenience operator for applications | # LANGUAGE TemplateHaskell #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PatternSynonyms #
module Ariel.Core.Types where
import Ariel.Common.Types
import Ariel.Prelude
import Control.Lens (Plated, children, transformM, makeLenses)
import GHC.Generics
import Language.Sexp.Located (Position, dummyPos)
import Logic.Unify
data Decl
= Decl Position QName Expr
deriving (Eq, Show, Generic)
data Ty
= TCon Name
| TApp Ty Ty
| TVar TyVar
| Forall [TyVar] Ty
| Metavar UVar
deriving (Eq, Show, Ord, Generic, Data)
pattern TArr :: Ty -> Ty -> Ty
pattern TArr t1 t2 = TApp (TApp (TCon "->") t1) t2
pattern TInt :: Ty
pattern TInt = TCon "Int"
pattern TString :: Ty
pattern TString = TCon "String"
pattern TBool :: Ty
pattern TBool = TCon "Bool"
pattern TIO :: Ty -> Ty
pattern TIO t = TApp (TCon "IO") t
instance Plated Ty
instance Unifiable Ty where
getVar (Metavar v) = Just v
getVar _ = Nothing
transformTermM = transformM
termChildren = children
data Kind
= Star
| KArr Kind Kind
deriving (Eq, Show, Ord, Data)
data Expr
= Int Int
| String Text
| Bool Bool
| Con QName Tag
| Global Position QName
| Lam Position Name Expr
| Let Position Name Expr Expr
| Prim Position Text [Expr]
| IOPrim Position Text [Expr]
| Case Expr (Map Tag Expr)
| Var Position Name
| App Position Expr Expr
| If Position Expr Expr Expr
| BindIO Position Expr Expr
| Ann Position Expr Ty
| Fix Position Expr
deriving (Eq, Show, Generic)
var :: Name -> Expr
var = Var dummyPos
(==>) :: Name -> Expr -> Expr
(==>) = Lam dummyPos
infixr 1 ==>
(@@) :: Expr -> Expr -> Expr
(@@) = App dummyPos
infixl 9 @@
data Defs = Defs
{ _globals :: Map QName Expr,
_sumTypes :: Map QName (Map Tag [Ty])
}
deriving (Eq, Show)
instance Semigroup Defs where
Defs gs1 st1 <> Defs gs2 st2 = Defs (gs1 <> gs2) (st1 <> st2)
instance Monoid Defs where
mempty = Defs mempty mempty
makeLenses ''Defs
|
2bb5710390f3f88589b318e8a8bc93f3e42c82c7194a5e3725ae0ad4fb90e533 | UnNetHack/pinobot | Bot.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - name - shadowing #
module Bot
( message,
)
where
import Control.Applicative hiding
( many,
(<|>),
)
import Control.Monad hiding (mapM_)
import Control.Monad.Trans.Writer
import Data.Foldable
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TL
import qualified Data.Text.Lazy.Builder as TLB
import NetHack.Data.Dice
import qualified NetHack.Data.Monster as MD
import qualified NetHack.Data.Variant as V
import Text.Parsec
import qualified Text.Parsec.Text as T
import Prelude hiding
( concatMap,
foldl,
foldl1,
mapM_,
)
-- Add variants here.
variants :: IO [V.Variant]
variants =
sequence $
variantify $
[ "Vanilla", -- first one is used by default
"Vanilla343",
"UnNetHack",
"UnNetHackPlus",
"SporkHack",
"GruntHack",
"Slashem",
"Brass",
"Dnethack",
"Notdnethack",
"SlashemExtended",
"SlashTHEM",
"Fourk",
"EvilHack",
"XNetHack",
"SpliceHack"
]
where
variantify = fmap $ \name -> V.loadVariant $ "variants/" ++ name ++ ".yaml"
Shamelessly stolen from HaskellWiki which in turn stole it from Lloyd
:
-- /~lloyd/tildeStrings/Alignment/92.IPL.html
--
Calculates the distance between two lists .
dist :: Eq a => [a] -> [a] -> Int
dist a b =
last
( if lab == 0
then mainDiag
else
if lab > 0
then lowers !! (lab - 1)
< 0
uppers !! (-1 - lab)
)
where
mainDiag = oneDiag a b (head uppers) (-1 : head lowers)
uppers = eachDiag a b (mainDiag : uppers) -- upper diagonals
lowers = eachDiag b a (mainDiag : lowers) -- lower diagonals
eachDiag _ [] _ = []
eachDiag a (_ : bs) (lastDiag : diags) =
oneDiag a bs nextDiag lastDiag : eachDiag a bs diags
where
nextDiag = head (tail diags)
eachDiag _ _ _ = undefined -- suppresses warnings
oneDiag a b diagAbove diagBelow = thisdiag
where
doDiag [] _ _ _ _ = []
doDiag _ [] _ _ _ = []
doDiag (ach : as) (bch : bs) nw n w =
me
: doDiag as bs me (tail n) (tail w)
where
me = if ach == bch then nw else 1 + min3 (head w) nw (head n)
firstelt = 1 + head diagBelow
thisdiag = firstelt : doDiag a b firstelt diagAbove (tail diagBelow)
lab = length a - length b
min3 x y z = if x < y then x else min y z
distT :: T.Text -> T.Text -> Int
distT t1 t2 = dist (T.unpack $ T.toLower t1) (T.unpack $ T.toLower t2)
-- Returns the most similar monster name along with its levenshtein distance.
mostSimilarMonster :: V.Variant -> T.Text -> (Int, T.Text)
mostSimilarMonster variant name =
minimumBy (\(a1, _) (a2, _) -> a1 `compare` a2) $
zip (map (distT name) all) all
where
all :: [T.Text]
all = V.allMonsterNames variant
-- Returns the most similar monster name but only if parameters and results are
-- reasonably "sane".
--
" Sane " here being : no overly long names allowed and if the
-- distance is too great, then the result is discarded.
mostSimilarMonsterSane :: V.Variant -> T.Text -> Maybe T.Text
mostSimilarMonsterSane variant text
| T.length text >= 60 =
Nothing
| otherwise =
let (distance, result) = mostSimilarMonster variant text
in if distance <= 3 then Just result else Nothing
-- | Same as above, but with less assurances.
mostSimilarMonsterHalfSane :: V.Variant -> T.Text -> Maybe T.Text
mostSimilarMonsterHalfSane variant text
| T.length text >= 60 =
Nothing
| otherwise =
let (_, result) = mostSimilarMonster variant text in Just result
decideVariant :: [V.Variant] -> T.Text -> V.Variant
decideVariant variants name =
fromMaybe (head variants) $
find (\var -> V.commandPrefix var == name) variants
relevantFlag :: MD.MonsterFlag -> Maybe T.Text
relevantFlag MD.FlDisplaces = Just "displaces"
relevantFlag MD.FlVanDmgRduc = Just "damage reduction"
relevantFlag MD.FlBlinkAway = Just "blinks away"
relevantFlag MD.FlFairy = Just "fairy"
relevantFlag MD.FlScentTracker = Just "tracks scents"
relevantFlag MD.FlOviparous = Just "oviparous"
relevantFlag MD.FlTouchPetrifies = Just "touch petrifies"
relevantFlag MD.FlInvisible = Just "invisible"
relevantFlag MD.FlWallwalk = Just "phases"
relevantFlag MD.FlFly = Just "flies"
relevantFlag MD.FlSwim = Just "swims"
relevantFlag MD.FlAmorphous = Just "amorphous"
relevantFlag MD.FlTunnel = Just "tunnels"
relevantFlag MD.FlCling = Just "clings"
relevantFlag MD.FlConceal = Just "conceals"
relevantFlag MD.FlAmphibious = Just "amphibious"
relevantFlag MD.FlBreathless = Just "breathless"
relevantFlag MD.FlSeeInvis = Just "seeinvis"
relevantFlag MD.FlThickHide = Just "thick hide"
relevantFlag MD.FlRegen = Just "regen"
relevantFlag MD.FlUnSolid = Just "unsolid"
relevantFlag MD.FlInfravisible = Just "infravis"
relevantFlag MD.FlCovetous = Just "covetous"
relevantFlag MD.FlMindless = Just "mindless"
relevantFlag MD.FlNoPoly = Just "nopoly"
relevantFlag MD.FlTeleport = Just "tele"
relevantFlag MD.FlUndead = Just "undead"
relevantFlag MD.FlDemon = Just "demon"
relevantFlag MD.FlVegan = Just "vegan"
relevantFlag MD.FlVegetarian = Just "vegetarian"
relevantFlag MD.FlStalk = Just "stalker"
relevantFlag MD.FlMetallivore = Just "metallivore"
relevantFlag MD.FlPoisonous = Just "poisonous"
relevantFlag MD.FlLithivore = Just "lithivore"
relevantFlag MD.FlPassesBars = Just "passes-bars"
relevantFlag MD.FlHatesSilver = Just "silverhate"
relevantFlag _ = Nothing
showB :: Show a => a -> TL.Builder
showB = TL.fromString . show
lineMonsterInformation :: MD.Monster -> T.Text
lineMonsterInformation mon =
TL.toStrict $
TL.toLazyText $
(TL.fromText $ MD.moName mon)
<> " ("
<> monsymbol
<> ")"
<> " | Lvl: "
<> showB (MD.moBaseLevel mon)
<> " | Diff: "
<> showB (MD.moDifficulty mon)
<> " | Spd: "
<> showB (MD.moSpeed mon)
<> " | Res: "
<> resistances (MD.moResistances mon)
<> "| Confer: "
<> confers (MD.moConferred mon)
<> "| MR: "
<> showB (MD.moMR mon)
<> " | Gen: "
<> generates (MD.moGenerationPlaces mon)
<> "| AC: "
<> case MD.moAC mon of
Left ac_int -> showB ac_int
Right ac_str -> TL.fromText ac_str
<> " | Atk: "
<> attacks (MD.moAttacks mon)
<> " | Align: "
<> showB (MD.moAlign mon)
<> " | "
<> flags
where
generates :: [MD.Place] -> TL.Builder
generates [] = "special "
generates places = mconcat $ fmap generationPlace places
generationPlace MD.Sheol = "sheol "
generationPlace MD.Gehennom = "gehennom "
generationPlace MD.Dungeons = "dungeons "
generationPlace MD.Unique = "unique "
isCarnivore = MD.hasFlag MD.FlCarnivore mon
isHerbivore = MD.hasFlag MD.FlHerbivore mon
isOmnivore = isCarnivore && isHerbivore
relevantFlagsW :: Writer [TL.Builder] ()
relevantFlagsW = do
when (MD.moGenocidable mon) $ tell ["genocidable"]
if isOmnivore
then tell ["omnivore"]
else do
when isCarnivore $ tell ["carnivore"]
when isHerbivore $ tell ["herbivore"]
mapM_ (tell . fmap TL.fromText . catMaybes . return . relevantFlag) $
MD.moFlags mon
relevantFlags :: [TL.Builder]
relevantFlags = execWriter relevantFlagsW
flags :: TL.Builder
flags
| null relevantFlags = "none"
| null $ tail relevantFlags = head relevantFlags
| otherwise = foldl1 (\accum str -> accum <> ", " <> str) relevantFlags
attacks :: [MD.Attack] -> TL.Builder
attacks [] = "none"
attacks [attack] = attackName attack
attacks xs = foldl1 (\accum str -> accum <> ", " <> str) (fmap attackName xs)
attackName :: MD.Attack -> TL.Builder
attackName (MD.Attack atype dtype (Dice d1 d2)) =
showB d1
<> "d"
<> showB d2
<> " "
<> attackTypeName atype
<> " "
<> attackDamageName dtype
attackTypeName MD.AtNone = "passive"
attackTypeName MD.AtClaw = "claw"
attackTypeName MD.AtBite = "bite"
attackTypeName MD.AtKick = "kick"
attackTypeName MD.AtButt = "butt"
attackTypeName MD.AtTouch = "touch"
attackTypeName MD.AtSting = "sting"
attackTypeName MD.AtHug = "hug"
attackTypeName MD.AtSpit = "spit"
attackTypeName MD.AtEngulf = "engulf"
attackTypeName MD.AtBreath = "breath"
attackTypeName MD.AtExplode = "explode"
attackTypeName MD.AtSuicideExplode = "suicide explode"
attackTypeName MD.AtGaze = "gaze"
attackTypeName MD.AtTentacle = "tentacle"
attackTypeName MD.AtWeapon = "weapon"
attackTypeName MD.AtCast = "cast"
attackTypeName MD.AtScre = "scream"
attackTypeName MD.AtMultiply = "multiply"
attackTypeName MD.AtArrow = "arrow"
attackTypeName MD.AtReach = "reach"
attackTypeName MD.AtMirror = "mirror"
attackTypeName MD.AtWhip = "whip"
attackTypeName MD.AtMMagical = "mmmmagical"
attackTypeName MD.AtReachingBite = "reaching"
attackTypeName MD.AtLash = "lashing"
attackTypeName MD.AtTrample = "trample"
attackTypeName MD.AtScratch = "scratch"
attackTypeName MD.AtIllurien = "illurien-swallow"
attackTypeName MD.AtTinker = "tinker"
attackTypeName MD.AtPhaseNonContact = "non-contacting-phase"
attackTypeName MD.AtBeamNonContact = "non-contacting-beam"
attackTypeName MD.AtMillionArms = "million-weaponized-arms"
attackTypeName MD.AtSpin = "spin"
attackTypeName MD.AtAny = "any"
attackTypeName MD.AtRangedThorns = "ranged-thorns"
attackTypeName MD.AtCloseRangeBreath = "close-range-breath"
attackTypeName MD.AtOffhandedWeapon = "offhanded-weapon"
attackTypeName MD.AtOffOffhandedWeapon = "offoffhanded-weapon"
attackTypeName MD.AtNonContactAttack = "non-contact-attack"
attackTypeName MD.AtReachTouch = "longreaching-touch"
attackTypeName MD.AtReachBite = "longreaching-bite"
attackTypeName MD.AtPassiveWideGaze = "passive-gaze"
attackTypeName MD.AtHitsIfTwoPreviousHitsConnect = "hits-if-two-previous-hits-connect"
attackTypeName MD.AtLashingVine = "lashing-vines"
attackTypeName MD.AtBlackGoat = "black-goat-shenanigans"
attackTypeName MD.AtAutoHit = "autohit"
attackTypeName MD.AtAdjacent = "adjacent"
attackTypeName MD.AtTalk = "talk"
attackTypeName MD.AtTailSlap = "tailslap"
attackTypeName MD.AtVolley = "volley"
attackTypeName MD.AtWolfHeadBite = "wolfhead-bite"
attackDamageName MD.AdDimness = "dimness"
attackDamageName MD.AdMapAmnesia = "map-amnesia"
attackDamageName MD.AdIncreaseWeight = "increase-weight"
attackDamageName MD.AdCast = "cast"
attackDamageName MD.AdChaos = "chaos"
attackDamageName MD.AdVomitInducing = "vomit-inducing"
attackDamageName MD.AdNegativeEnchantment = "negative-enchantment"
attackDamageName MD.AdVaporization = "vaporization"
attackDamageName MD.AdStoneEdge = "stone-edge"
attackDamageName MD.AdLitterBlob = "litter-blob"
attackDamageName MD.AdCreateTrap = "create-trap"
attackDamageName MD.AdRngIntervention = "rng-intervention"
attackDamageName MD.AdIdentityAttack = "identity-attack"
attackDamageName MD.AdFrenzy = "frenzy"
attackDamageName MD.AdNether = "nether"
attackDamageName MD.AdInsanity = "insanity"
attackDamageName MD.AdNastyTrap = "nasty-trap"
attackDamageName MD.AdSkillCapReduce = "skill-cap-reducting"
attackDamageName MD.AdDreamAttack = "dream-eating"
attackDamageName MD.AdBadRandomEffect = "bad-random-effect"
attackDamageName MD.AdFumble = "fumble"
attackDamageName MD.AdVenomous = "venomous"
attackDamageName MD.AdVulnerability = "vulnerability-inducing"
attackDamageName MD.AdCurseItems = "curse-items"
attackDamageName MD.AdSludge = "sludge"
attackDamageName MD.AdMasterBlaster = "masterblaster"
attackDamageName MD.AdPits = "pits"
attackDamageName MD.AdIceBlock = "iceblock"
attackDamageName MD.AdStinkingCloud = "stinking-cloud"
attackDamageName MD.AdFeelPain = "feel-pain"
attackDamageName MD.AdDeadGaze = "deadly-gaze"
attackDamageName MD.AdGravity = "gravity"
attackDamageName MD.AdSound = "sound"
attackDamageName MD.AdVampireDrain = "vampire-drain"
attackDamageName MD.AdNegativeProtection = "negative-protection"
attackDamageName MD.AdDepression = "depressing"
attackDamageName MD.AdPoisonStat = "poison-sting"
attackDamageName MD.AdNexus = "nexus"
attackDamageName MD.AdSuckEquipment = "suck-equipment"
attackDamageName MD.AdBanishment = "banishment"
attackDamageName MD.AdCursedUnihorn = "cursed-unicorn-horn"
attackDamageName MD.AdLazyness = "lazy"
attackDamageName MD.AdPlasma = "plasma"
attackDamageName MD.AdDrainsAllSortsOfStuff = "drains-all-sorts-of-stuff"
attackDamageName MD.AdFakeMessages = "fake-message"
attackDamageName MD.AdCharisma = "charisma-taking"
attackDamageName MD.AdWrath = "wrath"
attackDamageName MD.AdDrainLifeOrStats = "drain-life-and/or-stats"
attackDamageName MD.AdInertia = "inertia"
attackDamageName MD.AdThirsty = "thirsty"
attackDamageName MD.AdMana = "mana"
attackDamageName MD.AdSilverStarlightRapier = "silver-starlight-rapier"
attackDamageName MD.AdRandomGaze = "random gaze"
attackDamageName MD.AdHalfDragon = "half-dragon"
attackDamageName MD.AdStealByTeleportation = "steal-by-teleportation"
attackDamageName MD.AdFear = "fear"
attackDamageName MD.AdBlackWebShadow = "black-web-shadow"
attackDamageName MD.AdNetzach = "netzach"
attackDamageName MD.AdWatcherTentacleGaze = "magical-tentacle-gaze"
attackDamageName MD.AdNumb = "numb"
attackDamageName MD.AdFreezeSolid = "freeze-solid"
attackDamageName MD.AdWither = "wither"
attackDamageName MD.AdBurn = "burn"
attackDamageName MD.AdDisplacement = "displacement"
attackDamageName MD.AdTinker = "tinker"
attackDamageName MD.AdFireworks = "fireworks"
attackDamageName MD.AdOona = "oona"
attackDamageName MD.AdStudy = "study"
attackDamageName MD.AdCalm = "calm"
attackDamageName MD.AdTickle = "tickle"
attackDamageName MD.AdPoly = "poly"
attackDamageName MD.AdBehead = "behead"
attackDamageName MD.AdCancellation = "cancellation"
attackDamageName MD.AdPhys = "physical"
attackDamageName MD.AdMagicMissile = "magic missile"
attackDamageName MD.AdFire = "fire"
attackDamageName MD.AdCold = "cold"
attackDamageName MD.AdSleep = "sleep"
attackDamageName MD.AdDisintegrate = "disintegrate"
attackDamageName MD.AdElectricity = "shock"
attackDamageName MD.AdStrDrain = "drain str"
attackDamageName MD.AdAcid = "acid"
attackDamageName MD.AdSpecial1 = "special1"
attackDamageName MD.AdSpecial2 = "special2"
attackDamageName MD.AdBlind = "blind"
attackDamageName MD.AdStun = "stun"
attackDamageName MD.AdSlow = "slow"
attackDamageName MD.AdParalyse = "paralyze"
attackDamageName MD.AdLevelDrain = "level drain"
attackDamageName MD.AdMagicDrain = "magic drain"
attackDamageName MD.AdLegs = "legwound"
attackDamageName MD.AdStone = "petrification"
attackDamageName MD.AdSticking = "sticky"
attackDamageName MD.AdGoldSteal = "gold steal"
attackDamageName MD.AdItemSteal = "item steal"
attackDamageName MD.AdSeduce = "seduce"
attackDamageName MD.AdTeleport = "teleport"
attackDamageName MD.AdRust = "rust"
attackDamageName MD.AdConfuse = "confuse"
attackDamageName MD.AdDigest = "digest"
attackDamageName MD.AdHeal = "heal"
attackDamageName MD.AdWrap = "wrap"
attackDamageName MD.AdWere = "lycanthropy"
attackDamageName MD.AdDexDrain = "drain dex"
attackDamageName MD.AdConDrain = "drain con"
attackDamageName MD.AdIntDrain = "drain int"
attackDamageName MD.AdDisease = "disease"
attackDamageName MD.AdRot = "rot"
attackDamageName MD.AdSex = "sex"
attackDamageName MD.AdHallucination = "hallucination"
attackDamageName MD.AdDeath = "Death"
attackDamageName MD.AdPestilence = "Pestilence"
attackDamageName MD.AdFamine = "Famine"
attackDamageName MD.AdSlime = "slime"
attackDamageName MD.AdDisenchant = "disenchant"
attackDamageName MD.AdCorrode = "corrosion"
attackDamageName MD.AdClerical = "clerical"
attackDamageName MD.AdSpell = "spell"
attackDamageName MD.AdRandomBreath = "random breath"
attackDamageName MD.AdAmuletSteal = "amulet steal"
attackDamageName MD.AdCurse = "curse"
attackDamageName MD.AdBlink = "blink"
attackDamageName MD.AdLevelTeleport = "level teleport"
attackDamageName MD.AdDecapitate = "decapitate"
attackDamageName MD.AdFreeze = "freeze"
attackDamageName MD.AdPunisher = "punisher"
attackDamageName MD.AdDrown = "drown"
attackDamageName MD.AdShred = "shred"
attackDamageName MD.AdJailer = "jailer"
attackDamageName MD.AdBoulderArrow = "boulder-arrow"
attackDamageName MD.AdBoulderArrowRandomSpread =
"boulder-arrow-random-spread"
attackDamageName MD.AdMultiElementCounterAttackThatAngersTons =
"multi-elemental-counterattack-that-angers-tons" -- wtf
attackDamageName MD.AdPoison = "poison"
attackDamageName MD.AdWisdom = "wisdom"
attackDamageName MD.AdVorpal = "vorpal"
attackDamageName MD.AdStealQuestArtifact = "steals-quest-artifact"
attackDamageName MD.AdSpawnChaos = "spawn-chaos"
attackDamageName MD.AdIronBall = "iron-ball"
attackDamageName MD.AdGrow = "grow"
attackDamageName MD.AdSilver = "silver"
attackDamageName MD.AdAbduction = "abduction"
attackDamageName MD.AdElementalGaze = "elemental-gaze"
attackDamageName MD.AdAsmodeusBlood = "asmodeus-blood"
attackDamageName MD.AdMirror = "mirror"
attackDamageName MD.AdLeviathan = "leviathan"
attackDamageName MD.AdUnknownPriest = "unknown-priest"
attackDamageName MD.AdMalk = "immobilizing-destroying"
attackDamageName MD.AdTentacle = "tentacle"
attackDamageName MD.AdWet = "wet"
attackDamageName MD.AdHeadSpike = "head-spike"
attackDamageName MD.AdTele = "teleportation"
attackDamageName MD.AdLethe = "lethe-wet"
attackDamageName MD.AdHorn = "horn"
attackDamageName MD.AdSolar = "solar"
attackDamageName MD.AdEscalatingDamage = "escalating-damage"
attackDamageName MD.AdSoul = "soul"
attackDamageName MD.AdMist = "mist"
attackDamageName MD.AdSuck = "suck"
attackDamageName MD.AdDrainLuck = "drain luck"
attackDamageName MD.AdSpore = "spores"
attackDamageName MD.AdLava = "lava"
attackDamageName MD.AdSunflower = "sunflowerpower"
attackDamageName MD.AdFernExplosion = "fernxplosion"
attackDamageName MD.AdMandrake = "mandrake-shriek"
attackDamageName MD.AdPhysRetaliate = "retaliate"
attackDamageName MD.AdVamp = "vampire"
attackDamageName MD.AdWebs = "webs"
attackDamageName MD.AdWeeping = "levtele-drain"
attackDamageName MD.AdGaro = "rumor-dispense"
attackDamageName MD.AdGaroMaster = "oracle-dispense"
attackDamageName MD.AdLoadstones = "loadstone-throw"
attackDamageName MD.AdRemoveEngravings = "remove-engravings"
attackDamageName MD.AdIllurien = "illurien-swallow"
attackDamageName MD.AdLightRay = "light-ray"
attackDamageName MD.AdRemoveLight = "remove-light"
attackDamageName MD.AdDisarm = "disarm"
attackDamageName MD.AdIdentityNastiness = "identity-nastiness"
attackDamageName MD.AdItemDamager = "item-damaging"
attackDamageName MD.AdAntimatter = "antimatter"
attackDamageName MD.AdPain = "PAIN"
attackDamageName MD.AdTech = "technology"
attackDamageName MD.AdMemoryReduce = "memory-reduce"
attackDamageName MD.AdSkillReduce = "skill-reduce"
attackDamageName MD.AdStatDamage = "stat-damage"
attackDamageName MD.AdGearDamage = "gear-damaging"
attackDamageName MD.AdThievery = "thievery"
attackDamageName MD.AdLavaTiles = "lava-tiles"
attackDamageName MD.AdDeletesYourGame = "data-delete"
attackDamageName MD.AdDrainAlignment = "drain-alignment"
attackDamageName MD.AdAddSins = "makes-you-a-dirty-sinner"
attackDamageName MD.AdContamination = "contamination"
attackDamageName MD.AdAggravateMonster = "makes-you-aggravate-monsters"
attackDamageName MD.AdDestroyEq = "destroys-equipment"
attackDamageName MD.AdTrembling = "gives-you-parkinsons"
attackDamageName MD.AdAny = "any"
attackDamageName MD.AdCurseArmor = "curse-armor"
attackDamageName MD.AdIncreaseSanity = "increase-sanity"
attackDamageName MD.AdReallyBadEffect = "really-bad-effect"
attackDamageName MD.AdBleedout = "bleedout"
attackDamageName MD.AdShank = "shank"
attackDamageName MD.AdDrainScore = "drain-score"
attackDamageName MD.AdTerrainTerror = "terrain-terror"
attackDamageName MD.AdFeminism = "feminism"
attackDamageName MD.AdLevitation = "levitation"
attackDamageName MD.AdReduceMagicCancellation = "reduce-magic-cancellation"
attackDamageName MD.AdIllusion = "illusion"
attackDamageName MD.AdSpecificRegularAttack = "specific-regular-attack"
attackDamageName MD.AdSpecificNastyTrap = "specific-nasty-trap"
attackDamageName MD.AdDebuff = "debuff"
attackDamageName MD.AdNivellation = "nivellation"
attackDamageName MD.AdTechDrain = "technique-drain"
attackDamageName MD.AdBlasphemy = "makes-your-god-angry-at-you"
attackDamageName MD.AdDropItems = "drop-items"
attackDamageName MD.AdRemoveErosionProof = "remove-erosion-proof"
attackDamageName MD.AdFlame = "flame"
attackDamageName MD.AdPsionic = "psionic"
attackDamageName MD.AdLoud = "loud"
attackDamageName MD.AdKnockback = "knockback"
attackDamageName MD.AdWater = "water"
attackDamageName MD.AdPitAttack = "create-pit"
attackDamageName MD.AdDrainConstitution = "drain-constitution"
attackDamageName MD.AdDrainStrength = "drain-strength"
attackDamageName MD.AdDrainCharisma = "drain-charisma"
attackDamageName MD.AdDrainDexterity = "drain-dexterity"
attackDamageName MD.AdFleshHook = "flesh-hook"
attackDamageName MD.AdImplantEgg = "implant-egg"
attackDamageName MD.AdDessicate = "dessicate"
attackDamageName MD.AdArrowOfSlaying = "arrow-of-slaying"
attackDamageName MD.AdArchonFire = "archon-fire"
attackDamageName MD.AdGoldify = "goldify"
attackDamageName MD.AdMoonlightRapier = "moonlight-rapier"
attackDamageName MD.AdMummyRot = "rot"
attackDamageName MD.AdMindWipe = "mindwipe"
attackDamageName MD.AdSlowStoning = "slow-stoning"
attackDamageName MD.AdInflictDoubt = "inflict-doubt"
attackDamageName MD.AdRevelatoryWhisper = "revelatory-whisper"
attackDamageName MD.AdPull = "pull"
attackDamageName MD.AdMercuryBlade = "mercury-blade"
attackDamageName MD.AdBloodFrenzy = "bloodfrenzy"
attackDamageName MD.AdPollen = "pollen"
attackDamageName MD.AdElementalCold = "elemental-cold"
attackDamageName MD.AdElementalPoison = "elemental-poison"
attackDamageName MD.AdElementalFire = "elemental-fire"
attackDamageName MD.AdElementalElectric = "elemental-electric"
attackDamageName MD.AdElementalAcid = "elemental-acid"
attackDamageName MD.AdFourSeasons = "fourseasons"
attackDamageName MD.AdCreateSphere = "create-sphere"
attackDamageName MD.AdConflictTouch = "conflict-touch"
attackDamageName MD.AdAntiBloodAttack = "antiblood-attack"
attackDamageName MD.AdFirePoisonPhysicalBlindness = "fire+poison+physical+blind"
attackDamageName MD.AdCharm = "charm"
attackDamageName MD.AdScald = "scald"
attackDamageName MD.AdEatGold = "eat-gold"
attackDamageName MD.AdQuarkFlavour = "quark-flavour"
attackDamageName MD.AdMildHunger = "mild-hunger"
attackDamageName MD.AdShoe = "SHOE-ATTACK"
attackDamageName MD.AdLaser = "laser"
attackDamageName MD.AdNuke = "nuke"
attackDamageName MD.AdUnholy = "unholy"
attackDamageName MD.AdHoly = "holy"
attackDamageName MD.AdLokoban = "lokoban"
attackDamageName MD.AdRock = "rock"
attackDamageName MD.AdHalluSick = "hallusick"
attackDamageName MD.AdYank = "yank"
attackDamageName MD.AdBigExplosion = "big-explosion"
attackDamageName MD.AdExplodingMMSpellbook = "exploding-magic-missile-spellbooks"
attackDamageName MD.AdAlignmentBlast = "alignment-blast"
attackDamageName MD.AdReleaseAlignmentSpirits = "release-alignment-spirits"
attackDamageName MD.AdCrystalMemories = "crystal-memories"
attackDamageName MD.AdDilithiumCrystals = "dilithium-crystals"
attackDamageName MD.AdMirrorBlast = "mirror-blast"
attackDamageName MD.AdVoidWhispers = "void-whispers"
attackDamageName MD.AdWarMachineGaze = "war-machine-gaze"
attackDamageName MD.AdSimurgh = "simurgh"
attackDamageName MD.AdInjectLarva = "inject-larva"
attackDamageName MD.AdMakeSkeletons = "make-skeletons"
attackDamageName MD.AdPotionEffect = "potion-effect"
attackDamageName MD.AdKidnap = "kidnap"
attackDamageName MD.AdLaws = "law"
attackDamageName MD.AdGetLost = "get-lost"
attackDamageName MD.AdTransmute = "transmute"
attackDamageName MD.AdGrowHeads = "grow-heads"
attackDamageName MD.AdForgetItems = "1%-forget-items"
attackDamageName MD.AdWind = "wind"
attackDamageName MD.AdQuills = "quills"
attackDamageName MD.AdVoidDisintegrate = "void-disintegrate"
attackDamageName MD.AdPerHitDie = "per-hit-die"
attackDamageName MD.AdSeverePoison = "severe-poison"
attackDamageName MD.AdHolyUnholyEnergy = "holy-unholy-energy"
confers :: [MD.Resistance] -> TL.Builder
confers [] = "nothing "
confers xs = mconcat $ fmap resistanceName xs
resistances :: [MD.Resistance] -> TL.Builder
resistances [] = "none "
resistances xs = mconcat $ fmap resistanceName xs
resistanceName MD.ReFire = "fire "
resistanceName MD.ReCold = "cold "
resistanceName MD.ReSleep = "sleep "
resistanceName MD.ReDisintegrate = "disintegrate "
resistanceName MD.ReElectricity = "shock "
resistanceName MD.RePoison = "poison "
resistanceName MD.ReAcid = "acid "
resistanceName MD.RePetrification = "petrification "
resistanceName MD.ReDrain = "drain "
resistanceName MD.ReMagic = "magic "
TODO : get rid of IRCisms from this module . We are supposed to be
higher - level and not care whether we are on IRC or somewhere else .
monsymbol =
"\x03"
<> ircColor (MD.moColor mon)
<> ",01"
<> TLB.singleton (MD.moSymbol mon)
<> "\x0f"
ircColor :: MD.Color -> TL.Builder
ircColor MD.Black = "14"
ircColor MD.Red = "05"
ircColor MD.Blue = "02"
ircColor MD.BrightBlue = "12"
ircColor MD.BrightMagenta = "13"
ircColor MD.BrightCyan = "11"
ircColor MD.Cyan = "10"
ircColor MD.Orange = "04"
ircColor MD.Green = "03"
ircColor MD.Brown = "07"
ircColor MD.Magenta = "06"
ircColor MD.Gray = "15"
ircColor MD.BrightGreen = "09"
ircColor MD.White = "00"
ircColor MD.Yellow = "08"
message :: IO (T.Text -> IO (Maybe T.Text))
message = do
vars <- variants
return $ messager vars
where
This code matches @ ? or @x ? ( where x is variant ) anywhere on an IRC line .
This makes it possible for people who are using " IRC connectors " ( like the
one that makes Discord users appear on IRC through an IRC bot ) to use
.
--
-- E.g.
--
-- @v?test
--
-- Or
--
-- <@some_person_on_discord> @v?test
--
messager vars input
| T.null input = return Nothing
| T.head input /= '@' = messager vars (T.tail input)
| input == "@" = return Nothing
| T.head input == '@' = do
case message' vars (T.tail input) of
Right (Just ok) -> return (Just ok)
Right Nothing -> messager vars (T.tail input)
Left NoMonster -> return $ Just "No such monster."
| otherwise = return Nothing
filterNewLines :: String -> String
filterNewLines = fmap (\ch -> if ch == '\n' || ch == '\r' then ' ' else ch)
-- substandard parsec "string" function for texts
stringT :: Stream s m Char => T.Text -> ParsecT s u m T.Text
stringT txt = T.pack <$> string (T.unpack txt)
data NoMonster = NoMonster
deriving (Eq, Ord, Show, Read)
message' :: [V.Variant] -> T.Text -> Either NoMonster (Maybe T.Text)
message' variants input'
| T.head input' == '@' = next (T.tail input') True
| otherwise = next input' False
where
next input maximum_lev =
case runParser (parser maximum_lev) () "line" input of
Left errmsg -> Right $ Just $ T.pack $ filterNewLines $ show errmsg
Right okay -> okay
parser :: Bool -> T.Parser (Either NoMonster (Maybe T.Text))
parser maximum_lev = do
(variantStr, ignore) <-
foldl
( \previoustry variant ->
previoustry
<|> try
( (,)
<$> (stringT $ V.commandPrefix variant)
<*> try
(stringT "?")
)
)
(fail "")
variants
<|> ((,) <$> try (stringT "") <*> try (stringT "?"))
<|> (return ("", ""))
if ignore == "?"
then doPart maximum_lev $ decideVariant variants variantStr
else return (Right Nothing)
doPart maximum_lev variant = do
spaces
rawMonsterName <- many anyChar
let monsterName = (T.strip . T.pack) rawMonsterName
when (T.length monsterName <= 0) $
fail $
";I shall now launch the missiles that will cause "
<> "serious international side effects."
return $ case msms variant monsterName of
Nothing -> Left NoMonster
Just mon ->
Right $
Just $
( if T.toLower monsterName /= T.toLower mon
then
monsterName
<> " ~"
<> (T.pack $ show $ distT monsterName mon)
<> "~ "
else ""
)
<> lineMonsterInformation (fromJust $ V.monster variant mon)
where
msms =
if maximum_lev then mostSimilarMonsterHalfSane else mostSimilarMonsterSane
| null | https://raw.githubusercontent.com/UnNetHack/pinobot/34666dab1b7ea07c605f5110c96945bdd4d35f74/monsterdb/Bot.hs | haskell | # LANGUAGE OverloadedStrings #
Add variants here.
first one is used by default
/~lloyd/tildeStrings/Alignment/92.IPL.html
upper diagonals
lower diagonals
suppresses warnings
Returns the most similar monster name along with its levenshtein distance.
Returns the most similar monster name but only if parameters and results are
reasonably "sane".
distance is too great, then the result is discarded.
| Same as above, but with less assurances.
wtf
E.g.
@v?test
Or
<@some_person_on_discord> @v?test
substandard parsec "string" function for texts | # LANGUAGE FlexibleContexts #
# OPTIONS_GHC -fno - warn - name - shadowing #
module Bot
( message,
)
where
import Control.Applicative hiding
( many,
(<|>),
)
import Control.Monad hiding (mapM_)
import Control.Monad.Trans.Writer
import Data.Foldable
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TL
import qualified Data.Text.Lazy.Builder as TLB
import NetHack.Data.Dice
import qualified NetHack.Data.Monster as MD
import qualified NetHack.Data.Variant as V
import Text.Parsec
import qualified Text.Parsec.Text as T
import Prelude hiding
( concatMap,
foldl,
foldl1,
mapM_,
)
variants :: IO [V.Variant]
variants =
sequence $
variantify $
"Vanilla343",
"UnNetHack",
"UnNetHackPlus",
"SporkHack",
"GruntHack",
"Slashem",
"Brass",
"Dnethack",
"Notdnethack",
"SlashemExtended",
"SlashTHEM",
"Fourk",
"EvilHack",
"XNetHack",
"SpliceHack"
]
where
variantify = fmap $ \name -> V.loadVariant $ "variants/" ++ name ++ ".yaml"
Shamelessly stolen from HaskellWiki which in turn stole it from Lloyd
:
Calculates the distance between two lists .
dist :: Eq a => [a] -> [a] -> Int
dist a b =
last
( if lab == 0
then mainDiag
else
if lab > 0
then lowers !! (lab - 1)
< 0
uppers !! (-1 - lab)
)
where
mainDiag = oneDiag a b (head uppers) (-1 : head lowers)
eachDiag _ [] _ = []
eachDiag a (_ : bs) (lastDiag : diags) =
oneDiag a bs nextDiag lastDiag : eachDiag a bs diags
where
nextDiag = head (tail diags)
oneDiag a b diagAbove diagBelow = thisdiag
where
doDiag [] _ _ _ _ = []
doDiag _ [] _ _ _ = []
doDiag (ach : as) (bch : bs) nw n w =
me
: doDiag as bs me (tail n) (tail w)
where
me = if ach == bch then nw else 1 + min3 (head w) nw (head n)
firstelt = 1 + head diagBelow
thisdiag = firstelt : doDiag a b firstelt diagAbove (tail diagBelow)
lab = length a - length b
min3 x y z = if x < y then x else min y z
distT :: T.Text -> T.Text -> Int
distT t1 t2 = dist (T.unpack $ T.toLower t1) (T.unpack $ T.toLower t2)
mostSimilarMonster :: V.Variant -> T.Text -> (Int, T.Text)
mostSimilarMonster variant name =
minimumBy (\(a1, _) (a2, _) -> a1 `compare` a2) $
zip (map (distT name) all) all
where
all :: [T.Text]
all = V.allMonsterNames variant
" Sane " here being : no overly long names allowed and if the
mostSimilarMonsterSane :: V.Variant -> T.Text -> Maybe T.Text
mostSimilarMonsterSane variant text
| T.length text >= 60 =
Nothing
| otherwise =
let (distance, result) = mostSimilarMonster variant text
in if distance <= 3 then Just result else Nothing
mostSimilarMonsterHalfSane :: V.Variant -> T.Text -> Maybe T.Text
mostSimilarMonsterHalfSane variant text
| T.length text >= 60 =
Nothing
| otherwise =
let (_, result) = mostSimilarMonster variant text in Just result
decideVariant :: [V.Variant] -> T.Text -> V.Variant
decideVariant variants name =
fromMaybe (head variants) $
find (\var -> V.commandPrefix var == name) variants
relevantFlag :: MD.MonsterFlag -> Maybe T.Text
relevantFlag MD.FlDisplaces = Just "displaces"
relevantFlag MD.FlVanDmgRduc = Just "damage reduction"
relevantFlag MD.FlBlinkAway = Just "blinks away"
relevantFlag MD.FlFairy = Just "fairy"
relevantFlag MD.FlScentTracker = Just "tracks scents"
relevantFlag MD.FlOviparous = Just "oviparous"
relevantFlag MD.FlTouchPetrifies = Just "touch petrifies"
relevantFlag MD.FlInvisible = Just "invisible"
relevantFlag MD.FlWallwalk = Just "phases"
relevantFlag MD.FlFly = Just "flies"
relevantFlag MD.FlSwim = Just "swims"
relevantFlag MD.FlAmorphous = Just "amorphous"
relevantFlag MD.FlTunnel = Just "tunnels"
relevantFlag MD.FlCling = Just "clings"
relevantFlag MD.FlConceal = Just "conceals"
relevantFlag MD.FlAmphibious = Just "amphibious"
relevantFlag MD.FlBreathless = Just "breathless"
relevantFlag MD.FlSeeInvis = Just "seeinvis"
relevantFlag MD.FlThickHide = Just "thick hide"
relevantFlag MD.FlRegen = Just "regen"
relevantFlag MD.FlUnSolid = Just "unsolid"
relevantFlag MD.FlInfravisible = Just "infravis"
relevantFlag MD.FlCovetous = Just "covetous"
relevantFlag MD.FlMindless = Just "mindless"
relevantFlag MD.FlNoPoly = Just "nopoly"
relevantFlag MD.FlTeleport = Just "tele"
relevantFlag MD.FlUndead = Just "undead"
relevantFlag MD.FlDemon = Just "demon"
relevantFlag MD.FlVegan = Just "vegan"
relevantFlag MD.FlVegetarian = Just "vegetarian"
relevantFlag MD.FlStalk = Just "stalker"
relevantFlag MD.FlMetallivore = Just "metallivore"
relevantFlag MD.FlPoisonous = Just "poisonous"
relevantFlag MD.FlLithivore = Just "lithivore"
relevantFlag MD.FlPassesBars = Just "passes-bars"
relevantFlag MD.FlHatesSilver = Just "silverhate"
relevantFlag _ = Nothing
showB :: Show a => a -> TL.Builder
showB = TL.fromString . show
lineMonsterInformation :: MD.Monster -> T.Text
lineMonsterInformation mon =
TL.toStrict $
TL.toLazyText $
(TL.fromText $ MD.moName mon)
<> " ("
<> monsymbol
<> ")"
<> " | Lvl: "
<> showB (MD.moBaseLevel mon)
<> " | Diff: "
<> showB (MD.moDifficulty mon)
<> " | Spd: "
<> showB (MD.moSpeed mon)
<> " | Res: "
<> resistances (MD.moResistances mon)
<> "| Confer: "
<> confers (MD.moConferred mon)
<> "| MR: "
<> showB (MD.moMR mon)
<> " | Gen: "
<> generates (MD.moGenerationPlaces mon)
<> "| AC: "
<> case MD.moAC mon of
Left ac_int -> showB ac_int
Right ac_str -> TL.fromText ac_str
<> " | Atk: "
<> attacks (MD.moAttacks mon)
<> " | Align: "
<> showB (MD.moAlign mon)
<> " | "
<> flags
where
generates :: [MD.Place] -> TL.Builder
generates [] = "special "
generates places = mconcat $ fmap generationPlace places
generationPlace MD.Sheol = "sheol "
generationPlace MD.Gehennom = "gehennom "
generationPlace MD.Dungeons = "dungeons "
generationPlace MD.Unique = "unique "
isCarnivore = MD.hasFlag MD.FlCarnivore mon
isHerbivore = MD.hasFlag MD.FlHerbivore mon
isOmnivore = isCarnivore && isHerbivore
relevantFlagsW :: Writer [TL.Builder] ()
relevantFlagsW = do
when (MD.moGenocidable mon) $ tell ["genocidable"]
if isOmnivore
then tell ["omnivore"]
else do
when isCarnivore $ tell ["carnivore"]
when isHerbivore $ tell ["herbivore"]
mapM_ (tell . fmap TL.fromText . catMaybes . return . relevantFlag) $
MD.moFlags mon
relevantFlags :: [TL.Builder]
relevantFlags = execWriter relevantFlagsW
flags :: TL.Builder
flags
| null relevantFlags = "none"
| null $ tail relevantFlags = head relevantFlags
| otherwise = foldl1 (\accum str -> accum <> ", " <> str) relevantFlags
attacks :: [MD.Attack] -> TL.Builder
attacks [] = "none"
attacks [attack] = attackName attack
attacks xs = foldl1 (\accum str -> accum <> ", " <> str) (fmap attackName xs)
attackName :: MD.Attack -> TL.Builder
attackName (MD.Attack atype dtype (Dice d1 d2)) =
showB d1
<> "d"
<> showB d2
<> " "
<> attackTypeName atype
<> " "
<> attackDamageName dtype
attackTypeName MD.AtNone = "passive"
attackTypeName MD.AtClaw = "claw"
attackTypeName MD.AtBite = "bite"
attackTypeName MD.AtKick = "kick"
attackTypeName MD.AtButt = "butt"
attackTypeName MD.AtTouch = "touch"
attackTypeName MD.AtSting = "sting"
attackTypeName MD.AtHug = "hug"
attackTypeName MD.AtSpit = "spit"
attackTypeName MD.AtEngulf = "engulf"
attackTypeName MD.AtBreath = "breath"
attackTypeName MD.AtExplode = "explode"
attackTypeName MD.AtSuicideExplode = "suicide explode"
attackTypeName MD.AtGaze = "gaze"
attackTypeName MD.AtTentacle = "tentacle"
attackTypeName MD.AtWeapon = "weapon"
attackTypeName MD.AtCast = "cast"
attackTypeName MD.AtScre = "scream"
attackTypeName MD.AtMultiply = "multiply"
attackTypeName MD.AtArrow = "arrow"
attackTypeName MD.AtReach = "reach"
attackTypeName MD.AtMirror = "mirror"
attackTypeName MD.AtWhip = "whip"
attackTypeName MD.AtMMagical = "mmmmagical"
attackTypeName MD.AtReachingBite = "reaching"
attackTypeName MD.AtLash = "lashing"
attackTypeName MD.AtTrample = "trample"
attackTypeName MD.AtScratch = "scratch"
attackTypeName MD.AtIllurien = "illurien-swallow"
attackTypeName MD.AtTinker = "tinker"
attackTypeName MD.AtPhaseNonContact = "non-contacting-phase"
attackTypeName MD.AtBeamNonContact = "non-contacting-beam"
attackTypeName MD.AtMillionArms = "million-weaponized-arms"
attackTypeName MD.AtSpin = "spin"
attackTypeName MD.AtAny = "any"
attackTypeName MD.AtRangedThorns = "ranged-thorns"
attackTypeName MD.AtCloseRangeBreath = "close-range-breath"
attackTypeName MD.AtOffhandedWeapon = "offhanded-weapon"
attackTypeName MD.AtOffOffhandedWeapon = "offoffhanded-weapon"
attackTypeName MD.AtNonContactAttack = "non-contact-attack"
attackTypeName MD.AtReachTouch = "longreaching-touch"
attackTypeName MD.AtReachBite = "longreaching-bite"
attackTypeName MD.AtPassiveWideGaze = "passive-gaze"
attackTypeName MD.AtHitsIfTwoPreviousHitsConnect = "hits-if-two-previous-hits-connect"
attackTypeName MD.AtLashingVine = "lashing-vines"
attackTypeName MD.AtBlackGoat = "black-goat-shenanigans"
attackTypeName MD.AtAutoHit = "autohit"
attackTypeName MD.AtAdjacent = "adjacent"
attackTypeName MD.AtTalk = "talk"
attackTypeName MD.AtTailSlap = "tailslap"
attackTypeName MD.AtVolley = "volley"
attackTypeName MD.AtWolfHeadBite = "wolfhead-bite"
attackDamageName MD.AdDimness = "dimness"
attackDamageName MD.AdMapAmnesia = "map-amnesia"
attackDamageName MD.AdIncreaseWeight = "increase-weight"
attackDamageName MD.AdCast = "cast"
attackDamageName MD.AdChaos = "chaos"
attackDamageName MD.AdVomitInducing = "vomit-inducing"
attackDamageName MD.AdNegativeEnchantment = "negative-enchantment"
attackDamageName MD.AdVaporization = "vaporization"
attackDamageName MD.AdStoneEdge = "stone-edge"
attackDamageName MD.AdLitterBlob = "litter-blob"
attackDamageName MD.AdCreateTrap = "create-trap"
attackDamageName MD.AdRngIntervention = "rng-intervention"
attackDamageName MD.AdIdentityAttack = "identity-attack"
attackDamageName MD.AdFrenzy = "frenzy"
attackDamageName MD.AdNether = "nether"
attackDamageName MD.AdInsanity = "insanity"
attackDamageName MD.AdNastyTrap = "nasty-trap"
attackDamageName MD.AdSkillCapReduce = "skill-cap-reducting"
attackDamageName MD.AdDreamAttack = "dream-eating"
attackDamageName MD.AdBadRandomEffect = "bad-random-effect"
attackDamageName MD.AdFumble = "fumble"
attackDamageName MD.AdVenomous = "venomous"
attackDamageName MD.AdVulnerability = "vulnerability-inducing"
attackDamageName MD.AdCurseItems = "curse-items"
attackDamageName MD.AdSludge = "sludge"
attackDamageName MD.AdMasterBlaster = "masterblaster"
attackDamageName MD.AdPits = "pits"
attackDamageName MD.AdIceBlock = "iceblock"
attackDamageName MD.AdStinkingCloud = "stinking-cloud"
attackDamageName MD.AdFeelPain = "feel-pain"
attackDamageName MD.AdDeadGaze = "deadly-gaze"
attackDamageName MD.AdGravity = "gravity"
attackDamageName MD.AdSound = "sound"
attackDamageName MD.AdVampireDrain = "vampire-drain"
attackDamageName MD.AdNegativeProtection = "negative-protection"
attackDamageName MD.AdDepression = "depressing"
attackDamageName MD.AdPoisonStat = "poison-sting"
attackDamageName MD.AdNexus = "nexus"
attackDamageName MD.AdSuckEquipment = "suck-equipment"
attackDamageName MD.AdBanishment = "banishment"
attackDamageName MD.AdCursedUnihorn = "cursed-unicorn-horn"
attackDamageName MD.AdLazyness = "lazy"
attackDamageName MD.AdPlasma = "plasma"
attackDamageName MD.AdDrainsAllSortsOfStuff = "drains-all-sorts-of-stuff"
attackDamageName MD.AdFakeMessages = "fake-message"
attackDamageName MD.AdCharisma = "charisma-taking"
attackDamageName MD.AdWrath = "wrath"
attackDamageName MD.AdDrainLifeOrStats = "drain-life-and/or-stats"
attackDamageName MD.AdInertia = "inertia"
attackDamageName MD.AdThirsty = "thirsty"
attackDamageName MD.AdMana = "mana"
attackDamageName MD.AdSilverStarlightRapier = "silver-starlight-rapier"
attackDamageName MD.AdRandomGaze = "random gaze"
attackDamageName MD.AdHalfDragon = "half-dragon"
attackDamageName MD.AdStealByTeleportation = "steal-by-teleportation"
attackDamageName MD.AdFear = "fear"
attackDamageName MD.AdBlackWebShadow = "black-web-shadow"
attackDamageName MD.AdNetzach = "netzach"
attackDamageName MD.AdWatcherTentacleGaze = "magical-tentacle-gaze"
attackDamageName MD.AdNumb = "numb"
attackDamageName MD.AdFreezeSolid = "freeze-solid"
attackDamageName MD.AdWither = "wither"
attackDamageName MD.AdBurn = "burn"
attackDamageName MD.AdDisplacement = "displacement"
attackDamageName MD.AdTinker = "tinker"
attackDamageName MD.AdFireworks = "fireworks"
attackDamageName MD.AdOona = "oona"
attackDamageName MD.AdStudy = "study"
attackDamageName MD.AdCalm = "calm"
attackDamageName MD.AdTickle = "tickle"
attackDamageName MD.AdPoly = "poly"
attackDamageName MD.AdBehead = "behead"
attackDamageName MD.AdCancellation = "cancellation"
attackDamageName MD.AdPhys = "physical"
attackDamageName MD.AdMagicMissile = "magic missile"
attackDamageName MD.AdFire = "fire"
attackDamageName MD.AdCold = "cold"
attackDamageName MD.AdSleep = "sleep"
attackDamageName MD.AdDisintegrate = "disintegrate"
attackDamageName MD.AdElectricity = "shock"
attackDamageName MD.AdStrDrain = "drain str"
attackDamageName MD.AdAcid = "acid"
attackDamageName MD.AdSpecial1 = "special1"
attackDamageName MD.AdSpecial2 = "special2"
attackDamageName MD.AdBlind = "blind"
attackDamageName MD.AdStun = "stun"
attackDamageName MD.AdSlow = "slow"
attackDamageName MD.AdParalyse = "paralyze"
attackDamageName MD.AdLevelDrain = "level drain"
attackDamageName MD.AdMagicDrain = "magic drain"
attackDamageName MD.AdLegs = "legwound"
attackDamageName MD.AdStone = "petrification"
attackDamageName MD.AdSticking = "sticky"
attackDamageName MD.AdGoldSteal = "gold steal"
attackDamageName MD.AdItemSteal = "item steal"
attackDamageName MD.AdSeduce = "seduce"
attackDamageName MD.AdTeleport = "teleport"
attackDamageName MD.AdRust = "rust"
attackDamageName MD.AdConfuse = "confuse"
attackDamageName MD.AdDigest = "digest"
attackDamageName MD.AdHeal = "heal"
attackDamageName MD.AdWrap = "wrap"
attackDamageName MD.AdWere = "lycanthropy"
attackDamageName MD.AdDexDrain = "drain dex"
attackDamageName MD.AdConDrain = "drain con"
attackDamageName MD.AdIntDrain = "drain int"
attackDamageName MD.AdDisease = "disease"
attackDamageName MD.AdRot = "rot"
attackDamageName MD.AdSex = "sex"
attackDamageName MD.AdHallucination = "hallucination"
attackDamageName MD.AdDeath = "Death"
attackDamageName MD.AdPestilence = "Pestilence"
attackDamageName MD.AdFamine = "Famine"
attackDamageName MD.AdSlime = "slime"
attackDamageName MD.AdDisenchant = "disenchant"
attackDamageName MD.AdCorrode = "corrosion"
attackDamageName MD.AdClerical = "clerical"
attackDamageName MD.AdSpell = "spell"
attackDamageName MD.AdRandomBreath = "random breath"
attackDamageName MD.AdAmuletSteal = "amulet steal"
attackDamageName MD.AdCurse = "curse"
attackDamageName MD.AdBlink = "blink"
attackDamageName MD.AdLevelTeleport = "level teleport"
attackDamageName MD.AdDecapitate = "decapitate"
attackDamageName MD.AdFreeze = "freeze"
attackDamageName MD.AdPunisher = "punisher"
attackDamageName MD.AdDrown = "drown"
attackDamageName MD.AdShred = "shred"
attackDamageName MD.AdJailer = "jailer"
attackDamageName MD.AdBoulderArrow = "boulder-arrow"
attackDamageName MD.AdBoulderArrowRandomSpread =
"boulder-arrow-random-spread"
attackDamageName MD.AdMultiElementCounterAttackThatAngersTons =
attackDamageName MD.AdPoison = "poison"
attackDamageName MD.AdWisdom = "wisdom"
attackDamageName MD.AdVorpal = "vorpal"
attackDamageName MD.AdStealQuestArtifact = "steals-quest-artifact"
attackDamageName MD.AdSpawnChaos = "spawn-chaos"
attackDamageName MD.AdIronBall = "iron-ball"
attackDamageName MD.AdGrow = "grow"
attackDamageName MD.AdSilver = "silver"
attackDamageName MD.AdAbduction = "abduction"
attackDamageName MD.AdElementalGaze = "elemental-gaze"
attackDamageName MD.AdAsmodeusBlood = "asmodeus-blood"
attackDamageName MD.AdMirror = "mirror"
attackDamageName MD.AdLeviathan = "leviathan"
attackDamageName MD.AdUnknownPriest = "unknown-priest"
attackDamageName MD.AdMalk = "immobilizing-destroying"
attackDamageName MD.AdTentacle = "tentacle"
attackDamageName MD.AdWet = "wet"
attackDamageName MD.AdHeadSpike = "head-spike"
attackDamageName MD.AdTele = "teleportation"
attackDamageName MD.AdLethe = "lethe-wet"
attackDamageName MD.AdHorn = "horn"
attackDamageName MD.AdSolar = "solar"
attackDamageName MD.AdEscalatingDamage = "escalating-damage"
attackDamageName MD.AdSoul = "soul"
attackDamageName MD.AdMist = "mist"
attackDamageName MD.AdSuck = "suck"
attackDamageName MD.AdDrainLuck = "drain luck"
attackDamageName MD.AdSpore = "spores"
attackDamageName MD.AdLava = "lava"
attackDamageName MD.AdSunflower = "sunflowerpower"
attackDamageName MD.AdFernExplosion = "fernxplosion"
attackDamageName MD.AdMandrake = "mandrake-shriek"
attackDamageName MD.AdPhysRetaliate = "retaliate"
attackDamageName MD.AdVamp = "vampire"
attackDamageName MD.AdWebs = "webs"
attackDamageName MD.AdWeeping = "levtele-drain"
attackDamageName MD.AdGaro = "rumor-dispense"
attackDamageName MD.AdGaroMaster = "oracle-dispense"
attackDamageName MD.AdLoadstones = "loadstone-throw"
attackDamageName MD.AdRemoveEngravings = "remove-engravings"
attackDamageName MD.AdIllurien = "illurien-swallow"
attackDamageName MD.AdLightRay = "light-ray"
attackDamageName MD.AdRemoveLight = "remove-light"
attackDamageName MD.AdDisarm = "disarm"
attackDamageName MD.AdIdentityNastiness = "identity-nastiness"
attackDamageName MD.AdItemDamager = "item-damaging"
attackDamageName MD.AdAntimatter = "antimatter"
attackDamageName MD.AdPain = "PAIN"
attackDamageName MD.AdTech = "technology"
attackDamageName MD.AdMemoryReduce = "memory-reduce"
attackDamageName MD.AdSkillReduce = "skill-reduce"
attackDamageName MD.AdStatDamage = "stat-damage"
attackDamageName MD.AdGearDamage = "gear-damaging"
attackDamageName MD.AdThievery = "thievery"
attackDamageName MD.AdLavaTiles = "lava-tiles"
attackDamageName MD.AdDeletesYourGame = "data-delete"
attackDamageName MD.AdDrainAlignment = "drain-alignment"
attackDamageName MD.AdAddSins = "makes-you-a-dirty-sinner"
attackDamageName MD.AdContamination = "contamination"
attackDamageName MD.AdAggravateMonster = "makes-you-aggravate-monsters"
attackDamageName MD.AdDestroyEq = "destroys-equipment"
attackDamageName MD.AdTrembling = "gives-you-parkinsons"
attackDamageName MD.AdAny = "any"
attackDamageName MD.AdCurseArmor = "curse-armor"
attackDamageName MD.AdIncreaseSanity = "increase-sanity"
attackDamageName MD.AdReallyBadEffect = "really-bad-effect"
attackDamageName MD.AdBleedout = "bleedout"
attackDamageName MD.AdShank = "shank"
attackDamageName MD.AdDrainScore = "drain-score"
attackDamageName MD.AdTerrainTerror = "terrain-terror"
attackDamageName MD.AdFeminism = "feminism"
attackDamageName MD.AdLevitation = "levitation"
attackDamageName MD.AdReduceMagicCancellation = "reduce-magic-cancellation"
attackDamageName MD.AdIllusion = "illusion"
attackDamageName MD.AdSpecificRegularAttack = "specific-regular-attack"
attackDamageName MD.AdSpecificNastyTrap = "specific-nasty-trap"
attackDamageName MD.AdDebuff = "debuff"
attackDamageName MD.AdNivellation = "nivellation"
attackDamageName MD.AdTechDrain = "technique-drain"
attackDamageName MD.AdBlasphemy = "makes-your-god-angry-at-you"
attackDamageName MD.AdDropItems = "drop-items"
attackDamageName MD.AdRemoveErosionProof = "remove-erosion-proof"
attackDamageName MD.AdFlame = "flame"
attackDamageName MD.AdPsionic = "psionic"
attackDamageName MD.AdLoud = "loud"
attackDamageName MD.AdKnockback = "knockback"
attackDamageName MD.AdWater = "water"
attackDamageName MD.AdPitAttack = "create-pit"
attackDamageName MD.AdDrainConstitution = "drain-constitution"
attackDamageName MD.AdDrainStrength = "drain-strength"
attackDamageName MD.AdDrainCharisma = "drain-charisma"
attackDamageName MD.AdDrainDexterity = "drain-dexterity"
attackDamageName MD.AdFleshHook = "flesh-hook"
attackDamageName MD.AdImplantEgg = "implant-egg"
attackDamageName MD.AdDessicate = "dessicate"
attackDamageName MD.AdArrowOfSlaying = "arrow-of-slaying"
attackDamageName MD.AdArchonFire = "archon-fire"
attackDamageName MD.AdGoldify = "goldify"
attackDamageName MD.AdMoonlightRapier = "moonlight-rapier"
attackDamageName MD.AdMummyRot = "rot"
attackDamageName MD.AdMindWipe = "mindwipe"
attackDamageName MD.AdSlowStoning = "slow-stoning"
attackDamageName MD.AdInflictDoubt = "inflict-doubt"
attackDamageName MD.AdRevelatoryWhisper = "revelatory-whisper"
attackDamageName MD.AdPull = "pull"
attackDamageName MD.AdMercuryBlade = "mercury-blade"
attackDamageName MD.AdBloodFrenzy = "bloodfrenzy"
attackDamageName MD.AdPollen = "pollen"
attackDamageName MD.AdElementalCold = "elemental-cold"
attackDamageName MD.AdElementalPoison = "elemental-poison"
attackDamageName MD.AdElementalFire = "elemental-fire"
attackDamageName MD.AdElementalElectric = "elemental-electric"
attackDamageName MD.AdElementalAcid = "elemental-acid"
attackDamageName MD.AdFourSeasons = "fourseasons"
attackDamageName MD.AdCreateSphere = "create-sphere"
attackDamageName MD.AdConflictTouch = "conflict-touch"
attackDamageName MD.AdAntiBloodAttack = "antiblood-attack"
attackDamageName MD.AdFirePoisonPhysicalBlindness = "fire+poison+physical+blind"
attackDamageName MD.AdCharm = "charm"
attackDamageName MD.AdScald = "scald"
attackDamageName MD.AdEatGold = "eat-gold"
attackDamageName MD.AdQuarkFlavour = "quark-flavour"
attackDamageName MD.AdMildHunger = "mild-hunger"
attackDamageName MD.AdShoe = "SHOE-ATTACK"
attackDamageName MD.AdLaser = "laser"
attackDamageName MD.AdNuke = "nuke"
attackDamageName MD.AdUnholy = "unholy"
attackDamageName MD.AdHoly = "holy"
attackDamageName MD.AdLokoban = "lokoban"
attackDamageName MD.AdRock = "rock"
attackDamageName MD.AdHalluSick = "hallusick"
attackDamageName MD.AdYank = "yank"
attackDamageName MD.AdBigExplosion = "big-explosion"
attackDamageName MD.AdExplodingMMSpellbook = "exploding-magic-missile-spellbooks"
attackDamageName MD.AdAlignmentBlast = "alignment-blast"
attackDamageName MD.AdReleaseAlignmentSpirits = "release-alignment-spirits"
attackDamageName MD.AdCrystalMemories = "crystal-memories"
attackDamageName MD.AdDilithiumCrystals = "dilithium-crystals"
attackDamageName MD.AdMirrorBlast = "mirror-blast"
attackDamageName MD.AdVoidWhispers = "void-whispers"
attackDamageName MD.AdWarMachineGaze = "war-machine-gaze"
attackDamageName MD.AdSimurgh = "simurgh"
attackDamageName MD.AdInjectLarva = "inject-larva"
attackDamageName MD.AdMakeSkeletons = "make-skeletons"
attackDamageName MD.AdPotionEffect = "potion-effect"
attackDamageName MD.AdKidnap = "kidnap"
attackDamageName MD.AdLaws = "law"
attackDamageName MD.AdGetLost = "get-lost"
attackDamageName MD.AdTransmute = "transmute"
attackDamageName MD.AdGrowHeads = "grow-heads"
attackDamageName MD.AdForgetItems = "1%-forget-items"
attackDamageName MD.AdWind = "wind"
attackDamageName MD.AdQuills = "quills"
attackDamageName MD.AdVoidDisintegrate = "void-disintegrate"
attackDamageName MD.AdPerHitDie = "per-hit-die"
attackDamageName MD.AdSeverePoison = "severe-poison"
attackDamageName MD.AdHolyUnholyEnergy = "holy-unholy-energy"
confers :: [MD.Resistance] -> TL.Builder
confers [] = "nothing "
confers xs = mconcat $ fmap resistanceName xs
resistances :: [MD.Resistance] -> TL.Builder
resistances [] = "none "
resistances xs = mconcat $ fmap resistanceName xs
resistanceName MD.ReFire = "fire "
resistanceName MD.ReCold = "cold "
resistanceName MD.ReSleep = "sleep "
resistanceName MD.ReDisintegrate = "disintegrate "
resistanceName MD.ReElectricity = "shock "
resistanceName MD.RePoison = "poison "
resistanceName MD.ReAcid = "acid "
resistanceName MD.RePetrification = "petrification "
resistanceName MD.ReDrain = "drain "
resistanceName MD.ReMagic = "magic "
TODO : get rid of IRCisms from this module . We are supposed to be
higher - level and not care whether we are on IRC or somewhere else .
monsymbol =
"\x03"
<> ircColor (MD.moColor mon)
<> ",01"
<> TLB.singleton (MD.moSymbol mon)
<> "\x0f"
ircColor :: MD.Color -> TL.Builder
ircColor MD.Black = "14"
ircColor MD.Red = "05"
ircColor MD.Blue = "02"
ircColor MD.BrightBlue = "12"
ircColor MD.BrightMagenta = "13"
ircColor MD.BrightCyan = "11"
ircColor MD.Cyan = "10"
ircColor MD.Orange = "04"
ircColor MD.Green = "03"
ircColor MD.Brown = "07"
ircColor MD.Magenta = "06"
ircColor MD.Gray = "15"
ircColor MD.BrightGreen = "09"
ircColor MD.White = "00"
ircColor MD.Yellow = "08"
message :: IO (T.Text -> IO (Maybe T.Text))
message = do
vars <- variants
return $ messager vars
where
This code matches @ ? or @x ? ( where x is variant ) anywhere on an IRC line .
This makes it possible for people who are using " IRC connectors " ( like the
one that makes Discord users appear on IRC through an IRC bot ) to use
.
messager vars input
| T.null input = return Nothing
| T.head input /= '@' = messager vars (T.tail input)
| input == "@" = return Nothing
| T.head input == '@' = do
case message' vars (T.tail input) of
Right (Just ok) -> return (Just ok)
Right Nothing -> messager vars (T.tail input)
Left NoMonster -> return $ Just "No such monster."
| otherwise = return Nothing
filterNewLines :: String -> String
filterNewLines = fmap (\ch -> if ch == '\n' || ch == '\r' then ' ' else ch)
stringT :: Stream s m Char => T.Text -> ParsecT s u m T.Text
stringT txt = T.pack <$> string (T.unpack txt)
data NoMonster = NoMonster
deriving (Eq, Ord, Show, Read)
message' :: [V.Variant] -> T.Text -> Either NoMonster (Maybe T.Text)
message' variants input'
| T.head input' == '@' = next (T.tail input') True
| otherwise = next input' False
where
next input maximum_lev =
case runParser (parser maximum_lev) () "line" input of
Left errmsg -> Right $ Just $ T.pack $ filterNewLines $ show errmsg
Right okay -> okay
parser :: Bool -> T.Parser (Either NoMonster (Maybe T.Text))
parser maximum_lev = do
(variantStr, ignore) <-
foldl
( \previoustry variant ->
previoustry
<|> try
( (,)
<$> (stringT $ V.commandPrefix variant)
<*> try
(stringT "?")
)
)
(fail "")
variants
<|> ((,) <$> try (stringT "") <*> try (stringT "?"))
<|> (return ("", ""))
if ignore == "?"
then doPart maximum_lev $ decideVariant variants variantStr
else return (Right Nothing)
doPart maximum_lev variant = do
spaces
rawMonsterName <- many anyChar
let monsterName = (T.strip . T.pack) rawMonsterName
when (T.length monsterName <= 0) $
fail $
";I shall now launch the missiles that will cause "
<> "serious international side effects."
return $ case msms variant monsterName of
Nothing -> Left NoMonster
Just mon ->
Right $
Just $
( if T.toLower monsterName /= T.toLower mon
then
monsterName
<> " ~"
<> (T.pack $ show $ distT monsterName mon)
<> "~ "
else ""
)
<> lineMonsterInformation (fromJust $ V.monster variant mon)
where
msms =
if maximum_lev then mostSimilarMonsterHalfSane else mostSimilarMonsterSane
|
1cfeea064ae40f36196bd8e31eb0bc86491f68a16967ea135d50e80936a715e0 | brendanhay/terrafomo | Settings.hs | -- This module is auto-generated.
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - unused - imports #
-- |
Module : . PostgreSQL.Settings
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
module Terrafomo.PostgreSQL.Settings
(
-- * SchemaPolicy
newSchemaPolicy
, SchemaPolicy (..)
) where
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import GHC.Base (Proxy#, proxy#, ($))
import qualified Data.Functor.Const as P
import qualified Data.List.NonEmpty as P
import qualified Data.Map.Strict as P
import qualified Data.Maybe as P
import qualified Data.Text.Lazy as P
import qualified Prelude as P
import qualified Terrafomo.Encode as Encode
import qualified Terrafomo.HCL as TF
import qualified Terrafomo.HIL as TF
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.PostgreSQL.Types as P
import qualified Terrafomo.Schema as TF
-- | The @policy@ nested settings definition.
data SchemaPolicy s = SchemaPolicy_Internal
{ create :: TF.Expr s P.Bool
-- ^ @create@
-- - (Default __@false@__)
-- If true, allow the specified ROLEs to CREATE new objects within the
-- schema(s)
, create_with_grant :: TF.Expr s P.Bool
^
-- - (Default __@false@__)
-- If true, allow the specified ROLEs to CREATE new objects within the
-- schema(s) and GRANT the same CREATE privilege to different ROLEs
, role :: P.Maybe (TF.Expr s (TF.Expr s P.Text))
-- ^ @role@
-- - (Optional)
-- ROLE who will receive this policy (default: PUBLIC)
, usage :: TF.Expr s P.Bool
-- ^ @usage@
-- - (Default __@false@__)
-- If true, allow the specified ROLEs to use objects within the schema(s)
, usage_with_grant :: TF.Expr s P.Bool
-- ^ @usage_with_grant@
-- - (Default __@false@__)
-- If true, allow the specified ROLEs to use objects within the schema(s) and
-- GRANT the same USAGE privilege to different ROLEs
} deriving (P.Show)
-- | Construct a new @policy@ settings value.
newSchemaPolicy
:: SchemaPolicy s
newSchemaPolicy =
SchemaPolicy_Internal
{ create = TF.expr P.False
, create_with_grant = TF.expr P.False
, role = P.Nothing
, usage = TF.expr P.False
, usage_with_grant = TF.expr P.False
}
instance Lens.HasField "create" f (SchemaPolicy s) (TF.Expr s P.Bool) where
field = Lens.lens'
(create :: SchemaPolicy s -> TF.Expr s P.Bool)
(\s a -> s { create = a } :: SchemaPolicy s)
instance Lens.HasField "create_with_grant" f (SchemaPolicy s) (TF.Expr s P.Bool) where
field = Lens.lens'
(create_with_grant :: SchemaPolicy s -> TF.Expr s P.Bool)
(\s a -> s { create_with_grant = a } :: SchemaPolicy s)
instance Lens.HasField "role" f (SchemaPolicy s) (P.Maybe (TF.Expr s (TF.Expr s P.Text))) where
field = Lens.lens'
(role :: SchemaPolicy s -> P.Maybe (TF.Expr s (TF.Expr s P.Text)))
(\s a -> s { role = a } :: SchemaPolicy s)
instance Lens.HasField "usage" f (SchemaPolicy s) (TF.Expr s P.Bool) where
field = Lens.lens'
(usage :: SchemaPolicy s -> TF.Expr s P.Bool)
(\s a -> s { usage = a } :: SchemaPolicy s)
instance Lens.HasField "usage_with_grant" f (SchemaPolicy s) (TF.Expr s P.Bool) where
field = Lens.lens'
(usage_with_grant :: SchemaPolicy s -> TF.Expr s P.Bool)
(\s a -> s { usage_with_grant = a } :: SchemaPolicy s)
instance TF.ToHCL (SchemaPolicy s) where
toHCL SchemaPolicy_Internal{..} = TF.pairs $
P.mempty
<> TF.pair "create" create
<> TF.pair "create_with_grant" create_with_grant
<> P.maybe P.mempty (TF.pair "role") role
<> TF.pair "usage" usage
<> TF.pair "usage_with_grant" usage_with_grant
| null | https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-postgresql/gen/Terrafomo/PostgreSQL/Settings.hs | haskell | This module is auto-generated.
|
Stability : auto-generated
* SchemaPolicy
| The @policy@ nested settings definition.
^ @create@
- (Default __@false@__)
If true, allow the specified ROLEs to CREATE new objects within the
schema(s)
- (Default __@false@__)
If true, allow the specified ROLEs to CREATE new objects within the
schema(s) and GRANT the same CREATE privilege to different ROLEs
^ @role@
- (Optional)
ROLE who will receive this policy (default: PUBLIC)
^ @usage@
- (Default __@false@__)
If true, allow the specified ROLEs to use objects within the schema(s)
^ @usage_with_grant@
- (Default __@false@__)
If true, allow the specified ROLEs to use objects within the schema(s) and
GRANT the same USAGE privilege to different ROLEs
| Construct a new @policy@ settings value. |
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -fno - warn - unused - imports #
Module : . PostgreSQL.Settings
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Terrafomo.PostgreSQL.Settings
(
newSchemaPolicy
, SchemaPolicy (..)
) where
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import GHC.Base (Proxy#, proxy#, ($))
import qualified Data.Functor.Const as P
import qualified Data.List.NonEmpty as P
import qualified Data.Map.Strict as P
import qualified Data.Maybe as P
import qualified Data.Text.Lazy as P
import qualified Prelude as P
import qualified Terrafomo.Encode as Encode
import qualified Terrafomo.HCL as TF
import qualified Terrafomo.HIL as TF
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.PostgreSQL.Types as P
import qualified Terrafomo.Schema as TF
data SchemaPolicy s = SchemaPolicy_Internal
{ create :: TF.Expr s P.Bool
, create_with_grant :: TF.Expr s P.Bool
^
, role :: P.Maybe (TF.Expr s (TF.Expr s P.Text))
, usage :: TF.Expr s P.Bool
, usage_with_grant :: TF.Expr s P.Bool
} deriving (P.Show)
newSchemaPolicy
:: SchemaPolicy s
newSchemaPolicy =
SchemaPolicy_Internal
{ create = TF.expr P.False
, create_with_grant = TF.expr P.False
, role = P.Nothing
, usage = TF.expr P.False
, usage_with_grant = TF.expr P.False
}
instance Lens.HasField "create" f (SchemaPolicy s) (TF.Expr s P.Bool) where
field = Lens.lens'
(create :: SchemaPolicy s -> TF.Expr s P.Bool)
(\s a -> s { create = a } :: SchemaPolicy s)
instance Lens.HasField "create_with_grant" f (SchemaPolicy s) (TF.Expr s P.Bool) where
field = Lens.lens'
(create_with_grant :: SchemaPolicy s -> TF.Expr s P.Bool)
(\s a -> s { create_with_grant = a } :: SchemaPolicy s)
instance Lens.HasField "role" f (SchemaPolicy s) (P.Maybe (TF.Expr s (TF.Expr s P.Text))) where
field = Lens.lens'
(role :: SchemaPolicy s -> P.Maybe (TF.Expr s (TF.Expr s P.Text)))
(\s a -> s { role = a } :: SchemaPolicy s)
instance Lens.HasField "usage" f (SchemaPolicy s) (TF.Expr s P.Bool) where
field = Lens.lens'
(usage :: SchemaPolicy s -> TF.Expr s P.Bool)
(\s a -> s { usage = a } :: SchemaPolicy s)
instance Lens.HasField "usage_with_grant" f (SchemaPolicy s) (TF.Expr s P.Bool) where
field = Lens.lens'
(usage_with_grant :: SchemaPolicy s -> TF.Expr s P.Bool)
(\s a -> s { usage_with_grant = a } :: SchemaPolicy s)
instance TF.ToHCL (SchemaPolicy s) where
toHCL SchemaPolicy_Internal{..} = TF.pairs $
P.mempty
<> TF.pair "create" create
<> TF.pair "create_with_grant" create_with_grant
<> P.maybe P.mempty (TF.pair "role") role
<> TF.pair "usage" usage
<> TF.pair "usage_with_grant" usage_with_grant
|
be8e442e46a208b827bdd9a9515378955a0251826f6ea12731ad4ee7e284abdb | ChrisPenner/Candor | Primitives.hs | # LANGUAGE OverloadedLists #
module Primitives where
import AST
import RIO
import Types
import qualified Data.Map as M
primitives :: Bindings
primitives = Builtin <$> M.fromSet id (M.keysSet primitiveTypes)
primitiveTypes :: M.Map String Monotype
primitiveTypes =
[ ("+", TFunc intT (TFunc intT intT))
, ("-", TFunc intT (TFunc intT intT))
, ("*", TFunc intT (TFunc intT intT))
, ("++", TFunc stringT (TFunc stringT stringT))
, ("if", TFunc boolT (TFunc varT (TFunc varT varT)))
, ("==", TFunc varT (TFunc varT boolT))
]
| null | https://raw.githubusercontent.com/ChrisPenner/Candor/2cf2c3d8ff50aa63b29d21ec8538cf438961aa2e/src/Primitives.hs | haskell | # LANGUAGE OverloadedLists #
module Primitives where
import AST
import RIO
import Types
import qualified Data.Map as M
primitives :: Bindings
primitives = Builtin <$> M.fromSet id (M.keysSet primitiveTypes)
primitiveTypes :: M.Map String Monotype
primitiveTypes =
[ ("+", TFunc intT (TFunc intT intT))
, ("-", TFunc intT (TFunc intT intT))
, ("*", TFunc intT (TFunc intT intT))
, ("++", TFunc stringT (TFunc stringT stringT))
, ("if", TFunc boolT (TFunc varT (TFunc varT varT)))
, ("==", TFunc varT (TFunc varT boolT))
]
|
|
48de0c726ab4936f2850fd80a349c028dd4bd5736fdd0945ec88ee9cc2ed34c5 | fujita-y/ypsilon | program.scm | Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited .
;;; See LICENSE file for terms and conditions of use.
(define expand-top-level-program
(lambda (form env)
(define permute-env
(lambda (ht)
(let loop ((lst (core-hashtable->alist ht)) (bounds '()) (unbounds '()))
(cond ((null? lst) (append bounds unbounds))
((unbound? (cdar lst)) (loop (cdr lst) bounds (cons (car lst) unbounds)))
(else (loop (cdr lst) (cons (car lst) bounds) unbounds))))))
(define library-name `(,(string->symbol (format "program-~a" (make-uuid)))))
(destructuring-match form
((('import import-spec ...) body ...)
(let ((library-id (library-name->id form library-name))
(library-version (library-name->version form library-name)))
(and library-version (core-hashtable-set! (scheme-library-versions) library-id library-version))
(let ((imports (parse-imports form import-spec))
(depends (parse-depends form import-spec))
(ht-immutables (make-core-hashtable))
(ht-imports (make-core-hashtable)))
(for-each
(lambda (a)
(core-hashtable-set! ht-immutables (car a) #t)
(cond ((core-hashtable-ref ht-imports (car a) #f)
=>
(lambda (deno)
(or (eq? deno (cdr a))
(syntax-violation
"top-level program"
"duplicate import identifiers"
(abbreviated-take-form form 4 8)
(car a)))))
(else (core-hashtable-set! ht-imports (car a) (cdr a)))))
imports)
(let ((ht-env (make-shield-id-table body)) (ht-libenv (make-core-hashtable)))
(for-each
(lambda (a) (core-hashtable-set! ht-env (car a) (cdr a)) (core-hashtable-set! ht-libenv (car a) (cdr a)))
(core-hashtable->alist ht-imports))
(parameterize ((current-immutable-identifiers ht-immutables))
(expand-top-level-program-body
form
library-id
library-version
body
imports
depends
(extend-env private-primitives-environment (permute-env ht-env))
(permute-env ht-libenv)))))))
(_
(syntax-violation
"top-level program"
"expected import form and top-level body"
(abbreviated-take-form form 4 8))))))
(define expand-top-level-program-body
(lambda (form library-id library-version body imports depends env libenv)
(define initial-libenv #f)
(define macro-defs '())
(define extend-env!
(lambda (datum1 datum2)
(and (macro? datum2) (set! macro-defs (acons datum1 datum2 macro-defs)))
(set! env (extend-env (list (cons datum1 datum2)) env))
(for-each (lambda (a) (set-cdr! (cddr a) env)) macro-defs)))
(define extend-libenv!
(lambda (datum1 datum2)
(set! libenv (extend-env (list (cons datum1 datum2)) libenv))
(current-template-environment libenv)))
(define rewrite-body
(lambda (body defs macros renames)
(define rewrite-env
(lambda (env)
(let loop ((lst (reverse env)) (acc '()))
(cond ((null? lst) acc)
((uninterned-symbol? (caar lst))
(if (assq (cdar lst) defs)
(loop (cdr lst) (cons (cons (caar lst) (cddr (assq (cdar lst) libenv))) acc))
(loop (cdr lst) (cons (car lst) acc))))
((assq (caar lst) (cdr lst)) (loop (cdr lst) acc))
(else (loop (cdr lst) (cons (car lst) acc)))))))
(check-duplicate-definition "top-level program" defs macros renames)
(let ((env (rewrite-env env)))
(let ((rewrited-body (expand-each body env)))
(let ((rewrited-depends (map (lambda (dep) `(|.require-scheme-library| ',dep)) depends))
(rewrited-defs
(map (lambda (def)
(parameterize ((current-top-level-exterior (car def)))
(let ((lhs (cdr (assq (car def) renames))) (rhs (expand-form (cadr def) env)))
(set-closure-comment! rhs lhs)
`(define ,lhs ,rhs))))
defs)))
(let ((vars (map cadr rewrited-defs)) (assignments (map caddr rewrited-defs)))
(cond
((check-rec*-contract-violation vars assignments)
=>
(lambda (var)
(let ((id (any1 (lambda (a) (and (eq? (cdr a) (car var)) (car a))) renames)))
(current-macro-expression #f)
(syntax-violation
#f
(format "attempt to reference uninitialized variable ~u" id)
(any1
(lambda (e) (and (check-rec-contract-violation (list id) e) (annotate `(define ,@e) e)))
defs)))))))
(annotate `(begin ,@rewrited-depends ,@rewrited-defs ,@rewrited-body) form))))))
(define ht-imported-immutables (make-core-hashtable))
(define expression-tag (let ((num 0)) (lambda () (set! num (+ num 1)) (string->symbol (format ".e~a" num)))))
(current-template-environment libenv)
(for-each (lambda (b) (core-hashtable-set! ht-imported-immutables (car b) #t)) imports)
(let loop ((body (flatten-begin body env)) (defs '()) (macros '()) (renames '()))
(if (null? body)
(rewrite-body body (reverse defs) (reverse macros) renames)
(cond ((and (pair? body) (pair? (car body)) (symbol? (caar body)))
(let ((deno (env-lookup env (caar body))))
(cond ((eq? denote-begin deno) (loop (flatten-begin body env) defs macros renames))
((eq? denote-define-syntax deno)
(destructuring-match body
(((_ (? symbol? org) clause) more ...)
(begin
(and (core-hashtable-contains? ht-imported-immutables org)
(syntax-violation 'define-syntax "attempt to modify immutable binding" (car body)))
(let-values (((code . expr)
(parameterize ((current-template-environment initial-libenv))
(compile-macro (car body) clause env))))
(let ((new (generate-global-id library-id org)))
(extend-libenv! org (make-import new))
(cond ((procedure? code)
(extend-env! org (make-macro code env))
(loop
more
defs
(cons (list org 'procedure (car expr)) macros)
(acons org new renames)))
((macro-variable? code)
(extend-env! org (make-macro-variable (cadr code) env))
(loop
more
defs
(cons (list org 'variable (car expr)) macros)
(acons org new renames)))
(else
(extend-env! org (make-macro code env))
(loop
more
defs
(cons (list org 'template code) macros)
(acons org new renames))))))))
(_ (syntax-violation 'define-syntax "expected symbol and single expression" (car body)))))
((eq? denote-define deno)
(let ((def (annotate (cdr (desugar-define (car body))) (car body))))
(and (core-hashtable-contains? ht-imported-immutables (car def))
(syntax-violation 'define "attempt to modify immutable binding" (car body)))
(let ((org (car def)) (new (generate-global-id library-id (car def))))
(extend-env! org new)
(extend-libenv! org (make-import new))
(loop (cdr body) (cons def defs) macros (acons org new renames)))))
((or (macro? deno) (eq? denote-let-syntax deno) (eq? denote-letrec-syntax deno))
(let-values (((expr new) (expand-initial-forms (car body) env)))
(set! env new)
(loop (append (flatten-begin (list expr) env) (cdr body)) defs macros renames)))
(else
(loop (cons `(|.define| ,(expression-tag) ,(car body)) (cdr body)) defs macros renames)))))
(else (loop (cons `(|.define| ,(expression-tag) ,(car body)) (cdr body)) defs macros renames)))))))
| null | https://raw.githubusercontent.com/fujita-y/ypsilon/8b9cea4b59651e4bfd187db9d2e9ec68e2590e2d/heap/boot/macro/program.scm | scheme | See LICENSE file for terms and conditions of use. | Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited .
(define expand-top-level-program
(lambda (form env)
(define permute-env
(lambda (ht)
(let loop ((lst (core-hashtable->alist ht)) (bounds '()) (unbounds '()))
(cond ((null? lst) (append bounds unbounds))
((unbound? (cdar lst)) (loop (cdr lst) bounds (cons (car lst) unbounds)))
(else (loop (cdr lst) (cons (car lst) bounds) unbounds))))))
(define library-name `(,(string->symbol (format "program-~a" (make-uuid)))))
(destructuring-match form
((('import import-spec ...) body ...)
(let ((library-id (library-name->id form library-name))
(library-version (library-name->version form library-name)))
(and library-version (core-hashtable-set! (scheme-library-versions) library-id library-version))
(let ((imports (parse-imports form import-spec))
(depends (parse-depends form import-spec))
(ht-immutables (make-core-hashtable))
(ht-imports (make-core-hashtable)))
(for-each
(lambda (a)
(core-hashtable-set! ht-immutables (car a) #t)
(cond ((core-hashtable-ref ht-imports (car a) #f)
=>
(lambda (deno)
(or (eq? deno (cdr a))
(syntax-violation
"top-level program"
"duplicate import identifiers"
(abbreviated-take-form form 4 8)
(car a)))))
(else (core-hashtable-set! ht-imports (car a) (cdr a)))))
imports)
(let ((ht-env (make-shield-id-table body)) (ht-libenv (make-core-hashtable)))
(for-each
(lambda (a) (core-hashtable-set! ht-env (car a) (cdr a)) (core-hashtable-set! ht-libenv (car a) (cdr a)))
(core-hashtable->alist ht-imports))
(parameterize ((current-immutable-identifiers ht-immutables))
(expand-top-level-program-body
form
library-id
library-version
body
imports
depends
(extend-env private-primitives-environment (permute-env ht-env))
(permute-env ht-libenv)))))))
(_
(syntax-violation
"top-level program"
"expected import form and top-level body"
(abbreviated-take-form form 4 8))))))
(define expand-top-level-program-body
(lambda (form library-id library-version body imports depends env libenv)
(define initial-libenv #f)
(define macro-defs '())
(define extend-env!
(lambda (datum1 datum2)
(and (macro? datum2) (set! macro-defs (acons datum1 datum2 macro-defs)))
(set! env (extend-env (list (cons datum1 datum2)) env))
(for-each (lambda (a) (set-cdr! (cddr a) env)) macro-defs)))
(define extend-libenv!
(lambda (datum1 datum2)
(set! libenv (extend-env (list (cons datum1 datum2)) libenv))
(current-template-environment libenv)))
(define rewrite-body
(lambda (body defs macros renames)
(define rewrite-env
(lambda (env)
(let loop ((lst (reverse env)) (acc '()))
(cond ((null? lst) acc)
((uninterned-symbol? (caar lst))
(if (assq (cdar lst) defs)
(loop (cdr lst) (cons (cons (caar lst) (cddr (assq (cdar lst) libenv))) acc))
(loop (cdr lst) (cons (car lst) acc))))
((assq (caar lst) (cdr lst)) (loop (cdr lst) acc))
(else (loop (cdr lst) (cons (car lst) acc)))))))
(check-duplicate-definition "top-level program" defs macros renames)
(let ((env (rewrite-env env)))
(let ((rewrited-body (expand-each body env)))
(let ((rewrited-depends (map (lambda (dep) `(|.require-scheme-library| ',dep)) depends))
(rewrited-defs
(map (lambda (def)
(parameterize ((current-top-level-exterior (car def)))
(let ((lhs (cdr (assq (car def) renames))) (rhs (expand-form (cadr def) env)))
(set-closure-comment! rhs lhs)
`(define ,lhs ,rhs))))
defs)))
(let ((vars (map cadr rewrited-defs)) (assignments (map caddr rewrited-defs)))
(cond
((check-rec*-contract-violation vars assignments)
=>
(lambda (var)
(let ((id (any1 (lambda (a) (and (eq? (cdr a) (car var)) (car a))) renames)))
(current-macro-expression #f)
(syntax-violation
#f
(format "attempt to reference uninitialized variable ~u" id)
(any1
(lambda (e) (and (check-rec-contract-violation (list id) e) (annotate `(define ,@e) e)))
defs)))))))
(annotate `(begin ,@rewrited-depends ,@rewrited-defs ,@rewrited-body) form))))))
(define ht-imported-immutables (make-core-hashtable))
(define expression-tag (let ((num 0)) (lambda () (set! num (+ num 1)) (string->symbol (format ".e~a" num)))))
(current-template-environment libenv)
(for-each (lambda (b) (core-hashtable-set! ht-imported-immutables (car b) #t)) imports)
(let loop ((body (flatten-begin body env)) (defs '()) (macros '()) (renames '()))
(if (null? body)
(rewrite-body body (reverse defs) (reverse macros) renames)
(cond ((and (pair? body) (pair? (car body)) (symbol? (caar body)))
(let ((deno (env-lookup env (caar body))))
(cond ((eq? denote-begin deno) (loop (flatten-begin body env) defs macros renames))
((eq? denote-define-syntax deno)
(destructuring-match body
(((_ (? symbol? org) clause) more ...)
(begin
(and (core-hashtable-contains? ht-imported-immutables org)
(syntax-violation 'define-syntax "attempt to modify immutable binding" (car body)))
(let-values (((code . expr)
(parameterize ((current-template-environment initial-libenv))
(compile-macro (car body) clause env))))
(let ((new (generate-global-id library-id org)))
(extend-libenv! org (make-import new))
(cond ((procedure? code)
(extend-env! org (make-macro code env))
(loop
more
defs
(cons (list org 'procedure (car expr)) macros)
(acons org new renames)))
((macro-variable? code)
(extend-env! org (make-macro-variable (cadr code) env))
(loop
more
defs
(cons (list org 'variable (car expr)) macros)
(acons org new renames)))
(else
(extend-env! org (make-macro code env))
(loop
more
defs
(cons (list org 'template code) macros)
(acons org new renames))))))))
(_ (syntax-violation 'define-syntax "expected symbol and single expression" (car body)))))
((eq? denote-define deno)
(let ((def (annotate (cdr (desugar-define (car body))) (car body))))
(and (core-hashtable-contains? ht-imported-immutables (car def))
(syntax-violation 'define "attempt to modify immutable binding" (car body)))
(let ((org (car def)) (new (generate-global-id library-id (car def))))
(extend-env! org new)
(extend-libenv! org (make-import new))
(loop (cdr body) (cons def defs) macros (acons org new renames)))))
((or (macro? deno) (eq? denote-let-syntax deno) (eq? denote-letrec-syntax deno))
(let-values (((expr new) (expand-initial-forms (car body) env)))
(set! env new)
(loop (append (flatten-begin (list expr) env) (cdr body)) defs macros renames)))
(else
(loop (cons `(|.define| ,(expression-tag) ,(car body)) (cdr body)) defs macros renames)))))
(else (loop (cons `(|.define| ,(expression-tag) ,(car body)) (cdr body)) defs macros renames)))))))
|
aedb752110f990b36b961fa3b123ae0046dcde31b5d6d9a4d3b2d5ea8ab417ba | coccinelle/coccinelle | spgen_test.ml |
* This file is part of Coccinelle , lincensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, lincensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
(* ------------------------------------------------------------------------- *)
Regression tests .
* Process for :
* - file.cocci ( original cocci file )
* - file.config ( config file for running )
* - file.expected ( expected spgenerated file )
*
* Run < spgen file.cocci --config file.config -o file.actual.cocci >
* Compare file.actual.cocci with file.expected
* Run < spatch --parse - cocci file.actual.cocci -D context > .
* Process for spgen:
* - file.cocci (original cocci file)
* - file.config (config file for running spgen)
* - file.expected (expected spgenerated file)
*
* Run <spgen file.cocci --config file.config -o file.actual.cocci>
* Compare file.actual.cocci with file.expected
* Run <spatch --parse-cocci file.actual.cocci -D context>.
*)
(* ------------------------------------------------------------------------- *)
(* some common functions *)
let spf = Common.spf (* Printf.sprintf *)
let perr_nl = prerr_endline (* Common.pr2 *)
let perr = prerr_string (* Common.pr_no_nl *)
( path , file , ext ) - > path / file.ext
path / file.ext - > ( path , file , ext )
(* hardcoded values; timeout for testing + extension names *)
let timeout_per_file = 60
let exp_ext = "expected"
let act_ext = "actual.cocci"
let score_ext = "score" (* marshalling format used by Common *)
(* ------------------------------------------------------------------------- *)
more or less the same as in coccinelle / parsing_c / compare_c.ml .
* diff flags are
* -u : unified format ( ie . output diffs with - and + )
* -b : ignore changes in amount of whitespace
* -B : ignore changes in blank lines
* diff flags are
* -u: unified format (ie. output diffs with - and +)
* -b: ignore changes in amount of whitespace
* -B: ignore changes in blank lines
*)
let get_diff filename1 filename2 =
let com = spf "diff -u -b -B %s %s" filename1 filename2 in
let xs = Common.cmd_to_list com in
(* get rid of the --- and +++ lines *)
if xs = [] then xs else Common.drop 2 xs
(* Run spgen on <file>.cocci with <file>.config,
* compare to <file>.expected,
* add result to <score>.
*)
let compare_one score expected =
let (dir, base, ext) = nm2dbe expected in
let hashkey = base ^ "." ^ ext in
let actual = dbe2nm (dir, base, act_ext) in
let cocci = dbe2nm (dir, base, "cocci") in
let config = dbe2nm (dir, base, "config") in
if ext <> exp_ext then failwith ("expected extension "^exp_ext^", not "^ext);
if not(Sys.file_exists cocci) then failwith ("no cocci for " ^ expected);
if not(Sys.file_exists config) then failwith ("no config for " ^ expected);
try
Common.timeout_function "spgen_test" timeout_per_file (
fun () ->
perr_nl cocci;
(* spgenerate the file *)
let options = Spgen.make_options ~year:2000 ~output:actual cocci in
let _ = Spgen.run options in
(* check that the spgenerated file is parsable. Note that the parsing
* flag generating_mode must be false (this should be done in spgen.ml).
*)
Flag.set_defined_virtual_rules "context";
let _ = Parse_cocci.process actual None false in
match get_diff actual expected with
| [] ->
let _ = if Sys.file_exists actual then Sys.remove actual in
Hashtbl.add score hashkey Common.Ok
| difflist ->
let difflist = List.map (spf " %s\n") difflist in
let difflist = String.concat "" difflist in
let diff =
spf "INCORRECT: %s\n diff (actual vs expected) = \n%s"
actual difflist in
Hashtbl.add score hashkey (Common.Pb diff)
)
with exn ->
let s = spf "PROBLEM\n exn = %s\n" (Printexc.to_string exn) in
Hashtbl.add score hashkey (Common.Pb s)
Prints regression test statistics and information + updates score files .
* ( perhaps split , but then also have to refactor Common.regression_testing_vs )
*
* < test_dir > The directory in which the regression test files are stored
* < score > The new test information
* Similar to coccinelle / testing.ml , but with less stuff .
* (perhaps split, but then also have to refactor Common.regression_testing_vs)
*
* <test_dir> The directory in which the regression test files are stored
* <score> The new test information
* Similar to coccinelle/testing.ml, but with less stuff.
*)
let print_update_regression test_dir score =
if Hashtbl.length score <= 0 then failwith "There are no tests results ...";
let expected_score_file = dbe2nm (test_dir, "SCORE_expected", score_ext) in
let best_of_both_file = dbe2nm (test_dir, "SCORE_best_of_both", score_ext) in
let actual_score_file = dbe2nm (test_dir, "SCORE_actual", score_ext) in
perr_nl "--------------------------------";
perr_nl "statistics";
perr_nl "--------------------------------";
let print_result (filename, result) =
perr (spf "%-40s: " filename);
perr (
match result with
| Common.Ok -> "CORRECT\n"
| Common.Pb s -> s
) in
(* hash_to_list also sorts the entries by filename *)
List.iter print_result (Common.hash_to_list score);
perr_nl "--------------------------------";
perr_nl "regression testing information";
perr_nl "--------------------------------";
perr_nl ("regression file: "^ expected_score_file);
let expected_score =
if Sys.file_exists expected_score_file then
Common.load_score expected_score_file()
else
let s = Common.empty_score() in
let _ = Common.save_score s expected_score_file in
s
in
(* find and print changes in test results since last time *)
let new_bestscore = Common.regression_testing_vs score expected_score in
Common.save_score score actual_score_file;
Common.save_score new_bestscore best_of_both_file;
Common.print_total_score score;
let (good, total) = Common.total_scores score in
let (expected_good, expected_total) = Common.total_scores expected_score in
if good = expected_good then begin
perr_nl "Current score is equal to expected score; everything is fine"
end else
if good < expected_good then begin
perr_nl "Current score is lower than expected :(";
perr_nl (spf "(was expecting %d but got %d)\n" expected_good good);
perr_nl "If you think it's normal, then maybe you need to update the";
perr_nl (spf "score file %s, copying info from %s."
expected_score_file actual_score_file)
end else
(* if good > expected_good then *) begin
perr_nl "Current score is greater than expected :)";
perr_nl (spf "(was expecting %d but got %d)" expected_good good);
perr_nl "Generating new expected score file and saving old one";
Common.command2_y_or_no_exit_if_no
(spf "mv %s %s" expected_score_file (expected_score_file ^ ".save"));
Common.command2_y_or_no_exit_if_no
(spf "mv %s %s" best_of_both_file expected_score_file)
end
(* ------------------------------------------------------------------------- *)
(* ENTRY POINT *)
let regression_test ~test_dir =
(* sort expected result files by name *)
let test_files = dbe2nm (test_dir, "*", exp_ext) in
let e = Common.glob test_files in
let e = List.filter (fun f -> Common.filesize f > 0) e in
let expected_files = List.sort compare e in
if e = [] then failwith (
(spf "No test files with expected extension <.%s> found." exp_ext) ^
" Are you sure this is the right directory?"
);
(* populate score table *)
let actual_score = Common.empty_score() in
List.iter (compare_one actual_score) expected_files;
print_update_regression test_dir actual_score
| null | https://raw.githubusercontent.com/coccinelle/coccinelle/57cbff0c5768e22bb2d8c20e8dae74294515c6b3/tools/spgen/source/spgen_test.ml | ocaml | -------------------------------------------------------------------------
-------------------------------------------------------------------------
some common functions
Printf.sprintf
Common.pr2
Common.pr_no_nl
hardcoded values; timeout for testing + extension names
marshalling format used by Common
-------------------------------------------------------------------------
get rid of the --- and +++ lines
Run spgen on <file>.cocci with <file>.config,
* compare to <file>.expected,
* add result to <score>.
spgenerate the file
check that the spgenerated file is parsable. Note that the parsing
* flag generating_mode must be false (this should be done in spgen.ml).
hash_to_list also sorts the entries by filename
find and print changes in test results since last time
if good > expected_good then
-------------------------------------------------------------------------
ENTRY POINT
sort expected result files by name
populate score table |
* This file is part of Coccinelle , lincensed under the terms of the GPL v2 .
* See copyright.txt in the Coccinelle source code for more information .
* The Coccinelle source code can be obtained at
* This file is part of Coccinelle, lincensed under the terms of the GPL v2.
* See copyright.txt in the Coccinelle source code for more information.
* The Coccinelle source code can be obtained at
*)
Regression tests .
* Process for :
* - file.cocci ( original cocci file )
* - file.config ( config file for running )
* - file.expected ( expected spgenerated file )
*
* Run < spgen file.cocci --config file.config -o file.actual.cocci >
* Compare file.actual.cocci with file.expected
* Run < spatch --parse - cocci file.actual.cocci -D context > .
* Process for spgen:
* - file.cocci (original cocci file)
* - file.config (config file for running spgen)
* - file.expected (expected spgenerated file)
*
* Run <spgen file.cocci --config file.config -o file.actual.cocci>
* Compare file.actual.cocci with file.expected
* Run <spatch --parse-cocci file.actual.cocci -D context>.
*)
( path , file , ext ) - > path / file.ext
path / file.ext - > ( path , file , ext )
let timeout_per_file = 60
let exp_ext = "expected"
let act_ext = "actual.cocci"
more or less the same as in coccinelle / parsing_c / compare_c.ml .
* diff flags are
* -u : unified format ( ie . output diffs with - and + )
* -b : ignore changes in amount of whitespace
* -B : ignore changes in blank lines
* diff flags are
* -u: unified format (ie. output diffs with - and +)
* -b: ignore changes in amount of whitespace
* -B: ignore changes in blank lines
*)
let get_diff filename1 filename2 =
let com = spf "diff -u -b -B %s %s" filename1 filename2 in
let xs = Common.cmd_to_list com in
if xs = [] then xs else Common.drop 2 xs
let compare_one score expected =
let (dir, base, ext) = nm2dbe expected in
let hashkey = base ^ "." ^ ext in
let actual = dbe2nm (dir, base, act_ext) in
let cocci = dbe2nm (dir, base, "cocci") in
let config = dbe2nm (dir, base, "config") in
if ext <> exp_ext then failwith ("expected extension "^exp_ext^", not "^ext);
if not(Sys.file_exists cocci) then failwith ("no cocci for " ^ expected);
if not(Sys.file_exists config) then failwith ("no config for " ^ expected);
try
Common.timeout_function "spgen_test" timeout_per_file (
fun () ->
perr_nl cocci;
let options = Spgen.make_options ~year:2000 ~output:actual cocci in
let _ = Spgen.run options in
Flag.set_defined_virtual_rules "context";
let _ = Parse_cocci.process actual None false in
match get_diff actual expected with
| [] ->
let _ = if Sys.file_exists actual then Sys.remove actual in
Hashtbl.add score hashkey Common.Ok
| difflist ->
let difflist = List.map (spf " %s\n") difflist in
let difflist = String.concat "" difflist in
let diff =
spf "INCORRECT: %s\n diff (actual vs expected) = \n%s"
actual difflist in
Hashtbl.add score hashkey (Common.Pb diff)
)
with exn ->
let s = spf "PROBLEM\n exn = %s\n" (Printexc.to_string exn) in
Hashtbl.add score hashkey (Common.Pb s)
Prints regression test statistics and information + updates score files .
* ( perhaps split , but then also have to refactor Common.regression_testing_vs )
*
* < test_dir > The directory in which the regression test files are stored
* < score > The new test information
* Similar to coccinelle / testing.ml , but with less stuff .
* (perhaps split, but then also have to refactor Common.regression_testing_vs)
*
* <test_dir> The directory in which the regression test files are stored
* <score> The new test information
* Similar to coccinelle/testing.ml, but with less stuff.
*)
let print_update_regression test_dir score =
if Hashtbl.length score <= 0 then failwith "There are no tests results ...";
let expected_score_file = dbe2nm (test_dir, "SCORE_expected", score_ext) in
let best_of_both_file = dbe2nm (test_dir, "SCORE_best_of_both", score_ext) in
let actual_score_file = dbe2nm (test_dir, "SCORE_actual", score_ext) in
perr_nl "--------------------------------";
perr_nl "statistics";
perr_nl "--------------------------------";
let print_result (filename, result) =
perr (spf "%-40s: " filename);
perr (
match result with
| Common.Ok -> "CORRECT\n"
| Common.Pb s -> s
) in
List.iter print_result (Common.hash_to_list score);
perr_nl "--------------------------------";
perr_nl "regression testing information";
perr_nl "--------------------------------";
perr_nl ("regression file: "^ expected_score_file);
let expected_score =
if Sys.file_exists expected_score_file then
Common.load_score expected_score_file()
else
let s = Common.empty_score() in
let _ = Common.save_score s expected_score_file in
s
in
let new_bestscore = Common.regression_testing_vs score expected_score in
Common.save_score score actual_score_file;
Common.save_score new_bestscore best_of_both_file;
Common.print_total_score score;
let (good, total) = Common.total_scores score in
let (expected_good, expected_total) = Common.total_scores expected_score in
if good = expected_good then begin
perr_nl "Current score is equal to expected score; everything is fine"
end else
if good < expected_good then begin
perr_nl "Current score is lower than expected :(";
perr_nl (spf "(was expecting %d but got %d)\n" expected_good good);
perr_nl "If you think it's normal, then maybe you need to update the";
perr_nl (spf "score file %s, copying info from %s."
expected_score_file actual_score_file)
end else
perr_nl "Current score is greater than expected :)";
perr_nl (spf "(was expecting %d but got %d)" expected_good good);
perr_nl "Generating new expected score file and saving old one";
Common.command2_y_or_no_exit_if_no
(spf "mv %s %s" expected_score_file (expected_score_file ^ ".save"));
Common.command2_y_or_no_exit_if_no
(spf "mv %s %s" best_of_both_file expected_score_file)
end
let regression_test ~test_dir =
let test_files = dbe2nm (test_dir, "*", exp_ext) in
let e = Common.glob test_files in
let e = List.filter (fun f -> Common.filesize f > 0) e in
let expected_files = List.sort compare e in
if e = [] then failwith (
(spf "No test files with expected extension <.%s> found." exp_ext) ^
" Are you sure this is the right directory?"
);
let actual_score = Common.empty_score() in
List.iter (compare_one actual_score) expected_files;
print_update_regression test_dir actual_score
|
cac8466168ac612d98c9a63d45d83474863874b4e205a6a00788291fa28a8a40 | S8A/htdp-exercises | ex213.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex213) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp")) #f)))
; A Word is one of:
; – '() or
; – (cons 1String Word)
interpretation a Word is a list of 1Strings ( letters )
(define wde (explode "de"))
(define wcat (explode "cat"))
(define wrat (explode "rat"))
A List - of - words is one of :
; - '()
; - (cons Word List-of-words)
(define low0 '())
(define low1 (list wde))
(define low2 (list wde wcat))
(define low3 (list wde wcat wrat))
(define LOCATION "/usr/share/dict/words")
; A Dictionary is a List-of-strings.
(define DICT-AS-LIST (read-lines LOCATION))
A Letter is one of the following 1Strings :
; – "a"
; – ...
; – "z"
; or, equivalently, a member? of this list:
(define LETTERS (explode "abcdefghijklmnopqrstuvwxyz"))
; Word -> List-of-words
; finds all rearrangements of word
(define (arrangements w)
(cond
[(empty? w) (list '())]
[(cons? w)
(insert-everywhere/in-all-words (first w) (arrangements (rest w)))]))
(check-expect (arrangements '()) (list '()))
(check-expect (arrangements wde)
(list (list "d" "e") (list "e" "d")))
; 1String List-of-words -> List-of-words
; produces a list like the given one but with character x inserted at
; the beginning, between all letters, and at the end of all words of the
; given list
(define (insert-everywhere/in-all-words x low)
(cond
[(empty? low) '()]
[(cons? low)
(append (insert-everywhere x (first low))
(insert-everywhere/in-all-words x (rest low)))]))
(check-expect (insert-everywhere/in-all-words "d" '()) '())
(check-expect (insert-everywhere/in-all-words "d" (list '()))
(list (list "d")))
(check-expect (insert-everywhere/in-all-words "d" (list (list "e")))
(list (list "d" "e") (list "e" "d")))
(check-expect (insert-everywhere/in-all-words "d" (list (list "e" "r")
(list "r" "e")))
(list (list "d" "e" "r") (list "e" "d" "r") (list "e" "r" "d")
(list "d" "r" "e") (list "r" "d" "e") (list "r" "e" "d")))
; 1String Word -> List-of-words
; inserts the character x at every position between the characters of the word w
(define (insert-everywhere x w)
(cond
[(empty? w) (list (list x))]
[(cons? w)
(cons (prepend x w)
(prepend-to-each (first w) (insert-everywhere x (rest w))))]))
(check-expect (insert-everywhere "d" '())
(list (list "d")))
(check-expect (insert-everywhere "d" (list "e"))
(list (list "d" "e") (list "e" "d")))
(check-expect (insert-everywhere "d" (list "e" "r"))
(list (list "d" "e" "r") (list "e" "d" "r") (list "e" "r" "d")))
; 1String Word -> Word
; inserts the character x at the beginning of the given word
(define (prepend x w)
(cons x w))
(check-expect (prepend "d" '()) (list "d"))
(check-expect (prepend "d" (list "e")) (list "d" "e"))
(check-expect (prepend "d" (list "e" "r")) (list "d" "e" "r"))
; 1String List-of-words -> List-of-words
; inserts the character x at the beginning of each word in the given list
(define (prepend-to-each x low)
(cond
[(empty? low) '()]
[(cons? low)
(cons (prepend x (first low))
(prepend-to-each x (rest low)))]))
(check-expect (prepend-to-each "d" '()) '())
(check-expect (prepend-to-each "d" (list '())) (list (list "d")))
(check-expect (prepend-to-each "d" (list (list "e") (list "r")))
(list (explode "de") (explode "dr")))
(check-expect (prepend-to-each "d" (list (explode "er") (explode "re")))
(list (explode "der") (explode "dre")))
; List-of-strings -> Boolean
(define (all-words-from-rat? w)
(and (member? "rat" w) (member? "art" w) (member? "tar" w)))
; String -> List-of-strings
; finds all words that the letters of some given word spell
(define (alternative-words s)
(in-dictionary (words->strings (arrangements (string->word s)))))
;(check-member-of (alternative-words "cat")
; (list "act" "cat") (list "cat" "act"))
;(check-satisfied (alternative-words "rat") all-words-from-rat?)
; List-of-words -> List-of-strings
; turns all Words in low into Strings
(define (words->strings low)
(cond
[(empty? low) '()]
[(cons? low)
(cons (word->string (first low)) (words->strings (rest low)))]))
(check-expect (words->strings '()) '())
(check-expect (words->strings (list (explode "cat") (explode "act")))
(list "cat" "act"))
; List-of-strings -> List-of-strings
; picks out all those Strings that occur in the dictionary
(define (in-dictionary los)
(cond
[(empty? los) '()]
[(cons? los)
(if (member? (first los) DICT-AS-LIST)
(cons (first los) (in-dictionary (rest los)))
(in-dictionary (rest los)))]))
(check-expect (in-dictionary '()) '())
(check-expect (in-dictionary (list "act" "atc" "cat" "cta" "tac" "tca"))
(list "act" "cat"))
; String -> Word
; converts s to the chosen word representation
(define (string->word s) (explode s))
(check-expect (string->word "") '())
(check-expect (string->word "cat") (list "c" "a" "t"))
; Word -> String
; converts w to a string
(define (word->string w) (implode w))
(check-expect (word->string '()) "")
(check-expect (word->string (list "c" "a" "t")) "cat")
| null | https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex213.rkt | racket | about the language level of this file in a form that our tools can easily process.
A Word is one of:
– '() or
– (cons 1String Word)
- '()
- (cons Word List-of-words)
A Dictionary is a List-of-strings.
– "a"
– ...
– "z"
or, equivalently, a member? of this list:
Word -> List-of-words
finds all rearrangements of word
1String List-of-words -> List-of-words
produces a list like the given one but with character x inserted at
the beginning, between all letters, and at the end of all words of the
given list
1String Word -> List-of-words
inserts the character x at every position between the characters of the word w
1String Word -> Word
inserts the character x at the beginning of the given word
1String List-of-words -> List-of-words
inserts the character x at the beginning of each word in the given list
List-of-strings -> Boolean
String -> List-of-strings
finds all words that the letters of some given word spell
(check-member-of (alternative-words "cat")
(list "act" "cat") (list "cat" "act"))
(check-satisfied (alternative-words "rat") all-words-from-rat?)
List-of-words -> List-of-strings
turns all Words in low into Strings
List-of-strings -> List-of-strings
picks out all those Strings that occur in the dictionary
String -> Word
converts s to the chosen word representation
Word -> String
converts w to a string | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex213) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp")) #f)))
interpretation a Word is a list of 1Strings ( letters )
(define wde (explode "de"))
(define wcat (explode "cat"))
(define wrat (explode "rat"))
A List - of - words is one of :
(define low0 '())
(define low1 (list wde))
(define low2 (list wde wcat))
(define low3 (list wde wcat wrat))
(define LOCATION "/usr/share/dict/words")
(define DICT-AS-LIST (read-lines LOCATION))
A Letter is one of the following 1Strings :
(define LETTERS (explode "abcdefghijklmnopqrstuvwxyz"))
(define (arrangements w)
(cond
[(empty? w) (list '())]
[(cons? w)
(insert-everywhere/in-all-words (first w) (arrangements (rest w)))]))
(check-expect (arrangements '()) (list '()))
(check-expect (arrangements wde)
(list (list "d" "e") (list "e" "d")))
(define (insert-everywhere/in-all-words x low)
(cond
[(empty? low) '()]
[(cons? low)
(append (insert-everywhere x (first low))
(insert-everywhere/in-all-words x (rest low)))]))
(check-expect (insert-everywhere/in-all-words "d" '()) '())
(check-expect (insert-everywhere/in-all-words "d" (list '()))
(list (list "d")))
(check-expect (insert-everywhere/in-all-words "d" (list (list "e")))
(list (list "d" "e") (list "e" "d")))
(check-expect (insert-everywhere/in-all-words "d" (list (list "e" "r")
(list "r" "e")))
(list (list "d" "e" "r") (list "e" "d" "r") (list "e" "r" "d")
(list "d" "r" "e") (list "r" "d" "e") (list "r" "e" "d")))
(define (insert-everywhere x w)
(cond
[(empty? w) (list (list x))]
[(cons? w)
(cons (prepend x w)
(prepend-to-each (first w) (insert-everywhere x (rest w))))]))
(check-expect (insert-everywhere "d" '())
(list (list "d")))
(check-expect (insert-everywhere "d" (list "e"))
(list (list "d" "e") (list "e" "d")))
(check-expect (insert-everywhere "d" (list "e" "r"))
(list (list "d" "e" "r") (list "e" "d" "r") (list "e" "r" "d")))
(define (prepend x w)
(cons x w))
(check-expect (prepend "d" '()) (list "d"))
(check-expect (prepend "d" (list "e")) (list "d" "e"))
(check-expect (prepend "d" (list "e" "r")) (list "d" "e" "r"))
(define (prepend-to-each x low)
(cond
[(empty? low) '()]
[(cons? low)
(cons (prepend x (first low))
(prepend-to-each x (rest low)))]))
(check-expect (prepend-to-each "d" '()) '())
(check-expect (prepend-to-each "d" (list '())) (list (list "d")))
(check-expect (prepend-to-each "d" (list (list "e") (list "r")))
(list (explode "de") (explode "dr")))
(check-expect (prepend-to-each "d" (list (explode "er") (explode "re")))
(list (explode "der") (explode "dre")))
(define (all-words-from-rat? w)
(and (member? "rat" w) (member? "art" w) (member? "tar" w)))
(define (alternative-words s)
(in-dictionary (words->strings (arrangements (string->word s)))))
(define (words->strings low)
(cond
[(empty? low) '()]
[(cons? low)
(cons (word->string (first low)) (words->strings (rest low)))]))
(check-expect (words->strings '()) '())
(check-expect (words->strings (list (explode "cat") (explode "act")))
(list "cat" "act"))
(define (in-dictionary los)
(cond
[(empty? los) '()]
[(cons? los)
(if (member? (first los) DICT-AS-LIST)
(cons (first los) (in-dictionary (rest los)))
(in-dictionary (rest los)))]))
(check-expect (in-dictionary '()) '())
(check-expect (in-dictionary (list "act" "atc" "cat" "cta" "tac" "tca"))
(list "act" "cat"))
(define (string->word s) (explode s))
(check-expect (string->word "") '())
(check-expect (string->word "cat") (list "c" "a" "t"))
(define (word->string w) (implode w))
(check-expect (word->string '()) "")
(check-expect (word->string (list "c" "a" "t")) "cat")
|
0270a531b691b6d02f8cf4399f1f6afc59fc3a71a02ad4f4040b751e05880d4e | gadfly361/rid3 | container.cljs | (ns rid3.container
(:require
[cljsjs.d3]
[rid3.util :as util]))
(defn piece-did-mount [piece opts prev-classes]
(let [{:keys [id
ratom]} opts
{:keys [class
did-mount]
:or {did-mount (fn [node ratom]
node)}} piece
node (js/d3.select (util/node-selector id prev-classes))]
(-> node
(.append "g")
(.attr "class" class)
(did-mount ratom))))
(defn piece-did-update [piece opts prev-classes]
(let [{:keys [id
ratom]} opts
{:keys [class
did-mount
did-update]} piece
did-update (or did-update
did-mount ;; sane-fallback
(fn [node ratom]
node))
node (js/d3.select (str (util/node-selector id prev-classes)
" ." class))]
(did-update node ratom)))
| null | https://raw.githubusercontent.com/gadfly361/rid3/cae79fdbee3b5aba45e29b589425f9a17ef8613b/src/main/rid3/container.cljs | clojure | sane-fallback | (ns rid3.container
(:require
[cljsjs.d3]
[rid3.util :as util]))
(defn piece-did-mount [piece opts prev-classes]
(let [{:keys [id
ratom]} opts
{:keys [class
did-mount]
:or {did-mount (fn [node ratom]
node)}} piece
node (js/d3.select (util/node-selector id prev-classes))]
(-> node
(.append "g")
(.attr "class" class)
(did-mount ratom))))
(defn piece-did-update [piece opts prev-classes]
(let [{:keys [id
ratom]} opts
{:keys [class
did-mount
did-update]} piece
did-update (or did-update
(fn [node ratom]
node))
node (js/d3.select (str (util/node-selector id prev-classes)
" ." class))]
(did-update node ratom)))
|
1181be2169fd80514be20efd3a210e10c3d1ad39dd416b6fc25b50aada9072d8 | sarabander/p2pu-sicp | Ex1.22.scm | Needs the procedures of 1.21
;; Racket needs this
(define (runtime) (current-milliseconds))
(define (timed-prime-test n)
(start-prime-test n (runtime)))
;; The procedures differ from book originals
(define (start-prime-test n start-time)
(if (prime? n)
(report-prime n (- (runtime) start-time))
false))
(define (report-prime n elapsed-time)
(newline)
(display n)
(display " *** ")
(display elapsed-time)
(newline))
(timed-prime-test 242)
(time (timed-prime-test 4398042316799))
(time (timed-prime-test 1125899839733759))
(define (search-for-primes starting-with how-many)
(cond ((zero? how-many) (void))
((odd? starting-with)
(if (timed-prime-test starting-with)
(search-for-primes (+ 2 starting-with) (- how-many 1))
(search-for-primes (+ 2 starting-with) how-many)))
(else (search-for-primes (+ 1 starting-with) how-many))))
1009 , 1013 , 1019
10007 , 10009 , 10037
100003 , 100019 , 100043
1000003 , 1000033 , 1000037
;; search finishes faster than the runtime granularity (1 ms)
;; need to use larger numbers:
1000000007 , 1000000009 , 1000000021
average time 16 ms
10000000019 , 10000000033 , 10000000061
average time 42 ms
100000000003 , 100000000019 , 100000000057
average time 85 ms
1000000000039 , 1000000000061 , 1000000000063
average time 200 ms
(* 30 (sqrt 10))
Little less than ( sqrt 10 ) growth in time when input grows 10 times .
;; Seems to support the proportionality of number of steps and time.
| null | https://raw.githubusercontent.com/sarabander/p2pu-sicp/fbc49b67dac717da1487629fb2d7a7d86dfdbe32/1.2/Ex1.22.scm | scheme | Racket needs this
The procedures differ from book originals
search finishes faster than the runtime granularity (1 ms)
need to use larger numbers:
Seems to support the proportionality of number of steps and time. | Needs the procedures of 1.21
(define (runtime) (current-milliseconds))
(define (timed-prime-test n)
(start-prime-test n (runtime)))
(define (start-prime-test n start-time)
(if (prime? n)
(report-prime n (- (runtime) start-time))
false))
(define (report-prime n elapsed-time)
(newline)
(display n)
(display " *** ")
(display elapsed-time)
(newline))
(timed-prime-test 242)
(time (timed-prime-test 4398042316799))
(time (timed-prime-test 1125899839733759))
(define (search-for-primes starting-with how-many)
(cond ((zero? how-many) (void))
((odd? starting-with)
(if (timed-prime-test starting-with)
(search-for-primes (+ 2 starting-with) (- how-many 1))
(search-for-primes (+ 2 starting-with) how-many)))
(else (search-for-primes (+ 1 starting-with) how-many))))
1009 , 1013 , 1019
10007 , 10009 , 10037
100003 , 100019 , 100043
1000003 , 1000033 , 1000037
1000000007 , 1000000009 , 1000000021
average time 16 ms
10000000019 , 10000000033 , 10000000061
average time 42 ms
100000000003 , 100000000019 , 100000000057
average time 85 ms
1000000000039 , 1000000000061 , 1000000000063
average time 200 ms
(* 30 (sqrt 10))
Little less than ( sqrt 10 ) growth in time when input grows 10 times .
|
bbfe5359b1b62324019edc578a189d6d07be6cb2c53ef86073ae777271bac2ca | RefactoringTools/HaRe | QualClient.hs | module Renaming.QualClient where
foo is imported qualified as in QualClient . Renaming should
preserve the qualification there
preserve the qualification there
-}
import qualified Renaming.QualServer as QS
baz :: String
baz = QS.foo : "hello"
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/Renaming/QualClient.hs | haskell | module Renaming.QualClient where
foo is imported qualified as in QualClient . Renaming should
preserve the qualification there
preserve the qualification there
-}
import qualified Renaming.QualServer as QS
baz :: String
baz = QS.foo : "hello"
|
|
7deccde62628be9eec59d83885e4c39004c450c4ca0b256a627f1586026cd361 | shirok/Gauche | test.scm | ;;
;; testing file.util
;;
(use gauche.test)
(use scheme.list)
(use srfi.13)
(use gauche.uvector)
(test-start "file.*")
(test-section "file.util")
(use file.util)
(cond-expand
[gauche.os.windows
(test-module 'file.util :allow-undefined '(sys-symlink))]
[else
(test-module 'file.util)])
;; shorthand of normalizing pathname. this doesn't do anything on
unix , but on Windows the separator in PATHNAME is replaced .
NB : we remove the drive letter from DOS path to accommodate
;; different installations.
(define (n pathname . pathnames)
(define (normalize s)
(let1 s (sys-normalize-pathname s)
(if (#/^[a-zA-Z]:/ s) (string-drop s 2) s)))
(if (null? pathnames)
(normalize pathname)
(map normalize (cons pathname pathnames))))
;; mingw doesn't have fully compatible permissions as unix.
;; this procedure compensates it.
(define (P perm)
(cond-expand
[gauche.os.windows (let1 p (ash perm -6)
(logior p (ash p 3) (ash p 6)))]
[else perm]))
;;=====================================================================
(test-section "pathname utils")
(test* "build-path" "" (build-path ""))
(test* "build-path" "." (build-path "."))
(test* "build-path" (n "/") (build-path "/"))
(test* "build-path" (n "a/b/c") (build-path "a" "b" "c"))
(test* "build-path" (n "a/b/c") (build-path "a/" "b/" "c"))
(test* "build-path" (n "/a/b/c") (build-path "/" "a/b" "c"))
(test* "build-path" (n "./a/b/c") (build-path "." "a/b" "c"))
(test* "build-path" (test-error) (build-path "." "/a/b"))
(test* "build-path" (n "foo") (build-path "" "foo"))
(test* "build-path" (n "foo/bar") (build-path "" "foo" "" "bar"))
(test* "build-path" (n "foo") (build-path "" "foo" ""))
(test* "decompose-path" '("/a/b/c" "d" "e")
(values->list (decompose-path "/a/b/c/d.e")))
(test* "decompose-path" '("." "d" "e")
(values->list (decompose-path "d.e")))
(test* "decompose-path" '("." "d" "")
(values->list (decompose-path "d.")))
(test* "decompose-path" '("." "d" #f)
(values->list (decompose-path "d")))
(test* "decompose-path" '("/a.b" "c" #f)
(values->list (decompose-path "/a.b/c")))
(test* "decompose-path" '("/a.b" #f #f)
(values->list (decompose-path "/a.b/")))
(test* "decompose-path" '("/a.b" "c.c" "d")
(values->list (decompose-path "/a.b/c.c.d")))
(test* "decompose-path" '("/a.b" ".d" #f)
(values->list (decompose-path "/a.b/.d")))
(test* "path-extension" "c" (path-extension "/a.b/c.d/e.c"))
(test* "path-extension" "" (path-extension "/a.b/c.d/e.c."))
(test* "path-extension" #f (path-extension "/a.b/c.d/.e"))
(test* "path-extension" #f (path-extension "/a.b/c.d/e"))
(test* "path-sans-extension" "/a.b/c.d/e"
(path-sans-extension "/a.b/c.d/e.c"))
(test* "path-sans-extension" "/a.b/c.d/e.c"
(path-sans-extension "/a.b/c.d/e.c."))
(test* "path-sans-extension" "/a.b/c.d/.e"
(path-sans-extension "/a.b/c.d/.e"))
(test* "path-sans-extension" "/a.b/c.d/e"
(path-sans-extension "/a.b/c.d/e"))
(test* "path-sans-extension" "a" (path-sans-extension "a.c"))
(test* "path-sans-extension" "a" (path-sans-extension "a."))
(test* "path-sans-extension" "a" (path-sans-extension "a"))
(test* "path-sans-extension" ".a" (path-sans-extension ".a"))
(test* "path-sans-extension" ".a" (path-sans-extension ".a.c"))
(test* "path-swap-extension" "/a.b/c.d/e.o"
(path-swap-extension "/a.b/c.d/e.c" "o"))
(test* "path-swap-extension" "/a.b/c.d/e.c.o"
(path-swap-extension "/a.b/c.d/e.c." "o"))
(test* "path-swap-extension" "/a.b/c.d/.e.o"
(path-swap-extension "/a.b/c.d/.e" "o"))
(test* "path-swap-extension" "/a.b/c.d/e.o"
(path-swap-extension "/a.b/c.d/e" "o"))
(test* "path-swap-extension" "/a.b/c.d/e"
(path-swap-extension "/a.b/c.d/e.c" #f))
(test* "path-swap-extension" "a.o" (path-swap-extension "a.c" "o"))
(test* "path-swap-extension" "a.o" (path-swap-extension "a." "o"))
(test* "path-swap-extension" "a.o" (path-swap-extension "a" "o"))
(test* "path-swap-extension" ".a.o" (path-swap-extension ".a" "o"))
(test* "path-swap-extension" ".a.o" (path-swap-extension ".a.c" "o"))
;; find-file-in-paths is tested after diretory util tests
;;=====================================================================
(test-section "directories")
(test* "current-directory" (list (n "/") (n "/") #t #t)
(let* ([cur (sys-getcwd)]
[root (begin (current-directory "/")
(n (sys-getcwd)))]
[root* (n (current-directory))]
[cur* (begin (current-directory cur)
(sys-getcwd))]
[cur** (current-directory)])
(list root root* (string=? cur cur*) (string=? cur* cur**))))
;; prepare test data set
(define *test-tree*
`(test.out
((test1.o ,(make-string 100 #\o))
(test2.o ,(make-string 100 #\o))
(test3.o ,(make-string 100 #\i))
(test4.o ,(make-string 20000 #\i))
(test5.o ,(make-string 20000 #\i))
,@(cond-expand
[gauche.sys.symlink
'((test6.o :symlink "test1.o")
(test7.o :symlink "test6.o")
(test2.d :symlink "test.d"))]
[else
`((test6.o ,(make-string 100 #\o))
(test7.o ,(make-string 100 #\o))
(test2.d :mode #o777
((test10.o ,(make-string 100 #\o))
(test11.o ,(make-string 100 #\o))
test12.o)))])
(test.d ((test10.o ,(make-string 100 #\o))
,(cond-expand
[gauche.sys.symlink
'(test11.o :symlink "../test1.o")]
[else
`(test11.o ,(make-string 100 #\o))])
test12.o))
)))
(test-remove-files "test.out")
(test* "create-directory-tree" #t
(begin (create-directory-tree "." *test-tree*)
(and (file-is-directory? "test.out")
(file-is-regular? "test.out/test1.o")
(file-is-regular? "test.out/test2.o")
(file-is-regular? "test.out/test3.o")
(file-is-regular? "test.out/test4.o")
(file-is-regular? "test.out/test5.o")
(file-is-directory? "test.out/test.d")
(file-is-regular? "test.out/test.d/test10.o")
(file-is-regular? "test.out/test.d/test12.o"))))
(test* "check-directory-tree" #t
(check-directory-tree "." *test-tree*))
(test* "directory-list"
'("." ".." "test.d" "test1.o" "test2.d" "test2.o"
"test3.o" "test4.o" "test5.o" "test6.o" "test7.o" )
(directory-list "test.out"))
(test* "directory-list :children?"
'("test.d" "test1.o" "test2.d" "test2.o"
"test3.o" "test4.o" "test5.o" "test6.o" "test7.o" )
(directory-list "test.out" :children? #t))
(test* "directory-list :add-path?"
(n "test.out/." "test.out/.." "test.out/test.d" "test.out/test1.o"
"test.out/test2.d" "test.out/test2.o" "test.out/test3.o"
"test.out/test4.o" "test.out/test5.o" "test.out/test6.o"
"test.out/test7.o" )
(directory-list "test.out/" :add-path? #t))
(test* "directory-list :filter"
(n "test.out/test1.o"
"test.out/test2.o" "test.out/test3.o" "test.out/test4.o"
"test.out/test5.o" "test.out/test6.o" "test.out/test7.o" )
(directory-list "test.out" :add-path? #t
:filter (^p (string-suffix? "o" p))))
(test* "directory-list :filter"
(n "test.out/test1.o"
"test.out/test2.o" "test.out/test3.o" "test.out/test4.o"
"test.out/test5.o" "test.out/test6.o" "test.out/test7.o" )
(directory-list "test.out" :add-path? #t :filter-add-path? #t
:filter file-is-regular?))
(test* "directory-list2"
'(("." ".." "test.d" "test2.d")
("test1.o" "test2.o" "test3.o" "test4.o"
"test5.o" "test6.o" "test7.o" ))
(values->list (directory-list2 "test.out")))
(test* "directory-list2 :add-path"
`(,(n "test.out/." "test.out/.." "test.out/test.d" "test.out/test2.d")
,(n "test.out/test1.o" "test.out/test2.o" "test.out/test3.o"
"test.out/test4.o" "test.out/test5.o" "test.out/test6.o"
"test.out/test7.o"))
(values->list (directory-list2 "test.out" :add-path? #t)))
(test* "directory-list2 :children"
`(,(n "test.out/test.d" "test.out/test2.d")
,(n "test.out/test1.o" "test.out/test2.o" "test.out/test3.o"
"test.out/test4.o" "test.out/test5.o" "test.out/test6.o"
"test.out/test7.o"))
(values->list (directory-list2 "test.out" :add-path? #t :children? #t)))
(test* "directory-list2 :filter"
'(("test.d" "test2.d")
("test1.o" "test2.o" "test3.o" "test4.o"
"test5.o" "test6.o" "test7.o" ))
(values->list
(directory-list2 "test.out"
:filter (^p (string-contains p "test")))))
(cond-expand
[gauche.sys.symlink
(test* "directory-list2 :follow-link? #f"
'(("test.d")
("test1.o" "test2.d" "test2.o" "test3.o" "test4.o"
"test5.o" "test6.o" "test7.o" ))
(values->list
(directory-list2 "test.out" :follow-link? #f :children? #t)))]
[else])
(test* "directory-fold"
(n "test.out/test.d/test10.o" "test.out/test.d/test11.o"
"test.out/test1.o"
"test.out/test2.d/test10.o" "test.out/test2.d/test11.o"
"test.out/test2.o" "test.out/test3.o"
"test.out/test6.o" "test.out/test7.o")
(reverse
(directory-fold "test.out"
(^[path result]
(if (= (file-size path) 100)
(cons path result)
result))
'()))
)
(test* "directory-fold"
(n "test.out"
"test.out/test.d"
"test.out/test.d/test10.o"
"test.out/test.d/test11.o"
"test.out/test.d/test12.o"
"test.out/test1.o"
"test.out/test2.d"
"test.out/test2.d/test10.o"
"test.out/test2.d/test11.o"
"test.out/test2.d/test12.o"
"test.out/test2.o" "test.out/test3.o"
"test.out/test4.o" "test.out/test5.o"
"test.out/test6.o" "test.out/test7.o")
(reverse
(directory-fold "test.out" cons '()
:lister (^[path seed]
(values
(directory-list path
:add-path? #t
:children? #t)
(cons path seed)))))
)
(cond-expand
[gauche.sys.symlink
(test* "directory-fold :follow-link? #f"
(n "test.out/test.d/test10.o"
"test.out/test.d/test11.o"
"test.out/test1.o"
"test.out/test2.o" "test.out/test3.o"
"test.out/test6.o" "test.out/test7.o")
(reverse
(directory-fold "test.out"
(^[path result]
(if (and (file-is-regular? path)
(= (file-size path) 100))
(cons path result)
result))
'()
:follow-link? #f)))
;; this tests dangling symlink
(sys-symlink "foo" "test.out/test.dangling")
(test* "directory-fold :follow-link? #t; dangling link"
(n "test.out/test.d/test10.o" "test.out/test.d/test11.o"
"test.out/test.d/test12.o"
"test.out/test.dangling" "test.out/test1.o"
"test.out/test2.d/test10.o" "test.out/test2.d/test11.o"
"test.out/test2.d/test12.o"
"test.out/test2.o" "test.out/test3.o" "test.out/test4.o"
"test.out/test5.o" "test.out/test6.o" "test.out/test7.o")
(sort (directory-fold "test.out" cons '())))
(sys-unlink "test.out/test.dangling")]
[else])
(test* "directory-fold :lister"
(cond-expand
[gauche.sys.symlink
(n "test.out/test.d/test10.o" "test.out/test.d/test11.o"
"test.out/test.d/test12.o"
"test.out/test1.o")]
[else
(n "test.out/test.d/test10.o" "test.out/test.d/test11.o"
"test.out/test.d/test12.o"
"test.out/test2.d/test10.o" "test.out/test2.d/test11.o"
"test.out/test2.d/test12.o"
"test.out/test1.o")])
(reverse
(directory-fold "test.out" cons '()
:follow-link? #f
:lister (^[dir knil]
(receive (dirs files)
(directory-list2 dir :add-path? #t :children? #t :follow-link? #f)
(append dirs
(filter (cut string-contains <> "test1")
files))))))
)
(test-remove-files "test.out")
;;=====================================================================
(test-section "file utils")
(create-directory-tree "." *test-tree*)
;; resolve-path should be here for it uses test.out hierarchy created above.
'(test* "resolve-path" "/" (resolve-path "/"))
(test* "resolve-path" "." (resolve-path "."))
(test* "resolve-path" "test.out" (resolve-path "test.out"))
(cond-expand
[gauche.sys.symlink
(test* "resolve-path" "test.out/test1.o"
(resolve-path "test.out/test6.o"))
(test* "resolve-path" "test.out/test1.o"
(resolve-path "test.out/test7.o"))
(test* "resolve-path" "test.out/test1.o"
(resolve-path "test.out/test2.d/test11.o"))
(test* "resolve-path" "test.out/test1.o"
(resolve-path "test.out/test2.d/../test.d/test11.o"))
(test* "resolve-path" "test.out/test1.o"
(resolve-path "test.out/test.d/../test2.d/test11.o"))
]
[else])
(test* "file-type" #f
(file-type "nonexistent/file"))
(test* "file-type" '(directory directory regular)
(map file-type
'("test.out/test.d" "test.out/test2.d" "test.out/test1.o")))
(cond-expand
[gauche.sys.symlink
(test* "file-type :follow-link? #f" '(directory symlink regular)
(map (cut file-type <> :follow-link? #f)
'("test.out/test.d" "test.out/test2.d" "test.out/test1.o")))]
[else])
(test* "file-eq?" #t
(file-eq? "test.out/test1.o" "test.out/test1.o"))
(cond-expand
[gauche.sys.symlink
(test* "file-eq? (symlink)" #f
(file-eq? "test.out/test1.o" "test.out/test7.o"))]
[else])
(test* "file-eq?" #f
(file-eq? "test.out/test1.o" "test.out/test2.o"))
(test* "file-eqv?" #t
(file-eqv? "test.out/test1.o" "test.out/test1.o"))
(cond-expand
[gauche.sys.symlink
(test* "file-eqv? (symlink)" #t
(file-eqv? "test.out/test1.o" "test.out/test7.o"))
(test* "file-eqv? (symlink)" #t
(file-eqv? "test.out/test1.o" "test.out/test.d/test11.o"))]
[else])
(test* "file-eqv?" #f
(file-eqv? "test.out/test1.o" "test.out/test2.o"))
(test* "file-equal?" #t
(file-equal? "test.out/test1.o" "test.out/test1.o"))
(test* "file-equal?" #t
(file-equal? "test.out/test1.o" "test.out/test2.o"))
(test* "file-equal?" #f
(file-equal? "test.out/test1.o" "test.out/test4.o"))
(test* "file-equal?" #t
(file-equal? "test.out/test4.o" "test.out/test5.o"))
(let1 touched "test.out/touched"
(define (times file)
(let1 s (sys-stat file)
(list (~ s'atime) (~ s'mtime))))
(test* "touch-file :create #f" #t
(and (not (file-exists? touched))
(begin (touch-file touched :create #f)
(not (file-exists? touched)))))
(test* "touch-file" #t
(and (not (file-exists? touched))
(begin (touch-file touched)
(file-exists? touched))))
NB : win32 has a problem of reading file 's timestamp which can be
before 1970/1/1 _ on_local_time _ . For example , if it is 100 in UTC
and we call _ stat ( ) in the timezone UTC-8 , we get UINT_MAX . Here
;; we use a timestamp value large enough to avoid the problem.
(test* "touch-file :time" '(50001 50001)
(begin (touch-file touched :time 50001) (times touched)))
(test* "touch-file :time :type" '(60000 50001)
(begin (touch-file touched :time 60000 :type 'atime) (times touched)))
(test* "touch-file :time :type" '(60000 70000)
(begin (touch-file touched :time 70000 :type 'mtime) (times touched)))
(test* "touch-files" (n "test.out/touched" "test.out/touched1"
"test.out/touched2" "test.out/touched3")
(begin (touch-files (n "test.out/touched" "test.out/touched1"
"test.out/touched2" "test.out/touched3"))
(sort (glob "test.out/touched*"))))
)
(test* "copy-file (normal)" #t
(and (copy-file "test.out/test5.o" "test.out/test.copy")
(not (file-eq? "test.out/test5.o" "test.out/test.copy"))
(file-equal? "test.out/test5.o" "test.out/test.copy")))
(test* "copy-file (normal; permission check)"
(number->string (logand #o666 (lognot (sys-umask))) 8)
(number->string (file-perm "test.out/test.copy") 8))
(test* "copy-file (:if-exists :error)" (test-error)
(copy-file "test.out/test5.o" "test.out/test.copy"))
(test* "copy-file (:if-exists #f)" #f
(copy-file "test.out/test5.o" "test.out/test.copy" :if-exists #f))
(test* "copy-file (:if-exists :supersede)" #t
(and (copy-file "test.out/test1.o" "test.out/test.copy"
:if-exists :supersede)
(file-equal? "test.out/test1.o" "test.out/test.copy")
(not (file-exists? "test.out/test.copy.orig"))))
(test* "copy-file (:if-exists :backup)" #t
(and (copy-file "test.out/test5.o" "test.out/test.copy"
:if-exists :backup)
(file-equal? "test.out/test5.o" "test.out/test.copy")
(file-equal? "test.out/test1.o" "test.out/test.copy.orig")))
(test* "copy-file (:if-exists :backup)" #t
(and (copy-file "test.out/test1.o" "test.out/test.copy"
:if-exists :backup :backup-suffix "~")
(file-equal? "test.out/test1.o" "test.out/test.copy")
(file-equal? "test.out/test5.o" "test.out/test.copy~")))
(let ()
(define (check-copy-file-append . args)
(let1 preamble "********************************\n"
(sys-unlink "test.out/test.copy")
(sys-unlink "test.out/test.copy2")
(with-output-to-file "test.out/test.copy"
(^[] (display preamble)))
(apply copy-file "test.out/test1.o" "test.out/test.copy"
:if-exists :append args)
(with-output-to-file "test.out/test.copy2"
(^[] (display preamble)
(call-with-input-file "test.out/test1.o"
(^[in] (copy-port in (current-output-port))))))
(file-equal? "test.out/test.copy" "test.out/test.copy2")))
(test* "copy-file (:if-exists :append)" #t
(check-copy-file-append))
(test* "copy-file (:if-exists :append :safe #t)" #t
(check-copy-file-append :safe #t)))
(sys-unlink "test.out/test.copy")
(sys-unlink "test.out/test.copy2")
(sys-unlink "test.out/test.copy~")
(sys-unlink "test.out/test.copy.orig")
(cond-expand
[gauche.sys.symlink
(test* "copy-file (:follow-link? #f)" 'symlink
(begin
(copy-file "test.out/test6.o" "test.out/test.copy" :follow-link? #f)
(sys-system "ls -l test.out")
(file-type "test.out/test.copy" :follow-link? #f)))
(test* "copy-file (:follow-link? #f :if-exists :backup)"
'(symlink symlink)
(begin
(copy-file "test.out/test6.o" "test.out/test.copy"
:follow-link? #f :if-exists :backup :backup-suffix "~")
(list (file-type "test.out/test.copy" :follow-link? #f)
(file-type "test.out/test.copy~" :follow-link? #f))))
(sys-unlink "test.out/test.copy")
(sys-unlink "test.out/test.copy~")]
[else])
(test* "copy-file (normal, safe)" #t
(and (copy-file "test.out/test5.o" "test.out/test.copy" :safe #t)
(not (file-eq? "test.out/test5.o" "test.out/test.copy"))
(file-equal? "test.out/test5.o" "test.out/test.copy")))
(test* "copy-file (:if-exists :error, safe)" (test-error)
(copy-file "test.out/test5.o" "test.out/test.copy" :safe #t))
(test* "copy-file (:if-exists #f, safe)" #f
(copy-file "test.out/test5.o" "test.out/test.copy" :if-exists #f :safe #t))
(test* "copy-file (:if-exists :supersede, safe)" #t
(and (copy-file "test.out/test1.o" "test.out/test.copy"
:if-exists :supersede :safe #t)
(file-equal? "test.out/test1.o" "test.out/test.copy")
(not (file-exists? "test.out/test.copy.orig"))))
(test* "copy-file (:if-exists :backup, safe)" #t
(and (copy-file "test.out/test5.o" "test.out/test.copy"
:if-exists :backup :safe #t)
(file-equal? "test.out/test5.o" "test.out/test.copy")
(file-equal? "test.out/test1.o" "test.out/test.copy.orig")))
(test* "copy-file (:if-exists :backup, safe)" #t
(and (copy-file "test.out/test1.o" "test.out/test.copy"
:if-exists :backup :backup-suffix "~" :safe #t)
(file-equal? "test.out/test1.o" "test.out/test.copy")
(file-equal? "test.out/test5.o" "test.out/test.copy~")))
(test* "copy-file (same file)" (test-error)
(copy-file "test.out/test.copy" "test.out/test.copy"
:if-exists :supersede))
(sys-unlink "test.out/test.copy")
(test* "copy-file (keep-mode)" (P #o642)
(begin (sys-chmod "test.out/test1.o" #o642)
(copy-file "test.out/test1.o" "test.out/test.copy"
:keep-mode #t)
(file-perm "test.out/test.copy")))
(sys-unlink "test.out/test.copy")
(test* "copy-file (keep-mode w/safe)" (P #o624)
(begin (sys-chmod "test.out/test1.o" #o624)
(copy-file "test.out/test1.o" "test.out/test.copy"
:keep-mode #t)
(file-perm "test.out/test.copy")))
(sys-chmod "test.out/test1.o" #o644)
(sys-chmod "test.out/test.copy" #o644)
(test* "move-file (normal)" #t
(and (move-file "test.out/test.copy" "test.out/test.move")
(not (file-exists? "test.out/test.copy"))
(file-equal? "test.out/test1.o" "test.out/test.move")))
(test* "move-file (:if-exists :error)" (test-error)
(move-file "test.out/test5.o" "test.out/test.move"))
(test* "move-file (:if-exists :supersede)" #t
(and (move-file "test.out/test5.o" "test.out/test.move"
:if-exists :supersede)
(not (file-exists? "test.out/test5.o"))
(not (file-equal? "test.out/test1.o" "test.out/test.move"))))
(test* "move-file (:if-exists :backup)" #t
(and (move-file "test.out/test1.o" "test.out/test.move"
:if-exists :backup)
(not (file-exists? "test.out/test1.o"))
(file-equal? "test.out/test2.o" "test.out/test.move")
(file-equal? "test.out/test4.o" "test.out/test.move.orig")))
(test* "move-file (same file)" (test-error)
(move-file "test.out/test.move" "test.out/test.move"
:if-exists :supersede))
(let ()
(define (listdir d)
(map (cut regexp-replace #/^test2?\.out[\/\\]/ <> "")
(directory-fold d cons '())))
(test* "copy-directory*" (listdir "test.out")
(begin
(copy-directory* "test.out" "test2.out")
(listdir "test2.out"))
(cut lset= string=? <> <>))
(test* "remove-directory*" '(#f #f)
(begin
(remove-directory* "test.out")
(remove-directory* "test2.out")
(list (file-exists? "test.out") (file-exists? "test2.out"))))
;; check dangling link behavior
(cond-expand
[gauche.sys.symlink
(let ()
(define (tester desc fn expect . opts)
(test* #"dangling symlink - ~desc" expect
(begin
(sys-symlink "no such file" "test.out")
(apply fn "test.out" "test2.out" opts)
(and (file-is-symlink? "test2.out")
(string=? (sys-readlink "test.out")
(sys-readlink "test2.out")))))
(remove-files "test.out" "test2.out"))
(tester "copy-file" copy-file (test-error))
(tester "copy-file" copy-file #t :follow-link? #f)
(tester "copy-directory*" copy-directory* #t)
(tester "copy-directory*" copy-directory* (test-error) :follow-link? #t)
)]
[else])
)
;;
;; temporary file/dir
;;
(test* "call-with-temporary-file" '(#t #t #f)
(unwind-protect
(begin
(remove-files '("test.o"))
(make-directory* "test.o")
(receive (exists name)
(call-with-temporary-file
(^[oport name] (values (file-exists? name) name))
:directory "test.o"
:prefix "ooo")
(list exists
(boolean (#/test.o[\/\\]ooo\w+$/ name))
(file-exists? name))))
(remove-files '("test.o"))))
(test* "call-with-temporary-directory" '(#t #t #f)
(unwind-protect
(begin
(remove-files '("test.o"))
(make-directory* "test.o")
(receive (exists name)
(call-with-temporary-directory
(^[name] (values (file-is-directory? name) name))
:directory "test.o"
:prefix "ooo")
(list exists
(boolean (#/test.o[\/\\]ooo\w+$/ name))
(file-exists? name))))
(remove-files '("test.o"))))
;;
;; file->*
;;
(test* "file->string, if-does-not-exist #f" #f
(file->string "test.out" :if-does-not-exist #f))
(test* "file->string, if-does-not-exist :error" (test-error)
(file->string "test.out" :if-does-not-exist :error))
(with-output-to-file "test.out"
(cut display "humuhumu\nnukunuku\napua`a\n\n"))
(test* "file->string" "humuhumu\nnukunuku\napua`a\n\n"
(file->string "test.out"))
(test* "file->string-list" '("humuhumu" "nukunuku" "apua`a" "")
(file->string-list "test.out"))
(remove-files "test.out" "test2.out")
;;
;; with-lock-file
;;
(define (test-lock-file type)
(remove-files "test.out" "test.out.2")
(test* #"with-lock-file (~type) just lock&release" '(#t #f)
(let1 r (with-lock-file "test.out"
(^[] (file-exists? "test.out"))
:type type)
(list r (file-exists? "test.out"))))
(remove-files "test.out" "test.out.2")
(test* #"with-lock-file (~type) lock giveup" `((,<lock-file-failure> #t) #f)
(let1 r
(with-lock-file "test.out"
(^[]
(let1 r2
(guard (e (else (class-of e)))
(with-lock-file "test.out"
(^[] 'boo!)
:type type
:abandon-timeout #f
:retry-interval 0.1
:retry-limit 0.5))
(list r2 (file-exists? "test.out"))))
:type type)
(list r (file-exists? "test.out"))))
(remove-files "test.out" "test.out.2")
(test* #"with-lock-file (~type) stealing" 'got
(begin
(case type
[(file) (touch-file "test.out")]
[(directory) (make-directory* "test.out")])
(with-lock-file "test.out"
(^[] 'got)
:type type
:retry-interval 0.1
:retry-limit 5
:abandon-timeout 1)))
(remove-files "test.out" "test.out.2")
(test* #"with-lock-file (~type) stealing failure"
(test-error <lock-file-failure>)
(begin
(case type
[(file) (make-directory* "test.out")]
[(directory) (touch-file "test.out")])
(with-lock-file "test.out"
(^[] 'got)
:type type
:retry-interval 0.1
:retry-limit 0.5
:abandon-timeout 1)))
(remove-files "test.out" "test.out.2")
)
(test-lock-file 'file)
(test-lock-file 'directory)
;;
;; find-file-in-paths
;;
(let ()
(define (cleanup)
(when (file-exists? "test.out")
(remove-directory* "test.out")))
(define paths '("test.out/bin"
"test.out/usr/bin"
"test.out/usr/sbin"))
(cleanup)
(dolist [p paths] (make-directory* p))
(print (directory-list "."))
(touch-files '("test.out/bin/foo"
"test.out/bin/bar"
"test.out/bin/ban.com"
"test.out/usr/bin/foo"
"test.out/usr/bin/bar"
"test.out/usr/bin/baz"
"test.out/usr/bin/ban.exe"
"test.out/usr/sbin/foo"
"test.out/usr/sbin/bar"
"test.out/usr/sbin/ban"))
(unwind-protect
(begin
(test* "find-file-in-paths" (n "test.out/bin/foo")
(find-file-in-paths "foo"
:paths paths
:pred file-exists?))
(test* "find-file-in-paths" (n "test.out/usr/bin/foo")
(find-file-in-paths "foo"
:paths (cdr paths)
:pred file-exists?))
(test* "find-file-in-paths" (n "test.out/usr/sbin/ban")
(find-file-in-paths "ban"
:paths paths
:pred file-exists?))
(test* "find-file-in-paths" (n "test.out/usr/bin/ban.exe")
(find-file-in-paths "ban"
:paths paths
:pred file-exists?
:extensions '("exe")))
(test* "find-file-in-paths" (n "test.out/bin/ban.com")
(find-file-in-paths "ban"
:paths paths
:pred file-exists?
:extensions '("exe" "com")))
)
(cleanup))
)
;;=====================================================================
(test-section "file.event")
(use file.event)
(test-module 'file.event)
(test-module 'file.event.common) ;loaded via file.event
(define-module file-event-generic-test
(use gauche.test)
(use file.event.generic)
(test-module 'file.event.generic))
(define-module file-event-specific-test
(use gauche.test)
;; Those submodules are already loaded via file.event
(cond-expand
[gauche.sys.inotify (test-module 'file.event.inotify)]
[gauche.sys.kqueue (test-module 'file.event.kqueue)]
[else]))
(test-end)
| null | https://raw.githubusercontent.com/shirok/Gauche/95af59561eaca4bc9814a2623da8ef4f2dea9e24/ext/file/test.scm | scheme |
testing file.util
shorthand of normalizing pathname. this doesn't do anything on
different installations.
mingw doesn't have fully compatible permissions as unix.
this procedure compensates it.
=====================================================================
find-file-in-paths is tested after diretory util tests
=====================================================================
prepare test data set
this tests dangling symlink
=====================================================================
resolve-path should be here for it uses test.out hierarchy created above.
we use a timestamp value large enough to avoid the problem.
check dangling link behavior
temporary file/dir
file->*
with-lock-file
find-file-in-paths
=====================================================================
loaded via file.event
Those submodules are already loaded via file.event |
(use gauche.test)
(use scheme.list)
(use srfi.13)
(use gauche.uvector)
(test-start "file.*")
(test-section "file.util")
(use file.util)
(cond-expand
[gauche.os.windows
(test-module 'file.util :allow-undefined '(sys-symlink))]
[else
(test-module 'file.util)])
unix , but on Windows the separator in PATHNAME is replaced .
NB : we remove the drive letter from DOS path to accommodate
(define (n pathname . pathnames)
(define (normalize s)
(let1 s (sys-normalize-pathname s)
(if (#/^[a-zA-Z]:/ s) (string-drop s 2) s)))
(if (null? pathnames)
(normalize pathname)
(map normalize (cons pathname pathnames))))
(define (P perm)
(cond-expand
[gauche.os.windows (let1 p (ash perm -6)
(logior p (ash p 3) (ash p 6)))]
[else perm]))
(test-section "pathname utils")
(test* "build-path" "" (build-path ""))
(test* "build-path" "." (build-path "."))
(test* "build-path" (n "/") (build-path "/"))
(test* "build-path" (n "a/b/c") (build-path "a" "b" "c"))
(test* "build-path" (n "a/b/c") (build-path "a/" "b/" "c"))
(test* "build-path" (n "/a/b/c") (build-path "/" "a/b" "c"))
(test* "build-path" (n "./a/b/c") (build-path "." "a/b" "c"))
(test* "build-path" (test-error) (build-path "." "/a/b"))
(test* "build-path" (n "foo") (build-path "" "foo"))
(test* "build-path" (n "foo/bar") (build-path "" "foo" "" "bar"))
(test* "build-path" (n "foo") (build-path "" "foo" ""))
(test* "decompose-path" '("/a/b/c" "d" "e")
(values->list (decompose-path "/a/b/c/d.e")))
(test* "decompose-path" '("." "d" "e")
(values->list (decompose-path "d.e")))
(test* "decompose-path" '("." "d" "")
(values->list (decompose-path "d.")))
(test* "decompose-path" '("." "d" #f)
(values->list (decompose-path "d")))
(test* "decompose-path" '("/a.b" "c" #f)
(values->list (decompose-path "/a.b/c")))
(test* "decompose-path" '("/a.b" #f #f)
(values->list (decompose-path "/a.b/")))
(test* "decompose-path" '("/a.b" "c.c" "d")
(values->list (decompose-path "/a.b/c.c.d")))
(test* "decompose-path" '("/a.b" ".d" #f)
(values->list (decompose-path "/a.b/.d")))
(test* "path-extension" "c" (path-extension "/a.b/c.d/e.c"))
(test* "path-extension" "" (path-extension "/a.b/c.d/e.c."))
(test* "path-extension" #f (path-extension "/a.b/c.d/.e"))
(test* "path-extension" #f (path-extension "/a.b/c.d/e"))
(test* "path-sans-extension" "/a.b/c.d/e"
(path-sans-extension "/a.b/c.d/e.c"))
(test* "path-sans-extension" "/a.b/c.d/e.c"
(path-sans-extension "/a.b/c.d/e.c."))
(test* "path-sans-extension" "/a.b/c.d/.e"
(path-sans-extension "/a.b/c.d/.e"))
(test* "path-sans-extension" "/a.b/c.d/e"
(path-sans-extension "/a.b/c.d/e"))
(test* "path-sans-extension" "a" (path-sans-extension "a.c"))
(test* "path-sans-extension" "a" (path-sans-extension "a."))
(test* "path-sans-extension" "a" (path-sans-extension "a"))
(test* "path-sans-extension" ".a" (path-sans-extension ".a"))
(test* "path-sans-extension" ".a" (path-sans-extension ".a.c"))
(test* "path-swap-extension" "/a.b/c.d/e.o"
(path-swap-extension "/a.b/c.d/e.c" "o"))
(test* "path-swap-extension" "/a.b/c.d/e.c.o"
(path-swap-extension "/a.b/c.d/e.c." "o"))
(test* "path-swap-extension" "/a.b/c.d/.e.o"
(path-swap-extension "/a.b/c.d/.e" "o"))
(test* "path-swap-extension" "/a.b/c.d/e.o"
(path-swap-extension "/a.b/c.d/e" "o"))
(test* "path-swap-extension" "/a.b/c.d/e"
(path-swap-extension "/a.b/c.d/e.c" #f))
(test* "path-swap-extension" "a.o" (path-swap-extension "a.c" "o"))
(test* "path-swap-extension" "a.o" (path-swap-extension "a." "o"))
(test* "path-swap-extension" "a.o" (path-swap-extension "a" "o"))
(test* "path-swap-extension" ".a.o" (path-swap-extension ".a" "o"))
(test* "path-swap-extension" ".a.o" (path-swap-extension ".a.c" "o"))
(test-section "directories")
(test* "current-directory" (list (n "/") (n "/") #t #t)
(let* ([cur (sys-getcwd)]
[root (begin (current-directory "/")
(n (sys-getcwd)))]
[root* (n (current-directory))]
[cur* (begin (current-directory cur)
(sys-getcwd))]
[cur** (current-directory)])
(list root root* (string=? cur cur*) (string=? cur* cur**))))
(define *test-tree*
`(test.out
((test1.o ,(make-string 100 #\o))
(test2.o ,(make-string 100 #\o))
(test3.o ,(make-string 100 #\i))
(test4.o ,(make-string 20000 #\i))
(test5.o ,(make-string 20000 #\i))
,@(cond-expand
[gauche.sys.symlink
'((test6.o :symlink "test1.o")
(test7.o :symlink "test6.o")
(test2.d :symlink "test.d"))]
[else
`((test6.o ,(make-string 100 #\o))
(test7.o ,(make-string 100 #\o))
(test2.d :mode #o777
((test10.o ,(make-string 100 #\o))
(test11.o ,(make-string 100 #\o))
test12.o)))])
(test.d ((test10.o ,(make-string 100 #\o))
,(cond-expand
[gauche.sys.symlink
'(test11.o :symlink "../test1.o")]
[else
`(test11.o ,(make-string 100 #\o))])
test12.o))
)))
(test-remove-files "test.out")
(test* "create-directory-tree" #t
(begin (create-directory-tree "." *test-tree*)
(and (file-is-directory? "test.out")
(file-is-regular? "test.out/test1.o")
(file-is-regular? "test.out/test2.o")
(file-is-regular? "test.out/test3.o")
(file-is-regular? "test.out/test4.o")
(file-is-regular? "test.out/test5.o")
(file-is-directory? "test.out/test.d")
(file-is-regular? "test.out/test.d/test10.o")
(file-is-regular? "test.out/test.d/test12.o"))))
(test* "check-directory-tree" #t
(check-directory-tree "." *test-tree*))
(test* "directory-list"
'("." ".." "test.d" "test1.o" "test2.d" "test2.o"
"test3.o" "test4.o" "test5.o" "test6.o" "test7.o" )
(directory-list "test.out"))
(test* "directory-list :children?"
'("test.d" "test1.o" "test2.d" "test2.o"
"test3.o" "test4.o" "test5.o" "test6.o" "test7.o" )
(directory-list "test.out" :children? #t))
(test* "directory-list :add-path?"
(n "test.out/." "test.out/.." "test.out/test.d" "test.out/test1.o"
"test.out/test2.d" "test.out/test2.o" "test.out/test3.o"
"test.out/test4.o" "test.out/test5.o" "test.out/test6.o"
"test.out/test7.o" )
(directory-list "test.out/" :add-path? #t))
(test* "directory-list :filter"
(n "test.out/test1.o"
"test.out/test2.o" "test.out/test3.o" "test.out/test4.o"
"test.out/test5.o" "test.out/test6.o" "test.out/test7.o" )
(directory-list "test.out" :add-path? #t
:filter (^p (string-suffix? "o" p))))
(test* "directory-list :filter"
(n "test.out/test1.o"
"test.out/test2.o" "test.out/test3.o" "test.out/test4.o"
"test.out/test5.o" "test.out/test6.o" "test.out/test7.o" )
(directory-list "test.out" :add-path? #t :filter-add-path? #t
:filter file-is-regular?))
(test* "directory-list2"
'(("." ".." "test.d" "test2.d")
("test1.o" "test2.o" "test3.o" "test4.o"
"test5.o" "test6.o" "test7.o" ))
(values->list (directory-list2 "test.out")))
(test* "directory-list2 :add-path"
`(,(n "test.out/." "test.out/.." "test.out/test.d" "test.out/test2.d")
,(n "test.out/test1.o" "test.out/test2.o" "test.out/test3.o"
"test.out/test4.o" "test.out/test5.o" "test.out/test6.o"
"test.out/test7.o"))
(values->list (directory-list2 "test.out" :add-path? #t)))
(test* "directory-list2 :children"
`(,(n "test.out/test.d" "test.out/test2.d")
,(n "test.out/test1.o" "test.out/test2.o" "test.out/test3.o"
"test.out/test4.o" "test.out/test5.o" "test.out/test6.o"
"test.out/test7.o"))
(values->list (directory-list2 "test.out" :add-path? #t :children? #t)))
(test* "directory-list2 :filter"
'(("test.d" "test2.d")
("test1.o" "test2.o" "test3.o" "test4.o"
"test5.o" "test6.o" "test7.o" ))
(values->list
(directory-list2 "test.out"
:filter (^p (string-contains p "test")))))
(cond-expand
[gauche.sys.symlink
(test* "directory-list2 :follow-link? #f"
'(("test.d")
("test1.o" "test2.d" "test2.o" "test3.o" "test4.o"
"test5.o" "test6.o" "test7.o" ))
(values->list
(directory-list2 "test.out" :follow-link? #f :children? #t)))]
[else])
(test* "directory-fold"
(n "test.out/test.d/test10.o" "test.out/test.d/test11.o"
"test.out/test1.o"
"test.out/test2.d/test10.o" "test.out/test2.d/test11.o"
"test.out/test2.o" "test.out/test3.o"
"test.out/test6.o" "test.out/test7.o")
(reverse
(directory-fold "test.out"
(^[path result]
(if (= (file-size path) 100)
(cons path result)
result))
'()))
)
(test* "directory-fold"
(n "test.out"
"test.out/test.d"
"test.out/test.d/test10.o"
"test.out/test.d/test11.o"
"test.out/test.d/test12.o"
"test.out/test1.o"
"test.out/test2.d"
"test.out/test2.d/test10.o"
"test.out/test2.d/test11.o"
"test.out/test2.d/test12.o"
"test.out/test2.o" "test.out/test3.o"
"test.out/test4.o" "test.out/test5.o"
"test.out/test6.o" "test.out/test7.o")
(reverse
(directory-fold "test.out" cons '()
:lister (^[path seed]
(values
(directory-list path
:add-path? #t
:children? #t)
(cons path seed)))))
)
(cond-expand
[gauche.sys.symlink
(test* "directory-fold :follow-link? #f"
(n "test.out/test.d/test10.o"
"test.out/test.d/test11.o"
"test.out/test1.o"
"test.out/test2.o" "test.out/test3.o"
"test.out/test6.o" "test.out/test7.o")
(reverse
(directory-fold "test.out"
(^[path result]
(if (and (file-is-regular? path)
(= (file-size path) 100))
(cons path result)
result))
'()
:follow-link? #f)))
(sys-symlink "foo" "test.out/test.dangling")
(test* "directory-fold :follow-link? #t; dangling link"
(n "test.out/test.d/test10.o" "test.out/test.d/test11.o"
"test.out/test.d/test12.o"
"test.out/test.dangling" "test.out/test1.o"
"test.out/test2.d/test10.o" "test.out/test2.d/test11.o"
"test.out/test2.d/test12.o"
"test.out/test2.o" "test.out/test3.o" "test.out/test4.o"
"test.out/test5.o" "test.out/test6.o" "test.out/test7.o")
(sort (directory-fold "test.out" cons '())))
(sys-unlink "test.out/test.dangling")]
[else])
(test* "directory-fold :lister"
(cond-expand
[gauche.sys.symlink
(n "test.out/test.d/test10.o" "test.out/test.d/test11.o"
"test.out/test.d/test12.o"
"test.out/test1.o")]
[else
(n "test.out/test.d/test10.o" "test.out/test.d/test11.o"
"test.out/test.d/test12.o"
"test.out/test2.d/test10.o" "test.out/test2.d/test11.o"
"test.out/test2.d/test12.o"
"test.out/test1.o")])
(reverse
(directory-fold "test.out" cons '()
:follow-link? #f
:lister (^[dir knil]
(receive (dirs files)
(directory-list2 dir :add-path? #t :children? #t :follow-link? #f)
(append dirs
(filter (cut string-contains <> "test1")
files))))))
)
(test-remove-files "test.out")
(test-section "file utils")
(create-directory-tree "." *test-tree*)
'(test* "resolve-path" "/" (resolve-path "/"))
(test* "resolve-path" "." (resolve-path "."))
(test* "resolve-path" "test.out" (resolve-path "test.out"))
(cond-expand
[gauche.sys.symlink
(test* "resolve-path" "test.out/test1.o"
(resolve-path "test.out/test6.o"))
(test* "resolve-path" "test.out/test1.o"
(resolve-path "test.out/test7.o"))
(test* "resolve-path" "test.out/test1.o"
(resolve-path "test.out/test2.d/test11.o"))
(test* "resolve-path" "test.out/test1.o"
(resolve-path "test.out/test2.d/../test.d/test11.o"))
(test* "resolve-path" "test.out/test1.o"
(resolve-path "test.out/test.d/../test2.d/test11.o"))
]
[else])
(test* "file-type" #f
(file-type "nonexistent/file"))
(test* "file-type" '(directory directory regular)
(map file-type
'("test.out/test.d" "test.out/test2.d" "test.out/test1.o")))
(cond-expand
[gauche.sys.symlink
(test* "file-type :follow-link? #f" '(directory symlink regular)
(map (cut file-type <> :follow-link? #f)
'("test.out/test.d" "test.out/test2.d" "test.out/test1.o")))]
[else])
(test* "file-eq?" #t
(file-eq? "test.out/test1.o" "test.out/test1.o"))
(cond-expand
[gauche.sys.symlink
(test* "file-eq? (symlink)" #f
(file-eq? "test.out/test1.o" "test.out/test7.o"))]
[else])
(test* "file-eq?" #f
(file-eq? "test.out/test1.o" "test.out/test2.o"))
(test* "file-eqv?" #t
(file-eqv? "test.out/test1.o" "test.out/test1.o"))
(cond-expand
[gauche.sys.symlink
(test* "file-eqv? (symlink)" #t
(file-eqv? "test.out/test1.o" "test.out/test7.o"))
(test* "file-eqv? (symlink)" #t
(file-eqv? "test.out/test1.o" "test.out/test.d/test11.o"))]
[else])
(test* "file-eqv?" #f
(file-eqv? "test.out/test1.o" "test.out/test2.o"))
(test* "file-equal?" #t
(file-equal? "test.out/test1.o" "test.out/test1.o"))
(test* "file-equal?" #t
(file-equal? "test.out/test1.o" "test.out/test2.o"))
(test* "file-equal?" #f
(file-equal? "test.out/test1.o" "test.out/test4.o"))
(test* "file-equal?" #t
(file-equal? "test.out/test4.o" "test.out/test5.o"))
(let1 touched "test.out/touched"
(define (times file)
(let1 s (sys-stat file)
(list (~ s'atime) (~ s'mtime))))
(test* "touch-file :create #f" #t
(and (not (file-exists? touched))
(begin (touch-file touched :create #f)
(not (file-exists? touched)))))
(test* "touch-file" #t
(and (not (file-exists? touched))
(begin (touch-file touched)
(file-exists? touched))))
NB : win32 has a problem of reading file 's timestamp which can be
before 1970/1/1 _ on_local_time _ . For example , if it is 100 in UTC
and we call _ stat ( ) in the timezone UTC-8 , we get UINT_MAX . Here
(test* "touch-file :time" '(50001 50001)
(begin (touch-file touched :time 50001) (times touched)))
(test* "touch-file :time :type" '(60000 50001)
(begin (touch-file touched :time 60000 :type 'atime) (times touched)))
(test* "touch-file :time :type" '(60000 70000)
(begin (touch-file touched :time 70000 :type 'mtime) (times touched)))
(test* "touch-files" (n "test.out/touched" "test.out/touched1"
"test.out/touched2" "test.out/touched3")
(begin (touch-files (n "test.out/touched" "test.out/touched1"
"test.out/touched2" "test.out/touched3"))
(sort (glob "test.out/touched*"))))
)
(test* "copy-file (normal)" #t
(and (copy-file "test.out/test5.o" "test.out/test.copy")
(not (file-eq? "test.out/test5.o" "test.out/test.copy"))
(file-equal? "test.out/test5.o" "test.out/test.copy")))
(test* "copy-file (normal; permission check)"
(number->string (logand #o666 (lognot (sys-umask))) 8)
(number->string (file-perm "test.out/test.copy") 8))
(test* "copy-file (:if-exists :error)" (test-error)
(copy-file "test.out/test5.o" "test.out/test.copy"))
(test* "copy-file (:if-exists #f)" #f
(copy-file "test.out/test5.o" "test.out/test.copy" :if-exists #f))
(test* "copy-file (:if-exists :supersede)" #t
(and (copy-file "test.out/test1.o" "test.out/test.copy"
:if-exists :supersede)
(file-equal? "test.out/test1.o" "test.out/test.copy")
(not (file-exists? "test.out/test.copy.orig"))))
(test* "copy-file (:if-exists :backup)" #t
(and (copy-file "test.out/test5.o" "test.out/test.copy"
:if-exists :backup)
(file-equal? "test.out/test5.o" "test.out/test.copy")
(file-equal? "test.out/test1.o" "test.out/test.copy.orig")))
(test* "copy-file (:if-exists :backup)" #t
(and (copy-file "test.out/test1.o" "test.out/test.copy"
:if-exists :backup :backup-suffix "~")
(file-equal? "test.out/test1.o" "test.out/test.copy")
(file-equal? "test.out/test5.o" "test.out/test.copy~")))
(let ()
(define (check-copy-file-append . args)
(let1 preamble "********************************\n"
(sys-unlink "test.out/test.copy")
(sys-unlink "test.out/test.copy2")
(with-output-to-file "test.out/test.copy"
(^[] (display preamble)))
(apply copy-file "test.out/test1.o" "test.out/test.copy"
:if-exists :append args)
(with-output-to-file "test.out/test.copy2"
(^[] (display preamble)
(call-with-input-file "test.out/test1.o"
(^[in] (copy-port in (current-output-port))))))
(file-equal? "test.out/test.copy" "test.out/test.copy2")))
(test* "copy-file (:if-exists :append)" #t
(check-copy-file-append))
(test* "copy-file (:if-exists :append :safe #t)" #t
(check-copy-file-append :safe #t)))
(sys-unlink "test.out/test.copy")
(sys-unlink "test.out/test.copy2")
(sys-unlink "test.out/test.copy~")
(sys-unlink "test.out/test.copy.orig")
(cond-expand
[gauche.sys.symlink
(test* "copy-file (:follow-link? #f)" 'symlink
(begin
(copy-file "test.out/test6.o" "test.out/test.copy" :follow-link? #f)
(sys-system "ls -l test.out")
(file-type "test.out/test.copy" :follow-link? #f)))
(test* "copy-file (:follow-link? #f :if-exists :backup)"
'(symlink symlink)
(begin
(copy-file "test.out/test6.o" "test.out/test.copy"
:follow-link? #f :if-exists :backup :backup-suffix "~")
(list (file-type "test.out/test.copy" :follow-link? #f)
(file-type "test.out/test.copy~" :follow-link? #f))))
(sys-unlink "test.out/test.copy")
(sys-unlink "test.out/test.copy~")]
[else])
(test* "copy-file (normal, safe)" #t
(and (copy-file "test.out/test5.o" "test.out/test.copy" :safe #t)
(not (file-eq? "test.out/test5.o" "test.out/test.copy"))
(file-equal? "test.out/test5.o" "test.out/test.copy")))
(test* "copy-file (:if-exists :error, safe)" (test-error)
(copy-file "test.out/test5.o" "test.out/test.copy" :safe #t))
(test* "copy-file (:if-exists #f, safe)" #f
(copy-file "test.out/test5.o" "test.out/test.copy" :if-exists #f :safe #t))
(test* "copy-file (:if-exists :supersede, safe)" #t
(and (copy-file "test.out/test1.o" "test.out/test.copy"
:if-exists :supersede :safe #t)
(file-equal? "test.out/test1.o" "test.out/test.copy")
(not (file-exists? "test.out/test.copy.orig"))))
(test* "copy-file (:if-exists :backup, safe)" #t
(and (copy-file "test.out/test5.o" "test.out/test.copy"
:if-exists :backup :safe #t)
(file-equal? "test.out/test5.o" "test.out/test.copy")
(file-equal? "test.out/test1.o" "test.out/test.copy.orig")))
(test* "copy-file (:if-exists :backup, safe)" #t
(and (copy-file "test.out/test1.o" "test.out/test.copy"
:if-exists :backup :backup-suffix "~" :safe #t)
(file-equal? "test.out/test1.o" "test.out/test.copy")
(file-equal? "test.out/test5.o" "test.out/test.copy~")))
(test* "copy-file (same file)" (test-error)
(copy-file "test.out/test.copy" "test.out/test.copy"
:if-exists :supersede))
(sys-unlink "test.out/test.copy")
(test* "copy-file (keep-mode)" (P #o642)
(begin (sys-chmod "test.out/test1.o" #o642)
(copy-file "test.out/test1.o" "test.out/test.copy"
:keep-mode #t)
(file-perm "test.out/test.copy")))
(sys-unlink "test.out/test.copy")
(test* "copy-file (keep-mode w/safe)" (P #o624)
(begin (sys-chmod "test.out/test1.o" #o624)
(copy-file "test.out/test1.o" "test.out/test.copy"
:keep-mode #t)
(file-perm "test.out/test.copy")))
(sys-chmod "test.out/test1.o" #o644)
(sys-chmod "test.out/test.copy" #o644)
(test* "move-file (normal)" #t
(and (move-file "test.out/test.copy" "test.out/test.move")
(not (file-exists? "test.out/test.copy"))
(file-equal? "test.out/test1.o" "test.out/test.move")))
(test* "move-file (:if-exists :error)" (test-error)
(move-file "test.out/test5.o" "test.out/test.move"))
(test* "move-file (:if-exists :supersede)" #t
(and (move-file "test.out/test5.o" "test.out/test.move"
:if-exists :supersede)
(not (file-exists? "test.out/test5.o"))
(not (file-equal? "test.out/test1.o" "test.out/test.move"))))
(test* "move-file (:if-exists :backup)" #t
(and (move-file "test.out/test1.o" "test.out/test.move"
:if-exists :backup)
(not (file-exists? "test.out/test1.o"))
(file-equal? "test.out/test2.o" "test.out/test.move")
(file-equal? "test.out/test4.o" "test.out/test.move.orig")))
(test* "move-file (same file)" (test-error)
(move-file "test.out/test.move" "test.out/test.move"
:if-exists :supersede))
(let ()
(define (listdir d)
(map (cut regexp-replace #/^test2?\.out[\/\\]/ <> "")
(directory-fold d cons '())))
(test* "copy-directory*" (listdir "test.out")
(begin
(copy-directory* "test.out" "test2.out")
(listdir "test2.out"))
(cut lset= string=? <> <>))
(test* "remove-directory*" '(#f #f)
(begin
(remove-directory* "test.out")
(remove-directory* "test2.out")
(list (file-exists? "test.out") (file-exists? "test2.out"))))
(cond-expand
[gauche.sys.symlink
(let ()
(define (tester desc fn expect . opts)
(test* #"dangling symlink - ~desc" expect
(begin
(sys-symlink "no such file" "test.out")
(apply fn "test.out" "test2.out" opts)
(and (file-is-symlink? "test2.out")
(string=? (sys-readlink "test.out")
(sys-readlink "test2.out")))))
(remove-files "test.out" "test2.out"))
(tester "copy-file" copy-file (test-error))
(tester "copy-file" copy-file #t :follow-link? #f)
(tester "copy-directory*" copy-directory* #t)
(tester "copy-directory*" copy-directory* (test-error) :follow-link? #t)
)]
[else])
)
(test* "call-with-temporary-file" '(#t #t #f)
(unwind-protect
(begin
(remove-files '("test.o"))
(make-directory* "test.o")
(receive (exists name)
(call-with-temporary-file
(^[oport name] (values (file-exists? name) name))
:directory "test.o"
:prefix "ooo")
(list exists
(boolean (#/test.o[\/\\]ooo\w+$/ name))
(file-exists? name))))
(remove-files '("test.o"))))
(test* "call-with-temporary-directory" '(#t #t #f)
(unwind-protect
(begin
(remove-files '("test.o"))
(make-directory* "test.o")
(receive (exists name)
(call-with-temporary-directory
(^[name] (values (file-is-directory? name) name))
:directory "test.o"
:prefix "ooo")
(list exists
(boolean (#/test.o[\/\\]ooo\w+$/ name))
(file-exists? name))))
(remove-files '("test.o"))))
(test* "file->string, if-does-not-exist #f" #f
(file->string "test.out" :if-does-not-exist #f))
(test* "file->string, if-does-not-exist :error" (test-error)
(file->string "test.out" :if-does-not-exist :error))
(with-output-to-file "test.out"
(cut display "humuhumu\nnukunuku\napua`a\n\n"))
(test* "file->string" "humuhumu\nnukunuku\napua`a\n\n"
(file->string "test.out"))
(test* "file->string-list" '("humuhumu" "nukunuku" "apua`a" "")
(file->string-list "test.out"))
(remove-files "test.out" "test2.out")
(define (test-lock-file type)
(remove-files "test.out" "test.out.2")
(test* #"with-lock-file (~type) just lock&release" '(#t #f)
(let1 r (with-lock-file "test.out"
(^[] (file-exists? "test.out"))
:type type)
(list r (file-exists? "test.out"))))
(remove-files "test.out" "test.out.2")
(test* #"with-lock-file (~type) lock giveup" `((,<lock-file-failure> #t) #f)
(let1 r
(with-lock-file "test.out"
(^[]
(let1 r2
(guard (e (else (class-of e)))
(with-lock-file "test.out"
(^[] 'boo!)
:type type
:abandon-timeout #f
:retry-interval 0.1
:retry-limit 0.5))
(list r2 (file-exists? "test.out"))))
:type type)
(list r (file-exists? "test.out"))))
(remove-files "test.out" "test.out.2")
(test* #"with-lock-file (~type) stealing" 'got
(begin
(case type
[(file) (touch-file "test.out")]
[(directory) (make-directory* "test.out")])
(with-lock-file "test.out"
(^[] 'got)
:type type
:retry-interval 0.1
:retry-limit 5
:abandon-timeout 1)))
(remove-files "test.out" "test.out.2")
(test* #"with-lock-file (~type) stealing failure"
(test-error <lock-file-failure>)
(begin
(case type
[(file) (make-directory* "test.out")]
[(directory) (touch-file "test.out")])
(with-lock-file "test.out"
(^[] 'got)
:type type
:retry-interval 0.1
:retry-limit 0.5
:abandon-timeout 1)))
(remove-files "test.out" "test.out.2")
)
(test-lock-file 'file)
(test-lock-file 'directory)
(let ()
(define (cleanup)
(when (file-exists? "test.out")
(remove-directory* "test.out")))
(define paths '("test.out/bin"
"test.out/usr/bin"
"test.out/usr/sbin"))
(cleanup)
(dolist [p paths] (make-directory* p))
(print (directory-list "."))
(touch-files '("test.out/bin/foo"
"test.out/bin/bar"
"test.out/bin/ban.com"
"test.out/usr/bin/foo"
"test.out/usr/bin/bar"
"test.out/usr/bin/baz"
"test.out/usr/bin/ban.exe"
"test.out/usr/sbin/foo"
"test.out/usr/sbin/bar"
"test.out/usr/sbin/ban"))
(unwind-protect
(begin
(test* "find-file-in-paths" (n "test.out/bin/foo")
(find-file-in-paths "foo"
:paths paths
:pred file-exists?))
(test* "find-file-in-paths" (n "test.out/usr/bin/foo")
(find-file-in-paths "foo"
:paths (cdr paths)
:pred file-exists?))
(test* "find-file-in-paths" (n "test.out/usr/sbin/ban")
(find-file-in-paths "ban"
:paths paths
:pred file-exists?))
(test* "find-file-in-paths" (n "test.out/usr/bin/ban.exe")
(find-file-in-paths "ban"
:paths paths
:pred file-exists?
:extensions '("exe")))
(test* "find-file-in-paths" (n "test.out/bin/ban.com")
(find-file-in-paths "ban"
:paths paths
:pred file-exists?
:extensions '("exe" "com")))
)
(cleanup))
)
(test-section "file.event")
(use file.event)
(test-module 'file.event)
(define-module file-event-generic-test
(use gauche.test)
(use file.event.generic)
(test-module 'file.event.generic))
(define-module file-event-specific-test
(use gauche.test)
(cond-expand
[gauche.sys.inotify (test-module 'file.event.inotify)]
[gauche.sys.kqueue (test-module 'file.event.kqueue)]
[else]))
(test-end)
|
28d8059c9683196031cf81411e8b5a4a5cd4c9b134bace3d65c5da1610c823fa | squaresLab/footpatch | serialization.mli |
* Copyright ( c ) 2009 - 2013 Monoidics ltd .
* Copyright ( c ) 2013 - present Facebook , Inc.
* All rights reserved .
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree . An additional grant
* of patent rights can be found in the PATENTS file in the same directory .
* Copyright (c) 2009 - 2013 Monoidics ltd.
* Copyright (c) 2013 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*)
open! Utils
(** Serialization of data stuctures *)
(** Generic serializer *)
type 'a serializer
(** Serialization key, used to distinguish versions of serializers and avoid assert faults *)
type key
(** current key for an analysis results value *)
val analysis_results_key : key
(** current key for proc attributes *)
val attributes_key : key
(** current key for a cfg *)
val cfg_key : key
(** current key for a call graph *)
val cg_key : key
(** create a serializer from a file name
given an integer key used as double-check of the file type *)
val create_serializer : key -> 'a serializer
(** current key for a cluster *)
val cluster_key : key
(** extract a from_file function from a serializer *)
val from_file : 'a serializer -> DB.filename -> 'a option
(** extract a from_string function from a serializer *)
val from_string : 'a serializer -> string -> 'a option
(** current key for a procedure summary *)
val summary_key : key
(** current key for tenv *)
val tenv_key : key
(** extract a to_file function from a serializer *)
val to_file : 'a serializer -> DB.filename -> 'a -> unit
(** current key for an error trace *)
val trace_key : key
(** current key for lint issues *)
val lint_issues_key : key
(** current key for patch candidates *)
val td_patch_candidates_key : key
| null | https://raw.githubusercontent.com/squaresLab/footpatch/8b79c1964d89b833179aed7ed4fde0638a435782/infer/src/backend/serialization.mli | ocaml | * Serialization of data stuctures
* Generic serializer
* Serialization key, used to distinguish versions of serializers and avoid assert faults
* current key for an analysis results value
* current key for proc attributes
* current key for a cfg
* current key for a call graph
* create a serializer from a file name
given an integer key used as double-check of the file type
* current key for a cluster
* extract a from_file function from a serializer
* extract a from_string function from a serializer
* current key for a procedure summary
* current key for tenv
* extract a to_file function from a serializer
* current key for an error trace
* current key for lint issues
* current key for patch candidates |
* Copyright ( c ) 2009 - 2013 Monoidics ltd .
* Copyright ( c ) 2013 - present Facebook , Inc.
* All rights reserved .
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree . An additional grant
* of patent rights can be found in the PATENTS file in the same directory .
* Copyright (c) 2009 - 2013 Monoidics ltd.
* Copyright (c) 2013 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*)
open! Utils
type 'a serializer
type key
val analysis_results_key : key
val attributes_key : key
val cfg_key : key
val cg_key : key
val create_serializer : key -> 'a serializer
val cluster_key : key
val from_file : 'a serializer -> DB.filename -> 'a option
val from_string : 'a serializer -> string -> 'a option
val summary_key : key
val tenv_key : key
val to_file : 'a serializer -> DB.filename -> 'a -> unit
val trace_key : key
val lint_issues_key : key
val td_patch_candidates_key : key
|
e78235c79958424e5de4457913fb961bf246a44082b9b467ba67691f06ea26e9 | danidiaz/tailfile-hinotify | Streaming.hs | | Tail files in Unix , using types from the @streaming@ package .
-}
{-# LANGUAGE RankNTypes #-}
module System.IO.TailFile.Streaming where
import Data.ByteString (ByteString)
import Streaming
import Streaming.Eversion
import qualified System.IO.TailFile.Foldl
{-| Tail a file with a function that consumes a 'Stream'.
-}
tailFile :: FilePath
-> (forall t r. (MonadTrans t, MonadIO (t IO)) => Stream (Of Data.ByteString.ByteString) (t IO) r -> t IO (Of void r)) -- ^ Scary type, but any reasonably polymorphic (say, over 'MonadIO') function that consumes a 'Stream' can go here.
-> IO void
tailFile path consumer = System.IO.TailFile.Foldl.tailFile path (evertMIO consumer)
| null | https://raw.githubusercontent.com/danidiaz/tailfile-hinotify/14397104511664e786aeedcda76469faf172acdf/lib/System/IO/TailFile/Streaming.hs | haskell | # LANGUAGE RankNTypes #
| Tail a file with a function that consumes a 'Stream'.
^ Scary type, but any reasonably polymorphic (say, over 'MonadIO') function that consumes a 'Stream' can go here. | | Tail files in Unix , using types from the @streaming@ package .
-}
module System.IO.TailFile.Streaming where
import Data.ByteString (ByteString)
import Streaming
import Streaming.Eversion
import qualified System.IO.TailFile.Foldl
tailFile :: FilePath
-> IO void
tailFile path consumer = System.IO.TailFile.Foldl.tailFile path (evertMIO consumer)
|
1e7ee4bc9129800ea210dfc11657487ac2ed1599d1e3161a06a17a944a2abfcd | GlideAngle/flare-timing | Arrival.hs | # LANGUAGE DuplicateRecordFields #
|
Module : Flight . Track . Mask . Arrrival
Copyright : ( c ) Block Scope Limited 2017
License : MPL-2.0
Maintainer :
Stability : experimental
Tracks masked with task control zones .
Module : Flight.Track.Mask.Arrrival
Copyright : (c) Block Scope Limited 2017
License : MPL-2.0
Maintainer :
Stability : experimental
Tracks masked with task control zones.
-}
module Flight.Track.Mask.Arrival
( TaskMaskingArrival(..)
, CompMaskingArrival(..)
, mkCompMaskArrival, unMkCompMaskArrival
) where
import GHC.Generics (Generic)
import Data.Aeson (ToJSON(..), FromJSON(..))
import "flight-gap-allot" Flight.Score (Pilot(..), PilotsAtEss(..))
import Flight.Field (FieldOrdering(..))
import Flight.Units ()
import Flight.Track.Arrival (TrackArrival(..))
import Flight.Track.Mask.Cmp (cmp)
data TaskMaskingArrival =
TaskMaskingArrival
{ pilotsAtEss :: PilotsAtEss
^ The number of pilots at ESS .
, arrivalRank :: [(Pilot, TrackArrival)]
^ The rank order of arrival at ESS and arrival fraction .
}
deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON)
-- | For each task, the masking for arrival for that task.
data CompMaskingArrival =
CompMaskingArrival
{ pilotsAtEss :: [PilotsAtEss]
^ For each task , the number of pilots at ESS .
, arrivalRank :: [[(Pilot, TrackArrival)]]
^ For each task , the rank order of arrival at ESS and arrival fraction .
}
deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON)
mkCompMaskArrival :: [TaskMaskingArrival] -> CompMaskingArrival
mkCompMaskArrival ts =
uncurry CompMaskingArrival $ unzip
[ (p, a)
| TaskMaskingArrival{pilotsAtEss = p, arrivalRank = a} <- ts
]
unMkCompMaskArrival :: CompMaskingArrival -> [TaskMaskingArrival]
unMkCompMaskArrival CompMaskingArrival{pilotsAtEss = ps, arrivalRank = as} =
zipWith TaskMaskingArrival ps as
instance FieldOrdering TaskMaskingArrival where fieldOrder _ = cmp
instance FieldOrdering CompMaskingArrival where fieldOrder _ = cmp
| null | https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/comp/library/Flight/Track/Mask/Arrival.hs | haskell | | For each task, the masking for arrival for that task. | # LANGUAGE DuplicateRecordFields #
|
Module : Flight . Track . Mask . Arrrival
Copyright : ( c ) Block Scope Limited 2017
License : MPL-2.0
Maintainer :
Stability : experimental
Tracks masked with task control zones .
Module : Flight.Track.Mask.Arrrival
Copyright : (c) Block Scope Limited 2017
License : MPL-2.0
Maintainer :
Stability : experimental
Tracks masked with task control zones.
-}
module Flight.Track.Mask.Arrival
( TaskMaskingArrival(..)
, CompMaskingArrival(..)
, mkCompMaskArrival, unMkCompMaskArrival
) where
import GHC.Generics (Generic)
import Data.Aeson (ToJSON(..), FromJSON(..))
import "flight-gap-allot" Flight.Score (Pilot(..), PilotsAtEss(..))
import Flight.Field (FieldOrdering(..))
import Flight.Units ()
import Flight.Track.Arrival (TrackArrival(..))
import Flight.Track.Mask.Cmp (cmp)
data TaskMaskingArrival =
TaskMaskingArrival
{ pilotsAtEss :: PilotsAtEss
^ The number of pilots at ESS .
, arrivalRank :: [(Pilot, TrackArrival)]
^ The rank order of arrival at ESS and arrival fraction .
}
deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON)
data CompMaskingArrival =
CompMaskingArrival
{ pilotsAtEss :: [PilotsAtEss]
^ For each task , the number of pilots at ESS .
, arrivalRank :: [[(Pilot, TrackArrival)]]
^ For each task , the rank order of arrival at ESS and arrival fraction .
}
deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON)
mkCompMaskArrival :: [TaskMaskingArrival] -> CompMaskingArrival
mkCompMaskArrival ts =
uncurry CompMaskingArrival $ unzip
[ (p, a)
| TaskMaskingArrival{pilotsAtEss = p, arrivalRank = a} <- ts
]
unMkCompMaskArrival :: CompMaskingArrival -> [TaskMaskingArrival]
unMkCompMaskArrival CompMaskingArrival{pilotsAtEss = ps, arrivalRank = as} =
zipWith TaskMaskingArrival ps as
instance FieldOrdering TaskMaskingArrival where fieldOrder _ = cmp
instance FieldOrdering CompMaskingArrival where fieldOrder _ = cmp
|
22f92f6472274649e276ffa4e99e5e30987b428d6ad3e0e23b266cc3afbc96ea | shaolang/fan-fiction | project.clj | (defproject fan-fiction "0.2.0-SNAPSHOT"
:description "Write Storybook in ClojureScript with ease"
:url "-fiction"
:license {:name "MIT License"
:url "-license.org"}
:min-lein-version "2.7.1"
:source-paths ["src"]
:profiles {:dev {:dependencies [[org.clojure/clojurescript "1.10.844"
:scope "provided"]]
:resource-paths ["target"]
:clean-targets ^{:protect false} ["target"]}}
:scm {:name "git"
:url "-fiction"})
| null | https://raw.githubusercontent.com/shaolang/fan-fiction/8cec5756e54774d3063199e70366130e8b67c0d5/project.clj | clojure | (defproject fan-fiction "0.2.0-SNAPSHOT"
:description "Write Storybook in ClojureScript with ease"
:url "-fiction"
:license {:name "MIT License"
:url "-license.org"}
:min-lein-version "2.7.1"
:source-paths ["src"]
:profiles {:dev {:dependencies [[org.clojure/clojurescript "1.10.844"
:scope "provided"]]
:resource-paths ["target"]
:clean-targets ^{:protect false} ["target"]}}
:scm {:name "git"
:url "-fiction"})
|
|
17b61bcfd405460c5ef2f95c86268924792a5a26fbca521e71abc40c3bad0466 | ronxin/stolzen | ex3.52.scm | #lang scheme
(require "streams.scm")
(define sum 0)
(define (accum x)
(set! sum (+ x sum))
(display "Accum being processed, input param: ") (display x)
(display " sum: ") (display sum)
(newline)
sum
)
sum
(define seq (stream-map accum (stream-enumerate-interval 1 20)))
sum
seq
(define y (stream-filter even? seq))
(define z (stream-filter (lambda (x) (= (remainder x 5) 0)) seq))
(stream-ref y 7)
sum
(display-stream z)
sum
; What is the value of sum after each of the above expressions is evaluated?
; What is the printed response to evaluating the stream-ref and display-stream
; expressions? Would these responses differ if we had implemented (delay <exp>)
; simply as (lambda () <exp>) without using the optimization provided by memo-
; proc ? Explain.
| null | https://raw.githubusercontent.com/ronxin/stolzen/bb13d0a7deea53b65253bb4b61aaf2abe4467f0d/sicp/chapter3/3.5/ex3.52.scm | scheme | What is the value of sum after each of the above expressions is evaluated?
What is the printed response to evaluating the stream-ref and display-stream
expressions? Would these responses differ if we had implemented (delay <exp>)
simply as (lambda () <exp>) without using the optimization provided by memo-
proc ? Explain.
| #lang scheme
(require "streams.scm")
(define sum 0)
(define (accum x)
(set! sum (+ x sum))
(display "Accum being processed, input param: ") (display x)
(display " sum: ") (display sum)
(newline)
sum
)
sum
(define seq (stream-map accum (stream-enumerate-interval 1 20)))
sum
seq
(define y (stream-filter even? seq))
(define z (stream-filter (lambda (x) (= (remainder x 5) 0)) seq))
(stream-ref y 7)
sum
(display-stream z)
sum
|
1b5c27c8def06eb2cb99b2b7134c331784f98b5e216d725b4ef5cc0b2ee31e74 | ssor/erlangDemos | test.erl | -module(test).
-export([add_msg_radio/3]).
-export([test1/0, test2/0, test3/0]).
test3() ->
case file:consult("config.dat") of
{error, enoent} ->
io:format("The file does not exist~n");
{ok, Config} ->
Func = fun({Term1, Configs}) ->
case term1 == Term1 of
true -> io:format("-> ~p~n", [Configs]);
false -> void
end
end,
lists:foreach(Func, Config)
end.
test2() ->
AllExistingTags = [{"tag1", "01", "19"}, {"tag2", "02", "19"}, {"tag3", "03", "19"}],
String = format_tags_to_string(AllExistingTags, []),
io:format("~p~n", [String]).
test1() ->
add_msg_radio(data_collector, mt_event_sensor, []).
add_msg_radio(ModuleOfMsgSource, ModuleOfListener, Args) ->
ModuleOfMsgSource:add_handler(ModuleOfListener, Args).
format_tags_to_string([], String) -> String;
format_tags_to_string([H|T], String) ->
{Tag, Ant, Count} = H,
Packet = ",{" ++ Tag ++ "," ++ Ant ++ "," ++ Count ++ "}",
NewString = lists:append(String, Packet),
format_tags_to_string(T, NewString).
| null | https://raw.githubusercontent.com/ssor/erlangDemos/632cd905be2c4f275f1c1ae15238e711d7bb9147/msg_transfer_via_udp/src/test.erl | erlang | -module(test).
-export([add_msg_radio/3]).
-export([test1/0, test2/0, test3/0]).
test3() ->
case file:consult("config.dat") of
{error, enoent} ->
io:format("The file does not exist~n");
{ok, Config} ->
Func = fun({Term1, Configs}) ->
case term1 == Term1 of
true -> io:format("-> ~p~n", [Configs]);
false -> void
end
end,
lists:foreach(Func, Config)
end.
test2() ->
AllExistingTags = [{"tag1", "01", "19"}, {"tag2", "02", "19"}, {"tag3", "03", "19"}],
String = format_tags_to_string(AllExistingTags, []),
io:format("~p~n", [String]).
test1() ->
add_msg_radio(data_collector, mt_event_sensor, []).
add_msg_radio(ModuleOfMsgSource, ModuleOfListener, Args) ->
ModuleOfMsgSource:add_handler(ModuleOfListener, Args).
format_tags_to_string([], String) -> String;
format_tags_to_string([H|T], String) ->
{Tag, Ant, Count} = H,
Packet = ",{" ++ Tag ++ "," ++ Ant ++ "," ++ Count ++ "}",
NewString = lists:append(String, Packet),
format_tags_to_string(T, NewString).
|
|
2078eb892172d1fcb0231a7e0d23cae199f33b948f56921d71ff6155009b5715 | RefactoringTools/HaRe | PArr.hs | # LANGUAGE ParallelListComp #
module Layout.PArr where
blah xs ys = [ (x, y) | x <- xs | y <- ys ]
bar = [: 1 , 2 .. 3 :]
-- entry point for desugaring a parallel array comprehension
= [ : e | qss :] = < < [: e | qss :] > > ( ) [ :() :]
ary = let toP [ 1 .. 10 ]
arr2 = toP [ 1 .. 10 ]
f = [: i1 + i2 | i1 < - arr1 | i2 < - arr2 :]
in f ! : 1
ary = let arr1 = toP [1..10]
arr2 = toP [1..10]
f = [: i1 + i2 | i1 <- arr1 | i2 <- arr2 :]
in f !: 1
-}
foo = 'a'
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/Layout/PArr.hs | haskell | entry point for desugaring a parallel array comprehension | # LANGUAGE ParallelListComp #
module Layout.PArr where
blah xs ys = [ (x, y) | x <- xs | y <- ys ]
bar = [: 1 , 2 .. 3 :]
= [ : e | qss :] = < < [: e | qss :] > > ( ) [ :() :]
ary = let toP [ 1 .. 10 ]
arr2 = toP [ 1 .. 10 ]
f = [: i1 + i2 | i1 < - arr1 | i2 < - arr2 :]
in f ! : 1
ary = let arr1 = toP [1..10]
arr2 = toP [1..10]
f = [: i1 + i2 | i1 <- arr1 | i2 <- arr2 :]
in f !: 1
-}
foo = 'a'
|
f187ed400bfe561e4fe0f7d63584355c73d4d00c32efe1c3e48d71963b47fcb6 | ocaml-omake/omake | lm_map.mli | (* Map module based on red-black trees *)
open Lm_map_sig
module Make (Ord : OrderedType) : (S with type key = Ord.t)
module LmMake (Ord : OrderedType) : (LmMap with type key = Ord.t)
module LmMakeList (Ord : OrderedType) : (LmMapList with type key = Ord.t)
(*
* This version includes a sharing constraint so that maps can
* be used in recursive definitions. This exposes the internal
* representation, should you should avoid using it unless
* absolutely necessary (like in a recursive type definition).
*)
type ('key, 'value) tree
module LmMakeRec (Ord : OrderedType) : (LmMap with type key = Ord.t with type 'a t = (Ord.t, 'a) tree)
| null | https://raw.githubusercontent.com/ocaml-omake/omake/08b2a83fb558f6eb6847566cbe1a562230da2b14/src/libmojave/lm_map.mli | ocaml | Map module based on red-black trees
* This version includes a sharing constraint so that maps can
* be used in recursive definitions. This exposes the internal
* representation, should you should avoid using it unless
* absolutely necessary (like in a recursive type definition).
| open Lm_map_sig
module Make (Ord : OrderedType) : (S with type key = Ord.t)
module LmMake (Ord : OrderedType) : (LmMap with type key = Ord.t)
module LmMakeList (Ord : OrderedType) : (LmMapList with type key = Ord.t)
type ('key, 'value) tree
module LmMakeRec (Ord : OrderedType) : (LmMap with type key = Ord.t with type 'a t = (Ord.t, 'a) tree)
|
8a75dac6f371d0bc5fec9e7fbd58465782ff223e897be04f86604f25d1726157 | phadej/cabal-extras | Parse.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
-- This module is derivative of
--
Copyright ( c ) 2009 - 2018 < >
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
in the Software without restriction , including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
--
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
module CabalDocspec.Doctest.Parse (
Module (..),
DocTest (..),
Interaction,
Expression,
ExpectedResult,
ExpectedLine (..),
LineChunk (..),
parseModules,
) where
import Prelude
import Data.Char (isSpace)
import Data.List (isPrefixOf, stripPrefix)
import Data.Maybe (fromMaybe, isNothing)
import Data.String (IsString (..))
import CabalDocspec.Doctest.Extract
import CabalDocspec.Located
data DocTest = Example Expression ExpectedResult | Property Expression
deriving (Eq, Show)
data LineChunk = LineChunk String | WildCardChunk
deriving (Show, Eq)
instance IsString LineChunk where
fromString = LineChunk
data ExpectedLine = ExpectedLine [LineChunk] | WildCardLine
deriving (Show, Eq)
instance IsString ExpectedLine where
fromString = ExpectedLine . return . LineChunk
type Expression = String
type ExpectedResult = [ExpectedLine]
type Interaction = (Expression, ExpectedResult)
parseModules :: [Module (Located String)] -> [Module [Located DocTest]]
parseModules = filter (not . isEmpty) . map parseModule
where
isEmpty (Module _ setup tests) = null tests && isNothing setup
| Convert documentation to ` Example`s .
parseModule :: Module (Located String) -> Module [Located DocTest]
parseModule m = case parseComment <$> m of
Module name setup tests -> Module name setup_ (filter (not . null) tests)
where
setup_ = case setup of
Just [] -> Nothing
_ -> setup
parseComment :: Located String -> [Located DocTest]
parseComment c = properties ++ examples
where
examples = map (fmap $ uncurry Example) (parseInteractions c)
properties = map (fmap Property) (parseProperties c)
| Extract all properties from given comment .
parseProperties :: Located String -> [Located Expression]
parseProperties (L loc input) = go $ map (L loc) (lines input)
where
isPrompt :: Located String -> Bool
isPrompt = isPrefixOf "prop>" . dropWhile isSpace . unLoc
go xs = case dropWhile (not . isPrompt) xs of
prop:rest -> stripPrompt `fmap` prop : go rest
[] -> []
stripPrompt = strip . drop 5 . dropWhile isSpace
| Extract all interactions from given comment .
parseInteractions :: Located String -> [Located Interaction]
parseInteractions (L loc input) = go $ map (L loc) (lines input)
where
isPrompt :: Located String -> Bool
isPrompt = isPrefixOf ">>>" . dropWhile isSpace . unLoc
isBlankLine :: Located String -> Bool
isBlankLine = null . dropWhile isSpace . unLoc
isEndOfInteraction :: Located String -> Bool
isEndOfInteraction x = isPrompt x || isBlankLine x
go :: [Located String] -> [Located Interaction]
go xs = case dropWhile (not . isPrompt) xs of
prompt:rest
| ":{" : _ <- words (drop 3 (dropWhile isSpace (unLoc prompt))),
(ys,zs) <- break isBlankLine rest ->
toInteraction prompt ys : go zs
| otherwise ->
let
(ys,zs) = break isEndOfInteraction rest
in
toInteraction prompt ys : go zs
[] -> []
-- | Create an `Interaction`, strip superfluous whitespace as appropriate.
--
also merge lines between : { and :} , preserving whitespace inside
-- the block (since this is useful for avoiding {;}).
toInteraction :: Located String -> [Located String] -> Located Interaction
toInteraction (L loc x) xs = L loc $
(
(strip cleanedE) -- we do not care about leading and trailing
-- whitespace in expressions, so drop them
, map mkExpectedLine result_
)
where
1 . drop trailing whitespace from the prompt , remember the prefix
(prefix, e) = span isSpace x
(ePrompt, eRest) = splitAt 3 e
2 . drop , if possible , the exact same sequence of whitespace
-- characters from each result line
unindent pre = map (tryStripPrefix pre . unLoc)
cleanBody line = fromMaybe (unLoc line)
(stripPrefix ePrompt (dropWhile isSpace (unLoc line)))
(cleanedE, result_)
| (body , endLine : rest) <- break
( (==) [":}"] . take 1 . words . cleanBody)
xs
= (unlines (eRest : map cleanBody body ++
[dropWhile isSpace (cleanBody endLine)]),
unindent (takeWhile isSpace (unLoc endLine)) rest)
| otherwise = (eRest, unindent prefix xs)
tryStripPrefix :: String -> String -> String
tryStripPrefix prefix ys = fromMaybe ys $ stripPrefix prefix ys
mkExpectedLine :: String -> ExpectedLine
mkExpectedLine x = case x of
"<BLANKLINE>" -> ""
"..." -> WildCardLine
_ -> ExpectedLine $ mkLineChunks x
mkLineChunks :: String -> [LineChunk]
mkLineChunks = finish . foldr go (0, [], [])
where
mkChunk :: String -> [LineChunk]
mkChunk "" = []
mkChunk x = [LineChunk x]
go :: Char -> (Int, String, [LineChunk]) -> (Int, String, [LineChunk])
go '.' (count, acc, res) = if count == 2
then (0, "", WildCardChunk : mkChunk acc ++ res)
else (count + 1, acc, res)
go c (count, acc, res) = if count > 0
then (0, c : replicate count '.' ++ acc, res)
else (0, c : acc, res)
finish (count, acc, res) = mkChunk (replicate count '.' ++ acc) ++ res
-- | Remove leading and trailing whitespace.
strip :: String -> String
strip = dropWhile isSpace . reverse . dropWhile isSpace . reverse
| null | https://raw.githubusercontent.com/phadej/cabal-extras/378cac5495b829794d67f243b27a9317eeed0858/cabal-docspec/src/CabalDocspec/Doctest/Parse.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE PatternGuards #
This module is derivative of
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
| Create an `Interaction`, strip superfluous whitespace as appropriate.
the block (since this is useful for avoiding {;}).
we do not care about leading and trailing
whitespace in expressions, so drop them
characters from each result line
| Remove leading and trailing whitespace. |
Copyright ( c ) 2009 - 2018 < >
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
module CabalDocspec.Doctest.Parse (
Module (..),
DocTest (..),
Interaction,
Expression,
ExpectedResult,
ExpectedLine (..),
LineChunk (..),
parseModules,
) where
import Prelude
import Data.Char (isSpace)
import Data.List (isPrefixOf, stripPrefix)
import Data.Maybe (fromMaybe, isNothing)
import Data.String (IsString (..))
import CabalDocspec.Doctest.Extract
import CabalDocspec.Located
data DocTest = Example Expression ExpectedResult | Property Expression
deriving (Eq, Show)
data LineChunk = LineChunk String | WildCardChunk
deriving (Show, Eq)
instance IsString LineChunk where
fromString = LineChunk
data ExpectedLine = ExpectedLine [LineChunk] | WildCardLine
deriving (Show, Eq)
instance IsString ExpectedLine where
fromString = ExpectedLine . return . LineChunk
type Expression = String
type ExpectedResult = [ExpectedLine]
type Interaction = (Expression, ExpectedResult)
parseModules :: [Module (Located String)] -> [Module [Located DocTest]]
parseModules = filter (not . isEmpty) . map parseModule
where
isEmpty (Module _ setup tests) = null tests && isNothing setup
| Convert documentation to ` Example`s .
parseModule :: Module (Located String) -> Module [Located DocTest]
parseModule m = case parseComment <$> m of
Module name setup tests -> Module name setup_ (filter (not . null) tests)
where
setup_ = case setup of
Just [] -> Nothing
_ -> setup
parseComment :: Located String -> [Located DocTest]
parseComment c = properties ++ examples
where
examples = map (fmap $ uncurry Example) (parseInteractions c)
properties = map (fmap Property) (parseProperties c)
| Extract all properties from given comment .
parseProperties :: Located String -> [Located Expression]
parseProperties (L loc input) = go $ map (L loc) (lines input)
where
isPrompt :: Located String -> Bool
isPrompt = isPrefixOf "prop>" . dropWhile isSpace . unLoc
go xs = case dropWhile (not . isPrompt) xs of
prop:rest -> stripPrompt `fmap` prop : go rest
[] -> []
stripPrompt = strip . drop 5 . dropWhile isSpace
| Extract all interactions from given comment .
parseInteractions :: Located String -> [Located Interaction]
parseInteractions (L loc input) = go $ map (L loc) (lines input)
where
isPrompt :: Located String -> Bool
isPrompt = isPrefixOf ">>>" . dropWhile isSpace . unLoc
isBlankLine :: Located String -> Bool
isBlankLine = null . dropWhile isSpace . unLoc
isEndOfInteraction :: Located String -> Bool
isEndOfInteraction x = isPrompt x || isBlankLine x
go :: [Located String] -> [Located Interaction]
go xs = case dropWhile (not . isPrompt) xs of
prompt:rest
| ":{" : _ <- words (drop 3 (dropWhile isSpace (unLoc prompt))),
(ys,zs) <- break isBlankLine rest ->
toInteraction prompt ys : go zs
| otherwise ->
let
(ys,zs) = break isEndOfInteraction rest
in
toInteraction prompt ys : go zs
[] -> []
also merge lines between : { and :} , preserving whitespace inside
toInteraction :: Located String -> [Located String] -> Located Interaction
toInteraction (L loc x) xs = L loc $
(
, map mkExpectedLine result_
)
where
1 . drop trailing whitespace from the prompt , remember the prefix
(prefix, e) = span isSpace x
(ePrompt, eRest) = splitAt 3 e
2 . drop , if possible , the exact same sequence of whitespace
unindent pre = map (tryStripPrefix pre . unLoc)
cleanBody line = fromMaybe (unLoc line)
(stripPrefix ePrompt (dropWhile isSpace (unLoc line)))
(cleanedE, result_)
| (body , endLine : rest) <- break
( (==) [":}"] . take 1 . words . cleanBody)
xs
= (unlines (eRest : map cleanBody body ++
[dropWhile isSpace (cleanBody endLine)]),
unindent (takeWhile isSpace (unLoc endLine)) rest)
| otherwise = (eRest, unindent prefix xs)
tryStripPrefix :: String -> String -> String
tryStripPrefix prefix ys = fromMaybe ys $ stripPrefix prefix ys
mkExpectedLine :: String -> ExpectedLine
mkExpectedLine x = case x of
"<BLANKLINE>" -> ""
"..." -> WildCardLine
_ -> ExpectedLine $ mkLineChunks x
mkLineChunks :: String -> [LineChunk]
mkLineChunks = finish . foldr go (0, [], [])
where
mkChunk :: String -> [LineChunk]
mkChunk "" = []
mkChunk x = [LineChunk x]
go :: Char -> (Int, String, [LineChunk]) -> (Int, String, [LineChunk])
go '.' (count, acc, res) = if count == 2
then (0, "", WildCardChunk : mkChunk acc ++ res)
else (count + 1, acc, res)
go c (count, acc, res) = if count > 0
then (0, c : replicate count '.' ++ acc, res)
else (0, c : acc, res)
finish (count, acc, res) = mkChunk (replicate count '.' ++ acc) ++ res
strip :: String -> String
strip = dropWhile isSpace . reverse . dropWhile isSpace . reverse
|
e49f2714f77c13374272bfb755245e53cff20a488adb4f2ddfc27a784633e157 | iamFIREcracker/adventofcode | day25.lisp | (defpackage :aoc/2015/25 #.cl-user::*aoc-use*)
(in-package :aoc/2015/25)
(defun parse-target-position (lines)
(cl-ppcre:register-groups-bind ((#'parse-integer row col))
("row (\\d+), column (\\d+)" (first lines))
(list row col)))
(defun next-grid-position (&optional prev)
(if (not prev)
(list 1 1)
(let ((next (mapcar #'+ prev (list -1 1))))
(if (= (first next) 0)
(list (second next) 1)
next))))
(defun next-code (&optional prev)
(if (not prev) 20151125 (mod (* prev 252533) 33554393)))
(defun part1 (target)
(loop for pos = (next-grid-position) then (next-grid-position pos)
for code = (next-code) then (next-code code)
when (equal pos target) return code))
(define-solution (2015 25) (pos parse-target-position)
(values (part1 pos)))
(define-test (2015 25) (2650453))
| null | https://raw.githubusercontent.com/iamFIREcracker/adventofcode/c395df5e15657f0b9be6ec555e68dc777b0eb7ab/src/2015/day25.lisp | lisp | (defpackage :aoc/2015/25 #.cl-user::*aoc-use*)
(in-package :aoc/2015/25)
(defun parse-target-position (lines)
(cl-ppcre:register-groups-bind ((#'parse-integer row col))
("row (\\d+), column (\\d+)" (first lines))
(list row col)))
(defun next-grid-position (&optional prev)
(if (not prev)
(list 1 1)
(let ((next (mapcar #'+ prev (list -1 1))))
(if (= (first next) 0)
(list (second next) 1)
next))))
(defun next-code (&optional prev)
(if (not prev) 20151125 (mod (* prev 252533) 33554393)))
(defun part1 (target)
(loop for pos = (next-grid-position) then (next-grid-position pos)
for code = (next-code) then (next-code code)
when (equal pos target) return code))
(define-solution (2015 25) (pos parse-target-position)
(values (part1 pos)))
(define-test (2015 25) (2650453))
|
|
10328b8fed26090acc2bb05ceba039067be9fccf0f1d1fe6d0147ae4ce63dbff | baskeboler/cljs-karaoke-client | core.cljs | (ns cljs-karaoke.http.core
(:require [cljs-karaoke.http.events :as events]
[cljs-karaoke.http.subs :as sub]
[cljs-karaoke.http.views :as views]))
| null | https://raw.githubusercontent.com/baskeboler/cljs-karaoke-client/bb6512435eaa436d35034886be99213625847ee0/src/main/cljs_karaoke/http/core.cljs | clojure | (ns cljs-karaoke.http.core
(:require [cljs-karaoke.http.events :as events]
[cljs-karaoke.http.subs :as sub]
[cljs-karaoke.http.views :as views]))
|
|
63f30dc3d1b2629d46ad9ff13b7c06e0db1cb2228ecfaeae5c516b518a96224b | kierangrant/cl-qt-example | package.lisp | -*- Mode : Lisp ; Syntax : COMMON - LISP ; Base : 10 -*-
releases this code in the Public Domain
File : package.lisp
;; Description: Core Package File
(defpackage :cl-qt-example
(:use :cl :cffi)
(:export #:run-app))
| null | https://raw.githubusercontent.com/kierangrant/cl-qt-example/47ce65e1b0375c5716284a1f957cc70e083f52d7/package.lisp | lisp | Syntax : COMMON - LISP ; Base : 10 -*-
Description: Core Package File | releases this code in the Public Domain
File : package.lisp
(defpackage :cl-qt-example
(:use :cl :cffi)
(:export #:run-app))
|
68fbfcfc9abf18801122c5baa8f80b3f850cfce5e3ac01cf54add0f7de37f281 | gafiatulin/codewars | Stockbroker.hs | Ease the StockBroker
-- /
module Codewars.G964.Stockbroker where
import Data.Char (isDigit, isSpace)
import Data.Either (partitionEithers)
import Data.List (elemIndices, partition, groupBy)
import Data.List.Split (split, dropDelims, dropBlanks, oneOf)
balanceStatements "" = "Buy: 0 Sell: 0"
balanceStatements s = f correct ++ g malformed
where (malformed, correct) = partitionEithers . map validate . split (dropDelims $ oneOf ",") $ s
f = concat . (\(b, s) -> [("Buy: "++) . show . sum . map snd $ b , (" Sell: "++) . show . sum . map snd $ s]) . partition ((=="B") . fst)
g xs = if null xs then "" else concat . (\x -> [("; Badly formed "++) . (++": ") . show . length $ x, concat x]) . map ((++" ;") . dropWhile isSpace) $ xs
validAction "B" = True
validAction "S" = True
validAction _ = False
validInt :: String -> Bool
validInt = all isDigit
validDouble :: String -> Bool
validDouble = (\(ds, nds) -> ((>=2) . length $ ds) && ((==1) . length $ nds) && ((=='.') . head $ nds)) . partition isDigit
validate :: String -> Either String (String, Integer)
validate order | validOrder = Right (action, orderValue quantity price)
| otherwise = Left order
where validOrder = validInt quantity && validDouble price && validAction action
orderValue q p = round ((read q :: Double) * (read p :: Double))
(stock, quantity, price, action) = case split (dropDelims . dropBlanks $ oneOf " " ) order of
(a:b:c:d:[]) -> (a, b, c, d)
x -> ("", "", "", "E")
| null | https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/6%20kyu/Stockbroker.hs | haskell | / | Ease the StockBroker
module Codewars.G964.Stockbroker where
import Data.Char (isDigit, isSpace)
import Data.Either (partitionEithers)
import Data.List (elemIndices, partition, groupBy)
import Data.List.Split (split, dropDelims, dropBlanks, oneOf)
balanceStatements "" = "Buy: 0 Sell: 0"
balanceStatements s = f correct ++ g malformed
where (malformed, correct) = partitionEithers . map validate . split (dropDelims $ oneOf ",") $ s
f = concat . (\(b, s) -> [("Buy: "++) . show . sum . map snd $ b , (" Sell: "++) . show . sum . map snd $ s]) . partition ((=="B") . fst)
g xs = if null xs then "" else concat . (\x -> [("; Badly formed "++) . (++": ") . show . length $ x, concat x]) . map ((++" ;") . dropWhile isSpace) $ xs
validAction "B" = True
validAction "S" = True
validAction _ = False
validInt :: String -> Bool
validInt = all isDigit
validDouble :: String -> Bool
validDouble = (\(ds, nds) -> ((>=2) . length $ ds) && ((==1) . length $ nds) && ((=='.') . head $ nds)) . partition isDigit
validate :: String -> Either String (String, Integer)
validate order | validOrder = Right (action, orderValue quantity price)
| otherwise = Left order
where validOrder = validInt quantity && validDouble price && validAction action
orderValue q p = round ((read q :: Double) * (read p :: Double))
(stock, quantity, price, action) = case split (dropDelims . dropBlanks $ oneOf " " ) order of
(a:b:c:d:[]) -> (a, b, c, d)
x -> ("", "", "", "E")
|
e0b9dbf8e300cc1ec5e6c8589cf7ad780e357439c091fc418155530a4e4157b8 | bsaleil/lc | diviter.scm.scm | ;;------------------------------------------------------------------------------
Macros
(##define-macro (def-macro form . body)
`(##define-macro ,form (let () ,@body)))
(def-macro (FLOATvector-const . lst) `',(list->vector lst))
(def-macro (FLOATvector? x) `(vector? ,x))
(def-macro (FLOATvector . lst) `(vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector lst))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
;;------------------------------------------------------------------------------
Functions used by LC to get time info
(def-macro (##lc-time expr)
(let ((sym (gensym)))
`(let ((r (##lc-exec-stats (lambda () ,expr))))
(##print-perm-string "CPU time: ")
(##print-double (+ (cdr (assoc "User time" (cdr r)))
(cdr (assoc "Sys time" (cdr r)))))
(##print-perm-string "\n")
(##print-perm-string "GC CPU time: ")
(##print-double (+ (cdr (assoc "GC user time" (cdr r)))
(cdr (assoc "GC sys time" (cdr r)))))
(##print-perm-string "\n")
(map (lambda (el)
(##print-perm-string (car el))
(##print-perm-string ": ")
(##print-double (cdr el))
(##print-perm-string "\n"))
(cdr r))
r)))
(define (##lc-exec-stats thunk)
(let* ((at-start (##process-statistics))
(result (thunk))
(at-end (##process-statistics)))
(define (get-info msg idx)
(cons msg
(- (f64vector-ref at-end idx)
(f64vector-ref at-start idx))))
(list
result
(get-info "User time" 0)
(get-info "Sys time" 1)
(get-info "Real time" 2)
(get-info "GC user time" 3)
(get-info "GC sys time" 4)
(get-info "GC real time" 5)
(get-info "Nb gcs" 6))))
;;------------------------------------------------------------------------------
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(let ((run (apply run-maker args)))
(let ((result (car (##lc-time (run-bench name count ok? run)))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline))))))
; Gabriel benchmarks
(define boyer-iters 20)
(define browse-iters 600)
(define cpstak-iters 1000)
(define ctak-iters 100)
(define dderiv-iters 2000000)
(define deriv-iters 2000000)
(define destruc-iters 500)
(define diviter-iters 1000000)
(define divrec-iters 1000000)
(define puzzle-iters 100)
(define tak-iters 2000)
(define takl-iters 300)
(define trav1-iters 100)
(define trav2-iters 20)
(define triangl-iters 10)
and benchmarks
(define ack-iters 10)
(define array1-iters 1)
(define cat-iters 1)
(define string-iters 10)
(define sum1-iters 10)
(define sumloop-iters 10)
(define tail-iters 1)
(define wc-iters 1)
; C benchmarks
(define fft-iters 2000)
(define fib-iters 5)
(define fibfp-iters 2)
(define mbrot-iters 100)
(define nucleic-iters 5)
(define pnpoly-iters 100000)
(define sum-iters 20000)
(define sumfp-iters 20000)
(define tfib-iters 20)
; Other benchmarks
(define conform-iters 40)
(define dynamic-iters 20)
(define earley-iters 200)
(define fibc-iters 500)
(define graphs-iters 300)
(define lattice-iters 1)
(define matrix-iters 400)
(define maze-iters 4000)
(define mazefun-iters 1000)
(define nqueens-iters 2000)
(define paraffins-iters 1000)
(define peval-iters 200)
(define pi-iters 2)
(define primes-iters 100000)
(define ray-iters 5)
(define scheme-iters 20000)
(define simplex-iters 100000)
(define slatex-iters 20)
(define perm9-iters 10)
(define nboyer-iters 100)
(define sboyer-iters 100)
(define gcbench-iters 1)
(define compiler-iters 300)
(define nbody-iters 1)
(define fftrad4-iters 4)
DIVITER -- Benchmark which divides by 2 using lists of n ( ) 's .
(define (create-n n)
(do ((n n (- n 1))
(a '() (cons '() a)))
((= n 0) a)))
(define *ll* (create-n 200))
(define (iterative-div2 l)
(do ((l l (cddr l))
(a '() (cons (car l) a)))
((null? l) a)))
(define (main . args)
(run-benchmark
"diviter"
diviter-iters
(lambda (result)
(equal? result
'(() () () () () () () () () () () () () () () () () () () ()
() () () () () () () () () () () () () () () () () () () ()
() () () () () () () () () () () () () () () () () () () ()
() () () () () () () () () () () () () () () () () () () ()
() () () () () () () () () () () () () () () () () () () ())))
(lambda (l) (lambda () (iterative-div2 l)))
*ll*))
(main)
| null | https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/tools/benchtimes/resultVMIL-lc-gsc-lc/LC5/diviter.scm.scm | scheme | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Gabriel benchmarks
C benchmarks
Other benchmarks | Macros
(##define-macro (def-macro form . body)
`(##define-macro ,form (let () ,@body)))
(def-macro (FLOATvector-const . lst) `',(list->vector lst))
(def-macro (FLOATvector? x) `(vector? ,x))
(def-macro (FLOATvector . lst) `(vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector lst))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
Functions used by LC to get time info
(def-macro (##lc-time expr)
(let ((sym (gensym)))
`(let ((r (##lc-exec-stats (lambda () ,expr))))
(##print-perm-string "CPU time: ")
(##print-double (+ (cdr (assoc "User time" (cdr r)))
(cdr (assoc "Sys time" (cdr r)))))
(##print-perm-string "\n")
(##print-perm-string "GC CPU time: ")
(##print-double (+ (cdr (assoc "GC user time" (cdr r)))
(cdr (assoc "GC sys time" (cdr r)))))
(##print-perm-string "\n")
(map (lambda (el)
(##print-perm-string (car el))
(##print-perm-string ": ")
(##print-double (cdr el))
(##print-perm-string "\n"))
(cdr r))
r)))
(define (##lc-exec-stats thunk)
(let* ((at-start (##process-statistics))
(result (thunk))
(at-end (##process-statistics)))
(define (get-info msg idx)
(cons msg
(- (f64vector-ref at-end idx)
(f64vector-ref at-start idx))))
(list
result
(get-info "User time" 0)
(get-info "Sys time" 1)
(get-info "Real time" 2)
(get-info "GC user time" 3)
(get-info "GC sys time" 4)
(get-info "GC real time" 5)
(get-info "Nb gcs" 6))))
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(let ((run (apply run-maker args)))
(let ((result (car (##lc-time (run-bench name count ok? run)))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline))))))
(define boyer-iters 20)
(define browse-iters 600)
(define cpstak-iters 1000)
(define ctak-iters 100)
(define dderiv-iters 2000000)
(define deriv-iters 2000000)
(define destruc-iters 500)
(define diviter-iters 1000000)
(define divrec-iters 1000000)
(define puzzle-iters 100)
(define tak-iters 2000)
(define takl-iters 300)
(define trav1-iters 100)
(define trav2-iters 20)
(define triangl-iters 10)
and benchmarks
(define ack-iters 10)
(define array1-iters 1)
(define cat-iters 1)
(define string-iters 10)
(define sum1-iters 10)
(define sumloop-iters 10)
(define tail-iters 1)
(define wc-iters 1)
(define fft-iters 2000)
(define fib-iters 5)
(define fibfp-iters 2)
(define mbrot-iters 100)
(define nucleic-iters 5)
(define pnpoly-iters 100000)
(define sum-iters 20000)
(define sumfp-iters 20000)
(define tfib-iters 20)
(define conform-iters 40)
(define dynamic-iters 20)
(define earley-iters 200)
(define fibc-iters 500)
(define graphs-iters 300)
(define lattice-iters 1)
(define matrix-iters 400)
(define maze-iters 4000)
(define mazefun-iters 1000)
(define nqueens-iters 2000)
(define paraffins-iters 1000)
(define peval-iters 200)
(define pi-iters 2)
(define primes-iters 100000)
(define ray-iters 5)
(define scheme-iters 20000)
(define simplex-iters 100000)
(define slatex-iters 20)
(define perm9-iters 10)
(define nboyer-iters 100)
(define sboyer-iters 100)
(define gcbench-iters 1)
(define compiler-iters 300)
(define nbody-iters 1)
(define fftrad4-iters 4)
DIVITER -- Benchmark which divides by 2 using lists of n ( ) 's .
(define (create-n n)
(do ((n n (- n 1))
(a '() (cons '() a)))
((= n 0) a)))
(define *ll* (create-n 200))
(define (iterative-div2 l)
(do ((l l (cddr l))
(a '() (cons (car l) a)))
((null? l) a)))
(define (main . args)
(run-benchmark
"diviter"
diviter-iters
(lambda (result)
(equal? result
'(() () () () () () () () () () () () () () () () () () () ()
() () () () () () () () () () () () () () () () () () () ()
() () () () () () () () () () () () () () () () () () () ()
() () () () () () () () () () () () () () () () () () () ()
() () () () () () () () () () () () () () () () () () () ())))
(lambda (l) (lambda () (iterative-div2 l)))
*ll*))
(main)
|
dd760b2fd8ee8ec85b44fa07ad8b82d73d71c3e1ca78fe7eae3b275ea65d52e7 | jbclements/portaudio | test-stream-playback.rkt | #lang racket
(require "../portaudio.rkt"
"../callback-support.rkt"
"helpers.rkt"
"../devices.rkt"
ffi/vector
ffi/unsafe
rackunit
rackunit/text-ui
math/statistics)
;(pa-maybe-initialize)
;(display-device-table)
( set - output - device ! 5 )
(define twopi (* 2 pi))
(define (ptr->string ptr)
(number->string (cast ptr _pointer _uint64) 16))
(run-tests
(test-suite "low-level stream playback"
(let ()
(pa-maybe-initialize)
(define (open-test-stream callback streaming-info-ptr)
(pa-open-default-stream
0 ;; input channels
2 ;; output channels
'paInt16 ;; sample format
44100.0 ;; sample rate
0 ;;frames-per-buffer -- let the system decide
callback ;; callback (NULL means just wait for data)
streaming-info-ptr))
(define (test-start)
( sleep 2 )
(printf "starting now... "))
(define (test-end)
(printf "... ending now.\n")
(sleep 1))
(define log-counter 0)
(define log empty)
(define log2 empty)
(define log3 empty)
(define srinv (exact->inexact (/ 1 44100)))
(define (fill-buf ptr frames start-frame)
#;(printf "frames to write: ~s\n" frames)
#;(printf "pointer to write at: ~a\n"
(ptr->string ptr))
#;(printf "write up to: ~a\n"
(ptr->string (ptr-add ptr (* 4 frames))))
(set! log (cons frames log))
(set! log2 (cons start-frame log2))
(define base-t (exact->inexact (* start-frame srinv)))
(for ([i (in-range frames)])
(define t (+ base-t (* i srinv)))
(define sample (inexact->exact (round (* 32767 (* 0.2 (sin (* twopi t 403)))))))
(define sample-idx (* channels i))
(ptr-set! ptr _sint16 sample-idx sample)
(ptr-set! ptr _sint16 (add1 sample-idx) sample)))
(define (make-buffer-filler init-frame)
(define start-frame init-frame)
(lambda (ptr frames)
(begin0 (fill-buf ptr frames start-frame)
(set! start-frame (+ start-frame frames)))))
(let ()
;; map 0<rads<2pi to -pi/2<rads<pi/2
(define (left-half rads)
(cond [(<= rads (* 1/2 pi)) rads]
[(<= rads (* 3/2 pi)) (- pi rads)]
[else (- rads (* 2 pi))]))
(define (frac n)
(- n (floor n)))
(define t1 (make-s16vector 2048 0))
(time ((make-buffer-filler 2789) (s16vector->cpointer t1) 1024))
(for ([i (in-range 2048)])
(define t (floor (/ i 2)))
(check-= (asin (* 5.0 (/ (s16vector-ref t1 i) 32767.0)))
(left-half (* twopi (frac (* (/ 1 44100) (* (+ 2789 t) 403)))))
1e-2)))
;; first just play silence; there's no process feeding the buffer
also , test how a 20ms wakeup performs
(let ()
(define buffer-frames 2048)
(match-define (list stream-info all-done-ptr)
(make-streaming-info buffer-frames))
(define stream (open-test-stream streaming-callback
stream-info))
(pa-set-stream-finished-callback stream streaming-info-free)
(printf "total silence, 20ms racket callback interval\n")
(test-start)
(pa-start-stream stream)
(define log empty)
(thread
(lambda ()
(for ([i (in-range 200)])
(set! log (cons (stream-rec-last-frame-read stream-info) log))
(sleep 0.02))))
(sleep 4.0)
;; check 3x close:
(pa-close-stream stream)
(pa-close-stream stream)
(pa-close-stream stream)
(test-end)
(define log2 (reverse log))
(printf "faults: ~s\n" (stream-fails stream-info))
(define diffs (for/list ([j (in-list (rest log2))]
[i (in-list log2)])
(- j i)))
(define mean (/ (apply + diffs) (length diffs)))
(printf "log: ~s\n" log2)
(printf "diffs: ~s\n" diffs)
(printf "mean delay: ~s\n" (exact->inexact mean))
(check-equal? (all-done? all-done-ptr) #t))
;; try playing a looped buffer without dynamic filling:
(let ()
(define buffer-frames 22050)
(match-define (list stream-info all-done-ptr)
(make-streaming-info buffer-frames))
(define stream (open-test-stream streaming-callback stream-info))
(pa-set-stream-finished-callback stream streaming-info-free)
(printf "tone, hiccup every half-second \n")
;; manipulate the stream-info to pretend that a lot of info is there:
((make-buffer-filler 0) (stream-rec-buffer stream-info) 22050)
(set-stream-rec-last-frame-written! stream-info (* 44100 2))
(set-stream-rec-last-offset-written! stream-info 0)
(test-start)
(pa-start-stream stream)
(sleep 5.0)
;; check 3x stop:
(pa-close-stream stream)
(pa-close-stream stream)
(pa-close-stream stream)
(test-end)
(printf "faults: ~s\n" (stream-fails stream-info)))
;; play a tone:
(let ()
(define buffer-frames 2048)
(match-define (list stream-info all-done-ptr) (make-streaming-info buffer-frames))
(define stream (open-test-stream streaming-callback stream-info))
(pa-set-stream-finished-callback stream streaming-info-free)
(printf "tone at 403 Hz, 46 ms ring buffer, 20ms callback interval, lots of gc\n")
(define sleep-interval 0.02)
(define detected-all-done #f)
(define filling-thread
(thread
(lambda ()
(let loop ()
(cond [(not (all-done? all-done-ptr))
(define start-time (current-inexact-milliseconds))
(call-buffer-filler stream-info (make-buffer-filler 0))
(define time-used (/ (- (current-inexact-milliseconds) start-time)
1000.0))
(set! log3 (cons time-used log3))
(sleep (max 0.0 (- sleep-interval time-used)))
(loop)]
[else
(set! detected-all-done #t)])))))
(test-start)
(pa-start-stream stream)
(sleep 10.0)
(pa-close-stream stream)
(test-end)
(printf "fails: ~s\n" (stream-fails stream-info))
(define (mean l) (/ (apply + l) (length l)))
(define (stdevp l)
(define m (mean l))
(/ (for/sum ([i (in-list l)])
(sqr (- i m)))
(length l)))
(printf "time-used mean: ~s\n" (mean log3))
(printf "time-used stdev: ~s\n" (stdevp log3))
(check-equal? detected-all-done #t)
)
;; try a failing callback
(let ()
(define buffer-frames 2048)
(match-define (list stream-info all-done-ptr) (make-streaming-info buffer-frames))
(define stream (open-test-stream streaming-callback stream-info))
(pa-set-stream-finished-callback stream streaming-info-free)
(printf "tone at 403 Hz, mostly missing\n")
(define sleep-interval (/ (* 0.8 buffer-frames) 44100))
(define filling-thread
(thread
(lambda ()
(let loop ()
(unless (all-done? all-done-ptr)
(define start-time (current-inexact-milliseconds))
(call-buffer-filler stream-info (make-buffer-filler 0))
;; sleep way too long :
(sleep 0.5)
(define time-used (/ (- (current-inexact-milliseconds) start-time)
1000))
(set! log3 (cons time-used log3))
(sleep (max 0.0 (- sleep-interval time-used)))
(loop))))))
(test-start)
(pa-start-stream stream)
(sleep 2.0)
(pa-close-stream stream)
(test-end)
(printf "fails: ~s\n" (stream-fails stream-info))
(printf "time-used mean: ~s\n" (mean log3))
(printf "time-used stdev: ~s\n" (stddev log3))
)
)))
| null | https://raw.githubusercontent.com/jbclements/portaudio/77a03c86054a5d7a26ed0082215b61162eb8b651/portaudio/test/test-stream-playback.rkt | racket | (pa-maybe-initialize)
(display-device-table)
input channels
output channels
sample format
sample rate
frames-per-buffer -- let the system decide
callback (NULL means just wait for data)
(printf "frames to write: ~s\n" frames)
(printf "pointer to write at: ~a\n"
(printf "write up to: ~a\n"
map 0<rads<2pi to -pi/2<rads<pi/2
first just play silence; there's no process feeding the buffer
check 3x close:
try playing a looped buffer without dynamic filling:
manipulate the stream-info to pretend that a lot of info is there:
check 3x stop:
play a tone:
try a failing callback
sleep way too long : | #lang racket
(require "../portaudio.rkt"
"../callback-support.rkt"
"helpers.rkt"
"../devices.rkt"
ffi/vector
ffi/unsafe
rackunit
rackunit/text-ui
math/statistics)
( set - output - device ! 5 )
(define twopi (* 2 pi))
(define (ptr->string ptr)
(number->string (cast ptr _pointer _uint64) 16))
(run-tests
(test-suite "low-level stream playback"
(let ()
(pa-maybe-initialize)
(define (open-test-stream callback streaming-info-ptr)
(pa-open-default-stream
streaming-info-ptr))
(define (test-start)
( sleep 2 )
(printf "starting now... "))
(define (test-end)
(printf "... ending now.\n")
(sleep 1))
(define log-counter 0)
(define log empty)
(define log2 empty)
(define log3 empty)
(define srinv (exact->inexact (/ 1 44100)))
(define (fill-buf ptr frames start-frame)
(ptr->string ptr))
(ptr->string (ptr-add ptr (* 4 frames))))
(set! log (cons frames log))
(set! log2 (cons start-frame log2))
(define base-t (exact->inexact (* start-frame srinv)))
(for ([i (in-range frames)])
(define t (+ base-t (* i srinv)))
(define sample (inexact->exact (round (* 32767 (* 0.2 (sin (* twopi t 403)))))))
(define sample-idx (* channels i))
(ptr-set! ptr _sint16 sample-idx sample)
(ptr-set! ptr _sint16 (add1 sample-idx) sample)))
(define (make-buffer-filler init-frame)
(define start-frame init-frame)
(lambda (ptr frames)
(begin0 (fill-buf ptr frames start-frame)
(set! start-frame (+ start-frame frames)))))
(let ()
(define (left-half rads)
(cond [(<= rads (* 1/2 pi)) rads]
[(<= rads (* 3/2 pi)) (- pi rads)]
[else (- rads (* 2 pi))]))
(define (frac n)
(- n (floor n)))
(define t1 (make-s16vector 2048 0))
(time ((make-buffer-filler 2789) (s16vector->cpointer t1) 1024))
(for ([i (in-range 2048)])
(define t (floor (/ i 2)))
(check-= (asin (* 5.0 (/ (s16vector-ref t1 i) 32767.0)))
(left-half (* twopi (frac (* (/ 1 44100) (* (+ 2789 t) 403)))))
1e-2)))
also , test how a 20ms wakeup performs
(let ()
(define buffer-frames 2048)
(match-define (list stream-info all-done-ptr)
(make-streaming-info buffer-frames))
(define stream (open-test-stream streaming-callback
stream-info))
(pa-set-stream-finished-callback stream streaming-info-free)
(printf "total silence, 20ms racket callback interval\n")
(test-start)
(pa-start-stream stream)
(define log empty)
(thread
(lambda ()
(for ([i (in-range 200)])
(set! log (cons (stream-rec-last-frame-read stream-info) log))
(sleep 0.02))))
(sleep 4.0)
(pa-close-stream stream)
(pa-close-stream stream)
(pa-close-stream stream)
(test-end)
(define log2 (reverse log))
(printf "faults: ~s\n" (stream-fails stream-info))
(define diffs (for/list ([j (in-list (rest log2))]
[i (in-list log2)])
(- j i)))
(define mean (/ (apply + diffs) (length diffs)))
(printf "log: ~s\n" log2)
(printf "diffs: ~s\n" diffs)
(printf "mean delay: ~s\n" (exact->inexact mean))
(check-equal? (all-done? all-done-ptr) #t))
(let ()
(define buffer-frames 22050)
(match-define (list stream-info all-done-ptr)
(make-streaming-info buffer-frames))
(define stream (open-test-stream streaming-callback stream-info))
(pa-set-stream-finished-callback stream streaming-info-free)
(printf "tone, hiccup every half-second \n")
((make-buffer-filler 0) (stream-rec-buffer stream-info) 22050)
(set-stream-rec-last-frame-written! stream-info (* 44100 2))
(set-stream-rec-last-offset-written! stream-info 0)
(test-start)
(pa-start-stream stream)
(sleep 5.0)
(pa-close-stream stream)
(pa-close-stream stream)
(pa-close-stream stream)
(test-end)
(printf "faults: ~s\n" (stream-fails stream-info)))
(let ()
(define buffer-frames 2048)
(match-define (list stream-info all-done-ptr) (make-streaming-info buffer-frames))
(define stream (open-test-stream streaming-callback stream-info))
(pa-set-stream-finished-callback stream streaming-info-free)
(printf "tone at 403 Hz, 46 ms ring buffer, 20ms callback interval, lots of gc\n")
(define sleep-interval 0.02)
(define detected-all-done #f)
(define filling-thread
(thread
(lambda ()
(let loop ()
(cond [(not (all-done? all-done-ptr))
(define start-time (current-inexact-milliseconds))
(call-buffer-filler stream-info (make-buffer-filler 0))
(define time-used (/ (- (current-inexact-milliseconds) start-time)
1000.0))
(set! log3 (cons time-used log3))
(sleep (max 0.0 (- sleep-interval time-used)))
(loop)]
[else
(set! detected-all-done #t)])))))
(test-start)
(pa-start-stream stream)
(sleep 10.0)
(pa-close-stream stream)
(test-end)
(printf "fails: ~s\n" (stream-fails stream-info))
(define (mean l) (/ (apply + l) (length l)))
(define (stdevp l)
(define m (mean l))
(/ (for/sum ([i (in-list l)])
(sqr (- i m)))
(length l)))
(printf "time-used mean: ~s\n" (mean log3))
(printf "time-used stdev: ~s\n" (stdevp log3))
(check-equal? detected-all-done #t)
)
(let ()
(define buffer-frames 2048)
(match-define (list stream-info all-done-ptr) (make-streaming-info buffer-frames))
(define stream (open-test-stream streaming-callback stream-info))
(pa-set-stream-finished-callback stream streaming-info-free)
(printf "tone at 403 Hz, mostly missing\n")
(define sleep-interval (/ (* 0.8 buffer-frames) 44100))
(define filling-thread
(thread
(lambda ()
(let loop ()
(unless (all-done? all-done-ptr)
(define start-time (current-inexact-milliseconds))
(call-buffer-filler stream-info (make-buffer-filler 0))
(sleep 0.5)
(define time-used (/ (- (current-inexact-milliseconds) start-time)
1000))
(set! log3 (cons time-used log3))
(sleep (max 0.0 (- sleep-interval time-used)))
(loop))))))
(test-start)
(pa-start-stream stream)
(sleep 2.0)
(pa-close-stream stream)
(test-end)
(printf "fails: ~s\n" (stream-fails stream-info))
(printf "time-used mean: ~s\n" (mean log3))
(printf "time-used stdev: ~s\n" (stddev log3))
)
)))
|
1500fa5523783bf2841f0ff9c10053f47125aa72d6f60ced3a3cc56e6e6cf068 | isovector/ld52 | World.hs | module Game.World where
import Data.Set (Set)
import Engine.Types
drawWorld :: Set LevelLayer -> World -> Renderable
drawWorld layers = foldMap (drawLevel layers) . toList . w_levels
drawLevel :: Set LevelLayer -> Level -> Renderable
drawLevel layers lv = mconcat
[ -- drawBackgroundColor $ l_bgcolor lv
flip foldMap layers $ \l -> l_tiles lv l
]
tilesOf :: Rect Tile -> [V2 Tile]
tilesOf (Rect (V2 x y) (V2 w h)) = do
dx <- [0 .. w - 1]
dy <- [0 .. h - 1]
pure $ V2 (x + dx) (y + dy)
| null | https://raw.githubusercontent.com/isovector/ld52/157ee1f1eff8295e6e96c5b90539a5956b3a20a3/src/Game/World.hs | haskell | drawBackgroundColor $ l_bgcolor lv | module Game.World where
import Data.Set (Set)
import Engine.Types
drawWorld :: Set LevelLayer -> World -> Renderable
drawWorld layers = foldMap (drawLevel layers) . toList . w_levels
drawLevel :: Set LevelLayer -> Level -> Renderable
drawLevel layers lv = mconcat
flip foldMap layers $ \l -> l_tiles lv l
]
tilesOf :: Rect Tile -> [V2 Tile]
tilesOf (Rect (V2 x y) (V2 w h)) = do
dx <- [0 .. w - 1]
dy <- [0 .. h - 1]
pure $ V2 (x + dx) (y + dy)
|
faf983b572cc81aa87fb071d227f34e76f145e6db6801841737016fd6901f660 | kana-sama/sicp | 1.30 - iter sum.scm | (define (sum fn next a b)
(let loop ((i a) (result 0))
(cond ((> i b) result)
(else (loop (next i)
(+ result (fn i)))))))
| null | https://raw.githubusercontent.com/kana-sama/sicp/fc637d4b057cfcae1bae3d72ebc08e1af52e619d/1/1.30%20-%20iter%20sum.scm | scheme | (define (sum fn next a b)
(let loop ((i a) (result 0))
(cond ((> i b) result)
(else (loop (next i)
(+ result (fn i)))))))
|
|
a788a3a85aefa476cc4618b08b1b07bc4017678b69ea59dd7cd1b0baed7f82d6 | adoptingerlang/service_discovery | service_discovery_storage.erl | -module(service_discovery_storage).
-export([]).
-callback create(service_discovery:service()) -> binary() | {error, term()}.
-callback read(unicode:unicode_binary()) -> service_discovery:service() | {error, term()}.
-callback read_endpoints(unicode:unicode_binary()) -> [service_discovery:endpoint()] | {error, term()}.
-callback add_named_ports(unicode:unicode_binary(), service_discovery:named_ports()) -> ok | {error, term()}.
-callback list() -> [service_discovery:service()] | {error, term()}.
-callback register(service_discovery:name(), service_discovery:endpoint()) -> ok | {error, term()}.
| null | https://raw.githubusercontent.com/adoptingerlang/service_discovery/03bed070048e70ce267fa4a585fa157bbc883425/apps/service_discovery_storage/src/service_discovery_storage.erl | erlang | -module(service_discovery_storage).
-export([]).
-callback create(service_discovery:service()) -> binary() | {error, term()}.
-callback read(unicode:unicode_binary()) -> service_discovery:service() | {error, term()}.
-callback read_endpoints(unicode:unicode_binary()) -> [service_discovery:endpoint()] | {error, term()}.
-callback add_named_ports(unicode:unicode_binary(), service_discovery:named_ports()) -> ok | {error, term()}.
-callback list() -> [service_discovery:service()] | {error, term()}.
-callback register(service_discovery:name(), service_discovery:endpoint()) -> ok | {error, term()}.
|
|
7cac3bf95e235ad39dcf549fa4400ebcd2c3d27574c1e477d10787c8cf265567 | returntocorp/ocaml-tree-sitter-core | Missing_node.ml | (*
Ensure that the tree-sitter gives us a node in the CST for every node
in the grammar. Patterns (regexps) and token() constructs have no name
and tree-sitter will produce no node in the CST unless a name is
somehow assigned. We use the alias() construct to assign names to grammar
nodes that don't have one.
See:
- for patterns: -sitter/tree-sitter/issues/1151
- for token(): -sitter/tree-sitter/issues/1156
*)
open Printf
open Tree_sitter_t
type token_node_name =
| Literal of string
| Name of string
let get_token_node_name (token_contents : rule_body) : token_node_name option =
let rec get (x : rule_body) =
match x with
| SYMBOL name -> Some (Name name)
| STRING name -> Some (Literal name)
| BLANK -> None
| PATTERN _ -> None
| IMMEDIATE_TOKEN _ -> None
| TOKEN _ -> None
| REPEAT _ -> None
| REPEAT1 _ -> None
| CHOICE _ -> None
| SEQ _ -> None
| PREC (_prec, x) -> get x
| PREC_DYNAMIC (_prec, x) -> get x
| PREC_LEFT (_prec, x) -> get x
| PREC_RIGHT (_prec, x) -> get x
| ALIAS alias -> get alias.content
| FIELD (_field_name, x) -> get x
in
get token_contents
let extract_alias_rules_from_body add_rule body =
let rec extract (x : rule_body) =
match x with
| SYMBOL _
| STRING _
| BLANK -> x
| PATTERN _
| IMMEDIATE_TOKEN _
| TOKEN _ as x ->
let preferred_name = Type_name.name_ts_rule_body x in
let name = add_rule preferred_name x in
ALIAS {
value = name;
named = true;
content = x;
must_be_preserved = true;
}
| REPEAT x -> REPEAT (extract x)
| REPEAT1 x -> REPEAT1 (extract x)
| CHOICE xs -> CHOICE (List.map extract xs)
| SEQ xs -> SEQ (List.map extract xs)
| PREC (prec, x) -> PREC (prec, extract x)
| PREC_DYNAMIC (prec, x) -> PREC_DYNAMIC (prec, extract x)
| PREC_LEFT (prec, x) -> PREC_LEFT (prec, extract x)
| PREC_RIGHT (prec, x) -> PREC_RIGHT (prec, extract x)
| ALIAS alias -> ALIAS { alias with content = extract alias.content }
| FIELD (field_name, x) -> FIELD (field_name, extract x)
in
match body with
| PATTERN _
| IMMEDIATE_TOKEN _
| TOKEN _ as x ->
(* already at the root of a rule body, will have a name. *)
x
| x -> extract x
let extract_rules make_unique rules =
let new_rules = Hashtbl.create 100 in
let new_rule_bodies = Hashtbl.create 100 in
let add_rule preferred_name rule_body =
Avoid introducing two rules x and x _ for the same rule body if said
body occurs multiple times in the grammar . Instead , share the same
name and rule .
body occurs multiple times in the grammar. Instead, share the same
name and rule. *)
match Hashtbl.find_opt new_rule_bodies rule_body with
| Some name -> name
| None ->
let name = make_unique preferred_name in
Hashtbl.replace new_rules name rule_body;
Hashtbl.add new_rule_bodies rule_body name;
name
in
let rewritten_rules =
List.map (fun (name, body) ->
let body = extract_alias_rules_from_body add_rule body in
(name, body)
) rules
in
let new_rules =
Hashtbl.fold (fun name body acc -> (name, body) :: acc) new_rules []
|> List.sort (fun (a, _) (b, _) -> String.compare a b)
in
rewritten_rules @ new_rules
(*
Create rules for constructs that are known to produce a missing node.
*)
let work_around_missing_nodes grammar =
let rules = grammar.rules in
let make_unique =
let scope = Fresh.create_scope () in
fun preferred_name -> Fresh.create_name scope preferred_name
in
(* Register the rule names. They should be unique already. *)
List.iter (fun (name, _body) ->
let unique_name = make_unique name in
if unique_name <> name then
failwith (
sprintf "Grammar defines multiple rules with the same name: %s"
name
)
) rules;
(* Then create new rules. Their preferred names are automatically
derived and may collide. *)
let new_rules = extract_rules make_unique rules in
{ grammar with rules = new_rules }
| null | https://raw.githubusercontent.com/returntocorp/ocaml-tree-sitter-core/66fbeabb8c3fec69a30a2e7f3eec41bc2d112d40/src/gen/lib/Missing_node.ml | ocaml |
Ensure that the tree-sitter gives us a node in the CST for every node
in the grammar. Patterns (regexps) and token() constructs have no name
and tree-sitter will produce no node in the CST unless a name is
somehow assigned. We use the alias() construct to assign names to grammar
nodes that don't have one.
See:
- for patterns: -sitter/tree-sitter/issues/1151
- for token(): -sitter/tree-sitter/issues/1156
already at the root of a rule body, will have a name.
Create rules for constructs that are known to produce a missing node.
Register the rule names. They should be unique already.
Then create new rules. Their preferred names are automatically
derived and may collide. |
open Printf
open Tree_sitter_t
type token_node_name =
| Literal of string
| Name of string
let get_token_node_name (token_contents : rule_body) : token_node_name option =
let rec get (x : rule_body) =
match x with
| SYMBOL name -> Some (Name name)
| STRING name -> Some (Literal name)
| BLANK -> None
| PATTERN _ -> None
| IMMEDIATE_TOKEN _ -> None
| TOKEN _ -> None
| REPEAT _ -> None
| REPEAT1 _ -> None
| CHOICE _ -> None
| SEQ _ -> None
| PREC (_prec, x) -> get x
| PREC_DYNAMIC (_prec, x) -> get x
| PREC_LEFT (_prec, x) -> get x
| PREC_RIGHT (_prec, x) -> get x
| ALIAS alias -> get alias.content
| FIELD (_field_name, x) -> get x
in
get token_contents
let extract_alias_rules_from_body add_rule body =
let rec extract (x : rule_body) =
match x with
| SYMBOL _
| STRING _
| BLANK -> x
| PATTERN _
| IMMEDIATE_TOKEN _
| TOKEN _ as x ->
let preferred_name = Type_name.name_ts_rule_body x in
let name = add_rule preferred_name x in
ALIAS {
value = name;
named = true;
content = x;
must_be_preserved = true;
}
| REPEAT x -> REPEAT (extract x)
| REPEAT1 x -> REPEAT1 (extract x)
| CHOICE xs -> CHOICE (List.map extract xs)
| SEQ xs -> SEQ (List.map extract xs)
| PREC (prec, x) -> PREC (prec, extract x)
| PREC_DYNAMIC (prec, x) -> PREC_DYNAMIC (prec, extract x)
| PREC_LEFT (prec, x) -> PREC_LEFT (prec, extract x)
| PREC_RIGHT (prec, x) -> PREC_RIGHT (prec, extract x)
| ALIAS alias -> ALIAS { alias with content = extract alias.content }
| FIELD (field_name, x) -> FIELD (field_name, extract x)
in
match body with
| PATTERN _
| IMMEDIATE_TOKEN _
| TOKEN _ as x ->
x
| x -> extract x
let extract_rules make_unique rules =
let new_rules = Hashtbl.create 100 in
let new_rule_bodies = Hashtbl.create 100 in
let add_rule preferred_name rule_body =
Avoid introducing two rules x and x _ for the same rule body if said
body occurs multiple times in the grammar . Instead , share the same
name and rule .
body occurs multiple times in the grammar. Instead, share the same
name and rule. *)
match Hashtbl.find_opt new_rule_bodies rule_body with
| Some name -> name
| None ->
let name = make_unique preferred_name in
Hashtbl.replace new_rules name rule_body;
Hashtbl.add new_rule_bodies rule_body name;
name
in
let rewritten_rules =
List.map (fun (name, body) ->
let body = extract_alias_rules_from_body add_rule body in
(name, body)
) rules
in
let new_rules =
Hashtbl.fold (fun name body acc -> (name, body) :: acc) new_rules []
|> List.sort (fun (a, _) (b, _) -> String.compare a b)
in
rewritten_rules @ new_rules
let work_around_missing_nodes grammar =
let rules = grammar.rules in
let make_unique =
let scope = Fresh.create_scope () in
fun preferred_name -> Fresh.create_name scope preferred_name
in
List.iter (fun (name, _body) ->
let unique_name = make_unique name in
if unique_name <> name then
failwith (
sprintf "Grammar defines multiple rules with the same name: %s"
name
)
) rules;
let new_rules = extract_rules make_unique rules in
{ grammar with rules = new_rules }
|
4d80e592a3d77d7f0ff4f84402b0ef87548576108ea22b1ecf03d05044448d44 | cabol/erlbus | ebus_ps_local_SUITE.erl | -module(ebus_ps_local_SUITE).
%% Common Test
-export([
all/0,
init_per_suite/1,
end_per_suite/1
]).
%% Tests
-export([
t_subscribe/1,
t_unsubscribe/1,
t_unsubscribe2/1,
t_pid_removed_when_down/1,
t_subscriber_demonitored/1
]).
%%%===================================================================
%%% Common Test
%%%===================================================================
all() -> [
t_subscribe,
t_unsubscribe,
t_unsubscribe2,
t_pid_removed_when_down,
t_subscriber_demonitored
].
init_per_suite(Config) ->
ebus:start(),
PubSub = application:get_env(ebus, pubsub, []),
Config ++ PubSub.
end_per_suite(Config) ->
ebus:stop(),
Config.
%%%===================================================================
%%% Exported Tests Functions
%%%===================================================================
t_subscribe(Config) ->
% get config properties
ConfigMap = maps:from_list(Config),
#{name := PubSub, pool_size := PoolSize} = ConfigMap,
% subscribe
Pid = spawn_link(fun() -> timer:sleep(infinity) end),
[] = ebus_ps_local:subscribers(PubSub, PoolSize, <<"foo">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"foo">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, Pid, <<"foo">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"bar">>),
% broadcast
ok = ebus_ps_local:broadcast(PubSub, PoolSize, none, <<"foo">>, hellofoo),
hellofoo = ebus_proc:wait_for_msg(5000),
[hellofoo] = ebus_proc:messages(Pid),
ok = ebus_ps_local:broadcast(PubSub, PoolSize, none, <<"bar">>, hellobar),
hellobar = ebus_proc:wait_for_msg(5000),
[hellofoo] = ebus_proc:messages(Pid),
ok = ebus_ps_local:broadcast(PubSub, PoolSize, none, <<"unknown">>, hellobar),
[] = ebus_proc:messages(self()),
ok = ebus_ps_local:broadcast(PubSub, PoolSize, self(), <<"foo">>, hellofoo),
[hellofoo, hellofoo] = ebus_proc:messages(Pid),
[] = ebus_proc:messages(self()),
ct:print("\e[1;1m t_subscribe: \e[0m\e[32m[OK] \e[0m"),
ok.
t_unsubscribe(Config) ->
% get config properties
ConfigMap = maps:from_list(Config),
#{name := PubSub, pool_size := PoolSize} = ConfigMap,
Pid = spawn_link(fun() -> timer:sleep(infinity) end),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"topic1">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, Pid, <<"topic1">>),
SubL1 = lists:sort(
ebus_ps_local:subscribers(PubSub, PoolSize, <<"topic1">>)),
SubL2 = lists:sort([self(), Pid]),
SubL1 = SubL2,
ok = ebus_ps_local:unsubscribe(PubSub, PoolSize, self(), <<"topic1">>),
[Pid] = ebus_ps_local:subscribers(PubSub, PoolSize, <<"topic1">>),
ok = ebus_ps_local:broadcast(PubSub, PoolSize, none, <<"topic1">>, foo),
[] = ebus_proc:messages(),
[foo] = ebus_proc:messages(Pid),
ct:print("\e[1;1m t_unsubscribe: \e[0m\e[32m[OK] \e[0m"),
ok.
t_unsubscribe2(Config) ->
% get config properties
ConfigMap = maps:from_list(Config),
#{name := PubSub, pool_size := PoolSize} = ConfigMap,
unsubscribe GC collect topic when there are no more subscribers
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"topic1">>),
[<<"topic1">>] = ebus_ps_local:list(PubSub, PoolSize),
ok = ebus_ps_local:unsubscribe(PubSub, PoolSize, self(), <<"topic1">>),
0 = length(ebus_ps_local:list(PubSub, PoolSize)),
0 = length(ebus_ps_local:subscribers(PubSub, PoolSize, <<"topic1">>)),
% unsubscribe when topic does not exists
ok = ebus_ps_local:unsubscribe(PubSub, PoolSize, self(), <<"notexists">>),
0 = length(ebus_ps_local:subscribers(PubSub, PoolSize, <<"notexists">>)),
ct:print("\e[1;1m t_unsubscribe2: \e[0m\e[32m[OK] \e[0m"),
ok.
t_pid_removed_when_down(Config) ->
% get config properties
ConfigMap = maps:from_list(Config),
#{name := PubSub, pool_size := PoolSize} = ConfigMap,
{Pid, Ref} = spawn_monitor(fun() -> timer:sleep(infinity) end),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"topic5">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, Pid, <<"topic5">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, Pid, <<"topic6">>),
exit(Pid, kill),
{'DOWN', Ref, _, _, _} = ebus_proc:wait_for_msg(5000),
% Ensure DOWN is processed to avoid races
ebus_ps_local:subscribe(PubSub, PoolSize, Pid, <<"unknown">>),
ebus_ps_local:unsubscribe(PubSub, PoolSize, Pid, <<"unknown">>),
[] = ebus_ps_local:subscription(PubSub, PoolSize, Pid),
Self = self(),
[Self] = ebus_ps_local:subscribers(PubSub, PoolSize, <<"topic5">>),
[] = ebus_ps_local:subscribers(PubSub, PoolSize, <<"topic6">>),
% Assert topic was also garbage collected
[<<"topic5">>] = ebus_ps_local:list(PubSub, PoolSize),
ct:print("\e[1;1m t_pid_removed_when_down: \e[0m\e[32m[OK] \e[0m"),
ok.
t_subscriber_demonitored(Config) ->
% get config properties
ConfigMap = maps:from_list(Config),
#{name := PubSub, pool_size := PoolSize} = ConfigMap,
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"topic7">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"topic8">>),
Topics1 = ebus_ps_local:subscription(PubSub, PoolSize, self()),
[<<"topic7">>, <<"topic8">>] = lists:sort(Topics1),
ok = ebus_ps_local:unsubscribe(PubSub, PoolSize, self(), <<"topic7">>),
Topics2 = ebus_ps_local:subscription(PubSub, PoolSize, self()),
[<<"topic8">>] = lists:sort(Topics2),
ok = ebus_ps_local:unsubscribe(PubSub, PoolSize, self(), <<"topic8">>),
[] = ebus_ps_local:subscription(PubSub, PoolSize, self()),
ct:print("\e[1;1m t_subscriber_demonitored: \e[0m\e[32m[OK] \e[0m"),
ok.
| null | https://raw.githubusercontent.com/cabol/erlbus/050cb728ef09a0ad51c9297281602e362b5e233d/test/ebus_ps_local_SUITE.erl | erlang | Common Test
Tests
===================================================================
Common Test
===================================================================
===================================================================
Exported Tests Functions
===================================================================
get config properties
subscribe
broadcast
get config properties
get config properties
unsubscribe when topic does not exists
get config properties
Ensure DOWN is processed to avoid races
Assert topic was also garbage collected
get config properties | -module(ebus_ps_local_SUITE).
-export([
all/0,
init_per_suite/1,
end_per_suite/1
]).
-export([
t_subscribe/1,
t_unsubscribe/1,
t_unsubscribe2/1,
t_pid_removed_when_down/1,
t_subscriber_demonitored/1
]).
all() -> [
t_subscribe,
t_unsubscribe,
t_unsubscribe2,
t_pid_removed_when_down,
t_subscriber_demonitored
].
init_per_suite(Config) ->
ebus:start(),
PubSub = application:get_env(ebus, pubsub, []),
Config ++ PubSub.
end_per_suite(Config) ->
ebus:stop(),
Config.
t_subscribe(Config) ->
ConfigMap = maps:from_list(Config),
#{name := PubSub, pool_size := PoolSize} = ConfigMap,
Pid = spawn_link(fun() -> timer:sleep(infinity) end),
[] = ebus_ps_local:subscribers(PubSub, PoolSize, <<"foo">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"foo">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, Pid, <<"foo">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"bar">>),
ok = ebus_ps_local:broadcast(PubSub, PoolSize, none, <<"foo">>, hellofoo),
hellofoo = ebus_proc:wait_for_msg(5000),
[hellofoo] = ebus_proc:messages(Pid),
ok = ebus_ps_local:broadcast(PubSub, PoolSize, none, <<"bar">>, hellobar),
hellobar = ebus_proc:wait_for_msg(5000),
[hellofoo] = ebus_proc:messages(Pid),
ok = ebus_ps_local:broadcast(PubSub, PoolSize, none, <<"unknown">>, hellobar),
[] = ebus_proc:messages(self()),
ok = ebus_ps_local:broadcast(PubSub, PoolSize, self(), <<"foo">>, hellofoo),
[hellofoo, hellofoo] = ebus_proc:messages(Pid),
[] = ebus_proc:messages(self()),
ct:print("\e[1;1m t_subscribe: \e[0m\e[32m[OK] \e[0m"),
ok.
t_unsubscribe(Config) ->
ConfigMap = maps:from_list(Config),
#{name := PubSub, pool_size := PoolSize} = ConfigMap,
Pid = spawn_link(fun() -> timer:sleep(infinity) end),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"topic1">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, Pid, <<"topic1">>),
SubL1 = lists:sort(
ebus_ps_local:subscribers(PubSub, PoolSize, <<"topic1">>)),
SubL2 = lists:sort([self(), Pid]),
SubL1 = SubL2,
ok = ebus_ps_local:unsubscribe(PubSub, PoolSize, self(), <<"topic1">>),
[Pid] = ebus_ps_local:subscribers(PubSub, PoolSize, <<"topic1">>),
ok = ebus_ps_local:broadcast(PubSub, PoolSize, none, <<"topic1">>, foo),
[] = ebus_proc:messages(),
[foo] = ebus_proc:messages(Pid),
ct:print("\e[1;1m t_unsubscribe: \e[0m\e[32m[OK] \e[0m"),
ok.
t_unsubscribe2(Config) ->
ConfigMap = maps:from_list(Config),
#{name := PubSub, pool_size := PoolSize} = ConfigMap,
unsubscribe GC collect topic when there are no more subscribers
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"topic1">>),
[<<"topic1">>] = ebus_ps_local:list(PubSub, PoolSize),
ok = ebus_ps_local:unsubscribe(PubSub, PoolSize, self(), <<"topic1">>),
0 = length(ebus_ps_local:list(PubSub, PoolSize)),
0 = length(ebus_ps_local:subscribers(PubSub, PoolSize, <<"topic1">>)),
ok = ebus_ps_local:unsubscribe(PubSub, PoolSize, self(), <<"notexists">>),
0 = length(ebus_ps_local:subscribers(PubSub, PoolSize, <<"notexists">>)),
ct:print("\e[1;1m t_unsubscribe2: \e[0m\e[32m[OK] \e[0m"),
ok.
t_pid_removed_when_down(Config) ->
ConfigMap = maps:from_list(Config),
#{name := PubSub, pool_size := PoolSize} = ConfigMap,
{Pid, Ref} = spawn_monitor(fun() -> timer:sleep(infinity) end),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"topic5">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, Pid, <<"topic5">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, Pid, <<"topic6">>),
exit(Pid, kill),
{'DOWN', Ref, _, _, _} = ebus_proc:wait_for_msg(5000),
ebus_ps_local:subscribe(PubSub, PoolSize, Pid, <<"unknown">>),
ebus_ps_local:unsubscribe(PubSub, PoolSize, Pid, <<"unknown">>),
[] = ebus_ps_local:subscription(PubSub, PoolSize, Pid),
Self = self(),
[Self] = ebus_ps_local:subscribers(PubSub, PoolSize, <<"topic5">>),
[] = ebus_ps_local:subscribers(PubSub, PoolSize, <<"topic6">>),
[<<"topic5">>] = ebus_ps_local:list(PubSub, PoolSize),
ct:print("\e[1;1m t_pid_removed_when_down: \e[0m\e[32m[OK] \e[0m"),
ok.
t_subscriber_demonitored(Config) ->
ConfigMap = maps:from_list(Config),
#{name := PubSub, pool_size := PoolSize} = ConfigMap,
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"topic7">>),
ok = ebus_ps_local:subscribe(PubSub, PoolSize, self(), <<"topic8">>),
Topics1 = ebus_ps_local:subscription(PubSub, PoolSize, self()),
[<<"topic7">>, <<"topic8">>] = lists:sort(Topics1),
ok = ebus_ps_local:unsubscribe(PubSub, PoolSize, self(), <<"topic7">>),
Topics2 = ebus_ps_local:subscription(PubSub, PoolSize, self()),
[<<"topic8">>] = lists:sort(Topics2),
ok = ebus_ps_local:unsubscribe(PubSub, PoolSize, self(), <<"topic8">>),
[] = ebus_ps_local:subscription(PubSub, PoolSize, self()),
ct:print("\e[1;1m t_subscriber_demonitored: \e[0m\e[32m[OK] \e[0m"),
ok.
|
3bfce3366b8e098c5131d38aff1d9e34a60608414059e28a22b2a7404da62d40 | chetmurthy/ensemble | arrayf.ml | (**************************************************************)
ARRAYF.ML : functional arrays
Author : , 4/95
(**************************************************************)
type 'a t = 'a Arraye.t
(**************************************************************)
let append = Arraye.append
let bool_to_string = Arraye.bool_to_string
let combine = Arraye.combine
let concat = Arraye.concat
let copy = Arraye.copy
let create = Arraye.create
let doubleton = Arraye.doubleton
let empty = Arraye.empty
let filter = Arraye.filter
let filter_nones = Arraye.filter_nones
let flatten = Arraye.flatten
let for_all = Arraye.for_all
let for_all2 = Arraye.for_all2
let get = Arraye.get
let index = Arraye.index
let init = Arraye.init
let int_to_string = Arraye.int_to_string
let is_empty = Arraye.is_empty
let iter = Arraye.iter
let iteri = Arraye.iteri
let length = Arraye.length
let map = Arraye.map
let mapi = Arraye.mapi
let map2 = Arraye.map2
let mem = Arraye.mem
let of_array = Arraye.of_array
let of_arraye = Arraye.copy
let of_list = Arraye.of_list
let prependi = Arraye.prependi
let singleton = Arraye.singleton
let split = Arraye.split
let sub = Arraye.sub
let to_array = Arraye.to_array
let to_arraye = Arraye.copy
let to_list = Arraye.to_list
let to_string = Arraye.to_string
let fold = Arraye.fold
let fold_left = Arraye.fold_left
let fold_right = Arraye.fold_right
let ordered = Arraye.ordered
let exists = Arraye.exists
(**************************************************************)
(* If already ordered, then return input array.
*)
let sort cmp a =
if ordered cmp a then a else (
let a = Arraye.copy a in
Arraye.sort cmp a ;
a
)
(**************************************************************)
let fset a i x =
let a = Arraye.copy a in
Arraye.set a i x ;
a
(**************************************************************)
let max a =
let len = length a in
assert (len > 0) ;
let max = ref (get a 0) in
for i = 1 to pred len do
let v = get a i in
if v > !max then
max := v
done ;
!max
let to_ranks a =
let r = ref [] in
for i = 0 to pred (length a) do
if get a i then
r := i :: !r
done ;
!r
let of_ranks n l =
let a = create n false in
List.iter (fun i ->
Arraye.set a i true
) l ;
a
let gossip failed rank =
let l = ref [] in
for i = 0 to pred (length failed) do
if (not (Arraye.get failed i)) && i <> rank then
l := i :: !l
done ;
of_list !l
let super a b =
let la = length a in
let lb = length b in
if la <> lb then
failwith "super:mismatched lengths" ;
let super = ref true in
for i = 0 to pred la do
if Arraye.get b i && not (Arraye.get a i) then
super := false
done ;
!super
let min_false a =
let j = ref (length a) in
for i = pred (length a) downto 0 do
if not (Arraye.get a i) then
j := i
done ;
!j
let choose a k =
let n = Arraye.length a in
let k = Util.int_min n k in
let rec loop k l =
if k = 0 then l else (
let i = Arraye.get a (Random.int n) in
if List.mem i l then
loop k l
else
loop (pred k) (i::l)
)
in loop k []
(**************************************************************)
(* This should be used with care, it is unsafe.
*)
let to_array_break x = (Obj.magic x : 'a array)
let of_array_break x = (Obj.magic x : 'a t)
let of_array_map = Arraye.of_array_map
let to_array_map = Arraye.to_array_map
(**************************************************************)
| null | https://raw.githubusercontent.com/chetmurthy/ensemble/8266a89e68be24a4aaa5d594662e211eeaa6dc89/ensemble/server/util/arrayf.ml | ocaml | ************************************************************
************************************************************
************************************************************
************************************************************
If already ordered, then return input array.
************************************************************
************************************************************
************************************************************
This should be used with care, it is unsafe.
************************************************************ | ARRAYF.ML : functional arrays
Author : , 4/95
type 'a t = 'a Arraye.t
let append = Arraye.append
let bool_to_string = Arraye.bool_to_string
let combine = Arraye.combine
let concat = Arraye.concat
let copy = Arraye.copy
let create = Arraye.create
let doubleton = Arraye.doubleton
let empty = Arraye.empty
let filter = Arraye.filter
let filter_nones = Arraye.filter_nones
let flatten = Arraye.flatten
let for_all = Arraye.for_all
let for_all2 = Arraye.for_all2
let get = Arraye.get
let index = Arraye.index
let init = Arraye.init
let int_to_string = Arraye.int_to_string
let is_empty = Arraye.is_empty
let iter = Arraye.iter
let iteri = Arraye.iteri
let length = Arraye.length
let map = Arraye.map
let mapi = Arraye.mapi
let map2 = Arraye.map2
let mem = Arraye.mem
let of_array = Arraye.of_array
let of_arraye = Arraye.copy
let of_list = Arraye.of_list
let prependi = Arraye.prependi
let singleton = Arraye.singleton
let split = Arraye.split
let sub = Arraye.sub
let to_array = Arraye.to_array
let to_arraye = Arraye.copy
let to_list = Arraye.to_list
let to_string = Arraye.to_string
let fold = Arraye.fold
let fold_left = Arraye.fold_left
let fold_right = Arraye.fold_right
let ordered = Arraye.ordered
let exists = Arraye.exists
let sort cmp a =
if ordered cmp a then a else (
let a = Arraye.copy a in
Arraye.sort cmp a ;
a
)
let fset a i x =
let a = Arraye.copy a in
Arraye.set a i x ;
a
let max a =
let len = length a in
assert (len > 0) ;
let max = ref (get a 0) in
for i = 1 to pred len do
let v = get a i in
if v > !max then
max := v
done ;
!max
let to_ranks a =
let r = ref [] in
for i = 0 to pred (length a) do
if get a i then
r := i :: !r
done ;
!r
let of_ranks n l =
let a = create n false in
List.iter (fun i ->
Arraye.set a i true
) l ;
a
let gossip failed rank =
let l = ref [] in
for i = 0 to pred (length failed) do
if (not (Arraye.get failed i)) && i <> rank then
l := i :: !l
done ;
of_list !l
let super a b =
let la = length a in
let lb = length b in
if la <> lb then
failwith "super:mismatched lengths" ;
let super = ref true in
for i = 0 to pred la do
if Arraye.get b i && not (Arraye.get a i) then
super := false
done ;
!super
let min_false a =
let j = ref (length a) in
for i = pred (length a) downto 0 do
if not (Arraye.get a i) then
j := i
done ;
!j
let choose a k =
let n = Arraye.length a in
let k = Util.int_min n k in
let rec loop k l =
if k = 0 then l else (
let i = Arraye.get a (Random.int n) in
if List.mem i l then
loop k l
else
loop (pred k) (i::l)
)
in loop k []
let to_array_break x = (Obj.magic x : 'a array)
let of_array_break x = (Obj.magic x : 'a t)
let of_array_map = Arraye.of_array_map
let to_array_map = Arraye.to_array_map
|
1ec1980422c489cb61d54dad4bb7516868738faff3e08457c788d57f9f0a68d1 | fulcrologic/fulcro-inspect | helpers.cljs | (ns com.wsscode.oge.ui.helpers
(:require [clojure.string :as str]
[goog.object :as gobj]
[cljs.spec.alpha :as s]))
(defn js-get-in [x path]
(gobj/getValueByKeys x (clj->js path)))
(s/fdef js-get-in
:args (s/cat :x any? :path vector?)
:ret any?)
(defn html-attr-merge [a b]
(cond
(map? a) (merge a b)
(string? a) (str a " " b)
:else b))
(s/fdef html-attr-merge
:args (s/cat :a any? :b any?)
:ret any?)
(defn props->html
[attrs & props]
(->> (mapv #(dissoc % :react-key) props)
(apply merge-with html-attr-merge (dissoc attrs :react-key))
(into {} (filter (fn [[k _]] (simple-keyword? k))))
(clj->js)))
(defn expand-classes [css classes]
{:className (str/join " " (mapv css classes))})
(s/fdef expand-classes
:args (s/cat :css map? :classes map?)
:ret map?)
(defn strings [strings]
(->> strings
(map #(str "\"" % "\""))
(str/join " ")))
| null | https://raw.githubusercontent.com/fulcrologic/fulcro-inspect/a03b61cbd95384c0f03aa936368bcf5cf573fa32/src/ui/com/wsscode/oge/ui/helpers.cljs | clojure | (ns com.wsscode.oge.ui.helpers
(:require [clojure.string :as str]
[goog.object :as gobj]
[cljs.spec.alpha :as s]))
(defn js-get-in [x path]
(gobj/getValueByKeys x (clj->js path)))
(s/fdef js-get-in
:args (s/cat :x any? :path vector?)
:ret any?)
(defn html-attr-merge [a b]
(cond
(map? a) (merge a b)
(string? a) (str a " " b)
:else b))
(s/fdef html-attr-merge
:args (s/cat :a any? :b any?)
:ret any?)
(defn props->html
[attrs & props]
(->> (mapv #(dissoc % :react-key) props)
(apply merge-with html-attr-merge (dissoc attrs :react-key))
(into {} (filter (fn [[k _]] (simple-keyword? k))))
(clj->js)))
(defn expand-classes [css classes]
{:className (str/join " " (mapv css classes))})
(s/fdef expand-classes
:args (s/cat :css map? :classes map?)
:ret map?)
(defn strings [strings]
(->> strings
(map #(str "\"" % "\""))
(str/join " ")))
|
|
12be87465b0eccafa0deab2d5bb35c1f431fc5d1eb4acbdffa4c33ed3f6dfa26 | mariari/Misc-ML-Scripts | Parsing.hs | {-# LANGUAGE DeriveTraversable #-}
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
-- |
-- Hardening S-expressions into a more readable form. Here we use a
-- mixture of record structures and aliases. Each cover a form that we
-- wish to talk about rather than just match away at
--
-- - _The form for transformation follows this structure_
# + begin_src haskell
-- -- the data type
-- data Form = ... deriving (Show)
is < Form > : : Sexp . T - > Bool
to < Form > : : Sexp . T - > Maybe < Form >
-- from<Form> :: <Form> -> Sexp.T
# + end_src
-- + With the following properties of the forms
-- #+begin_src haskell
∀ s : Sexp . is < Form > s = True ⟷ is - just ( to < Form > s )
--
-- to<Form> 。 from<Form> = Just
-- #+end_src
-- _TODO_
1 . Figure out if we can even express a spec system in
-- Haskell... =to<Form>= and =From<From>= have the exact same signature
2 . replace the repeat code with the = to < Form>= with an abstraction
3 . put the meta data with the form so we do n't have to do it by
-- hand in the code that uses this
1 . Use = . Library . LineNum=
2 . append the = Form= With this
3 . have to < Form > fill this
4 . Have extra smart consturctors that are = < form>= , so that we
-- can automatically fill in this meta data
module Data.Sexp.Structure.Parsing where
import Mari.Library hiding (Type)
import qualified Mari.Library.NameSymbol as NameSymbol
import qualified Data.Sexp as Sexp
import Data.Sexp.Structure.Helpers
-- | @Defun@ is the base defun structure
-- currently it does not have matching
data Defun = Defun
{ defunName :: Sexp.T,
defunArgs :: Sexp.T,
defunBody :: Sexp.T
}
deriving (Show)
data Include = Include
{ includeName :: NameSymbol.T
}
deriving (Show)
data Alias = Alias
{ aliasName :: NameSymbol.T,
aliasModuleOf :: NameSymbol.T
}
deriving (Show)
-- | @Type@ is the type declaration structure
data Type = Type
{ -- TODO ∷ we should really have a field the signature currently we
-- don't really support that without doing it by hand. Maybe our
-- generator should help here, or we should have a way of talking
-- about named arguments somehow, and unfolding the slots in a
-- way....
typeNameAndSig :: Sexp.T,
typeArgs :: Sexp.T,
typeBody :: Sexp.T
}
deriving (Show)
-- | @PredAns@ is an abstraction over questions and answers
data PredAns = PredAns {predAnsPredicate :: Sexp.T, predAnsAnswer :: Sexp.T}
deriving (Show)
| @Cond@ here Cond form takes a list of predicate answers
newtype Cond = Cond {condEntailments :: [PredAns]} deriving (Show)
-- | @Signature@ is the signature of the term
data Signature = Signature
{ signatureName :: Sexp.T,
signatureSig :: Sexp.T
}
deriving (Show)
data LetSignature = LetSignature
{ letSignatureName :: Sexp.T,
letSignatureSig :: Sexp.T,
letSignatureRest :: Sexp.T
}
deriving (Show)
-- | @LetType@ is the let-type form of the language
data LetType = LetType
{ letTypeNameAndSig :: Sexp.T,
letTypeArgs :: Sexp.T,
letTypeBody :: Sexp.T,
letTypeRest :: Sexp.T
}
deriving (Show)
-- | @Let@ is the let form of the language
-- it has a name, arguments, body, and the body
data Let = Let
{ letName :: Sexp.T,
letArgs :: Sexp.T,
letBody :: Sexp.T,
letRest :: Sexp.T
}
deriving (Show)
data Case = Case
{ caseOn :: Sexp.T,
caseImplications :: [DeconBody]
}
deriving (Show)
-- | @DeconBody@ is an abstraction over a matching body form
data DeconBody = DeconBody
{ deconBodyDeconsturctor :: Sexp.T,
deconBodyBody :: Sexp.T
}
deriving (Show)
data Arrow = Arrow
{ arrowName :: Sexp.T,
arrowBody :: Sexp.T
}
deriving (Show)
data Lambda = Lambda
{ lambdaArgs :: Sexp.T,
lambdaBody :: Sexp.T
}
deriving (Show)
| @NameBind@ represents a type naming scheme in a record
data NameBind = Pun Punned | NotPun NotPunned
deriving (Show)
-- | @NotPunned@ represents a punned type name in a record
data NotPunned = NotPunned
{ notPunnedName :: Sexp.T,
notPunnedValue :: Sexp.T
}
deriving (Show)
data NameUsage = NameUsage
{ nameUsageName :: Sexp.T,
nameUsageUsage :: Sexp.T,
nameUsageValue :: Sexp.T
}
deriving (Show)
newtype Punned = Punned
{ punnedName :: Sexp.T
}
deriving (Show)
newtype Record = Record
{ recordValue :: [NameBind]
}
deriving (Show)
newtype RecordDec = RecordDec
{ recordDecValue :: [NameUsage]
}
deriving (Show)
-- | @Infix@ represents an infix function
data Infix = Infix
{ infixOp :: Sexp.T,
infixLeft :: Sexp.T,
infixRight :: Sexp.T
}
deriving (Show)
newtype Open = Open
{ openName :: Sexp.T
}
deriving (Show)
data OpenIn = OpenIn
{ openInName :: Sexp.T,
openInBody :: Sexp.T
}
deriving (Show)
newtype Declare = Declare
{ declareClaim :: Sexp.T
}
deriving (Show)
data Declaim = Declaim
{ declaimClaim :: Sexp.T,
declaimBody :: Sexp.T
}
deriving (Show)
-- | @DefModule@ - Stands in for a module declaration
data DefModule = DefModule
{ defModuleName :: Sexp.T,
defModuleArgs :: Sexp.T,
defModuleBody :: Sexp.T
}
deriving (Show)
-- | @LefModule@ - Stands in for a module let declaration
data LetModule = LetModule
{ letModuleName :: Sexp.T,
letModuleArgs :: Sexp.T,
letModuleBody :: Sexp.T,
letModuleRest :: Sexp.T
}
deriving (Show)
newtype Primitive = Primitive
{ primitiveName :: Sexp.T
}
deriving (Show)
data Effect = Effect
{ effectName :: Sexp.T,
effectOps :: Sexp.T
}
deriving (Show)
data DefHandler = DefHandler
{ defHandlerName :: Sexp.T,
defHandlerOps :: Sexp.T
}
deriving (Show)
data LetOp = LetOp
{ letOpName :: Sexp.T,
letOpArgs :: Sexp.T,
letOpBody :: Sexp.T
}
deriving (Show)
data LetRet = LetRet
{ letRetArg :: Sexp.T,
letRetBody :: Sexp.T
}
deriving (Show)
newtype Do = Do
{ doStatements :: Sexp.T
}
deriving (Show)
newtype DoDeep = DoDeep
{ doDeepStatements :: [DoBodyFull]
}
deriving (Show)
data DoBodyFull
= WithBinder
{ doBodyFullName :: NameSymbol.T,
doBodyFullBBody :: Sexp.T
}
| NoBinder {doBodyFullBody :: Sexp.T}
deriving (Show)
--
Used to transform into WithBinder
data Binder = Binder
{ binderName :: NameSymbol.T,
binderBody :: Sexp.T
}
deriving (Show)
Used to for
newtype DoBody = DoBody {doBodySexp :: Sexp.T}
data DoOp = DoOp
{ doOpName :: Sexp.T,
doOpArgs :: Sexp.T
}
deriving (Show)
newtype DoPure = DoPure
{ doPureArg :: Sexp.T
}
deriving (Show)
data Via = Via
{ viaHandler :: Sexp.T,
viaProgram :: Sexp.T
}
deriving (Show)
data Header = Header
{ headerName :: NameSymbol.T,
headerSexps :: Sexp.T
}
deriving (Show)
--------------------------------------------------------------------------------
-- Converter functions
-- The format for these are
name < Form > : : NameSymbol . T
is < Form > : : Sexp . T - > Bool
to < Form > : : Sexp . T - > Maybe < Form >
-- from<Form> :: <Form> -> Sexp.T
--------------------------------------------------------------------------------
-------------------------------------------
-- Not Generated, due to limited generation
-------------------------------------------
--------------------
NotPunned no Grouping
--------------------
fromNotPunnedGroup :: [NotPunned] -> Sexp.T
fromNotPunnedGroup = Sexp.unGroupBy2 . toStarList fromNotPunned
toNotPunnedGroup :: Sexp.T -> Maybe [NotPunned]
toNotPunnedGroup = fromStarList toNotPunned . Sexp.groupBy2
--------------------
-- Name Bind
--------------------
toNameBind :: Sexp.T -> Maybe NameBind
toNameBind sexp =
fmap Pun (toPunned sexp) <|> fmap NotPun (toNotPunned sexp)
fromNameBind :: NameBind -> Sexp.T
fromNameBind (Pun pun) = fromPunned pun
fromNameBind (NotPun notPun) = fromNotPunned notPun
instance Sexp.Serialize NameBind where
deserialize = toNameBind
serialize = fromNameBind
--------------------
-- Do Body Full
--------------------
-- TODO ∷ Change the frontend generator, as this does not fulfill it.
toDoBodyFull :: Sexp.T -> Maybe DoBodyFull
toDoBodyFull sexp =
fmap binderToBody (toBinder sexp) <|> Just (NoBinder sexp)
fromDoBodyFull :: DoBodyFull -> Sexp.T
fromDoBodyFull (NoBinder sexp) = sexp
fromDoBodyFull (WithBinder name body) = Binder name body |> fromBinder
binderToBody :: Binder -> DoBodyFull
binderToBody (Binder name body) = WithBinder name body
instance Sexp.Serialize DoBodyFull where
deserialize = toDoBodyFull
serialize = fromDoBodyFull
----------------------------------------
-- Generated
----------------------------------------
----------------------------------------
-- Type
----------------------------------------
nameType :: NameSymbol.T
nameType = "type"
isType :: Sexp.T -> Bool
isType (Sexp.Cons form _) = Sexp.isAtomNamed form nameType
isType _ = False
toType :: Sexp.T -> Maybe Type
toType form
| isType form =
case form of
_nameType Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 ->
Type sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromType :: Type -> Sexp.T
fromType (Type sexp1 sexp2 sexp3) =
Sexp.listStar [Sexp.atom nameType, sexp1, sexp2, sexp3]
instance Sexp.Serialize Type where
deserialize = toType
serialize = fromType
----------------------------------------
LetType
----------------------------------------
nameLetType :: NameSymbol.T
nameLetType = ":let-type"
isLetType :: Sexp.T -> Bool
isLetType (Sexp.Cons form _) = Sexp.isAtomNamed form nameLetType
isLetType _ = False
toLetType :: Sexp.T -> Maybe LetType
toLetType form
| isLetType form =
case form of
_nameLetType Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> sexp4 Sexp.:> Sexp.Nil ->
LetType sexp1 sexp2 sexp3 sexp4 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLetType :: LetType -> Sexp.T
fromLetType (LetType sexp1 sexp2 sexp3 sexp4) =
Sexp.list [Sexp.atom nameLetType, sexp1, sexp2, sexp3, sexp4]
instance Sexp.Serialize LetType where
deserialize = toLetType
serialize = fromLetType
----------------------------------------
-- Include
----------------------------------------
nameInclude :: NameSymbol.T
nameInclude = ":include"
isInclude :: Sexp.T -> Bool
isInclude (Sexp.Cons form _) = Sexp.isAtomNamed form nameInclude
isInclude _ = False
toInclude :: Sexp.T -> Maybe Include
toInclude form
| isInclude form =
case form of
_nameInclude Sexp.:> nameSymbol1 Sexp.:> Sexp.Nil
| Just nameSymbol1 <- toNameSymbol nameSymbol1 ->
Include nameSymbol1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromInclude :: Include -> Sexp.T
fromInclude (Include nameSymbol1) =
Sexp.list [Sexp.atom nameInclude, fromNameSymbol nameSymbol1]
instance Sexp.Serialize Include where
deserialize = toInclude
serialize = fromInclude
----------------------------------------
----------------------------------------
nameAlias :: NameSymbol.T
nameAlias = ":alias"
isAlias :: Sexp.T -> Bool
isAlias (Sexp.Cons form _) = Sexp.isAtomNamed form nameAlias
isAlias _ = False
toAlias :: Sexp.T -> Maybe Alias
toAlias form
| isAlias form =
case form of
_nameAlias Sexp.:> nameSymbol1 Sexp.:> nameSymbol2 Sexp.:> Sexp.Nil
| Just nameSymbol1 <- toNameSymbol nameSymbol1,
Just nameSymbol2 <- toNameSymbol nameSymbol2 ->
Alias nameSymbol1 nameSymbol2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromAlias :: Alias -> Sexp.T
fromAlias (Alias nameSymbol1 nameSymbol2) =
Sexp.list [Sexp.atom nameAlias, fromNameSymbol nameSymbol1, fromNameSymbol nameSymbol2]
instance Sexp.Serialize Alias where
deserialize = toAlias
serialize = fromAlias
----------------------------------------
Defun
----------------------------------------
nameDefun :: NameSymbol.T
nameDefun = ":defun"
isDefun :: Sexp.T -> Bool
isDefun (Sexp.Cons form _) = Sexp.isAtomNamed form nameDefun
isDefun _ = False
toDefun :: Sexp.T -> Maybe Defun
toDefun form
| isDefun form =
case form of
_nameDefun Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> Sexp.Nil ->
Defun sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDefun :: Defun -> Sexp.T
fromDefun (Defun sexp1 sexp2 sexp3) =
Sexp.list [Sexp.atom nameDefun, sexp1, sexp2, sexp3]
instance Sexp.Serialize Defun where
deserialize = toDefun
serialize = fromDefun
----------------------------------------
Signature
----------------------------------------
nameSignature :: NameSymbol.T
nameSignature = ":defsig"
isSignature :: Sexp.T -> Bool
isSignature (Sexp.Cons form _) = Sexp.isAtomNamed form nameSignature
isSignature _ = False
toSignature :: Sexp.T -> Maybe Signature
toSignature form
| isSignature form =
case form of
_nameSignature Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Signature sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromSignature :: Signature -> Sexp.T
fromSignature (Signature sexp1 sexp2) =
Sexp.list [Sexp.atom nameSignature, sexp1, sexp2]
instance Sexp.Serialize Signature where
deserialize = toSignature
serialize = fromSignature
----------------------------------------
LetSignature
----------------------------------------
nameLetSignature :: NameSymbol.T
nameLetSignature = ":let-sig"
isLetSignature :: Sexp.T -> Bool
isLetSignature (Sexp.Cons form _) = Sexp.isAtomNamed form nameLetSignature
isLetSignature _ = False
toLetSignature :: Sexp.T -> Maybe LetSignature
toLetSignature form
| isLetSignature form =
case form of
_nameLetSignature Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> Sexp.Nil ->
LetSignature sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLetSignature :: LetSignature -> Sexp.T
fromLetSignature (LetSignature sexp1 sexp2 sexp3) =
Sexp.list [Sexp.atom nameLetSignature, sexp1, sexp2, sexp3]
instance Sexp.Serialize LetSignature where
deserialize = toLetSignature
serialize = fromLetSignature
----------------------------------------
-- Let
----------------------------------------
nameLet :: NameSymbol.T
nameLet = "let"
isLet :: Sexp.T -> Bool
isLet (Sexp.Cons form _) = Sexp.isAtomNamed form nameLet
isLet _ = False
toLet :: Sexp.T -> Maybe Let
toLet form
| isLet form =
case form of
_nameLet Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> sexp4 Sexp.:> Sexp.Nil ->
Let sexp1 sexp2 sexp3 sexp4 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLet :: Let -> Sexp.T
fromLet (Let sexp1 sexp2 sexp3 sexp4) =
Sexp.list [Sexp.atom nameLet, sexp1, sexp2, sexp3, sexp4]
instance Sexp.Serialize Let where
deserialize = toLet
serialize = fromLet
----------------------------------------
PredAns
----------------------------------------
toPredAns :: Sexp.T -> Maybe PredAns
toPredAns form =
case form of
sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
PredAns sexp1 sexp2 |> Just
_ ->
Nothing
fromPredAns :: PredAns -> Sexp.T
fromPredAns (PredAns sexp1 sexp2) =
Sexp.list [sexp1, sexp2]
instance Sexp.Serialize PredAns where
deserialize = toPredAns
serialize = fromPredAns
----------------------------------------
-- Cond
----------------------------------------
nameCond :: NameSymbol.T
nameCond = ":cond"
isCond :: Sexp.T -> Bool
isCond (Sexp.Cons form _) = Sexp.isAtomNamed form nameCond
isCond _ = False
toCond :: Sexp.T -> Maybe Cond
toCond form
| isCond form =
case form of
_nameCond Sexp.:> predAns1
| Just predAns1 <- toPredAns `fromStarList` predAns1 ->
Cond predAns1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromCond :: Cond -> Sexp.T
fromCond (Cond predAns1) =
Sexp.listStar [Sexp.atom nameCond, fromPredAns `toStarList` predAns1]
instance Sexp.Serialize Cond where
deserialize = toCond
serialize = fromCond
----------------------------------------
-- DeconBody
----------------------------------------
toDeconBody :: Sexp.T -> Maybe DeconBody
toDeconBody form =
case form of
sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
DeconBody sexp1 sexp2 |> Just
_ ->
Nothing
fromDeconBody :: DeconBody -> Sexp.T
fromDeconBody (DeconBody sexp1 sexp2) =
Sexp.list [sexp1, sexp2]
instance Sexp.Serialize DeconBody where
deserialize = toDeconBody
serialize = fromDeconBody
----------------------------------------
-- Case
----------------------------------------
nameCase :: NameSymbol.T
nameCase = "case"
isCase :: Sexp.T -> Bool
isCase (Sexp.Cons form _) = Sexp.isAtomNamed form nameCase
isCase _ = False
toCase :: Sexp.T -> Maybe Case
toCase form
| isCase form =
case form of
_nameCase Sexp.:> sexp1 Sexp.:> deconBody2
| Just deconBody2 <- toDeconBody `fromStarList` deconBody2 ->
Case sexp1 deconBody2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromCase :: Case -> Sexp.T
fromCase (Case sexp1 deconBody2) =
Sexp.listStar [Sexp.atom nameCase, sexp1, fromDeconBody `toStarList` deconBody2]
instance Sexp.Serialize Case where
deserialize = toCase
serialize = fromCase
----------------------------------------
Arrow
----------------------------------------
nameArrow :: NameSymbol.T
nameArrow = "%<-"
isArrow :: Sexp.T -> Bool
isArrow (Sexp.Cons form _) = Sexp.isAtomNamed form nameArrow
isArrow _ = False
toArrow :: Sexp.T -> Maybe Arrow
toArrow form
| isArrow form =
case form of
_nameArrow Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Arrow sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromArrow :: Arrow -> Sexp.T
fromArrow (Arrow sexp1 sexp2) =
Sexp.list [Sexp.atom nameArrow, sexp1, sexp2]
instance Sexp.Serialize Arrow where
deserialize = toArrow
serialize = fromArrow
----------------------------------------
-- Lambda
----------------------------------------
nameLambda :: NameSymbol.T
nameLambda = ":lambda"
isLambda :: Sexp.T -> Bool
isLambda (Sexp.Cons form _) = Sexp.isAtomNamed form nameLambda
isLambda _ = False
toLambda :: Sexp.T -> Maybe Lambda
toLambda form
| isLambda form =
case form of
_nameLambda Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Lambda sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLambda :: Lambda -> Sexp.T
fromLambda (Lambda sexp1 sexp2) =
Sexp.list [Sexp.atom nameLambda, sexp1, sexp2]
instance Sexp.Serialize Lambda where
deserialize = toLambda
serialize = fromLambda
----------------------------------------
Punned
----------------------------------------
toPunned :: Sexp.T -> Maybe Punned
toPunned form =
case form of
sexp1 Sexp.:> Sexp.Nil ->
Punned sexp1 |> Just
_ ->
Nothing
fromPunned :: Punned -> Sexp.T
fromPunned (Punned sexp1) =
Sexp.list [sexp1]
instance Sexp.Serialize Punned where
deserialize = toPunned
serialize = fromPunned
----------------------------------------
NotPunned
----------------------------------------
toNotPunned :: Sexp.T -> Maybe NotPunned
toNotPunned form =
case form of
sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
NotPunned sexp1 sexp2 |> Just
_ ->
Nothing
fromNotPunned :: NotPunned -> Sexp.T
fromNotPunned (NotPunned sexp1 sexp2) =
Sexp.list [sexp1, sexp2]
instance Sexp.Serialize NotPunned where
deserialize = toNotPunned
serialize = fromNotPunned
----------------------------------------
NameUsage
----------------------------------------
toNameUsage :: Sexp.T -> Maybe NameUsage
toNameUsage form =
case form of
sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> Sexp.Nil ->
NameUsage sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
fromNameUsage :: NameUsage -> Sexp.T
fromNameUsage (NameUsage sexp1 sexp2 sexp3) =
Sexp.list [sexp1, sexp2, sexp3]
instance Sexp.Serialize NameUsage where
deserialize = toNameUsage
serialize = fromNameUsage
----------------------------------------
-- Record
----------------------------------------
nameRecord :: NameSymbol.T
nameRecord = ":record"
isRecord :: Sexp.T -> Bool
isRecord (Sexp.Cons form _) = Sexp.isAtomNamed form nameRecord
isRecord _ = False
toRecord :: Sexp.T -> Maybe Record
toRecord form
| isRecord form =
case form of
_nameRecord Sexp.:> nameBind1
| Just nameBind1 <- toNameBind `fromStarList` nameBind1 ->
Record nameBind1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromRecord :: Record -> Sexp.T
fromRecord (Record nameBind1) =
Sexp.listStar [Sexp.atom nameRecord, fromNameBind `toStarList` nameBind1]
instance Sexp.Serialize Record where
deserialize = toRecord
serialize = fromRecord
----------------------------------------
-- Infix
----------------------------------------
nameInfix :: NameSymbol.T
nameInfix = ":infix"
isInfix :: Sexp.T -> Bool
isInfix (Sexp.Cons form _) = Sexp.isAtomNamed form nameInfix
isInfix _ = False
toInfix :: Sexp.T -> Maybe Infix
toInfix form
| isInfix form =
case form of
_nameInfix Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> Sexp.Nil ->
Infix sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromInfix :: Infix -> Sexp.T
fromInfix (Infix sexp1 sexp2 sexp3) =
Sexp.list [Sexp.atom nameInfix, sexp1, sexp2, sexp3]
instance Sexp.Serialize Infix where
deserialize = toInfix
serialize = fromInfix
----------------------------------------
-- OpenIn
----------------------------------------
nameOpenIn :: NameSymbol.T
nameOpenIn = ":open-in"
isOpenIn :: Sexp.T -> Bool
isOpenIn (Sexp.Cons form _) = Sexp.isAtomNamed form nameOpenIn
isOpenIn _ = False
toOpenIn :: Sexp.T -> Maybe OpenIn
toOpenIn form
| isOpenIn form =
case form of
_nameOpenIn Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
OpenIn sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromOpenIn :: OpenIn -> Sexp.T
fromOpenIn (OpenIn sexp1 sexp2) =
Sexp.list [Sexp.atom nameOpenIn, sexp1, sexp2]
instance Sexp.Serialize OpenIn where
deserialize = toOpenIn
serialize = fromOpenIn
----------------------------------------
-- Open
----------------------------------------
nameOpen :: NameSymbol.T
nameOpen = "open"
isOpen :: Sexp.T -> Bool
isOpen (Sexp.Cons form _) = Sexp.isAtomNamed form nameOpen
isOpen _ = False
toOpen :: Sexp.T -> Maybe Open
toOpen form
| isOpen form =
case form of
_nameOpen Sexp.:> sexp1 Sexp.:> Sexp.Nil ->
Open sexp1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromOpen :: Open -> Sexp.T
fromOpen (Open sexp1) =
Sexp.list [Sexp.atom nameOpen, sexp1]
instance Sexp.Serialize Open where
deserialize = toOpen
serialize = fromOpen
----------------------------------------
-- Declare
----------------------------------------
nameDeclare :: NameSymbol.T
nameDeclare = "declare"
isDeclare :: Sexp.T -> Bool
isDeclare (Sexp.Cons form _) = Sexp.isAtomNamed form nameDeclare
isDeclare _ = False
toDeclare :: Sexp.T -> Maybe Declare
toDeclare form
| isDeclare form =
case form of
_nameDeclare Sexp.:> sexp1 Sexp.:> Sexp.Nil ->
Declare sexp1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDeclare :: Declare -> Sexp.T
fromDeclare (Declare sexp1) =
Sexp.list [Sexp.atom nameDeclare, sexp1]
instance Sexp.Serialize Declare where
deserialize = toDeclare
serialize = fromDeclare
----------------------------------------
-- Declaim
----------------------------------------
nameDeclaim :: NameSymbol.T
nameDeclaim = ":declaim"
isDeclaim :: Sexp.T -> Bool
isDeclaim (Sexp.Cons form _) = Sexp.isAtomNamed form nameDeclaim
isDeclaim _ = False
toDeclaim :: Sexp.T -> Maybe Declaim
toDeclaim form
| isDeclaim form =
case form of
_nameDeclaim Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Declaim sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDeclaim :: Declaim -> Sexp.T
fromDeclaim (Declaim sexp1 sexp2) =
Sexp.list [Sexp.atom nameDeclaim, sexp1, sexp2]
instance Sexp.Serialize Declaim where
deserialize = toDeclaim
serialize = fromDeclaim
----------------------------------------
DefModule
----------------------------------------
nameDefModule :: NameSymbol.T
nameDefModule = ":defmodule"
isDefModule :: Sexp.T -> Bool
isDefModule (Sexp.Cons form _) = Sexp.isAtomNamed form nameDefModule
isDefModule _ = False
toDefModule :: Sexp.T -> Maybe DefModule
toDefModule form
| isDefModule form =
case form of
_nameDefModule Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 ->
DefModule sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDefModule :: DefModule -> Sexp.T
fromDefModule (DefModule sexp1 sexp2 sexp3) =
Sexp.listStar [Sexp.atom nameDefModule, sexp1, sexp2, sexp3]
instance Sexp.Serialize DefModule where
deserialize = toDefModule
serialize = fromDefModule
----------------------------------------
-- Do
----------------------------------------
nameDo :: NameSymbol.T
nameDo = ":do"
isDo :: Sexp.T -> Bool
isDo (Sexp.Cons form _) = Sexp.isAtomNamed form nameDo
isDo _ = False
toDo :: Sexp.T -> Maybe Do
toDo form
| isDo form =
case form of
_nameDo Sexp.:> sexp1 ->
Do sexp1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDo :: Do -> Sexp.T
fromDo (Do sexp1) =
Sexp.listStar [Sexp.atom nameDo, sexp1]
instance Sexp.Serialize Do where
deserialize = toDo
serialize = fromDo
----------------------------------------
LetModule
----------------------------------------
nameLetModule :: NameSymbol.T
nameLetModule = ":let-mod"
isLetModule :: Sexp.T -> Bool
isLetModule (Sexp.Cons form _) = Sexp.isAtomNamed form nameLetModule
isLetModule _ = False
toLetModule :: Sexp.T -> Maybe LetModule
toLetModule form
| isLetModule form =
case form of
_nameLetModule Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> sexp4 Sexp.:> Sexp.Nil ->
LetModule sexp1 sexp2 sexp3 sexp4 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLetModule :: LetModule -> Sexp.T
fromLetModule (LetModule sexp1 sexp2 sexp3 sexp4) =
Sexp.list [Sexp.atom nameLetModule, sexp1, sexp2, sexp3, sexp4]
instance Sexp.Serialize LetModule where
deserialize = toLetModule
serialize = fromLetModule
----------------------------------------
-- Effect
----------------------------------------
nameEffect :: NameSymbol.T
nameEffect = ":defeff"
isEffect :: Sexp.T -> Bool
isEffect (Sexp.Cons form _) = Sexp.isAtomNamed form nameEffect
isEffect _ = False
toEffect :: Sexp.T -> Maybe Effect
toEffect form
| isEffect form =
case form of
_nameEffect Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Effect sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromEffect :: Effect -> Sexp.T
fromEffect (Effect sexp1 sexp2) =
Sexp.list [Sexp.atom nameEffect, sexp1, sexp2]
instance Sexp.Serialize Effect where
deserialize = toEffect
serialize = fromEffect
----------------------------------------
DefHandler
----------------------------------------
nameDefHandler :: NameSymbol.T
nameDefHandler = ":defhandler"
isDefHandler :: Sexp.T -> Bool
isDefHandler (Sexp.Cons form _) = Sexp.isAtomNamed form nameDefHandler
isDefHandler _ = False
toDefHandler :: Sexp.T -> Maybe DefHandler
toDefHandler form
| isDefHandler form =
case form of
_nameDefHandler Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
DefHandler sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDefHandler :: DefHandler -> Sexp.T
fromDefHandler (DefHandler sexp1 sexp2) =
Sexp.list [Sexp.atom nameDefHandler, sexp1, sexp2]
instance Sexp.Serialize DefHandler where
deserialize = toDefHandler
serialize = fromDefHandler
----------------------------------------
LetRet
----------------------------------------
nameLetRet :: NameSymbol.T
nameLetRet = ":defret"
isLetRet :: Sexp.T -> Bool
isLetRet (Sexp.Cons form _) = Sexp.isAtomNamed form nameLetRet
isLetRet _ = False
toLetRet :: Sexp.T -> Maybe LetRet
toLetRet form
| isLetRet form =
case form of
_nameLetRet Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
LetRet sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLetRet :: LetRet -> Sexp.T
fromLetRet (LetRet sexp1 sexp2) =
Sexp.list [Sexp.atom nameLetRet, sexp1, sexp2]
instance Sexp.Serialize LetRet where
deserialize = toLetRet
serialize = fromLetRet
----------------------------------------
LetOp
----------------------------------------
nameLetOp :: NameSymbol.T
nameLetOp = ":defop"
isLetOp :: Sexp.T -> Bool
isLetOp (Sexp.Cons form _) = Sexp.isAtomNamed form nameLetOp
isLetOp _ = False
toLetOp :: Sexp.T -> Maybe LetOp
toLetOp form
| isLetOp form =
case form of
_nameLetOp Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> Sexp.Nil ->
LetOp sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLetOp :: LetOp -> Sexp.T
fromLetOp (LetOp sexp1 sexp2 sexp3) =
Sexp.list [Sexp.atom nameLetOp, sexp1, sexp2, sexp3]
instance Sexp.Serialize LetOp where
deserialize = toLetOp
serialize = fromLetOp
----------------------------------------
-- RecordDec
----------------------------------------
nameRecordDec :: NameSymbol.T
nameRecordDec = ":record-d"
isRecordDec :: Sexp.T -> Bool
isRecordDec (Sexp.Cons form _) = Sexp.isAtomNamed form nameRecordDec
isRecordDec _ = False
toRecordDec :: Sexp.T -> Maybe RecordDec
toRecordDec form
| isRecordDec form =
case form of
_nameRecordDec Sexp.:> nameUsage1
| Just nameUsage1 <- toNameUsage `fromStarList` nameUsage1 ->
RecordDec nameUsage1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromRecordDec :: RecordDec -> Sexp.T
fromRecordDec (RecordDec nameUsage1) =
Sexp.listStar [Sexp.atom nameRecordDec, fromNameUsage `toStarList` nameUsage1]
instance Sexp.Serialize RecordDec where
deserialize = toRecordDec
serialize = fromRecordDec
----------------------------------------
-- Primitive
----------------------------------------
namePrimitive :: NameSymbol.T
namePrimitive = ":primitive"
isPrimitive :: Sexp.T -> Bool
isPrimitive (Sexp.Cons form _) = Sexp.isAtomNamed form namePrimitive
isPrimitive _ = False
toPrimitive :: Sexp.T -> Maybe Primitive
toPrimitive form
| isPrimitive form =
case form of
_namePrimitive Sexp.:> sexp1 Sexp.:> Sexp.Nil ->
Primitive sexp1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromPrimitive :: Primitive -> Sexp.T
fromPrimitive (Primitive sexp1) =
Sexp.list [Sexp.atom namePrimitive, sexp1]
instance Sexp.Serialize Primitive where
deserialize = toPrimitive
serialize = fromPrimitive
----------------------------------------
-- Binder
----------------------------------------
nameBinder :: NameSymbol.T
nameBinder = ":<-"
isBinder :: Sexp.T -> Bool
isBinder (Sexp.Cons form _) = Sexp.isAtomNamed form nameBinder
isBinder _ = False
toBinder :: Sexp.T -> Maybe Binder
toBinder form
| isBinder form =
case form of
_nameBinder Sexp.:> nameSymbol1 Sexp.:> sexp2 Sexp.:> Sexp.Nil
| Just nameSymbol1 <- toNameSymbol nameSymbol1 ->
Binder nameSymbol1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromBinder :: Binder -> Sexp.T
fromBinder (Binder nameSymbol1 sexp2) =
Sexp.list [Sexp.atom nameBinder, fromNameSymbol nameSymbol1, sexp2]
instance Sexp.Serialize Binder where
deserialize = toBinder
serialize = fromBinder
----------------------------------------
DoDeep
----------------------------------------
nameDoDeep :: NameSymbol.T
nameDoDeep = ":do"
isDoDeep :: Sexp.T -> Bool
isDoDeep (Sexp.Cons form _) = Sexp.isAtomNamed form nameDoDeep
isDoDeep _ = False
toDoDeep :: Sexp.T -> Maybe DoDeep
toDoDeep form
| isDoDeep form =
case form of
_nameDoDeep Sexp.:> doBodyFull1
| Just doBodyFull1 <- toDoBodyFull `fromStarList` doBodyFull1 ->
DoDeep doBodyFull1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDoDeep :: DoDeep -> Sexp.T
fromDoDeep (DoDeep doBodyFull1) =
Sexp.listStar [Sexp.atom nameDoDeep, fromDoBodyFull `toStarList` doBodyFull1]
instance Sexp.Serialize DoDeep where
deserialize = toDoDeep
serialize = fromDoDeep
----------------------------------------
-- DoPure
----------------------------------------
nameDoPure :: NameSymbol.T
nameDoPure = ":do-pure"
isDoPure :: Sexp.T -> Bool
isDoPure (Sexp.Cons form _) = Sexp.isAtomNamed form nameDoPure
isDoPure _ = False
toDoPure :: Sexp.T -> Maybe DoPure
toDoPure form
| isDoPure form =
case form of
_nameDoPure Sexp.:> sexp1 Sexp.:> Sexp.Nil ->
DoPure sexp1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDoPure :: DoPure -> Sexp.T
fromDoPure (DoPure sexp1) =
Sexp.list [Sexp.atom nameDoPure, sexp1]
instance Sexp.Serialize DoPure where
deserialize = toDoPure
serialize = fromDoPure
----------------------------------------
-- DoOp
----------------------------------------
nameDoOp :: NameSymbol.T
nameDoOp = ":do-op"
isDoOp :: Sexp.T -> Bool
isDoOp (Sexp.Cons form _) = Sexp.isAtomNamed form nameDoOp
isDoOp _ = False
toDoOp :: Sexp.T -> Maybe DoOp
toDoOp form
| isDoOp form =
case form of
_nameDoOp Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
DoOp sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDoOp :: DoOp -> Sexp.T
fromDoOp (DoOp sexp1 sexp2) =
Sexp.list [Sexp.atom nameDoOp, sexp1, sexp2]
instance Sexp.Serialize DoOp where
deserialize = toDoOp
serialize = fromDoOp
----------------------------------------
-- Via
----------------------------------------
nameVia :: NameSymbol.T
nameVia = ":via"
isVia :: Sexp.T -> Bool
isVia (Sexp.Cons form _) = Sexp.isAtomNamed form nameVia
isVia _ = False
toVia :: Sexp.T -> Maybe Via
toVia form
| isVia form =
case form of
_nameVia Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Via sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromVia :: Via -> Sexp.T
fromVia (Via sexp1 sexp2) =
Sexp.list [Sexp.atom nameVia, sexp1, sexp2]
instance Sexp.Serialize Via where
deserialize = toVia
serialize = fromVia
----------------------------------------
-- Header
----------------------------------------
nameHeader :: NameSymbol.T
nameHeader = ":header"
isHeader :: Sexp.T -> Bool
isHeader (Sexp.Cons form _) = Sexp.isAtomNamed form nameHeader
isHeader _ = False
toHeader :: Sexp.T -> Maybe Header
toHeader form
| isHeader form =
case form of
_nameHeader Sexp.:> nameSymbol1 Sexp.:> sexp2
| Just nameSymbol1 <- toNameSymbol nameSymbol1 ->
Header nameSymbol1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromHeader :: Header -> Sexp.T
fromHeader (Header nameSymbol1 sexp2) =
Sexp.listStar [Sexp.atom nameHeader, fromNameSymbol nameSymbol1, sexp2]
instance Sexp.Serialize Header where
deserialize = toHeader
serialize = fromHeader
| null | https://raw.githubusercontent.com/mariari/Misc-ML-Scripts/376a7d55b565bf9205e697c5c3b78e1d6b6aedcd/Haskell/Sexp/src/Data/Sexp/Structure/Parsing.hs | haskell | # LANGUAGE DeriveTraversable #
|
Hardening S-expressions into a more readable form. Here we use a
mixture of record structures and aliases. Each cover a form that we
wish to talk about rather than just match away at
- _The form for transformation follows this structure_
-- the data type
data Form = ... deriving (Show)
from<Form> :: <Form> -> Sexp.T
+ With the following properties of the forms
#+begin_src haskell
to<Form> 。 from<Form> = Just
#+end_src
_TODO_
Haskell... =to<Form>= and =From<From>= have the exact same signature
hand in the code that uses this
can automatically fill in this meta data
| @Defun@ is the base defun structure
currently it does not have matching
| @Type@ is the type declaration structure
TODO ∷ we should really have a field the signature currently we
don't really support that without doing it by hand. Maybe our
generator should help here, or we should have a way of talking
about named arguments somehow, and unfolding the slots in a
way....
| @PredAns@ is an abstraction over questions and answers
| @Signature@ is the signature of the term
| @LetType@ is the let-type form of the language
| @Let@ is the let form of the language
it has a name, arguments, body, and the body
| @DeconBody@ is an abstraction over a matching body form
| @NotPunned@ represents a punned type name in a record
| @Infix@ represents an infix function
| @DefModule@ - Stands in for a module declaration
| @LefModule@ - Stands in for a module let declaration
------------------------------------------------------------------------------
Converter functions
The format for these are
from<Form> :: <Form> -> Sexp.T
------------------------------------------------------------------------------
-----------------------------------------
Not Generated, due to limited generation
-----------------------------------------
------------------
------------------
------------------
Name Bind
------------------
------------------
Do Body Full
------------------
TODO ∷ Change the frontend generator, as this does not fulfill it.
--------------------------------------
Generated
--------------------------------------
--------------------------------------
Type
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
Include
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
Let
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
Cond
--------------------------------------
--------------------------------------
DeconBody
--------------------------------------
--------------------------------------
Case
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
Lambda
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
Record
--------------------------------------
--------------------------------------
Infix
--------------------------------------
--------------------------------------
OpenIn
--------------------------------------
--------------------------------------
Open
--------------------------------------
--------------------------------------
Declare
--------------------------------------
--------------------------------------
Declaim
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
Do
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
Effect
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
RecordDec
--------------------------------------
--------------------------------------
Primitive
--------------------------------------
--------------------------------------
Binder
--------------------------------------
--------------------------------------
--------------------------------------
--------------------------------------
DoPure
--------------------------------------
--------------------------------------
DoOp
--------------------------------------
--------------------------------------
Via
--------------------------------------
--------------------------------------
Header
-------------------------------------- | # LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# + begin_src haskell
is < Form > : : Sexp . T - > Bool
to < Form > : : Sexp . T - > Maybe < Form >
# + end_src
∀ s : Sexp . is < Form > s = True ⟷ is - just ( to < Form > s )
1 . Figure out if we can even express a spec system in
2 . replace the repeat code with the = to < Form>= with an abstraction
3 . put the meta data with the form so we do n't have to do it by
1 . Use = . Library . LineNum=
2 . append the = Form= With this
3 . have to < Form > fill this
4 . Have extra smart consturctors that are = < form>= , so that we
module Data.Sexp.Structure.Parsing where
import Mari.Library hiding (Type)
import qualified Mari.Library.NameSymbol as NameSymbol
import qualified Data.Sexp as Sexp
import Data.Sexp.Structure.Helpers
data Defun = Defun
{ defunName :: Sexp.T,
defunArgs :: Sexp.T,
defunBody :: Sexp.T
}
deriving (Show)
data Include = Include
{ includeName :: NameSymbol.T
}
deriving (Show)
data Alias = Alias
{ aliasName :: NameSymbol.T,
aliasModuleOf :: NameSymbol.T
}
deriving (Show)
data Type = Type
typeNameAndSig :: Sexp.T,
typeArgs :: Sexp.T,
typeBody :: Sexp.T
}
deriving (Show)
data PredAns = PredAns {predAnsPredicate :: Sexp.T, predAnsAnswer :: Sexp.T}
deriving (Show)
| @Cond@ here Cond form takes a list of predicate answers
newtype Cond = Cond {condEntailments :: [PredAns]} deriving (Show)
data Signature = Signature
{ signatureName :: Sexp.T,
signatureSig :: Sexp.T
}
deriving (Show)
data LetSignature = LetSignature
{ letSignatureName :: Sexp.T,
letSignatureSig :: Sexp.T,
letSignatureRest :: Sexp.T
}
deriving (Show)
data LetType = LetType
{ letTypeNameAndSig :: Sexp.T,
letTypeArgs :: Sexp.T,
letTypeBody :: Sexp.T,
letTypeRest :: Sexp.T
}
deriving (Show)
data Let = Let
{ letName :: Sexp.T,
letArgs :: Sexp.T,
letBody :: Sexp.T,
letRest :: Sexp.T
}
deriving (Show)
data Case = Case
{ caseOn :: Sexp.T,
caseImplications :: [DeconBody]
}
deriving (Show)
data DeconBody = DeconBody
{ deconBodyDeconsturctor :: Sexp.T,
deconBodyBody :: Sexp.T
}
deriving (Show)
data Arrow = Arrow
{ arrowName :: Sexp.T,
arrowBody :: Sexp.T
}
deriving (Show)
data Lambda = Lambda
{ lambdaArgs :: Sexp.T,
lambdaBody :: Sexp.T
}
deriving (Show)
| @NameBind@ represents a type naming scheme in a record
data NameBind = Pun Punned | NotPun NotPunned
deriving (Show)
data NotPunned = NotPunned
{ notPunnedName :: Sexp.T,
notPunnedValue :: Sexp.T
}
deriving (Show)
data NameUsage = NameUsage
{ nameUsageName :: Sexp.T,
nameUsageUsage :: Sexp.T,
nameUsageValue :: Sexp.T
}
deriving (Show)
newtype Punned = Punned
{ punnedName :: Sexp.T
}
deriving (Show)
newtype Record = Record
{ recordValue :: [NameBind]
}
deriving (Show)
newtype RecordDec = RecordDec
{ recordDecValue :: [NameUsage]
}
deriving (Show)
data Infix = Infix
{ infixOp :: Sexp.T,
infixLeft :: Sexp.T,
infixRight :: Sexp.T
}
deriving (Show)
newtype Open = Open
{ openName :: Sexp.T
}
deriving (Show)
data OpenIn = OpenIn
{ openInName :: Sexp.T,
openInBody :: Sexp.T
}
deriving (Show)
newtype Declare = Declare
{ declareClaim :: Sexp.T
}
deriving (Show)
data Declaim = Declaim
{ declaimClaim :: Sexp.T,
declaimBody :: Sexp.T
}
deriving (Show)
data DefModule = DefModule
{ defModuleName :: Sexp.T,
defModuleArgs :: Sexp.T,
defModuleBody :: Sexp.T
}
deriving (Show)
data LetModule = LetModule
{ letModuleName :: Sexp.T,
letModuleArgs :: Sexp.T,
letModuleBody :: Sexp.T,
letModuleRest :: Sexp.T
}
deriving (Show)
newtype Primitive = Primitive
{ primitiveName :: Sexp.T
}
deriving (Show)
data Effect = Effect
{ effectName :: Sexp.T,
effectOps :: Sexp.T
}
deriving (Show)
data DefHandler = DefHandler
{ defHandlerName :: Sexp.T,
defHandlerOps :: Sexp.T
}
deriving (Show)
data LetOp = LetOp
{ letOpName :: Sexp.T,
letOpArgs :: Sexp.T,
letOpBody :: Sexp.T
}
deriving (Show)
data LetRet = LetRet
{ letRetArg :: Sexp.T,
letRetBody :: Sexp.T
}
deriving (Show)
newtype Do = Do
{ doStatements :: Sexp.T
}
deriving (Show)
newtype DoDeep = DoDeep
{ doDeepStatements :: [DoBodyFull]
}
deriving (Show)
data DoBodyFull
= WithBinder
{ doBodyFullName :: NameSymbol.T,
doBodyFullBBody :: Sexp.T
}
| NoBinder {doBodyFullBody :: Sexp.T}
deriving (Show)
Used to transform into WithBinder
data Binder = Binder
{ binderName :: NameSymbol.T,
binderBody :: Sexp.T
}
deriving (Show)
Used to for
newtype DoBody = DoBody {doBodySexp :: Sexp.T}
data DoOp = DoOp
{ doOpName :: Sexp.T,
doOpArgs :: Sexp.T
}
deriving (Show)
newtype DoPure = DoPure
{ doPureArg :: Sexp.T
}
deriving (Show)
data Via = Via
{ viaHandler :: Sexp.T,
viaProgram :: Sexp.T
}
deriving (Show)
data Header = Header
{ headerName :: NameSymbol.T,
headerSexps :: Sexp.T
}
deriving (Show)
name < Form > : : NameSymbol . T
is < Form > : : Sexp . T - > Bool
to < Form > : : Sexp . T - > Maybe < Form >
NotPunned no Grouping
fromNotPunnedGroup :: [NotPunned] -> Sexp.T
fromNotPunnedGroup = Sexp.unGroupBy2 . toStarList fromNotPunned
toNotPunnedGroup :: Sexp.T -> Maybe [NotPunned]
toNotPunnedGroup = fromStarList toNotPunned . Sexp.groupBy2
toNameBind :: Sexp.T -> Maybe NameBind
toNameBind sexp =
fmap Pun (toPunned sexp) <|> fmap NotPun (toNotPunned sexp)
fromNameBind :: NameBind -> Sexp.T
fromNameBind (Pun pun) = fromPunned pun
fromNameBind (NotPun notPun) = fromNotPunned notPun
instance Sexp.Serialize NameBind where
deserialize = toNameBind
serialize = fromNameBind
toDoBodyFull :: Sexp.T -> Maybe DoBodyFull
toDoBodyFull sexp =
fmap binderToBody (toBinder sexp) <|> Just (NoBinder sexp)
fromDoBodyFull :: DoBodyFull -> Sexp.T
fromDoBodyFull (NoBinder sexp) = sexp
fromDoBodyFull (WithBinder name body) = Binder name body |> fromBinder
binderToBody :: Binder -> DoBodyFull
binderToBody (Binder name body) = WithBinder name body
instance Sexp.Serialize DoBodyFull where
deserialize = toDoBodyFull
serialize = fromDoBodyFull
nameType :: NameSymbol.T
nameType = "type"
isType :: Sexp.T -> Bool
isType (Sexp.Cons form _) = Sexp.isAtomNamed form nameType
isType _ = False
toType :: Sexp.T -> Maybe Type
toType form
| isType form =
case form of
_nameType Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 ->
Type sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromType :: Type -> Sexp.T
fromType (Type sexp1 sexp2 sexp3) =
Sexp.listStar [Sexp.atom nameType, sexp1, sexp2, sexp3]
instance Sexp.Serialize Type where
deserialize = toType
serialize = fromType
LetType
nameLetType :: NameSymbol.T
nameLetType = ":let-type"
isLetType :: Sexp.T -> Bool
isLetType (Sexp.Cons form _) = Sexp.isAtomNamed form nameLetType
isLetType _ = False
toLetType :: Sexp.T -> Maybe LetType
toLetType form
| isLetType form =
case form of
_nameLetType Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> sexp4 Sexp.:> Sexp.Nil ->
LetType sexp1 sexp2 sexp3 sexp4 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLetType :: LetType -> Sexp.T
fromLetType (LetType sexp1 sexp2 sexp3 sexp4) =
Sexp.list [Sexp.atom nameLetType, sexp1, sexp2, sexp3, sexp4]
instance Sexp.Serialize LetType where
deserialize = toLetType
serialize = fromLetType
nameInclude :: NameSymbol.T
nameInclude = ":include"
isInclude :: Sexp.T -> Bool
isInclude (Sexp.Cons form _) = Sexp.isAtomNamed form nameInclude
isInclude _ = False
toInclude :: Sexp.T -> Maybe Include
toInclude form
| isInclude form =
case form of
_nameInclude Sexp.:> nameSymbol1 Sexp.:> Sexp.Nil
| Just nameSymbol1 <- toNameSymbol nameSymbol1 ->
Include nameSymbol1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromInclude :: Include -> Sexp.T
fromInclude (Include nameSymbol1) =
Sexp.list [Sexp.atom nameInclude, fromNameSymbol nameSymbol1]
instance Sexp.Serialize Include where
deserialize = toInclude
serialize = fromInclude
nameAlias :: NameSymbol.T
nameAlias = ":alias"
isAlias :: Sexp.T -> Bool
isAlias (Sexp.Cons form _) = Sexp.isAtomNamed form nameAlias
isAlias _ = False
toAlias :: Sexp.T -> Maybe Alias
toAlias form
| isAlias form =
case form of
_nameAlias Sexp.:> nameSymbol1 Sexp.:> nameSymbol2 Sexp.:> Sexp.Nil
| Just nameSymbol1 <- toNameSymbol nameSymbol1,
Just nameSymbol2 <- toNameSymbol nameSymbol2 ->
Alias nameSymbol1 nameSymbol2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromAlias :: Alias -> Sexp.T
fromAlias (Alias nameSymbol1 nameSymbol2) =
Sexp.list [Sexp.atom nameAlias, fromNameSymbol nameSymbol1, fromNameSymbol nameSymbol2]
instance Sexp.Serialize Alias where
deserialize = toAlias
serialize = fromAlias
Defun
nameDefun :: NameSymbol.T
nameDefun = ":defun"
isDefun :: Sexp.T -> Bool
isDefun (Sexp.Cons form _) = Sexp.isAtomNamed form nameDefun
isDefun _ = False
toDefun :: Sexp.T -> Maybe Defun
toDefun form
| isDefun form =
case form of
_nameDefun Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> Sexp.Nil ->
Defun sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDefun :: Defun -> Sexp.T
fromDefun (Defun sexp1 sexp2 sexp3) =
Sexp.list [Sexp.atom nameDefun, sexp1, sexp2, sexp3]
instance Sexp.Serialize Defun where
deserialize = toDefun
serialize = fromDefun
Signature
nameSignature :: NameSymbol.T
nameSignature = ":defsig"
isSignature :: Sexp.T -> Bool
isSignature (Sexp.Cons form _) = Sexp.isAtomNamed form nameSignature
isSignature _ = False
toSignature :: Sexp.T -> Maybe Signature
toSignature form
| isSignature form =
case form of
_nameSignature Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Signature sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromSignature :: Signature -> Sexp.T
fromSignature (Signature sexp1 sexp2) =
Sexp.list [Sexp.atom nameSignature, sexp1, sexp2]
instance Sexp.Serialize Signature where
deserialize = toSignature
serialize = fromSignature
LetSignature
nameLetSignature :: NameSymbol.T
nameLetSignature = ":let-sig"
isLetSignature :: Sexp.T -> Bool
isLetSignature (Sexp.Cons form _) = Sexp.isAtomNamed form nameLetSignature
isLetSignature _ = False
toLetSignature :: Sexp.T -> Maybe LetSignature
toLetSignature form
| isLetSignature form =
case form of
_nameLetSignature Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> Sexp.Nil ->
LetSignature sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLetSignature :: LetSignature -> Sexp.T
fromLetSignature (LetSignature sexp1 sexp2 sexp3) =
Sexp.list [Sexp.atom nameLetSignature, sexp1, sexp2, sexp3]
instance Sexp.Serialize LetSignature where
deserialize = toLetSignature
serialize = fromLetSignature
nameLet :: NameSymbol.T
nameLet = "let"
isLet :: Sexp.T -> Bool
isLet (Sexp.Cons form _) = Sexp.isAtomNamed form nameLet
isLet _ = False
toLet :: Sexp.T -> Maybe Let
toLet form
| isLet form =
case form of
_nameLet Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> sexp4 Sexp.:> Sexp.Nil ->
Let sexp1 sexp2 sexp3 sexp4 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLet :: Let -> Sexp.T
fromLet (Let sexp1 sexp2 sexp3 sexp4) =
Sexp.list [Sexp.atom nameLet, sexp1, sexp2, sexp3, sexp4]
instance Sexp.Serialize Let where
deserialize = toLet
serialize = fromLet
PredAns
toPredAns :: Sexp.T -> Maybe PredAns
toPredAns form =
case form of
sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
PredAns sexp1 sexp2 |> Just
_ ->
Nothing
fromPredAns :: PredAns -> Sexp.T
fromPredAns (PredAns sexp1 sexp2) =
Sexp.list [sexp1, sexp2]
instance Sexp.Serialize PredAns where
deserialize = toPredAns
serialize = fromPredAns
nameCond :: NameSymbol.T
nameCond = ":cond"
isCond :: Sexp.T -> Bool
isCond (Sexp.Cons form _) = Sexp.isAtomNamed form nameCond
isCond _ = False
toCond :: Sexp.T -> Maybe Cond
toCond form
| isCond form =
case form of
_nameCond Sexp.:> predAns1
| Just predAns1 <- toPredAns `fromStarList` predAns1 ->
Cond predAns1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromCond :: Cond -> Sexp.T
fromCond (Cond predAns1) =
Sexp.listStar [Sexp.atom nameCond, fromPredAns `toStarList` predAns1]
instance Sexp.Serialize Cond where
deserialize = toCond
serialize = fromCond
toDeconBody :: Sexp.T -> Maybe DeconBody
toDeconBody form =
case form of
sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
DeconBody sexp1 sexp2 |> Just
_ ->
Nothing
fromDeconBody :: DeconBody -> Sexp.T
fromDeconBody (DeconBody sexp1 sexp2) =
Sexp.list [sexp1, sexp2]
instance Sexp.Serialize DeconBody where
deserialize = toDeconBody
serialize = fromDeconBody
nameCase :: NameSymbol.T
nameCase = "case"
isCase :: Sexp.T -> Bool
isCase (Sexp.Cons form _) = Sexp.isAtomNamed form nameCase
isCase _ = False
toCase :: Sexp.T -> Maybe Case
toCase form
| isCase form =
case form of
_nameCase Sexp.:> sexp1 Sexp.:> deconBody2
| Just deconBody2 <- toDeconBody `fromStarList` deconBody2 ->
Case sexp1 deconBody2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromCase :: Case -> Sexp.T
fromCase (Case sexp1 deconBody2) =
Sexp.listStar [Sexp.atom nameCase, sexp1, fromDeconBody `toStarList` deconBody2]
instance Sexp.Serialize Case where
deserialize = toCase
serialize = fromCase
Arrow
nameArrow :: NameSymbol.T
nameArrow = "%<-"
isArrow :: Sexp.T -> Bool
isArrow (Sexp.Cons form _) = Sexp.isAtomNamed form nameArrow
isArrow _ = False
toArrow :: Sexp.T -> Maybe Arrow
toArrow form
| isArrow form =
case form of
_nameArrow Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Arrow sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromArrow :: Arrow -> Sexp.T
fromArrow (Arrow sexp1 sexp2) =
Sexp.list [Sexp.atom nameArrow, sexp1, sexp2]
instance Sexp.Serialize Arrow where
deserialize = toArrow
serialize = fromArrow
nameLambda :: NameSymbol.T
nameLambda = ":lambda"
isLambda :: Sexp.T -> Bool
isLambda (Sexp.Cons form _) = Sexp.isAtomNamed form nameLambda
isLambda _ = False
toLambda :: Sexp.T -> Maybe Lambda
toLambda form
| isLambda form =
case form of
_nameLambda Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Lambda sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLambda :: Lambda -> Sexp.T
fromLambda (Lambda sexp1 sexp2) =
Sexp.list [Sexp.atom nameLambda, sexp1, sexp2]
instance Sexp.Serialize Lambda where
deserialize = toLambda
serialize = fromLambda
Punned
toPunned :: Sexp.T -> Maybe Punned
toPunned form =
case form of
sexp1 Sexp.:> Sexp.Nil ->
Punned sexp1 |> Just
_ ->
Nothing
fromPunned :: Punned -> Sexp.T
fromPunned (Punned sexp1) =
Sexp.list [sexp1]
instance Sexp.Serialize Punned where
deserialize = toPunned
serialize = fromPunned
NotPunned
toNotPunned :: Sexp.T -> Maybe NotPunned
toNotPunned form =
case form of
sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
NotPunned sexp1 sexp2 |> Just
_ ->
Nothing
fromNotPunned :: NotPunned -> Sexp.T
fromNotPunned (NotPunned sexp1 sexp2) =
Sexp.list [sexp1, sexp2]
instance Sexp.Serialize NotPunned where
deserialize = toNotPunned
serialize = fromNotPunned
NameUsage
toNameUsage :: Sexp.T -> Maybe NameUsage
toNameUsage form =
case form of
sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> Sexp.Nil ->
NameUsage sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
fromNameUsage :: NameUsage -> Sexp.T
fromNameUsage (NameUsage sexp1 sexp2 sexp3) =
Sexp.list [sexp1, sexp2, sexp3]
instance Sexp.Serialize NameUsage where
deserialize = toNameUsage
serialize = fromNameUsage
nameRecord :: NameSymbol.T
nameRecord = ":record"
isRecord :: Sexp.T -> Bool
isRecord (Sexp.Cons form _) = Sexp.isAtomNamed form nameRecord
isRecord _ = False
toRecord :: Sexp.T -> Maybe Record
toRecord form
| isRecord form =
case form of
_nameRecord Sexp.:> nameBind1
| Just nameBind1 <- toNameBind `fromStarList` nameBind1 ->
Record nameBind1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromRecord :: Record -> Sexp.T
fromRecord (Record nameBind1) =
Sexp.listStar [Sexp.atom nameRecord, fromNameBind `toStarList` nameBind1]
instance Sexp.Serialize Record where
deserialize = toRecord
serialize = fromRecord
nameInfix :: NameSymbol.T
nameInfix = ":infix"
isInfix :: Sexp.T -> Bool
isInfix (Sexp.Cons form _) = Sexp.isAtomNamed form nameInfix
isInfix _ = False
toInfix :: Sexp.T -> Maybe Infix
toInfix form
| isInfix form =
case form of
_nameInfix Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> Sexp.Nil ->
Infix sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromInfix :: Infix -> Sexp.T
fromInfix (Infix sexp1 sexp2 sexp3) =
Sexp.list [Sexp.atom nameInfix, sexp1, sexp2, sexp3]
instance Sexp.Serialize Infix where
deserialize = toInfix
serialize = fromInfix
nameOpenIn :: NameSymbol.T
nameOpenIn = ":open-in"
isOpenIn :: Sexp.T -> Bool
isOpenIn (Sexp.Cons form _) = Sexp.isAtomNamed form nameOpenIn
isOpenIn _ = False
toOpenIn :: Sexp.T -> Maybe OpenIn
toOpenIn form
| isOpenIn form =
case form of
_nameOpenIn Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
OpenIn sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromOpenIn :: OpenIn -> Sexp.T
fromOpenIn (OpenIn sexp1 sexp2) =
Sexp.list [Sexp.atom nameOpenIn, sexp1, sexp2]
instance Sexp.Serialize OpenIn where
deserialize = toOpenIn
serialize = fromOpenIn
nameOpen :: NameSymbol.T
nameOpen = "open"
isOpen :: Sexp.T -> Bool
isOpen (Sexp.Cons form _) = Sexp.isAtomNamed form nameOpen
isOpen _ = False
toOpen :: Sexp.T -> Maybe Open
toOpen form
| isOpen form =
case form of
_nameOpen Sexp.:> sexp1 Sexp.:> Sexp.Nil ->
Open sexp1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromOpen :: Open -> Sexp.T
fromOpen (Open sexp1) =
Sexp.list [Sexp.atom nameOpen, sexp1]
instance Sexp.Serialize Open where
deserialize = toOpen
serialize = fromOpen
nameDeclare :: NameSymbol.T
nameDeclare = "declare"
isDeclare :: Sexp.T -> Bool
isDeclare (Sexp.Cons form _) = Sexp.isAtomNamed form nameDeclare
isDeclare _ = False
toDeclare :: Sexp.T -> Maybe Declare
toDeclare form
| isDeclare form =
case form of
_nameDeclare Sexp.:> sexp1 Sexp.:> Sexp.Nil ->
Declare sexp1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDeclare :: Declare -> Sexp.T
fromDeclare (Declare sexp1) =
Sexp.list [Sexp.atom nameDeclare, sexp1]
instance Sexp.Serialize Declare where
deserialize = toDeclare
serialize = fromDeclare
nameDeclaim :: NameSymbol.T
nameDeclaim = ":declaim"
isDeclaim :: Sexp.T -> Bool
isDeclaim (Sexp.Cons form _) = Sexp.isAtomNamed form nameDeclaim
isDeclaim _ = False
toDeclaim :: Sexp.T -> Maybe Declaim
toDeclaim form
| isDeclaim form =
case form of
_nameDeclaim Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Declaim sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDeclaim :: Declaim -> Sexp.T
fromDeclaim (Declaim sexp1 sexp2) =
Sexp.list [Sexp.atom nameDeclaim, sexp1, sexp2]
instance Sexp.Serialize Declaim where
deserialize = toDeclaim
serialize = fromDeclaim
DefModule
nameDefModule :: NameSymbol.T
nameDefModule = ":defmodule"
isDefModule :: Sexp.T -> Bool
isDefModule (Sexp.Cons form _) = Sexp.isAtomNamed form nameDefModule
isDefModule _ = False
toDefModule :: Sexp.T -> Maybe DefModule
toDefModule form
| isDefModule form =
case form of
_nameDefModule Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 ->
DefModule sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDefModule :: DefModule -> Sexp.T
fromDefModule (DefModule sexp1 sexp2 sexp3) =
Sexp.listStar [Sexp.atom nameDefModule, sexp1, sexp2, sexp3]
instance Sexp.Serialize DefModule where
deserialize = toDefModule
serialize = fromDefModule
nameDo :: NameSymbol.T
nameDo = ":do"
isDo :: Sexp.T -> Bool
isDo (Sexp.Cons form _) = Sexp.isAtomNamed form nameDo
isDo _ = False
toDo :: Sexp.T -> Maybe Do
toDo form
| isDo form =
case form of
_nameDo Sexp.:> sexp1 ->
Do sexp1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDo :: Do -> Sexp.T
fromDo (Do sexp1) =
Sexp.listStar [Sexp.atom nameDo, sexp1]
instance Sexp.Serialize Do where
deserialize = toDo
serialize = fromDo
LetModule
nameLetModule :: NameSymbol.T
nameLetModule = ":let-mod"
isLetModule :: Sexp.T -> Bool
isLetModule (Sexp.Cons form _) = Sexp.isAtomNamed form nameLetModule
isLetModule _ = False
toLetModule :: Sexp.T -> Maybe LetModule
toLetModule form
| isLetModule form =
case form of
_nameLetModule Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> sexp4 Sexp.:> Sexp.Nil ->
LetModule sexp1 sexp2 sexp3 sexp4 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLetModule :: LetModule -> Sexp.T
fromLetModule (LetModule sexp1 sexp2 sexp3 sexp4) =
Sexp.list [Sexp.atom nameLetModule, sexp1, sexp2, sexp3, sexp4]
instance Sexp.Serialize LetModule where
deserialize = toLetModule
serialize = fromLetModule
nameEffect :: NameSymbol.T
nameEffect = ":defeff"
isEffect :: Sexp.T -> Bool
isEffect (Sexp.Cons form _) = Sexp.isAtomNamed form nameEffect
isEffect _ = False
toEffect :: Sexp.T -> Maybe Effect
toEffect form
| isEffect form =
case form of
_nameEffect Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Effect sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromEffect :: Effect -> Sexp.T
fromEffect (Effect sexp1 sexp2) =
Sexp.list [Sexp.atom nameEffect, sexp1, sexp2]
instance Sexp.Serialize Effect where
deserialize = toEffect
serialize = fromEffect
DefHandler
nameDefHandler :: NameSymbol.T
nameDefHandler = ":defhandler"
isDefHandler :: Sexp.T -> Bool
isDefHandler (Sexp.Cons form _) = Sexp.isAtomNamed form nameDefHandler
isDefHandler _ = False
toDefHandler :: Sexp.T -> Maybe DefHandler
toDefHandler form
| isDefHandler form =
case form of
_nameDefHandler Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
DefHandler sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDefHandler :: DefHandler -> Sexp.T
fromDefHandler (DefHandler sexp1 sexp2) =
Sexp.list [Sexp.atom nameDefHandler, sexp1, sexp2]
instance Sexp.Serialize DefHandler where
deserialize = toDefHandler
serialize = fromDefHandler
LetRet
nameLetRet :: NameSymbol.T
nameLetRet = ":defret"
isLetRet :: Sexp.T -> Bool
isLetRet (Sexp.Cons form _) = Sexp.isAtomNamed form nameLetRet
isLetRet _ = False
toLetRet :: Sexp.T -> Maybe LetRet
toLetRet form
| isLetRet form =
case form of
_nameLetRet Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
LetRet sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLetRet :: LetRet -> Sexp.T
fromLetRet (LetRet sexp1 sexp2) =
Sexp.list [Sexp.atom nameLetRet, sexp1, sexp2]
instance Sexp.Serialize LetRet where
deserialize = toLetRet
serialize = fromLetRet
LetOp
nameLetOp :: NameSymbol.T
nameLetOp = ":defop"
isLetOp :: Sexp.T -> Bool
isLetOp (Sexp.Cons form _) = Sexp.isAtomNamed form nameLetOp
isLetOp _ = False
toLetOp :: Sexp.T -> Maybe LetOp
toLetOp form
| isLetOp form =
case form of
_nameLetOp Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> sexp3 Sexp.:> Sexp.Nil ->
LetOp sexp1 sexp2 sexp3 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromLetOp :: LetOp -> Sexp.T
fromLetOp (LetOp sexp1 sexp2 sexp3) =
Sexp.list [Sexp.atom nameLetOp, sexp1, sexp2, sexp3]
instance Sexp.Serialize LetOp where
deserialize = toLetOp
serialize = fromLetOp
nameRecordDec :: NameSymbol.T
nameRecordDec = ":record-d"
isRecordDec :: Sexp.T -> Bool
isRecordDec (Sexp.Cons form _) = Sexp.isAtomNamed form nameRecordDec
isRecordDec _ = False
toRecordDec :: Sexp.T -> Maybe RecordDec
toRecordDec form
| isRecordDec form =
case form of
_nameRecordDec Sexp.:> nameUsage1
| Just nameUsage1 <- toNameUsage `fromStarList` nameUsage1 ->
RecordDec nameUsage1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromRecordDec :: RecordDec -> Sexp.T
fromRecordDec (RecordDec nameUsage1) =
Sexp.listStar [Sexp.atom nameRecordDec, fromNameUsage `toStarList` nameUsage1]
instance Sexp.Serialize RecordDec where
deserialize = toRecordDec
serialize = fromRecordDec
namePrimitive :: NameSymbol.T
namePrimitive = ":primitive"
isPrimitive :: Sexp.T -> Bool
isPrimitive (Sexp.Cons form _) = Sexp.isAtomNamed form namePrimitive
isPrimitive _ = False
toPrimitive :: Sexp.T -> Maybe Primitive
toPrimitive form
| isPrimitive form =
case form of
_namePrimitive Sexp.:> sexp1 Sexp.:> Sexp.Nil ->
Primitive sexp1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromPrimitive :: Primitive -> Sexp.T
fromPrimitive (Primitive sexp1) =
Sexp.list [Sexp.atom namePrimitive, sexp1]
instance Sexp.Serialize Primitive where
deserialize = toPrimitive
serialize = fromPrimitive
nameBinder :: NameSymbol.T
nameBinder = ":<-"
isBinder :: Sexp.T -> Bool
isBinder (Sexp.Cons form _) = Sexp.isAtomNamed form nameBinder
isBinder _ = False
toBinder :: Sexp.T -> Maybe Binder
toBinder form
| isBinder form =
case form of
_nameBinder Sexp.:> nameSymbol1 Sexp.:> sexp2 Sexp.:> Sexp.Nil
| Just nameSymbol1 <- toNameSymbol nameSymbol1 ->
Binder nameSymbol1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromBinder :: Binder -> Sexp.T
fromBinder (Binder nameSymbol1 sexp2) =
Sexp.list [Sexp.atom nameBinder, fromNameSymbol nameSymbol1, sexp2]
instance Sexp.Serialize Binder where
deserialize = toBinder
serialize = fromBinder
DoDeep
nameDoDeep :: NameSymbol.T
nameDoDeep = ":do"
isDoDeep :: Sexp.T -> Bool
isDoDeep (Sexp.Cons form _) = Sexp.isAtomNamed form nameDoDeep
isDoDeep _ = False
toDoDeep :: Sexp.T -> Maybe DoDeep
toDoDeep form
| isDoDeep form =
case form of
_nameDoDeep Sexp.:> doBodyFull1
| Just doBodyFull1 <- toDoBodyFull `fromStarList` doBodyFull1 ->
DoDeep doBodyFull1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDoDeep :: DoDeep -> Sexp.T
fromDoDeep (DoDeep doBodyFull1) =
Sexp.listStar [Sexp.atom nameDoDeep, fromDoBodyFull `toStarList` doBodyFull1]
instance Sexp.Serialize DoDeep where
deserialize = toDoDeep
serialize = fromDoDeep
nameDoPure :: NameSymbol.T
nameDoPure = ":do-pure"
isDoPure :: Sexp.T -> Bool
isDoPure (Sexp.Cons form _) = Sexp.isAtomNamed form nameDoPure
isDoPure _ = False
toDoPure :: Sexp.T -> Maybe DoPure
toDoPure form
| isDoPure form =
case form of
_nameDoPure Sexp.:> sexp1 Sexp.:> Sexp.Nil ->
DoPure sexp1 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDoPure :: DoPure -> Sexp.T
fromDoPure (DoPure sexp1) =
Sexp.list [Sexp.atom nameDoPure, sexp1]
instance Sexp.Serialize DoPure where
deserialize = toDoPure
serialize = fromDoPure
nameDoOp :: NameSymbol.T
nameDoOp = ":do-op"
isDoOp :: Sexp.T -> Bool
isDoOp (Sexp.Cons form _) = Sexp.isAtomNamed form nameDoOp
isDoOp _ = False
toDoOp :: Sexp.T -> Maybe DoOp
toDoOp form
| isDoOp form =
case form of
_nameDoOp Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
DoOp sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromDoOp :: DoOp -> Sexp.T
fromDoOp (DoOp sexp1 sexp2) =
Sexp.list [Sexp.atom nameDoOp, sexp1, sexp2]
instance Sexp.Serialize DoOp where
deserialize = toDoOp
serialize = fromDoOp
nameVia :: NameSymbol.T
nameVia = ":via"
isVia :: Sexp.T -> Bool
isVia (Sexp.Cons form _) = Sexp.isAtomNamed form nameVia
isVia _ = False
toVia :: Sexp.T -> Maybe Via
toVia form
| isVia form =
case form of
_nameVia Sexp.:> sexp1 Sexp.:> sexp2 Sexp.:> Sexp.Nil ->
Via sexp1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromVia :: Via -> Sexp.T
fromVia (Via sexp1 sexp2) =
Sexp.list [Sexp.atom nameVia, sexp1, sexp2]
instance Sexp.Serialize Via where
deserialize = toVia
serialize = fromVia
nameHeader :: NameSymbol.T
nameHeader = ":header"
isHeader :: Sexp.T -> Bool
isHeader (Sexp.Cons form _) = Sexp.isAtomNamed form nameHeader
isHeader _ = False
toHeader :: Sexp.T -> Maybe Header
toHeader form
| isHeader form =
case form of
_nameHeader Sexp.:> nameSymbol1 Sexp.:> sexp2
| Just nameSymbol1 <- toNameSymbol nameSymbol1 ->
Header nameSymbol1 sexp2 |> Just
_ ->
Nothing
| otherwise =
Nothing
fromHeader :: Header -> Sexp.T
fromHeader (Header nameSymbol1 sexp2) =
Sexp.listStar [Sexp.atom nameHeader, fromNameSymbol nameSymbol1, sexp2]
instance Sexp.Serialize Header where
deserialize = toHeader
serialize = fromHeader
|
b4e02b22da2a55f5112a7df5ca49571e754823023ee7c400c7c4f832b93edc73 | c-cube/ocaml-containers | t_bq.ml | module Test = (val Containers_testlib.make ~__FILE__ ())
open Test
open CCBlockingQueue;;
t @@ fun () ->
let q = create 1 in
let t1 =
CCThread.spawn (fun () ->
push q 1;
push q 2)
in
let t2 =
CCThread.spawn (fun () ->
push q 3;
push q 4)
in
let l = CCLock.create [] in
let t3 =
CCThread.spawn (fun () ->
for _i = 1 to 4 do
let x = take q in
CCLock.update l (fun l -> x :: l)
done)
in
Thread.join t1;
Thread.join t2;
Thread.join t3;
assert_equal [ 1; 2; 3; 4 ] (List.sort Stdlib.compare (CCLock.get l));
true
;;
t @@ fun () ->
let n = 1000 in
let lists =
[|
CCList.(1 -- n); CCList.(n + 1 -- (2 * n)); CCList.((2 * n) + 1 -- (3 * n));
|]
in
let q = create 2 in
let senders =
CCThread.Arr.spawn 3 (fun i ->
if i = 1 then
push_list q lists.(i)
(* test push_list *)
else
List.iter (push q) lists.(i))
in
let res = CCLock.create [] in
let receivers =
CCThread.Arr.spawn 3 (fun i ->
if i = 1 then (
let l = take_list q n in
CCLock.update res (fun acc -> l @ acc)
) else
for _j = 1 to n do
let x = take q in
CCLock.update res (fun acc -> x :: acc)
done)
in
CCThread.Arr.join senders;
CCThread.Arr.join receivers;
let l = CCLock.get res |> List.sort Stdlib.compare in
assert_equal CCList.(1 -- (3 * n)) l;
true
| null | https://raw.githubusercontent.com/c-cube/ocaml-containers/69f2805f1073c4ebd1063bbd58380d17e62f6324/tests/thread/t_bq.ml | ocaml | test push_list | module Test = (val Containers_testlib.make ~__FILE__ ())
open Test
open CCBlockingQueue;;
t @@ fun () ->
let q = create 1 in
let t1 =
CCThread.spawn (fun () ->
push q 1;
push q 2)
in
let t2 =
CCThread.spawn (fun () ->
push q 3;
push q 4)
in
let l = CCLock.create [] in
let t3 =
CCThread.spawn (fun () ->
for _i = 1 to 4 do
let x = take q in
CCLock.update l (fun l -> x :: l)
done)
in
Thread.join t1;
Thread.join t2;
Thread.join t3;
assert_equal [ 1; 2; 3; 4 ] (List.sort Stdlib.compare (CCLock.get l));
true
;;
t @@ fun () ->
let n = 1000 in
let lists =
[|
CCList.(1 -- n); CCList.(n + 1 -- (2 * n)); CCList.((2 * n) + 1 -- (3 * n));
|]
in
let q = create 2 in
let senders =
CCThread.Arr.spawn 3 (fun i ->
if i = 1 then
push_list q lists.(i)
else
List.iter (push q) lists.(i))
in
let res = CCLock.create [] in
let receivers =
CCThread.Arr.spawn 3 (fun i ->
if i = 1 then (
let l = take_list q n in
CCLock.update res (fun acc -> l @ acc)
) else
for _j = 1 to n do
let x = take q in
CCLock.update res (fun acc -> x :: acc)
done)
in
CCThread.Arr.join senders;
CCThread.Arr.join receivers;
let l = CCLock.get res |> List.sort Stdlib.compare in
assert_equal CCList.(1 -- (3 * n)) l;
true
|
f83cd12fced6d88ab2f12e32cf01bd809ab3a8e394d7354394bf3101395cb69c | aantron/hyper | connect.mli | This file is part of Hyper , released under the MIT license . See LICENSE.md
for details , or visit .
Copyright 2022
for details, or visit .
Copyright 2022 Anton Bachin *)
type 'a promise = 'a Dream_pure.Message.promise
type request = Dream_pure.Message.request
type response = Dream_pure.Message.response
(* val send : request -> response promise *)
val no_pool :
?transport:[ `HTTP1 | `HTTPS | `HTTP2 | `WS ] -> request -> response promise
(* Used for testing. *)
| null | https://raw.githubusercontent.com/aantron/hyper/d4f41825bd25b0da48cb75f127257204b46ce76a/src/http/connect.mli | ocaml | val send : request -> response promise
Used for testing. | This file is part of Hyper , released under the MIT license . See LICENSE.md
for details , or visit .
Copyright 2022
for details, or visit .
Copyright 2022 Anton Bachin *)
type 'a promise = 'a Dream_pure.Message.promise
type request = Dream_pure.Message.request
type response = Dream_pure.Message.response
val no_pool :
?transport:[ `HTTP1 | `HTTPS | `HTTP2 | `WS ] -> request -> response promise
|
5f20721ce02fcc6b73aa7cbd64a4d5bd661e0c917326e251fd30e606ec616c81 | ekmett/linear | Plucker.hs | module Plucker (tests) where
import Linear
import Linear.Plucker
import Linear.Plucker.Coincides
import Test.HUnit
ln2,ln3,ln4,ln5,ln6,ln7,ln8,ln9 :: Plucker Float
ln2 = plucker3D (V3 1 3 0) (V3 1 3 (-2)) -- starting line
ln3 = plucker3D (V3 2 3 0) (V3 2 3 (-2)) -- parallel
ln4 = plucker3D (V3 2 4 0) (V3 1 4 (-2)) -- ccw
ln5 = plucker3D (V3 (-2) 4 0) (V3 2 4 (-2)) -- cw
ln6 = plucker3D (V3 2 3 0) (V3 1 3 (-2)) -- intersect
ln7 = plucker3D (V3 1 3 0) (V3 1 3 2) -- reversed
ln8 = plucker3D (V3 0 4 4) (V3 0 (-4) (-4)) -- through origin
ln9 = Plucker 1 2 3 4 5 6 -- not a 3D line
tests :: Test
tests = test [ "parallel" ~: parallel ln2 ln3 ~?= True
, "CCW" ~: passes ln2 ln4 ~?= Counterclockwise
, "CW" ~: passes ln2 ln5 ~?= Clockwise
, "intersect1" ~: intersects ln2 ln6 ~?= True
, "intersect2" ~: intersects ln2 ln3 ~?= False
, "line equality 1" ~: Line ln2 == Line ln2 ~?= True
, "line equality 2" ~: Line ln2 == Line ln7 ~?= True
, "line equality 3" ~: Line ln2 == Ray ln7 ~?= True
, "line equality 4" ~: Ray ln2 == Line ln7 ~?= True
, "ray equality 1" ~: Ray ln2 == Ray ln7 ~?= False
, "ray equality 2" ~: Ray ln2 == Ray (3 *^ ln2) ~?= True
, "ray equality 3" ~: Ray ln2 == Ray (negate ln7) ~?= True
, "quadrance" ~: nearZero (quadranceToOrigin ln2 - 10) ~?= True
, "closest 1" ~:
nearZero (qd (V3 1 3 0) $ closestToOrigin ln2) ~?= True
, "closest 2" ~: nearZero (qd 0 $ closestToOrigin ln8) ~?= True
, "isLine 1" ~: isLine ln2 ~?= True
, "isLine 2" ~: isLine ln9 ~?= False ]
| null | https://raw.githubusercontent.com/ekmett/linear/9bb5d69d25f96dd338769f81927d5101b90663af/tests/Plucker.hs | haskell | starting line
parallel
ccw
cw
intersect
reversed
through origin
not a 3D line | module Plucker (tests) where
import Linear
import Linear.Plucker
import Linear.Plucker.Coincides
import Test.HUnit
ln2,ln3,ln4,ln5,ln6,ln7,ln8,ln9 :: Plucker Float
tests :: Test
tests = test [ "parallel" ~: parallel ln2 ln3 ~?= True
, "CCW" ~: passes ln2 ln4 ~?= Counterclockwise
, "CW" ~: passes ln2 ln5 ~?= Clockwise
, "intersect1" ~: intersects ln2 ln6 ~?= True
, "intersect2" ~: intersects ln2 ln3 ~?= False
, "line equality 1" ~: Line ln2 == Line ln2 ~?= True
, "line equality 2" ~: Line ln2 == Line ln7 ~?= True
, "line equality 3" ~: Line ln2 == Ray ln7 ~?= True
, "line equality 4" ~: Ray ln2 == Line ln7 ~?= True
, "ray equality 1" ~: Ray ln2 == Ray ln7 ~?= False
, "ray equality 2" ~: Ray ln2 == Ray (3 *^ ln2) ~?= True
, "ray equality 3" ~: Ray ln2 == Ray (negate ln7) ~?= True
, "quadrance" ~: nearZero (quadranceToOrigin ln2 - 10) ~?= True
, "closest 1" ~:
nearZero (qd (V3 1 3 0) $ closestToOrigin ln2) ~?= True
, "closest 2" ~: nearZero (qd 0 $ closestToOrigin ln8) ~?= True
, "isLine 1" ~: isLine ln2 ~?= True
, "isLine 2" ~: isLine ln9 ~?= False ]
|
960565b66b185e902386f977737dff117a65537fa1f21b83a5be8c98b79cf52d | simon-katz/lein-nomis-ns-graph | graph_test.clj | (ns leiningen.nomis-ns-graph.p200-graphing.graph-test
(:require [clojure.java.io :as io]
[leiningen.lein-test-utils :as ltu]
[leiningen.nomis-ns-graph.p200-graphing.graph :as subject :refer :all]
[midje.sweet :refer :all]))
;;;; ___________________________________________________________________________
(fact "`nsn->pieces` works"
(#'subject/nsn->pieces "a.bb.ccc")
=> '[a bb ccc])
(fact "`nsn->last-piece` works"
(#'subject/nsn->last-piece "a.bb.ccc")
=> 'ccc)
(fact "`nsn->parent-nsn` works"
(fact "without parent"
(#'subject/nsn->parent-nsn "a")
=> nil)
(fact "with parent"
(#'subject/nsn->parent-nsn "a.bb.ccc")
=> 'a.bb))
(fact "`nsn->all-parent-nsns-incl-self` works"
(fact
(#'subject/nsn->all-parent-nsns-incl-self 'a.bb.ccc)
=> '[a.bb.ccc a.bb a])
(fact
(#'subject/nsn->all-parent-nsns-incl-self 'a)
=> '[a]))
;;;; ___________________________________________________________________________
(defn check-graphing [filename
ns-graph-spec]
(let [dir "test-resources/output/ns-graphing/"
expected-file-name-base (str dir filename)
[expected-file-name
actual-file-name] [(str expected-file-name-base "-expected.gv")
(str expected-file-name-base "-actual.gv")]]
(let [dot-data (ns-graph-spec->dot-data ns-graph-spec)]
(when
;; Take care to only do this when necessary, so that diff tools
;; don't show unnecessary diffs in file timestamps.
(or (not (.exists (io/file actual-file-name)))
(not= dot-data
(slurp actual-file-name)))
(spit actual-file-name
dot-data))
(fact (slurp expected-file-name)
=> dot-data))))
(fact "clj"
(check-graphing
"nomis-ns-graph-clj"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-inclusions-and-externals"
(check-graphing
"nomis-ns-graph-clj-with-inclusions-and-externals"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:inclusions ["user" "midje"]
:show-non-project-deps true
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-exclusions-and-externals"
(check-graphing
"nomis-ns-graph-clj-with-exclusions-and-externals"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:exclusions ["user" "midje"]
:show-non-project-deps true
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "cljs"
(check-graphing
"nomis-ns-graph-cljs"
{:platform :cljs
:source-paths ["test-resources/example-projects/nomisdraw/src/cljs"
"test-resources/example-projects/nomisdraw/cljs/src"]
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "cljs-with-externals"
(check-graphing
"nomis-ns-graph-cljs-with-externals"
{:platform :cljs
:source-paths ["test-resources/example-projects/nomisdraw/src/cljs"
"test-resources/example-projects/nomisdraw/cljs/src"]
:show-non-project-deps true
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-inclusions-re"
(check-graphing
"nomis-ns-graph-clj-with-inclusions-re"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:inclusions-re "u.er|\\.sys"
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-exclusions-re"
(check-graphing
"nomis-ns-graph-clj-with-exclusions-re"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:exclusions-re "u.er|\\.sys"
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-inclusions-and-inclusions-re"
(check-graphing
"nomis-ns-graph-clj-with-inclusions-and-inclusions-re"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:inclusions ["user" "nomisdraw.services.provided.web.server"]
:inclusions-re "u.er|\\.sys"
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-exclusions-and-exclusions-re"
(check-graphing
"nomis-ns-graph-clj-with-exclusions-and-exclusions-re"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:exclusions ["user"]
:exclusions-re "\\.sys"
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-inclusions-re-and-exclusions-re"
(check-graphing
"nomis-ns-graph-clj-with-inclusions-re-and-exclusions-re"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:inclusions-re "\\.services\\."
:exclusions-re "\\.handlers\\."
:project-group "nomisdraw"
:project-name "nomisdraw"}))
| null | https://raw.githubusercontent.com/simon-katz/lein-nomis-ns-graph/e30d8af3022ee1d9b1c49571847925c45617e66b/test/leiningen/nomis_ns_graph/p200_graphing/graph_test.clj | clojure | ___________________________________________________________________________
___________________________________________________________________________
Take care to only do this when necessary, so that diff tools
don't show unnecessary diffs in file timestamps. | (ns leiningen.nomis-ns-graph.p200-graphing.graph-test
(:require [clojure.java.io :as io]
[leiningen.lein-test-utils :as ltu]
[leiningen.nomis-ns-graph.p200-graphing.graph :as subject :refer :all]
[midje.sweet :refer :all]))
(fact "`nsn->pieces` works"
(#'subject/nsn->pieces "a.bb.ccc")
=> '[a bb ccc])
(fact "`nsn->last-piece` works"
(#'subject/nsn->last-piece "a.bb.ccc")
=> 'ccc)
(fact "`nsn->parent-nsn` works"
(fact "without parent"
(#'subject/nsn->parent-nsn "a")
=> nil)
(fact "with parent"
(#'subject/nsn->parent-nsn "a.bb.ccc")
=> 'a.bb))
(fact "`nsn->all-parent-nsns-incl-self` works"
(fact
(#'subject/nsn->all-parent-nsns-incl-self 'a.bb.ccc)
=> '[a.bb.ccc a.bb a])
(fact
(#'subject/nsn->all-parent-nsns-incl-self 'a)
=> '[a]))
(defn check-graphing [filename
ns-graph-spec]
(let [dir "test-resources/output/ns-graphing/"
expected-file-name-base (str dir filename)
[expected-file-name
actual-file-name] [(str expected-file-name-base "-expected.gv")
(str expected-file-name-base "-actual.gv")]]
(let [dot-data (ns-graph-spec->dot-data ns-graph-spec)]
(when
(or (not (.exists (io/file actual-file-name)))
(not= dot-data
(slurp actual-file-name)))
(spit actual-file-name
dot-data))
(fact (slurp expected-file-name)
=> dot-data))))
(fact "clj"
(check-graphing
"nomis-ns-graph-clj"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-inclusions-and-externals"
(check-graphing
"nomis-ns-graph-clj-with-inclusions-and-externals"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:inclusions ["user" "midje"]
:show-non-project-deps true
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-exclusions-and-externals"
(check-graphing
"nomis-ns-graph-clj-with-exclusions-and-externals"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:exclusions ["user" "midje"]
:show-non-project-deps true
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "cljs"
(check-graphing
"nomis-ns-graph-cljs"
{:platform :cljs
:source-paths ["test-resources/example-projects/nomisdraw/src/cljs"
"test-resources/example-projects/nomisdraw/cljs/src"]
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "cljs-with-externals"
(check-graphing
"nomis-ns-graph-cljs-with-externals"
{:platform :cljs
:source-paths ["test-resources/example-projects/nomisdraw/src/cljs"
"test-resources/example-projects/nomisdraw/cljs/src"]
:show-non-project-deps true
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-inclusions-re"
(check-graphing
"nomis-ns-graph-clj-with-inclusions-re"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:inclusions-re "u.er|\\.sys"
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-exclusions-re"
(check-graphing
"nomis-ns-graph-clj-with-exclusions-re"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:exclusions-re "u.er|\\.sys"
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-inclusions-and-inclusions-re"
(check-graphing
"nomis-ns-graph-clj-with-inclusions-and-inclusions-re"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:inclusions ["user" "nomisdraw.services.provided.web.server"]
:inclusions-re "u.er|\\.sys"
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-exclusions-and-exclusions-re"
(check-graphing
"nomis-ns-graph-clj-with-exclusions-and-exclusions-re"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:exclusions ["user"]
:exclusions-re "\\.sys"
:project-group "nomisdraw"
:project-name "nomisdraw"}))
(fact "clj-with-inclusions-re-and-exclusions-re"
(check-graphing
"nomis-ns-graph-clj-with-inclusions-re-and-exclusions-re"
{:platform :clj
:source-paths ["test-resources/example-projects/nomisdraw/dev"
"test-resources/example-projects/nomisdraw/src/clj"]
:inclusions-re "\\.services\\."
:exclusions-re "\\.handlers\\."
:project-group "nomisdraw"
:project-name "nomisdraw"}))
|
0b1c12ef134d26bb63665440073494df54f237da030af8a62532ac8060e21f22 | xh4/web-toolkit | file.lisp | (in-package :http-test)
(in-suite :http-test)
(test file-size
(it
(with-static-files (root "abc")
(with-open-file (stream (merge-pathnames "abc" root)
:direction :output
:element-type '(unsigned-byte 8)
:if-exists :supersede)
(write-sequence (make-array 42 :initial-element 42) stream))
(let ((file (make-instance 'http::file
:pathname (merge-pathnames "abc" root))))
(is (equal 42 (http::file-size file)))))))
(test file-size/not-exists
(it
(with-static-files (root)
(let ((file (make-instance 'http::file
:pathname (merge-pathnames "xxx" root))))
(is (equal nil (http::file-size file)))))))
| null | https://raw.githubusercontent.com/xh4/web-toolkit/e510d44a25b36ca8acd66734ed1ee9f5fe6ecd09/test/http/file.lisp | lisp | (in-package :http-test)
(in-suite :http-test)
(test file-size
(it
(with-static-files (root "abc")
(with-open-file (stream (merge-pathnames "abc" root)
:direction :output
:element-type '(unsigned-byte 8)
:if-exists :supersede)
(write-sequence (make-array 42 :initial-element 42) stream))
(let ((file (make-instance 'http::file
:pathname (merge-pathnames "abc" root))))
(is (equal 42 (http::file-size file)))))))
(test file-size/not-exists
(it
(with-static-files (root)
(let ((file (make-instance 'http::file
:pathname (merge-pathnames "xxx" root))))
(is (equal nil (http::file-size file)))))))
|
|
33355df0760ff730d0e071113376a78ced9aa2d09842470701fe8fbfe8e3d0d6 | mstksg/advent-of-code-2021 | Day16.hs | -- |
Module : AOC.Challenge .
-- License : BSD3
--
-- Stability : experimental
-- Portability : non-portable
--
Day 16 . See " AOC.Solver " for the types used in this module !
module AOC.Challenge.Day16 (
day16a
, day16b
) where
import AOC.Common (TokStream(..), digitToIntSafe, parseBinary, toBinaryFixed)
import AOC.Solver ((:~>)(..))
import Control.Applicative (empty)
import Control.DeepSeq (NFData)
import Control.Lens (preview, _Right)
import Control.Monad (replicateM)
import Data.Bifunctor (bimap)
import Data.Functor.Foldable (cata)
import Data.Functor.Foldable.TH (makeBaseFunctor)
import Data.Void (Void)
import GHC.Generics (Generic)
import qualified Text.Megaparsec as P
type Version = Int
data Packet = Operator Version Op [Packet]
| Literal Version Int
deriving stock (Show, Generic)
deriving anyclass NFData
data Op = OSum
| OProd
| OMin
| OMax
| OGT
| OLT
| OEQ
deriving stock (Show, Generic)
deriving anyclass NFData
makeBaseFunctor ''Packet
day16 :: Show a => (PacketF a -> a) -> TokStream Bool :~> a
day16 alg = MkSol
{ sParse = Just . TokStream
. concatMap (maybe [] id . fmap (toBinaryFixed 4) . digitToIntSafe)
, sShow = show
, sSolve = fmap (cata alg . snd) . preview _Right . P.runParser parsePacket ""
}
day16a :: TokStream Bool :~> Int
day16a = day16 \case
OperatorF v _ ps -> v + sum ps
LiteralF v _ -> v
day16b :: TokStream Bool :~> Int
day16b = day16 evalPackF
evalPackF :: PacketF Int -> Int
evalPackF = \case
OperatorF _ o is -> evalOp o is
LiteralF _ i -> i
where
evalOp = \case
OSum -> sum
OProd -> product
OMin -> minimum
OMax -> maximum
OGT -> \case [a,b] -> if a > b then 1 else 0
_ -> -1
OLT -> \case [a,b] -> if a < b then 1 else 0
_ -> -1
OEQ -> \case [a,b] -> if a == b then 1 else 0
_ -> -1
type Parser = P.Parsec Void (TokStream Bool)
-- includes the length of items parsed
parsePacket :: Parser (Int, Packet)
parsePacket = do
v <- parseBinary <$> replicateM 3 P.anySingle
t <- parseType
case t of
Nothing -> bimap (+ 6) (Literal v) <$> parseLiteral
Just o -> bimap (+ 6) (Operator v o) <$> parseOperator
where
parseType :: Parser (Maybe Op)
parseType = do
t <- parseBinary <$> replicateM 3 P.anySingle
case t of
0 -> pure $ Just OSum
1 -> pure $ Just OProd
2 -> pure $ Just OMin
3 -> pure $ Just OMax
4 -> pure Nothing
5 -> pure $ Just OGT
6 -> pure $ Just OLT
7 -> pure $ Just OEQ
_ -> empty
parseLiteral :: Parser (Int, Int)
parseLiteral = do
n <- parseLitChunks
pure (length n * 5, parseBinary (concat n))
parseLitChunks :: Parser [[Bool]]
parseLitChunks = do
goOn <- P.anySingle
digs <- replicateM 4 P.anySingle
if goOn
then (digs:) <$> parseLitChunks
else pure [digs]
parseOperator :: Parser (Int, [Packet])
parseOperator = do
lt <- P.anySingle
if lt
then do
n <- parseBinary <$> replicateM 11 P.anySingle
(len, ps) <- unzip <$> replicateM n parsePacket
pure (sum len + 11 + 1, ps)
else do
n <- parseBinary <$> replicateM 15 P.anySingle
(n+1+15,) <$> parsePacketsLength n
parsePacketsLength :: Int -> Parser [Packet]
parsePacketsLength n = do
(ln, p) <- parsePacket
if ln == n
then pure [p]
else (p:) <$> parsePacketsLength (n-ln)
| null | https://raw.githubusercontent.com/mstksg/advent-of-code-2021/0b934c388d1757ab1be056f33dc2b1d56d45a2ad/src/AOC/Challenge/Day16.hs | haskell | |
License : BSD3
Stability : experimental
Portability : non-portable
includes the length of items parsed | Module : AOC.Challenge .
Day 16 . See " AOC.Solver " for the types used in this module !
module AOC.Challenge.Day16 (
day16a
, day16b
) where
import AOC.Common (TokStream(..), digitToIntSafe, parseBinary, toBinaryFixed)
import AOC.Solver ((:~>)(..))
import Control.Applicative (empty)
import Control.DeepSeq (NFData)
import Control.Lens (preview, _Right)
import Control.Monad (replicateM)
import Data.Bifunctor (bimap)
import Data.Functor.Foldable (cata)
import Data.Functor.Foldable.TH (makeBaseFunctor)
import Data.Void (Void)
import GHC.Generics (Generic)
import qualified Text.Megaparsec as P
type Version = Int
data Packet = Operator Version Op [Packet]
| Literal Version Int
deriving stock (Show, Generic)
deriving anyclass NFData
data Op = OSum
| OProd
| OMin
| OMax
| OGT
| OLT
| OEQ
deriving stock (Show, Generic)
deriving anyclass NFData
makeBaseFunctor ''Packet
day16 :: Show a => (PacketF a -> a) -> TokStream Bool :~> a
day16 alg = MkSol
{ sParse = Just . TokStream
. concatMap (maybe [] id . fmap (toBinaryFixed 4) . digitToIntSafe)
, sShow = show
, sSolve = fmap (cata alg . snd) . preview _Right . P.runParser parsePacket ""
}
day16a :: TokStream Bool :~> Int
day16a = day16 \case
OperatorF v _ ps -> v + sum ps
LiteralF v _ -> v
day16b :: TokStream Bool :~> Int
day16b = day16 evalPackF
evalPackF :: PacketF Int -> Int
evalPackF = \case
OperatorF _ o is -> evalOp o is
LiteralF _ i -> i
where
evalOp = \case
OSum -> sum
OProd -> product
OMin -> minimum
OMax -> maximum
OGT -> \case [a,b] -> if a > b then 1 else 0
_ -> -1
OLT -> \case [a,b] -> if a < b then 1 else 0
_ -> -1
OEQ -> \case [a,b] -> if a == b then 1 else 0
_ -> -1
type Parser = P.Parsec Void (TokStream Bool)
parsePacket :: Parser (Int, Packet)
parsePacket = do
v <- parseBinary <$> replicateM 3 P.anySingle
t <- parseType
case t of
Nothing -> bimap (+ 6) (Literal v) <$> parseLiteral
Just o -> bimap (+ 6) (Operator v o) <$> parseOperator
where
parseType :: Parser (Maybe Op)
parseType = do
t <- parseBinary <$> replicateM 3 P.anySingle
case t of
0 -> pure $ Just OSum
1 -> pure $ Just OProd
2 -> pure $ Just OMin
3 -> pure $ Just OMax
4 -> pure Nothing
5 -> pure $ Just OGT
6 -> pure $ Just OLT
7 -> pure $ Just OEQ
_ -> empty
parseLiteral :: Parser (Int, Int)
parseLiteral = do
n <- parseLitChunks
pure (length n * 5, parseBinary (concat n))
parseLitChunks :: Parser [[Bool]]
parseLitChunks = do
goOn <- P.anySingle
digs <- replicateM 4 P.anySingle
if goOn
then (digs:) <$> parseLitChunks
else pure [digs]
parseOperator :: Parser (Int, [Packet])
parseOperator = do
lt <- P.anySingle
if lt
then do
n <- parseBinary <$> replicateM 11 P.anySingle
(len, ps) <- unzip <$> replicateM n parsePacket
pure (sum len + 11 + 1, ps)
else do
n <- parseBinary <$> replicateM 15 P.anySingle
(n+1+15,) <$> parsePacketsLength n
parsePacketsLength :: Int -> Parser [Packet]
parsePacketsLength n = do
(ln, p) <- parsePacket
if ln == n
then pure [p]
else (p:) <$> parsePacketsLength (n-ln)
|
e820c31b8ae04db7dca25f03974e0f8e9c5ba408e3f137d6b312a3f691e03ac8 | TrustInSoft/tis-interpreter | initial_state.mli | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
(* *)
(* you can redistribute it and/or modify it under the terms of the GNU *)
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
(* *)
(* It is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU Lesser General Public License for more details. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(** Creation of the initial state for Value. *)
val initial_state_not_lib_entry: unit -> Cvalue.Model.t
val initial_state_lib_entry: unit -> Cvalue.Model.t
val initialize_var_using_type:
Cil_types.varinfo -> Cvalue.Model.t -> Cvalue.Model.t
val initialize_args:
Cil_types.varinfo -> Cil_types.varinfo ->
Cvalue.Model.t -> Cvalue.Model.t
(*
Local Variables:
compile-command: "make -C ../../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/value/legacy/initial_state.mli | ocaml | ************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
************************************************************************
* Creation of the initial state for Value.
Local Variables:
compile-command: "make -C ../../../.."
End:
| Modified by TrustInSoft
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
val initial_state_not_lib_entry: unit -> Cvalue.Model.t
val initial_state_lib_entry: unit -> Cvalue.Model.t
val initialize_var_using_type:
Cil_types.varinfo -> Cvalue.Model.t -> Cvalue.Model.t
val initialize_args:
Cil_types.varinfo -> Cil_types.varinfo ->
Cvalue.Model.t -> Cvalue.Model.t
|
3d932a787b72cbbf707878481ab4468ebef747ad325609a10dc8f65310335328 | dizengrong/erlang_game | util_math.erl | @author dzR < >
%% @doc 和数学运算相关的方法
-module (util_math).
-export([ceil/1, floor/1, ceil_div/2]).
%% @doc 向上取整
ceil(N) ->
T = trunc(N),
case N == T of
true -> T;
false -> 1 + T
end.
@doc 向下取整
floor(X) ->
T = trunc(X),
case (X < T) of
true -> T - 1;
_ -> T
end.
%% @doc 对A除以B的商向上取整
ceil_div(A, B) ->
C = A div B,
case A rem B == 0 of
true -> C;
false -> C + 1
end.
| null | https://raw.githubusercontent.com/dizengrong/erlang_game/4598f97daa9ca5eecff292ac401dd8f903eea867/gerl/src/util/util_math.erl | erlang | @doc 和数学运算相关的方法
@doc 向上取整
@doc 对A除以B的商向上取整 | @author dzR < >
-module (util_math).
-export([ceil/1, floor/1, ceil_div/2]).
ceil(N) ->
T = trunc(N),
case N == T of
true -> T;
false -> 1 + T
end.
@doc 向下取整
floor(X) ->
T = trunc(X),
case (X < T) of
true -> T - 1;
_ -> T
end.
ceil_div(A, B) ->
C = A div B,
case A rem B == 0 of
true -> C;
false -> C + 1
end.
|
108a1f4b1d63a1ec8ab7b4072ccdbcc65298db66ff0326e4fbc7d1c211c9e6ee | ulricha/dsh | Common.hs | module Database.DSH.VSL.Opt.Properties.Common where
import Control.Monad
import Database.DSH.VSL.Opt.Properties.Types
unpack :: Show a => String -> VectorProp a -> Either String a
unpack _ (VProp b) = Right b
unpack moduleName p = Left $ "no single vector in " ++ moduleName ++ " " ++ (show p)
mapUnpack :: Show a => String
-> VectorProp a
-> VectorProp a
-> (a -> a -> VectorProp a)
-> Either String (VectorProp a)
mapUnpack moduleName e1 e2 f = let ue1 = unpack moduleName e1
ue2 = unpack moduleName e2
in liftM2 f ue1 ue2
| null | https://raw.githubusercontent.com/ulricha/dsh/e6cd5c6bea575e62a381e89bfc4cc7cb97485106/src/Database/DSH/VSL/Opt/Properties/Common.hs | haskell | module Database.DSH.VSL.Opt.Properties.Common where
import Control.Monad
import Database.DSH.VSL.Opt.Properties.Types
unpack :: Show a => String -> VectorProp a -> Either String a
unpack _ (VProp b) = Right b
unpack moduleName p = Left $ "no single vector in " ++ moduleName ++ " " ++ (show p)
mapUnpack :: Show a => String
-> VectorProp a
-> VectorProp a
-> (a -> a -> VectorProp a)
-> Either String (VectorProp a)
mapUnpack moduleName e1 e2 f = let ue1 = unpack moduleName e1
ue2 = unpack moduleName e2
in liftM2 f ue1 ue2
|
|
80d7c12e5578769030887017692f9beb175c868b96897e0c62162475e9a26608 | Quid2/zm | K306f1981b41c.hs | {-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
module Test.ZM.ADT.Bool.K306f1981b41c (Bool(..)) where
import qualified Prelude(Eq,Ord,Show)
import qualified GHC.Generics
import qualified Flat
import qualified Data.Model
data Bool = False
| True
deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat)
instance Data.Model.Model Bool
| null | https://raw.githubusercontent.com/Quid2/zm/02c0514777a75ac054bfd6251edd884372faddea/test/Test/ZM/ADT/Bool/K306f1981b41c.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveGeneric # | module Test.ZM.ADT.Bool.K306f1981b41c (Bool(..)) where
import qualified Prelude(Eq,Ord,Show)
import qualified GHC.Generics
import qualified Flat
import qualified Data.Model
data Bool = False
| True
deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat)
instance Data.Model.Model Bool
|
98cba1ba0f9b6558c1b31822c5c6f45daee6f90cc7a5f6b267addb02f75840b6 | input-output-hk/iohk-monitoring-framework | IOManager.hs | --
-- copied from -output-hk/ouroboros-network
--
# LANGUAGE CPP #
{-# LANGUAGE RankNTypes #-}
| A shim layer for ` Win32 - network ` 's ` IOManager `
--
module Cardano.BM.IOManager
( module X
) where
import System.IOManager as X
| null | https://raw.githubusercontent.com/input-output-hk/iohk-monitoring-framework/21e00a449029fc7e864869d1b1aecd2834157083/iohk-monitoring/src/Cardano/BM/IOManager.hs | haskell |
copied from -output-hk/ouroboros-network
# LANGUAGE RankNTypes #
| # LANGUAGE CPP #
| A shim layer for ` Win32 - network ` 's ` IOManager `
module Cardano.BM.IOManager
( module X
) where
import System.IOManager as X
|
58cdf16776bd9476b3f05885cce399c82c88de60635dc4def145c5dc256be06e | biokoda/actordb_core | actordb_tunnel.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(actordb_tunnel).
-behaviour(gen_server).
-export([start/0,stop/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3,print_info/0]).
-export([]).
-include_lib("actordb_core/include/actordb.hrl").
% Every write thread in actordb_driver uses a TCP "tunnel" to replicate data.
% Generated pages during writes get sent over to nodes in cluster. Write threads are dumb
and all they do is write to FD . Data is prefixed with info that tells the other side
% what this data is.
% The receiving node has a circuit breaker (actordb_util:actor_ae_stream) for every actor.
% If the receiver does not want the data (raft conditions) it will close the receiving process
% thus breaking the circuit and the received data gets sent to a dead process.
%
This gen_server creates the actual TCP connection fds and takes them away from erlang runtime .
start() ->
gen_server:start_link({local,?MODULE},?MODULE, [], []).
stop() ->
gen_server:call(?MODULE, stop).
print_info() ->
gen_server:call(?MODULE,print_info).
-record(dp,{
% Sockets for every write thread for every driver.
# { { ThreadIndex , DriverName , ConnectionSlot } = > { Type , Socket } }
sockets = #{},
slots for 8 raft cluster connections
Set element is : NodeName
slots = {undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined}}).
handle_call(print_info,_,P) ->
?AINF("~p",[P]),
{reply,ok,P};
handle_call(stop, _, P) ->
{stop, shutdown, stopped, P}.
handle_cast(_, P) ->
{noreply, P}.
handle_info({tcpfail,Driver,Thread,Pos}, P) ->
?AERR("Lost connection to=~p on thread=~p",[element(Pos+1,P#dp.slots), Thread]),
case maps:get({Thread,Driver,Pos}, P#dp.sockets, undefined) of
undefined ->
?AERR("Connection {~p,~p} not found in map=~p",[Thread,Pos,P#dp.sockets]),
{noreply, P};
{Type,Sock} when is_port(Sock) ->
gen_tcp:close(Sock),
Socks = P#dp.sockets,
{noreply, P#dp{sockets = Socks#{{Thread, Driver, Pos} => {Type, undefined}}}};
{_Type, _} ->
{noreply, P}
end;
handle_info(reconnect_raft,P) ->
erlang:send_after(500,self(),reconnect_raft),
{noreply,P#dp{sockets = check_reconnect(P#dp.slots,maps:to_list(P#dp.sockets), P#dp.sockets)}};
handle_info({actordb,sharedstate_change},P) ->
MG1 = actordb_sharedstate:read_global(master_group),
case lists:member(actordb_conf:node_name(),MG1) of
true ->
MG = MG1 -- [actordb_conf:node_name()];
false ->
MG = bkdcore:cluster_nodes()
end,
? AINF("Storing raft connections ~p ~p",[MG , : cluster_nodes ( ) ] ) ,
{Slots, ToConnect} = store_raft_connection(MG,P#dp.slots,[]),
{noreply, P#dp{slots = Slots, sockets = connect(Slots, ToConnect,P#dp.sockets)}};
handle_info({raft_connections,L},P) ->
?ADBG("received raft connections"),
{Slots,ToConnect} = store_raft_connection(L,P#dp.slots,[]),
{noreply, P#dp{slots = Slots, sockets = connect(Slots, ToConnect,P#dp.sockets)}};
handle_info({'DOWN',_Monitor,_,Pid,Reason}, P) ->
case [{K,Type} || {K,{Type,Pd}} <- maps:to_list(P#dp.sockets), Pd == Pid] of
[{K,Type}] when element(1,Reason) == connection ->
?ADBG("Storing connection"),
Sock = element(2,Reason),
{ok,Fd} = prim_inet:getfd(Sock),
{Thread, Driver, Pos} = K,
ok = apply(Driver,set_thread_fd,[Thread,Fd,Pos,Type]),
{noreply, P#dp{sockets = (P#dp.sockets)#{K => {Type, Sock}}}};
[{K,Type}] ->
{noreply, P#dp{sockets = (P#dp.sockets)#{K => {Type, undefined}}}};
_Msg ->
{noreply,P}
end;
handle_info({stop},P) ->
handle_info({stop,noreason},P);
handle_info({stop,Reason},P) ->
{stop, Reason, P};
handle_info(M, P) ->
?AERR("Invalid msg ~p",[M]),
{noreply, P}.
terminate(_, _) ->
ok.
code_change(_, P, _) ->
{ok, P}.
init(_) ->
erlang:send_after(500,self(),reconnect_raft),
actordb_sharedstate:subscribe_changes(?MODULE),
ok = actordb_driver:set_tunnel_connector(),
% ok = aqdrv:set_tunnel_connector(),
{ok,#dp{}}.
%
check_reconnect(Slots,[{{_Thread, _Driver, Pos} = K, {Type,undefined}}|T], Sockets) ->
Nd = element(Pos+1,Slots),
{IP,_Port} = bkdcore:node_address(Nd),
Port = getport(Nd),
{Pid,_} = spawn_monitor(fun() -> doconnect(IP, Port, Nd) end),
check_reconnect(Slots,T, Sockets#{K => {Type, Pid}});
case doconnect(IP , Port , Nd , K ) of
% {ok, Sock} ->
% {ok,Fd} = prim_inet:getfd(Sock),
? AINF("Reconnected to ~p",[Nd ] ) ,
ok = apply(Driver , set_thread_fd,[Thread , Fd , Pos , Type ] ) ,
% check_reconnect(Slots,T, Sockets#{K => {Type, Sock}});
% false ->
% check_reconnect(Slots,T, Sockets)
% end;
check_reconnect(Slots,[_|T], S) ->
check_reconnect(Slots,T, S);
check_reconnect(_,[], S) ->
S.
connect(Slots,[H|TC], Sockets) ->
NWThreads = length(actordb_conf:paths()) * actordb_conf:wthreads(),
ThrL = lists:seq(0,NWThreads-1),
connect(Slots,TC, connect_threads(Slots,actordb_driver,ThrL, H,Sockets));
connect(_,[],S) ->
S.
connect_threads(Slots, Driver, [Thread|T], {Nd, Pos, Type} = Info, Sockets) ->
{IP,_Port} = bkdcore:node_address(Nd),
Port = getport(Nd),
Nd = element(Pos+1,Slots),
K = {Thread, Driver, Pos},
% Start = os:timestamp(),
{Pid,_} = spawn_monitor(fun() -> doconnect(IP, Port, Nd) end),
% {ok, Sock} ->
% ?AINF("Connected"),
% {ok,Fd} = prim_inet:getfd(Sock),
ok = apply(Driver , set_thread_fd,[Thread , Fd , Pos , Type ] ) ,
? AINF("Connected to ~p , took=~pms",[Nd , timer : now_diff(os : timestamp(),Start ) div 1000 ] ) ,
% connect_threads(Slots, Driver, T, Info, Sockets#{K => {Type, Sock}});
% false ->
connect_threads(Slots, Driver, T, Info, Sockets#{K => {Type, Pid}});
% end;
connect_threads(_Slots, _Driver,[],_Info,S) ->
S.
getport(Nd) ->
case application:get_env(actordb_core, pmd) of
{ok,_Obj} ->
actordb_pmd:node_to_port(Nd) + 1;
_ ->
{_,Port} = bkdcore:node_address(Nd),
Port
end.
doconnect(IP, Port, Nd) ->
?ADBG("doconnect ~p",[Nd]),
case gen_tcp:connect(IP,Port,[{active, false},{packet,4},
{keepalive,true},{send_timeout,10000}], 500) of
{ok,S} ->
inet:setopts(S,[{nodelay, true}]),
case gen_tcp:send(S,conhdr(Nd)) of
ok ->
?ADBG("Opened tunnel to ~p",[Nd]),
ok = prim_inet:ignorefd(S,true),
ok = gen_tcp:controlling_process(S,whereis(?MODULE)),
exit({connection, S});
_Er ->
exit(_Er)
end;
_Er ->
?ADBG("doconnect to=~p failed ~p",[Nd,_Er]),
exit(_Er)
end.
conhdr(Nd) ->
[bkdcore:rpccookie(Nd),"tunnel,",actordb_conf:node_name(),",actordb_util"].
store_raft_connection([Nd|T],Tuple,ToConnect) ->
case getpos(Tuple,1,Nd) of
undefined ->
Pos = getempty(Tuple,1),
{IP,Port} = bkdcore:node_address(Nd),
case lists:member(Nd,bkdcore:cluster_nodes()) of
true ->
Type = 1;
false ->
Type = 2
end,
?AINF("Starting raft connection to ~p",[{Nd,IP,Port}]),
store_raft_connection(T, setelement(Pos,Tuple,Nd), [{Nd, Pos-1, Type}|ToConnect]);
_ ->
store_raft_connection(T,Tuple, ToConnect)
end;
store_raft_connection([],T, ToConnect) ->
{T,ToConnect}.
getempty(T,N) ->
case element(N,T) of
undefined ->
N;
_ ->
getempty(T,N+1)
end.
getpos(T,N,Nd) when tuple_size(T) >= N ->
case element(N,T) of
Nd when is_binary(Nd) ->
N;
_ ->
getpos(T,N+1,Nd)
end;
getpos(_,_,_) ->
undefined.
| null | https://raw.githubusercontent.com/biokoda/actordb_core/8dcd08a0897055af89c3ce20d99ed5e64d0c33eb/src/actordb_tunnel.erl | erlang | Every write thread in actordb_driver uses a TCP "tunnel" to replicate data.
Generated pages during writes get sent over to nodes in cluster. Write threads are dumb
what this data is.
The receiving node has a circuit breaker (actordb_util:actor_ae_stream) for every actor.
If the receiver does not want the data (raft conditions) it will close the receiving process
thus breaking the circuit and the received data gets sent to a dead process.
Sockets for every write thread for every driver.
ok = aqdrv:set_tunnel_connector(),
{ok, Sock} ->
{ok,Fd} = prim_inet:getfd(Sock),
check_reconnect(Slots,T, Sockets#{K => {Type, Sock}});
false ->
check_reconnect(Slots,T, Sockets)
end;
Start = os:timestamp(),
{ok, Sock} ->
?AINF("Connected"),
{ok,Fd} = prim_inet:getfd(Sock),
connect_threads(Slots, Driver, T, Info, Sockets#{K => {Type, Sock}});
false ->
end; | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(actordb_tunnel).
-behaviour(gen_server).
-export([start/0,stop/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3,print_info/0]).
-export([]).
-include_lib("actordb_core/include/actordb.hrl").
and all they do is write to FD . Data is prefixed with info that tells the other side
This gen_server creates the actual TCP connection fds and takes them away from erlang runtime .
start() ->
gen_server:start_link({local,?MODULE},?MODULE, [], []).
stop() ->
gen_server:call(?MODULE, stop).
print_info() ->
gen_server:call(?MODULE,print_info).
-record(dp,{
# { { ThreadIndex , DriverName , ConnectionSlot } = > { Type , Socket } }
sockets = #{},
slots for 8 raft cluster connections
Set element is : NodeName
slots = {undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined}}).
handle_call(print_info,_,P) ->
?AINF("~p",[P]),
{reply,ok,P};
handle_call(stop, _, P) ->
{stop, shutdown, stopped, P}.
handle_cast(_, P) ->
{noreply, P}.
handle_info({tcpfail,Driver,Thread,Pos}, P) ->
?AERR("Lost connection to=~p on thread=~p",[element(Pos+1,P#dp.slots), Thread]),
case maps:get({Thread,Driver,Pos}, P#dp.sockets, undefined) of
undefined ->
?AERR("Connection {~p,~p} not found in map=~p",[Thread,Pos,P#dp.sockets]),
{noreply, P};
{Type,Sock} when is_port(Sock) ->
gen_tcp:close(Sock),
Socks = P#dp.sockets,
{noreply, P#dp{sockets = Socks#{{Thread, Driver, Pos} => {Type, undefined}}}};
{_Type, _} ->
{noreply, P}
end;
handle_info(reconnect_raft,P) ->
erlang:send_after(500,self(),reconnect_raft),
{noreply,P#dp{sockets = check_reconnect(P#dp.slots,maps:to_list(P#dp.sockets), P#dp.sockets)}};
handle_info({actordb,sharedstate_change},P) ->
MG1 = actordb_sharedstate:read_global(master_group),
case lists:member(actordb_conf:node_name(),MG1) of
true ->
MG = MG1 -- [actordb_conf:node_name()];
false ->
MG = bkdcore:cluster_nodes()
end,
? AINF("Storing raft connections ~p ~p",[MG , : cluster_nodes ( ) ] ) ,
{Slots, ToConnect} = store_raft_connection(MG,P#dp.slots,[]),
{noreply, P#dp{slots = Slots, sockets = connect(Slots, ToConnect,P#dp.sockets)}};
handle_info({raft_connections,L},P) ->
?ADBG("received raft connections"),
{Slots,ToConnect} = store_raft_connection(L,P#dp.slots,[]),
{noreply, P#dp{slots = Slots, sockets = connect(Slots, ToConnect,P#dp.sockets)}};
handle_info({'DOWN',_Monitor,_,Pid,Reason}, P) ->
case [{K,Type} || {K,{Type,Pd}} <- maps:to_list(P#dp.sockets), Pd == Pid] of
[{K,Type}] when element(1,Reason) == connection ->
?ADBG("Storing connection"),
Sock = element(2,Reason),
{ok,Fd} = prim_inet:getfd(Sock),
{Thread, Driver, Pos} = K,
ok = apply(Driver,set_thread_fd,[Thread,Fd,Pos,Type]),
{noreply, P#dp{sockets = (P#dp.sockets)#{K => {Type, Sock}}}};
[{K,Type}] ->
{noreply, P#dp{sockets = (P#dp.sockets)#{K => {Type, undefined}}}};
_Msg ->
{noreply,P}
end;
handle_info({stop},P) ->
handle_info({stop,noreason},P);
handle_info({stop,Reason},P) ->
{stop, Reason, P};
handle_info(M, P) ->
?AERR("Invalid msg ~p",[M]),
{noreply, P}.
terminate(_, _) ->
ok.
code_change(_, P, _) ->
{ok, P}.
init(_) ->
erlang:send_after(500,self(),reconnect_raft),
actordb_sharedstate:subscribe_changes(?MODULE),
ok = actordb_driver:set_tunnel_connector(),
{ok,#dp{}}.
check_reconnect(Slots,[{{_Thread, _Driver, Pos} = K, {Type,undefined}}|T], Sockets) ->
Nd = element(Pos+1,Slots),
{IP,_Port} = bkdcore:node_address(Nd),
Port = getport(Nd),
{Pid,_} = spawn_monitor(fun() -> doconnect(IP, Port, Nd) end),
check_reconnect(Slots,T, Sockets#{K => {Type, Pid}});
case doconnect(IP , Port , Nd , K ) of
? AINF("Reconnected to ~p",[Nd ] ) ,
ok = apply(Driver , set_thread_fd,[Thread , Fd , Pos , Type ] ) ,
check_reconnect(Slots,[_|T], S) ->
check_reconnect(Slots,T, S);
check_reconnect(_,[], S) ->
S.
connect(Slots,[H|TC], Sockets) ->
NWThreads = length(actordb_conf:paths()) * actordb_conf:wthreads(),
ThrL = lists:seq(0,NWThreads-1),
connect(Slots,TC, connect_threads(Slots,actordb_driver,ThrL, H,Sockets));
connect(_,[],S) ->
S.
connect_threads(Slots, Driver, [Thread|T], {Nd, Pos, Type} = Info, Sockets) ->
{IP,_Port} = bkdcore:node_address(Nd),
Port = getport(Nd),
Nd = element(Pos+1,Slots),
K = {Thread, Driver, Pos},
{Pid,_} = spawn_monitor(fun() -> doconnect(IP, Port, Nd) end),
ok = apply(Driver , set_thread_fd,[Thread , Fd , Pos , Type ] ) ,
? AINF("Connected to ~p , took=~pms",[Nd , timer : now_diff(os : timestamp(),Start ) div 1000 ] ) ,
connect_threads(Slots, Driver, T, Info, Sockets#{K => {Type, Pid}});
connect_threads(_Slots, _Driver,[],_Info,S) ->
S.
getport(Nd) ->
case application:get_env(actordb_core, pmd) of
{ok,_Obj} ->
actordb_pmd:node_to_port(Nd) + 1;
_ ->
{_,Port} = bkdcore:node_address(Nd),
Port
end.
doconnect(IP, Port, Nd) ->
?ADBG("doconnect ~p",[Nd]),
case gen_tcp:connect(IP,Port,[{active, false},{packet,4},
{keepalive,true},{send_timeout,10000}], 500) of
{ok,S} ->
inet:setopts(S,[{nodelay, true}]),
case gen_tcp:send(S,conhdr(Nd)) of
ok ->
?ADBG("Opened tunnel to ~p",[Nd]),
ok = prim_inet:ignorefd(S,true),
ok = gen_tcp:controlling_process(S,whereis(?MODULE)),
exit({connection, S});
_Er ->
exit(_Er)
end;
_Er ->
?ADBG("doconnect to=~p failed ~p",[Nd,_Er]),
exit(_Er)
end.
conhdr(Nd) ->
[bkdcore:rpccookie(Nd),"tunnel,",actordb_conf:node_name(),",actordb_util"].
store_raft_connection([Nd|T],Tuple,ToConnect) ->
case getpos(Tuple,1,Nd) of
undefined ->
Pos = getempty(Tuple,1),
{IP,Port} = bkdcore:node_address(Nd),
case lists:member(Nd,bkdcore:cluster_nodes()) of
true ->
Type = 1;
false ->
Type = 2
end,
?AINF("Starting raft connection to ~p",[{Nd,IP,Port}]),
store_raft_connection(T, setelement(Pos,Tuple,Nd), [{Nd, Pos-1, Type}|ToConnect]);
_ ->
store_raft_connection(T,Tuple, ToConnect)
end;
store_raft_connection([],T, ToConnect) ->
{T,ToConnect}.
getempty(T,N) ->
case element(N,T) of
undefined ->
N;
_ ->
getempty(T,N+1)
end.
getpos(T,N,Nd) when tuple_size(T) >= N ->
case element(N,T) of
Nd when is_binary(Nd) ->
N;
_ ->
getpos(T,N+1,Nd)
end;
getpos(_,_,_) ->
undefined.
|
ba9921550e8cc40dd348f4ca315f8f2f41e3f1359937dd013008726ba7352cb1 | ulrikstrid/ocaml-oidc | Internal.ml | open Utils
let to_string_body (res : Piaf.Response.t) = Piaf.Body.to_string res.body
let read_registration ~http_client ~client_id ~(discovery : Oidc.Discover.t) =
match discovery.registration_endpoint with
| Some endpoint -> (
let open Lwt_result.Infix in
let registration_path = endpoint |> Uri.path in
let query = Uri.encoded_of_query [("client_id", [client_id])] in
let uri = registration_path ^ query in
Piaf.Client.get http_client uri >>= to_string_body >>= fun s ->
match Oidc.Client.dynamic_of_string s with
| Ok s -> Lwt_result.return s
| Error e -> Lwt_result.fail (`Msg e))
| None -> Lwt_result.fail (`Msg "No_registration_endpoint")
let register (type store)
~(kv : (module KeyValue.KV with type value = string and type store = store))
~(store : store) ~http_client ~meta ~(discovery : Oidc.Discover.t) =
let (module KV) = kv in
let open Lwt_result.Infix in
( KV.get ~store "dynamic_string" >>= fun dynamic_string ->
Lwt.return
(match Oidc.Client.dynamic_of_string dynamic_string with
| Error e -> Error (`Msg e)
| Ok dynamic ->
if Oidc.Client.dynamic_is_expired dynamic then Error `Expired_client
else Ok dynamic) )
|> fun r ->
Lwt.bind r (fun x ->
match (x, discovery.registration_endpoint) with
| Ok dynamic, _ -> Lwt_result.return dynamic
| Error _, Some endpoint ->
let meta_string = Oidc.Client.meta_to_string meta in
let body = Piaf.Body.of_string meta_string in
let registration_path = endpoint |> Uri.path in
( Piaf.Client.post http_client ~body registration_path >>= to_string_body
>>= fun dynamic_string ->
let () = Log.debug (fun m -> m "dynamic string: %s" dynamic_string) in
let open Lwt.Syntax in
let+ () = KV.set ~store "dynamic_string" dynamic_string in
Ok dynamic_string )
>>= fun s ->
(match Oidc.Client.dynamic_of_string s with
| Ok s -> Ok s
| Error e -> Error (`Msg e))
|> Lwt.return
| Error _, None -> Lwt_result.fail (`Msg "No_registration_endpoint"))
let discover (type store)
~(kv : (module KeyValue.KV with type value = string and type store = store))
~(store : store) ~http_client ~provider_uri :
(Oidc.Discover.t, Piaf.Error.t) Lwt_result.t =
let (module KV) = kv in
let open Lwt.Syntax in
let save discovery =
Log.debug (fun m -> m "discovery: %s" discovery);
let+ () = KV.set ~store "discovery" discovery in
discovery
in
let* result = KV.get ~store "discovery" in
let open Lwt_result.Syntax in
let* discovery =
match result with
| Ok discovery -> Lwt_result.return discovery
| Error _ ->
let discover_path =
Uri.path provider_uri ^ "/.well-known/openid-configuration"
in
let* response = Piaf.Client.get http_client discover_path in
let* body = to_string_body response in
Lwt.bind (save body) (fun body -> Lwt_result.return body)
in
Lwt.return
(Result.map_error (fun x -> `Msg x) (Oidc.Discover.of_string discovery))
let jwks (type store)
~(kv : (module KeyValue.KV with type value = string and type store = store))
~(store : store) ~http_client ~provider_uri =
let open Lwt_result.Infix in
let open Lwt_result.Syntax in
let (module KV) = kv in
let save jwks =
KV.set ~store "jwks" jwks |> Lwt_result.ok >|= fun _ -> jwks
in
Lwt.bind (KV.get ~store "jwks") (fun result ->
match result with
| Ok jwks -> Lwt_result.return jwks
| Error _ ->
let* discovery = discover ~kv ~store ~http_client ~provider_uri in
let jwks_path = discovery.jwks_uri |> Uri.path in
Piaf.Client.get http_client jwks_path >>= to_string_body >>= save)
|> Lwt_result.map Jose.Jwks.of_string
(* TODO: Move to oidc lib *)
let validate_userinfo ~(jwt : Jose.Jwt.t) userinfo =
let userinfo_json = Yojson.Safe.from_string userinfo in
let userinfo_sub =
Yojson.Safe.Util.member "sub" userinfo_json
|> Yojson.Safe.Util.to_string_option
in
let sub =
Yojson.Safe.Util.member "sub" jwt.payload |> Yojson.Safe.Util.to_string
in
match userinfo_sub with
| Some s when s = sub ->
Log.debug (fun m -> m "Userinfo is valid");
Ok userinfo
| Some s ->
Log.debug (fun m -> m "Userinfo has invalid sub, expected %s got %s" sub s);
Error `Sub_missmatch
| None ->
Log.debug (fun m -> m "Userinfo is missing sub");
Error `Missing_sub
| null | https://raw.githubusercontent.com/ulrikstrid/ocaml-oidc/5e295f86fc6090815caf3a4acb555fccd62b8d2b/oidc-client/Internal.ml | ocaml | TODO: Move to oidc lib | open Utils
let to_string_body (res : Piaf.Response.t) = Piaf.Body.to_string res.body
let read_registration ~http_client ~client_id ~(discovery : Oidc.Discover.t) =
match discovery.registration_endpoint with
| Some endpoint -> (
let open Lwt_result.Infix in
let registration_path = endpoint |> Uri.path in
let query = Uri.encoded_of_query [("client_id", [client_id])] in
let uri = registration_path ^ query in
Piaf.Client.get http_client uri >>= to_string_body >>= fun s ->
match Oidc.Client.dynamic_of_string s with
| Ok s -> Lwt_result.return s
| Error e -> Lwt_result.fail (`Msg e))
| None -> Lwt_result.fail (`Msg "No_registration_endpoint")
let register (type store)
~(kv : (module KeyValue.KV with type value = string and type store = store))
~(store : store) ~http_client ~meta ~(discovery : Oidc.Discover.t) =
let (module KV) = kv in
let open Lwt_result.Infix in
( KV.get ~store "dynamic_string" >>= fun dynamic_string ->
Lwt.return
(match Oidc.Client.dynamic_of_string dynamic_string with
| Error e -> Error (`Msg e)
| Ok dynamic ->
if Oidc.Client.dynamic_is_expired dynamic then Error `Expired_client
else Ok dynamic) )
|> fun r ->
Lwt.bind r (fun x ->
match (x, discovery.registration_endpoint) with
| Ok dynamic, _ -> Lwt_result.return dynamic
| Error _, Some endpoint ->
let meta_string = Oidc.Client.meta_to_string meta in
let body = Piaf.Body.of_string meta_string in
let registration_path = endpoint |> Uri.path in
( Piaf.Client.post http_client ~body registration_path >>= to_string_body
>>= fun dynamic_string ->
let () = Log.debug (fun m -> m "dynamic string: %s" dynamic_string) in
let open Lwt.Syntax in
let+ () = KV.set ~store "dynamic_string" dynamic_string in
Ok dynamic_string )
>>= fun s ->
(match Oidc.Client.dynamic_of_string s with
| Ok s -> Ok s
| Error e -> Error (`Msg e))
|> Lwt.return
| Error _, None -> Lwt_result.fail (`Msg "No_registration_endpoint"))
let discover (type store)
~(kv : (module KeyValue.KV with type value = string and type store = store))
~(store : store) ~http_client ~provider_uri :
(Oidc.Discover.t, Piaf.Error.t) Lwt_result.t =
let (module KV) = kv in
let open Lwt.Syntax in
let save discovery =
Log.debug (fun m -> m "discovery: %s" discovery);
let+ () = KV.set ~store "discovery" discovery in
discovery
in
let* result = KV.get ~store "discovery" in
let open Lwt_result.Syntax in
let* discovery =
match result with
| Ok discovery -> Lwt_result.return discovery
| Error _ ->
let discover_path =
Uri.path provider_uri ^ "/.well-known/openid-configuration"
in
let* response = Piaf.Client.get http_client discover_path in
let* body = to_string_body response in
Lwt.bind (save body) (fun body -> Lwt_result.return body)
in
Lwt.return
(Result.map_error (fun x -> `Msg x) (Oidc.Discover.of_string discovery))
let jwks (type store)
~(kv : (module KeyValue.KV with type value = string and type store = store))
~(store : store) ~http_client ~provider_uri =
let open Lwt_result.Infix in
let open Lwt_result.Syntax in
let (module KV) = kv in
let save jwks =
KV.set ~store "jwks" jwks |> Lwt_result.ok >|= fun _ -> jwks
in
Lwt.bind (KV.get ~store "jwks") (fun result ->
match result with
| Ok jwks -> Lwt_result.return jwks
| Error _ ->
let* discovery = discover ~kv ~store ~http_client ~provider_uri in
let jwks_path = discovery.jwks_uri |> Uri.path in
Piaf.Client.get http_client jwks_path >>= to_string_body >>= save)
|> Lwt_result.map Jose.Jwks.of_string
let validate_userinfo ~(jwt : Jose.Jwt.t) userinfo =
let userinfo_json = Yojson.Safe.from_string userinfo in
let userinfo_sub =
Yojson.Safe.Util.member "sub" userinfo_json
|> Yojson.Safe.Util.to_string_option
in
let sub =
Yojson.Safe.Util.member "sub" jwt.payload |> Yojson.Safe.Util.to_string
in
match userinfo_sub with
| Some s when s = sub ->
Log.debug (fun m -> m "Userinfo is valid");
Ok userinfo
| Some s ->
Log.debug (fun m -> m "Userinfo has invalid sub, expected %s got %s" sub s);
Error `Sub_missmatch
| None ->
Log.debug (fun m -> m "Userinfo is missing sub");
Error `Missing_sub
|
2b6f72ac1620334be7fe38e855bee91c913e02543a09a15e732e220580c45c45 | abella-prover/abella | test_prover.ml | open OUnit
open Test_helper
open Term
open Metaterm
open Prover
let assert_n_subgoals n =
if n <> 1 + List.length !subgoals then
assert_failure ("Expected " ^ (string_of_int n) ^ " subgoal(s), " ^
"but current proof state is,\n\n" ^ get_display ())
let assert_proof proof_function =
try
proof_function () ;
assert_failure ("Proof not completed,\n\n" ^ get_display ())
with Failure("Proof completed.") -> ()
let assert_goal goal =
assert_string_equal goal (metaterm_to_string sequent.goal)
let setup_prover ?clauses:(clauses=[])
?goal:(goal="") ?lemmas:(lemmas=[]) () =
full_reset_prover () ;
add_clauses clauses ;
if goal <> "" then Prover.sequent.goal <- freshen goal ;
Prover.lemmas :=
List.map (fun (name,body) -> (name, parse_metaterm body)) lemmas
let tests =
"Prover" >:::
[
"New variables added to context" >::
(fun () ->
setup_prover ()
~clauses:eval_clauses ;
add_hyp (freshen "{eval A B}") ;
case "H1" ;
assert_bool "R should be added to variable list"
(List.mem_assoc "R" sequent.vars)
) ;
"Intros should raise over support" >::
(fun () ->
setup_prover ()
~goal:"forall L, rel1 n1 L" ;
intros [] ;
assert_goal "rel1 n1 (L n1)"
) ;
"Intros on multiple nabla variables" >::
(fun () ->
setup_prover ()
~goal:"nabla (x:i) y, x = y" ;
intros [] ;
assert_goal "n1 = n2"
) ;
"Assert test" >::
(fun () ->
setup_prover ()
~goal:"{a}" ;
assert_hyp (parse_umetaterm "{b}") ;
assert_n_subgoals 2 ;
assert_pprint_equal "{b}" sequent.goal ;
skip () ;
assert_n_subgoals 1 ;
assert_pprint_equal "{a}" sequent.goal ;
match sequent.hyps with
| [h] -> assert_pprint_equal "{b}" h.term
| _ -> assert_failure "Expected one hypothesis"
) ;
"Monotone test" >::
(fun () ->
setup_prover () ;
add_hyp (freshen "{L, E |- conc A}*") ;
monotone "H1" (parse_uterm "a :: b :: nil") ;
assert_n_subgoals 2 ;
assert_pprint_equal
"forall X, member X (E :: L) -> member X (a :: b :: nil)"
sequent.goal ;
skip () ;
assert_n_subgoals 1 ;
match sequent.hyps with
| [_; h] ->
assert_pprint_equal "{b, a |- conc A}*" h.term
| _ -> assert_failure "Expected two hypotheses"
) ;
"Split test" >::
(fun () ->
setup_prover ()
~goal:"{A} /\\ {B}" ;
split false ;
assert_n_subgoals 2 ;
assert_pprint_equal "{A}" sequent.goal ;
skip () ;
match sequent.hyps with
| [] -> assert_pprint_equal "{B}" sequent.goal
| _ -> assert_failure "Expected no hypotheses"
) ;
"SplitStar test" >::
(fun () ->
setup_prover ()
~goal:"{A} /\\ {B}" ;
split true ;
assert_n_subgoals 2 ;
assert_pprint_equal "{A}" sequent.goal ;
skip () ;
match sequent.hyps with
| [h] ->
assert_pprint_equal "{A}" h.term ;
assert_pprint_equal "{B}" sequent.goal
| _ -> assert_failure "Expected one hypothesis"
) ;
"Split many test" >::
(fun () ->
setup_prover ()
~goal:"({A} /\\ {B}) /\\ ({C} /\\ {D})" ;
split false ;
assert_n_subgoals 4 ;
assert_pprint_equal "{A}" sequent.goal ;
skip () ;
assert_pprint_equal "{B}" sequent.goal ;
skip () ;
assert_pprint_equal "{C}" sequent.goal ;
skip () ;
assert_pprint_equal "{D}" sequent.goal
) ;
"SplitStar many test" >::
(fun () ->
setup_prover ()
~goal:"{A} /\\ {B} /\\ {C}" ;
split true ;
assert_n_subgoals 3 ;
assert_pprint_equal "{A}" sequent.goal ;
skip () ;
begin match sequent.hyps with
| [h] ->
assert_pprint_equal "{A}" h.term ;
assert_pprint_equal "{B}" sequent.goal
| _ -> assert_failure "Expected one hypothesis"
end ;
skip () ;
begin match sequent.hyps with
| [h1; h2] ->
assert_pprint_equal "{A}" h1.term ;
assert_pprint_equal "{B}" h2.term ;
assert_pprint_equal "{C}" sequent.goal
| _ -> assert_failure "Expected two hypotheses"
end
) ;
"Needless split" >::
(fun () ->
setup_prover ()
~goal:"{A}" ;
assert_raises (Failure "Needless use of split")
(fun () -> split false)
) ;
"Exists test" >::
(fun () ->
setup_prover ()
~goal:"exists A, foo A" ;
exists (parse_uterm "t1") ;
assert_pprint_equal "foo t1" sequent.goal) ;
"Obligations from apply should be added as subgoals" >::
(fun () ->
setup_prover ()
~goal:"baz B" ;
add_hyp
(freshen ("forall A, foo A -> bar A -> baz A")) ;
add_hyp (freshen "foo B") ;
assert_n_subgoals 1 ;
apply "H1" ["H2"; "_"] [] ;
assert_n_subgoals 2 ;
assert_pprint_equal "bar B" sequent.goal ;
skip () ;
assert_n_subgoals 1 ;
assert_pprint_equal "baz B" sequent.goal ;
);
"Apply should trigger case analysis" >::
(fun () ->
setup_prover () ;
add_hyp (freshen "forall A, foo A -> bar A /\\ baz A") ;
add_hyp (freshen "foo B") ;
apply "H1" ["H2"] [] ;
assert_pprint_equal "bar B" (get_hyp "H3") ;
assert_pprint_equal "baz B" (get_hyp "H4") ;
);
"Cases should not consume fresh hyp names" >::
(fun () ->
setup_prover ()
~clauses:eval_clauses
~goal:"forall P V, {typeof P V} -> {typeof P V}" ;
intros [] ;
case ~keep:true "H1" ;
assert_n_subgoals 2 ;
assert_string_list_equal ["H1"; "H2"]
(List.map (fun h -> h.id) sequent.hyps) ;
search () ;
assert_n_subgoals 1 ;
assert_string_list_equal
["H1"; "H2"; "H3"] (List.map (fun h -> h.id) sequent.hyps)
) ;
"Skip should remove current subcase" >::
(fun () ->
setup_prover ()
~clauses:eval_clauses
~goal:"forall P V, {typeof P V} -> {typeof P V}" ;
intros [] ;
case "H1" ;
assert_n_subgoals 2 ;
skip () ;
assert_n_subgoals 1 ;
) ;
"Add example (lemmas)" >::
(fun () ->
let addition_clauses = parse_clauses "
add z N N.
add (s A) B (s C) :- add A B C.
nat z.
nat (s N) :- nat N."
in
setup_prover ()
~clauses:addition_clauses
~goal:"forall A B C, {nat B} -> {add A B C} -> {add B A C}"
~lemmas:[
("base", "forall N, {nat N} -> {add N z N}") ;
("step", "forall A B C, {add A B C} -> {add A (s B) (s C)}")] ;
assert_proof
(fun () ->
induction [2] ;
intros [] ;
case "H2" ;
assert_n_subgoals 2 ;
apply "base" ["H1"] [] ;
search () ;
assert_n_subgoals 1 ;
apply "IH" ["H1"; "H3"] [] ;
apply "step" ["H4"] [] ;
search () ;
)
) ;
"Undo should restore previous save state" >::
(fun () ->
setup_prover ()
~clauses:eval_clauses
~goal:"forall P V T, {eval P V} -> {typeof P T} -> {typeof V T}" ;
induction [1] ;
intros [] ;
assert_n_subgoals 1 ;
save_undo_state () ;
case "H1" ;
assert_n_subgoals 2 ;
undo () ;
assert_n_subgoals 1 ;
case "H1" ;
assert_n_subgoals 2 ;
) ;
"Inst should error on vacuous" >::
(fun () ->
setup_prover ()
~goal:"{b}" ;
add_hyp (freshen "{a}") ;
assert_raises (Failure("Vacuous instantiation"))
(fun () -> inst "H1" [("n1", (parse_uterm "t1"))])
) ;
"Proving OR" >::
(fun () ->
let clauses = parse_clauses "p1 t1. p1 t2. eq X X." in
setup_prover ()
~clauses:clauses
~goal:"forall X, {p1 X} -> {eq X t1} \\/ {eq X t2}" ;
assert_proof
(fun () ->
induction [1] ;
intros [] ;
case "H1" ;
assert_n_subgoals 2 ;
search () ;
assert_n_subgoals 1 ;
search () ;
)
) ;
"OR on left side of arrow" >::
(fun () ->
let clauses = parse_clauses "p1 t1. p1 t2. eq X X." in
setup_prover ()
~clauses:clauses
~goal:"forall X, {eq X t1} \\/ {eq X t2} -> {p1 X}" ;
assert_proof
(fun () ->
intros [] ;
case "H1" ;
assert_n_subgoals 2 ;
case "H2" ;
search () ;
assert_n_subgoals 1 ;
case "H2" ;
search () ;
)
) ;
"Using IH with OR" >::
(fun () ->
let clauses = parse_clauses
("nat z. nat (s X) :- nat X." ^
"even z. even (s X) :- odd X." ^
"odd (s z). odd (s X) :- even X.") in
setup_prover ()
~clauses:clauses
~goal:"forall X, {nat X} -> {even X} \\/ {odd X}" ;
assert_proof
(fun () ->
induction [1] ;
intros [] ;
case "H1" ;
assert_n_subgoals 2 ;
search () ;
assert_n_subgoals 1 ;
apply "IH" ["H2"] [] ;
case "H3" ;
assert_n_subgoals 2 ;
search () ;
assert_n_subgoals 1 ;
search () ;
)
) ;
"Toplevel logic variable should produce error in apply" >::
(fun () ->
setup_prover () ;
add_hyp (freshen "forall A, {a} -> bar A") ;
add_hyp (freshen "{a}") ;
try
apply "H1" ["H2"] [] ;
assert_failure ("Logic variable did not produce error\n\n" ^
get_display ())
with
| Failure("Found logic variable at toplevel") -> ()
) ;
"Search should not find the inductive hypothesis" >::
(fun () ->
setup_prover ()
~goal:"forall X, {p1 X} -> {p2 X}" ;
induction [1] ;
search () ;
This may throw Failure("Proof completed " ) which
indicates test failure
indicates test failure *)
);
"Search should not find complex co-inductive hypothesis" >::
(fun () ->
setup_prover ()
~goal:"forall X, foo X -> bar X" ;
add_defs ["bar"] Abella_types.CoInductive
(parse_defs "bar X := bar X.") ;
coinduction () ;
search () ;
This may throw Failure("Proof completed " ) which
indicates test failure
indicates test failure *)
);
"Search should find simple co-inductive hypothesis" >::
(fun () ->
setup_prover ()
~goal:"bar X" ;
add_defs ["bar"] Abella_types.CoInductive
(parse_defs "bar X := bar X.") ;
assert_proof
(fun () ->
coinduction () ;
search ())
);
"Apply should not work with IH as argument" >::
(fun () ->
setup_prover ()
~lemmas:[("lem", "(forall X, foo X -> bar X) -> {a}")]
~goal:"forall X, foo X -> bar X" ;
add_defs ["foo"] Abella_types.Inductive
(parse_defs "foo X := foo X.") ;
induction [1] ;
assert_raises_any (fun () -> apply "lem" ["IH"] []) ;
);
"Apply should not work with CH as argument" >::
(fun () ->
setup_prover ()
~lemmas:[("lem", "(forall X, foo X -> bar X) -> {a}")]
~goal:"forall X, foo X -> bar X" ;
add_defs ["bar"] Abella_types.CoInductive
(parse_defs "bar X := bar X.") ;
coinduction () ;
assert_raises_any (fun () -> apply "lem" ["CH"] []) ;
);
"Apply should not work with coinductively restricted argument" >::
(fun () ->
setup_prover ()
~lemmas:[("lem", "forall X, foo X -> bar X")]
~goal:"forall X, foo X + -> bar X" ;
intros [] ;
assert_raises_any (fun () -> apply "lem" ["H1"] []) ;
);
"Case-analysis with nabla in the head, two in a row" >::
(fun () ->
setup_prover ()
~goal:"forall X Y, foo X -> foo Y -> \
(X = Y \\/ (X = Y -> false))" ;
add_defs ["foo"] Abella_types.Inductive
(parse_defs "nabla x, foo x.") ;
assert_proof
(fun () ->
intros [] ;
case "H1" ;
assert_n_subgoals 1 ;
case "H2" ;
assert_n_subgoals 2 ;
right () ;
intros [] ;
case "H3" ;
assert_n_subgoals 1 ;
search ()
)
) ;
"Induction within coinduction should fail" >::
(fun () ->
setup_prover ()
~goal:"forall X, foo X -> bar X" ;
add_defs ["foo"] Abella_types.Inductive
(parse_defs "foo X := foo X.") ;
add_defs ["bar"] Abella_types.CoInductive
(parse_defs "bar X := bar X.") ;
coinduction () ;
assert_raises (Failure "Induction within coinduction is not allowed")
(fun () -> induction [1]) ;
) ;
"Coinduction within induction should fail" >::
(fun () ->
setup_prover ()
~goal:"forall X, foo X -> bar X" ;
add_defs ["foo"] Abella_types.Inductive
(parse_defs "foo X := foo X.") ;
add_defs ["bar"] Abella_types.CoInductive
(parse_defs "bar X := bar X.") ;
induction [1] ;
assert_raises (Failure "Coinduction within induction is not allowed")
coinduction ;
) ;
"Huet's unification example" >::
(fun () ->
setup_prover ()
~goal:"forall F X, F (F X) = r1 (r1 t1) ->
(F = x1\\r1 (r1 t1)) \\/
(F = x1\\r1 x1 /\\ X = t1) \\/
(F = x1\\x1 /\\ X = r1 (r1 t1))" ;
assert_proof
(fun () ->
intros [] ;
case "H1" ;
assert_n_subgoals 2 ;
case "H2" ;
assert_n_subgoals 3 ;
case "H3" ;
assert_n_subgoals 3 ;
search () ;
assert_n_subgoals 2 ;
search () ;
assert_n_subgoals 1 ;
search () ;
);
) ;
"Split theorem" >::
(fun () ->
let t =
parse_metaterm
("forall X, foo X -> " ^
"(forall Y, nabla Z, bar Y -> bar Z) /\\" ^
"(forall W, baz W)")
in
match split_theorem t with
| [t1; t2] ->
assert_pprint_equal
"forall X Y, nabla Z, foo X -> bar Y -> bar Z" t1 ;
assert_pprint_equal
"forall X W, foo X -> baz W" t2 ;
| ts -> assert_int_equal 2 (List.length ts)
);
"Split theorem (variable capture)" >::
(fun () ->
let t = parse_metaterm "forall X, foo X -> (forall X, bar X)" in
assert_raises (Failure "Variable renaming required")
(fun () -> split_theorem t)
);
"Split theorem (variable/constant capture)" >::
(fun () ->
let t = parse_metaterm "foo t1 -> (forall t1, bar t1)" in
assert_raises (Failure "Variable renaming required")
(fun () -> split_theorem t)
);
"Split with raising" >::
(fun () ->
let t =
parse_metaterm
("forall X, nabla Z, rel1 X Z -> " ^
"(forall Y, nabla Z', rel2 Y Z') /\\" ^
"(forall W, foo W)")
in
match split_theorem t with
| [t1; t2] ->
assert_pprint_equal
"forall X Y, nabla Z Z', rel1 X Z -> rel2 (Y Z) Z'" t1 ;
assert_pprint_equal
"forall X W, nabla Z, rel1 X Z -> foo (W Z)" t2 ;
| ts -> assert_int_equal 2 (List.length ts)
);
"Split with raising (types test)" >::
(fun () ->
let t = parse_metaterm "nabla (Z1:tm) (Z2:ty), forall Y, foo Y" in
match split_theorem t with
| [t1] ->
assert_pprint_equal
"forall Y, nabla Z1 Z2, foo (Y Z1 Z2)" t1 ;
begin match t1 with
| Binding(Forall, [(y, ty)], _) ->
assert_ty_pprint_equal "tm -> ty -> i" ty ;
| _ -> assert false
end
| ts -> assert_int_equal 1 (List.length ts)
);
"Split with raising and subordination" >::
(fun () ->
let t =
parse_metaterm "nabla (x:sr_a) (y:sr_b), forall A B, sr_a_b A B"
in
match split_theorem t with
| [t1] ->
assert_pprint_equal
"forall A B, nabla x y, sr_a_b (A x) (B x y)" t1 ;
| ts -> assert_int_equal 1 (List.length ts)
);
"Intros should use subordination information" >::
(fun () ->
setup_prover ()
~goal:"nabla x y, forall X Y, sr_a_b x y -> sr_a_b X Y" ;
intros [] ;
assert_goal "sr_a_b (X n1) (Y n2 n1)" ;
);
"Should not be able to close built-in types" >::
(fun () ->
let should_not_close id =
assert_raises (Failure ("Cannot close " ^ id))
(fun () -> close_types [id])
in
should_not_close "o" ;
should_not_close "olist" ;
should_not_close "prop" ;
);
]
| null | https://raw.githubusercontent.com/abella-prover/abella/d3a2d56b750cab84c3bee46ab041d37ad5f8addd/test/test_prover.ml | ocaml | open OUnit
open Test_helper
open Term
open Metaterm
open Prover
let assert_n_subgoals n =
if n <> 1 + List.length !subgoals then
assert_failure ("Expected " ^ (string_of_int n) ^ " subgoal(s), " ^
"but current proof state is,\n\n" ^ get_display ())
let assert_proof proof_function =
try
proof_function () ;
assert_failure ("Proof not completed,\n\n" ^ get_display ())
with Failure("Proof completed.") -> ()
let assert_goal goal =
assert_string_equal goal (metaterm_to_string sequent.goal)
let setup_prover ?clauses:(clauses=[])
?goal:(goal="") ?lemmas:(lemmas=[]) () =
full_reset_prover () ;
add_clauses clauses ;
if goal <> "" then Prover.sequent.goal <- freshen goal ;
Prover.lemmas :=
List.map (fun (name,body) -> (name, parse_metaterm body)) lemmas
let tests =
"Prover" >:::
[
"New variables added to context" >::
(fun () ->
setup_prover ()
~clauses:eval_clauses ;
add_hyp (freshen "{eval A B}") ;
case "H1" ;
assert_bool "R should be added to variable list"
(List.mem_assoc "R" sequent.vars)
) ;
"Intros should raise over support" >::
(fun () ->
setup_prover ()
~goal:"forall L, rel1 n1 L" ;
intros [] ;
assert_goal "rel1 n1 (L n1)"
) ;
"Intros on multiple nabla variables" >::
(fun () ->
setup_prover ()
~goal:"nabla (x:i) y, x = y" ;
intros [] ;
assert_goal "n1 = n2"
) ;
"Assert test" >::
(fun () ->
setup_prover ()
~goal:"{a}" ;
assert_hyp (parse_umetaterm "{b}") ;
assert_n_subgoals 2 ;
assert_pprint_equal "{b}" sequent.goal ;
skip () ;
assert_n_subgoals 1 ;
assert_pprint_equal "{a}" sequent.goal ;
match sequent.hyps with
| [h] -> assert_pprint_equal "{b}" h.term
| _ -> assert_failure "Expected one hypothesis"
) ;
"Monotone test" >::
(fun () ->
setup_prover () ;
add_hyp (freshen "{L, E |- conc A}*") ;
monotone "H1" (parse_uterm "a :: b :: nil") ;
assert_n_subgoals 2 ;
assert_pprint_equal
"forall X, member X (E :: L) -> member X (a :: b :: nil)"
sequent.goal ;
skip () ;
assert_n_subgoals 1 ;
match sequent.hyps with
| [_; h] ->
assert_pprint_equal "{b, a |- conc A}*" h.term
| _ -> assert_failure "Expected two hypotheses"
) ;
"Split test" >::
(fun () ->
setup_prover ()
~goal:"{A} /\\ {B}" ;
split false ;
assert_n_subgoals 2 ;
assert_pprint_equal "{A}" sequent.goal ;
skip () ;
match sequent.hyps with
| [] -> assert_pprint_equal "{B}" sequent.goal
| _ -> assert_failure "Expected no hypotheses"
) ;
"SplitStar test" >::
(fun () ->
setup_prover ()
~goal:"{A} /\\ {B}" ;
split true ;
assert_n_subgoals 2 ;
assert_pprint_equal "{A}" sequent.goal ;
skip () ;
match sequent.hyps with
| [h] ->
assert_pprint_equal "{A}" h.term ;
assert_pprint_equal "{B}" sequent.goal
| _ -> assert_failure "Expected one hypothesis"
) ;
"Split many test" >::
(fun () ->
setup_prover ()
~goal:"({A} /\\ {B}) /\\ ({C} /\\ {D})" ;
split false ;
assert_n_subgoals 4 ;
assert_pprint_equal "{A}" sequent.goal ;
skip () ;
assert_pprint_equal "{B}" sequent.goal ;
skip () ;
assert_pprint_equal "{C}" sequent.goal ;
skip () ;
assert_pprint_equal "{D}" sequent.goal
) ;
"SplitStar many test" >::
(fun () ->
setup_prover ()
~goal:"{A} /\\ {B} /\\ {C}" ;
split true ;
assert_n_subgoals 3 ;
assert_pprint_equal "{A}" sequent.goal ;
skip () ;
begin match sequent.hyps with
| [h] ->
assert_pprint_equal "{A}" h.term ;
assert_pprint_equal "{B}" sequent.goal
| _ -> assert_failure "Expected one hypothesis"
end ;
skip () ;
begin match sequent.hyps with
| [h1; h2] ->
assert_pprint_equal "{A}" h1.term ;
assert_pprint_equal "{B}" h2.term ;
assert_pprint_equal "{C}" sequent.goal
| _ -> assert_failure "Expected two hypotheses"
end
) ;
"Needless split" >::
(fun () ->
setup_prover ()
~goal:"{A}" ;
assert_raises (Failure "Needless use of split")
(fun () -> split false)
) ;
"Exists test" >::
(fun () ->
setup_prover ()
~goal:"exists A, foo A" ;
exists (parse_uterm "t1") ;
assert_pprint_equal "foo t1" sequent.goal) ;
"Obligations from apply should be added as subgoals" >::
(fun () ->
setup_prover ()
~goal:"baz B" ;
add_hyp
(freshen ("forall A, foo A -> bar A -> baz A")) ;
add_hyp (freshen "foo B") ;
assert_n_subgoals 1 ;
apply "H1" ["H2"; "_"] [] ;
assert_n_subgoals 2 ;
assert_pprint_equal "bar B" sequent.goal ;
skip () ;
assert_n_subgoals 1 ;
assert_pprint_equal "baz B" sequent.goal ;
);
"Apply should trigger case analysis" >::
(fun () ->
setup_prover () ;
add_hyp (freshen "forall A, foo A -> bar A /\\ baz A") ;
add_hyp (freshen "foo B") ;
apply "H1" ["H2"] [] ;
assert_pprint_equal "bar B" (get_hyp "H3") ;
assert_pprint_equal "baz B" (get_hyp "H4") ;
);
"Cases should not consume fresh hyp names" >::
(fun () ->
setup_prover ()
~clauses:eval_clauses
~goal:"forall P V, {typeof P V} -> {typeof P V}" ;
intros [] ;
case ~keep:true "H1" ;
assert_n_subgoals 2 ;
assert_string_list_equal ["H1"; "H2"]
(List.map (fun h -> h.id) sequent.hyps) ;
search () ;
assert_n_subgoals 1 ;
assert_string_list_equal
["H1"; "H2"; "H3"] (List.map (fun h -> h.id) sequent.hyps)
) ;
"Skip should remove current subcase" >::
(fun () ->
setup_prover ()
~clauses:eval_clauses
~goal:"forall P V, {typeof P V} -> {typeof P V}" ;
intros [] ;
case "H1" ;
assert_n_subgoals 2 ;
skip () ;
assert_n_subgoals 1 ;
) ;
"Add example (lemmas)" >::
(fun () ->
let addition_clauses = parse_clauses "
add z N N.
add (s A) B (s C) :- add A B C.
nat z.
nat (s N) :- nat N."
in
setup_prover ()
~clauses:addition_clauses
~goal:"forall A B C, {nat B} -> {add A B C} -> {add B A C}"
~lemmas:[
("base", "forall N, {nat N} -> {add N z N}") ;
("step", "forall A B C, {add A B C} -> {add A (s B) (s C)}")] ;
assert_proof
(fun () ->
induction [2] ;
intros [] ;
case "H2" ;
assert_n_subgoals 2 ;
apply "base" ["H1"] [] ;
search () ;
assert_n_subgoals 1 ;
apply "IH" ["H1"; "H3"] [] ;
apply "step" ["H4"] [] ;
search () ;
)
) ;
"Undo should restore previous save state" >::
(fun () ->
setup_prover ()
~clauses:eval_clauses
~goal:"forall P V T, {eval P V} -> {typeof P T} -> {typeof V T}" ;
induction [1] ;
intros [] ;
assert_n_subgoals 1 ;
save_undo_state () ;
case "H1" ;
assert_n_subgoals 2 ;
undo () ;
assert_n_subgoals 1 ;
case "H1" ;
assert_n_subgoals 2 ;
) ;
"Inst should error on vacuous" >::
(fun () ->
setup_prover ()
~goal:"{b}" ;
add_hyp (freshen "{a}") ;
assert_raises (Failure("Vacuous instantiation"))
(fun () -> inst "H1" [("n1", (parse_uterm "t1"))])
) ;
"Proving OR" >::
(fun () ->
let clauses = parse_clauses "p1 t1. p1 t2. eq X X." in
setup_prover ()
~clauses:clauses
~goal:"forall X, {p1 X} -> {eq X t1} \\/ {eq X t2}" ;
assert_proof
(fun () ->
induction [1] ;
intros [] ;
case "H1" ;
assert_n_subgoals 2 ;
search () ;
assert_n_subgoals 1 ;
search () ;
)
) ;
"OR on left side of arrow" >::
(fun () ->
let clauses = parse_clauses "p1 t1. p1 t2. eq X X." in
setup_prover ()
~clauses:clauses
~goal:"forall X, {eq X t1} \\/ {eq X t2} -> {p1 X}" ;
assert_proof
(fun () ->
intros [] ;
case "H1" ;
assert_n_subgoals 2 ;
case "H2" ;
search () ;
assert_n_subgoals 1 ;
case "H2" ;
search () ;
)
) ;
"Using IH with OR" >::
(fun () ->
let clauses = parse_clauses
("nat z. nat (s X) :- nat X." ^
"even z. even (s X) :- odd X." ^
"odd (s z). odd (s X) :- even X.") in
setup_prover ()
~clauses:clauses
~goal:"forall X, {nat X} -> {even X} \\/ {odd X}" ;
assert_proof
(fun () ->
induction [1] ;
intros [] ;
case "H1" ;
assert_n_subgoals 2 ;
search () ;
assert_n_subgoals 1 ;
apply "IH" ["H2"] [] ;
case "H3" ;
assert_n_subgoals 2 ;
search () ;
assert_n_subgoals 1 ;
search () ;
)
) ;
"Toplevel logic variable should produce error in apply" >::
(fun () ->
setup_prover () ;
add_hyp (freshen "forall A, {a} -> bar A") ;
add_hyp (freshen "{a}") ;
try
apply "H1" ["H2"] [] ;
assert_failure ("Logic variable did not produce error\n\n" ^
get_display ())
with
| Failure("Found logic variable at toplevel") -> ()
) ;
"Search should not find the inductive hypothesis" >::
(fun () ->
setup_prover ()
~goal:"forall X, {p1 X} -> {p2 X}" ;
induction [1] ;
search () ;
This may throw Failure("Proof completed " ) which
indicates test failure
indicates test failure *)
);
"Search should not find complex co-inductive hypothesis" >::
(fun () ->
setup_prover ()
~goal:"forall X, foo X -> bar X" ;
add_defs ["bar"] Abella_types.CoInductive
(parse_defs "bar X := bar X.") ;
coinduction () ;
search () ;
This may throw Failure("Proof completed " ) which
indicates test failure
indicates test failure *)
);
"Search should find simple co-inductive hypothesis" >::
(fun () ->
setup_prover ()
~goal:"bar X" ;
add_defs ["bar"] Abella_types.CoInductive
(parse_defs "bar X := bar X.") ;
assert_proof
(fun () ->
coinduction () ;
search ())
);
"Apply should not work with IH as argument" >::
(fun () ->
setup_prover ()
~lemmas:[("lem", "(forall X, foo X -> bar X) -> {a}")]
~goal:"forall X, foo X -> bar X" ;
add_defs ["foo"] Abella_types.Inductive
(parse_defs "foo X := foo X.") ;
induction [1] ;
assert_raises_any (fun () -> apply "lem" ["IH"] []) ;
);
"Apply should not work with CH as argument" >::
(fun () ->
setup_prover ()
~lemmas:[("lem", "(forall X, foo X -> bar X) -> {a}")]
~goal:"forall X, foo X -> bar X" ;
add_defs ["bar"] Abella_types.CoInductive
(parse_defs "bar X := bar X.") ;
coinduction () ;
assert_raises_any (fun () -> apply "lem" ["CH"] []) ;
);
"Apply should not work with coinductively restricted argument" >::
(fun () ->
setup_prover ()
~lemmas:[("lem", "forall X, foo X -> bar X")]
~goal:"forall X, foo X + -> bar X" ;
intros [] ;
assert_raises_any (fun () -> apply "lem" ["H1"] []) ;
);
"Case-analysis with nabla in the head, two in a row" >::
(fun () ->
setup_prover ()
~goal:"forall X Y, foo X -> foo Y -> \
(X = Y \\/ (X = Y -> false))" ;
add_defs ["foo"] Abella_types.Inductive
(parse_defs "nabla x, foo x.") ;
assert_proof
(fun () ->
intros [] ;
case "H1" ;
assert_n_subgoals 1 ;
case "H2" ;
assert_n_subgoals 2 ;
right () ;
intros [] ;
case "H3" ;
assert_n_subgoals 1 ;
search ()
)
) ;
"Induction within coinduction should fail" >::
(fun () ->
setup_prover ()
~goal:"forall X, foo X -> bar X" ;
add_defs ["foo"] Abella_types.Inductive
(parse_defs "foo X := foo X.") ;
add_defs ["bar"] Abella_types.CoInductive
(parse_defs "bar X := bar X.") ;
coinduction () ;
assert_raises (Failure "Induction within coinduction is not allowed")
(fun () -> induction [1]) ;
) ;
"Coinduction within induction should fail" >::
(fun () ->
setup_prover ()
~goal:"forall X, foo X -> bar X" ;
add_defs ["foo"] Abella_types.Inductive
(parse_defs "foo X := foo X.") ;
add_defs ["bar"] Abella_types.CoInductive
(parse_defs "bar X := bar X.") ;
induction [1] ;
assert_raises (Failure "Coinduction within induction is not allowed")
coinduction ;
) ;
"Huet's unification example" >::
(fun () ->
setup_prover ()
~goal:"forall F X, F (F X) = r1 (r1 t1) ->
(F = x1\\r1 (r1 t1)) \\/
(F = x1\\r1 x1 /\\ X = t1) \\/
(F = x1\\x1 /\\ X = r1 (r1 t1))" ;
assert_proof
(fun () ->
intros [] ;
case "H1" ;
assert_n_subgoals 2 ;
case "H2" ;
assert_n_subgoals 3 ;
case "H3" ;
assert_n_subgoals 3 ;
search () ;
assert_n_subgoals 2 ;
search () ;
assert_n_subgoals 1 ;
search () ;
);
) ;
"Split theorem" >::
(fun () ->
let t =
parse_metaterm
("forall X, foo X -> " ^
"(forall Y, nabla Z, bar Y -> bar Z) /\\" ^
"(forall W, baz W)")
in
match split_theorem t with
| [t1; t2] ->
assert_pprint_equal
"forall X Y, nabla Z, foo X -> bar Y -> bar Z" t1 ;
assert_pprint_equal
"forall X W, foo X -> baz W" t2 ;
| ts -> assert_int_equal 2 (List.length ts)
);
"Split theorem (variable capture)" >::
(fun () ->
let t = parse_metaterm "forall X, foo X -> (forall X, bar X)" in
assert_raises (Failure "Variable renaming required")
(fun () -> split_theorem t)
);
"Split theorem (variable/constant capture)" >::
(fun () ->
let t = parse_metaterm "foo t1 -> (forall t1, bar t1)" in
assert_raises (Failure "Variable renaming required")
(fun () -> split_theorem t)
);
"Split with raising" >::
(fun () ->
let t =
parse_metaterm
("forall X, nabla Z, rel1 X Z -> " ^
"(forall Y, nabla Z', rel2 Y Z') /\\" ^
"(forall W, foo W)")
in
match split_theorem t with
| [t1; t2] ->
assert_pprint_equal
"forall X Y, nabla Z Z', rel1 X Z -> rel2 (Y Z) Z'" t1 ;
assert_pprint_equal
"forall X W, nabla Z, rel1 X Z -> foo (W Z)" t2 ;
| ts -> assert_int_equal 2 (List.length ts)
);
"Split with raising (types test)" >::
(fun () ->
let t = parse_metaterm "nabla (Z1:tm) (Z2:ty), forall Y, foo Y" in
match split_theorem t with
| [t1] ->
assert_pprint_equal
"forall Y, nabla Z1 Z2, foo (Y Z1 Z2)" t1 ;
begin match t1 with
| Binding(Forall, [(y, ty)], _) ->
assert_ty_pprint_equal "tm -> ty -> i" ty ;
| _ -> assert false
end
| ts -> assert_int_equal 1 (List.length ts)
);
"Split with raising and subordination" >::
(fun () ->
let t =
parse_metaterm "nabla (x:sr_a) (y:sr_b), forall A B, sr_a_b A B"
in
match split_theorem t with
| [t1] ->
assert_pprint_equal
"forall A B, nabla x y, sr_a_b (A x) (B x y)" t1 ;
| ts -> assert_int_equal 1 (List.length ts)
);
"Intros should use subordination information" >::
(fun () ->
setup_prover ()
~goal:"nabla x y, forall X Y, sr_a_b x y -> sr_a_b X Y" ;
intros [] ;
assert_goal "sr_a_b (X n1) (Y n2 n1)" ;
);
"Should not be able to close built-in types" >::
(fun () ->
let should_not_close id =
assert_raises (Failure ("Cannot close " ^ id))
(fun () -> close_types [id])
in
should_not_close "o" ;
should_not_close "olist" ;
should_not_close "prop" ;
);
]
|
|
c14d27e518e8833c30cd9908b2737b8986827081dd0a6b4f11d87a8dc0aa0fee | Eduap-com/WordMat | c1f4kb.lisp | ;;; Compiled by f2cl version:
( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " )
;;; Using Lisp CMU Common Lisp snapshot-2020-04 (21D Unicode)
;;;
;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
;;; (:coerce-assigns :as-needed) (:array-type ':array)
;;; (:array-slicing t) (:declare-common nil)
;;; (:float-format single-float))
(in-package "FFTPACK5")
(defun c1f4kb (ido l1 na cc in1 ch in2 wa)
(declare (type (array double-float (*)) wa ch cc)
(type (f2cl-lib:integer4) in2 in1 na l1 ido))
(f2cl-lib:with-multi-array-data
((cc double-float cc-%data% cc-%offset%)
(ch double-float ch-%data% ch-%offset%)
(wa double-float wa-%data% wa-%offset%))
(prog ((ci4 0.0d0) (ci2 0.0d0) (cr4 0.0d0) (cr2 0.0d0) (ci3 0.0d0)
(cr3 0.0d0) (i 0) (tr3 0.0d0) (ti4 0.0d0) (tr2 0.0d0) (tr1 0.0d0)
(ti3 0.0d0) (tr4 0.0d0) (ti2 0.0d0) (ti1 0.0d0) (k 0))
(declare (type (f2cl-lib:integer4) k i)
(type (double-float) ti1 ti2 tr4 ti3 tr1 tr2 ti4 tr3 cr3 ci3 cr2
cr4 ci2 ci4))
(if (or (> ido 1) (= na 1)) (go label102))
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k l1) nil)
(tagbody
(setf ti1
(-
(f2cl-lib:fref cc-%data%
(2 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti2
(+
(f2cl-lib:fref cc-%data%
(2 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr4
(-
(f2cl-lib:fref cc-%data%
(2 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti3
(+
(f2cl-lib:fref cc-%data%
(2 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr1
(-
(f2cl-lib:fref cc-%data%
(1 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr2
(+
(f2cl-lib:fref cc-%data%
(1 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti4
(-
(f2cl-lib:fref cc-%data%
(1 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr3
(+
(f2cl-lib:fref cc-%data%
(1 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf (f2cl-lib:fref cc-%data%
(1 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(+ tr2 tr3))
(setf (f2cl-lib:fref cc-%data%
(1 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(- tr2 tr3))
(setf (f2cl-lib:fref cc-%data%
(2 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(+ ti2 ti3))
(setf (f2cl-lib:fref cc-%data%
(2 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(- ti2 ti3))
(setf (f2cl-lib:fref cc-%data%
(1 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(+ tr1 tr4))
(setf (f2cl-lib:fref cc-%data%
(1 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(- tr1 tr4))
(setf (f2cl-lib:fref cc-%data%
(2 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(+ ti1 ti4))
(setf (f2cl-lib:fref cc-%data%
(2 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(- ti1 ti4))
label101))
(go end_label)
label102
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k l1) nil)
(tagbody
(setf ti1
(-
(f2cl-lib:fref cc-%data%
(2 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti2
(+
(f2cl-lib:fref cc-%data%
(2 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr4
(-
(f2cl-lib:fref cc-%data%
(2 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti3
(+
(f2cl-lib:fref cc-%data%
(2 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr1
(-
(f2cl-lib:fref cc-%data%
(1 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr2
(+
(f2cl-lib:fref cc-%data%
(1 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti4
(-
(f2cl-lib:fref cc-%data%
(1 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr3
(+
(f2cl-lib:fref cc-%data%
(1 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf (f2cl-lib:fref ch-%data%
(1 k 1 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ tr2 tr3))
(setf (f2cl-lib:fref ch-%data%
(1 k 3 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(- tr2 tr3))
(setf (f2cl-lib:fref ch-%data%
(2 k 1 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ ti2 ti3))
(setf (f2cl-lib:fref ch-%data%
(2 k 3 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(- ti2 ti3))
(setf (f2cl-lib:fref ch-%data%
(1 k 2 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ tr1 tr4))
(setf (f2cl-lib:fref ch-%data%
(1 k 4 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(- tr1 tr4))
(setf (f2cl-lib:fref ch-%data%
(2 k 2 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ ti1 ti4))
(setf (f2cl-lib:fref ch-%data%
(2 k 4 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(- ti1 ti4))
label103))
(if (= ido 1) (go end_label))
(f2cl-lib:fdo (i 2 (f2cl-lib:int-add i 1))
((> i ido) nil)
(tagbody
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k l1) nil)
(tagbody
(setf ti1
(-
(f2cl-lib:fref cc-%data%
(2 k i 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k i 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti2
(+
(f2cl-lib:fref cc-%data%
(2 k i 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k i 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti3
(+
(f2cl-lib:fref cc-%data%
(2 k i 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k i 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr4
(-
(f2cl-lib:fref cc-%data%
(2 k i 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k i 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr1
(-
(f2cl-lib:fref cc-%data%
(1 k i 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k i 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr2
(+
(f2cl-lib:fref cc-%data%
(1 k i 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k i 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti4
(-
(f2cl-lib:fref cc-%data%
(1 k i 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k i 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr3
(+
(f2cl-lib:fref cc-%data%
(1 k i 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k i 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf (f2cl-lib:fref ch-%data%
(1 k 1 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ tr2 tr3))
(setf cr3 (- tr2 tr3))
(setf (f2cl-lib:fref ch-%data%
(2 k 1 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ ti2 ti3))
(setf ci3 (- ti2 ti3))
(setf cr2 (+ tr1 tr4))
(setf cr4 (- tr1 tr4))
(setf ci2 (+ ti1 ti4))
(setf ci4 (- ti1 ti4))
(setf (f2cl-lib:fref ch-%data%
(1 k 2 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(-
(*
(f2cl-lib:fref wa-%data%
(i 1 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr2)
(*
(f2cl-lib:fref wa-%data%
(i 1 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci2)))
(setf (f2cl-lib:fref ch-%data%
(2 k 2 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+
(*
(f2cl-lib:fref wa-%data%
(i 1 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci2)
(*
(f2cl-lib:fref wa-%data%
(i 1 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr2)))
(setf (f2cl-lib:fref ch-%data%
(1 k 3 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(-
(*
(f2cl-lib:fref wa-%data%
(i 2 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr3)
(*
(f2cl-lib:fref wa-%data%
(i 2 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci3)))
(setf (f2cl-lib:fref ch-%data%
(2 k 3 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+
(*
(f2cl-lib:fref wa-%data%
(i 2 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci3)
(*
(f2cl-lib:fref wa-%data%
(i 2 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr3)))
(setf (f2cl-lib:fref ch-%data%
(1 k 4 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(-
(*
(f2cl-lib:fref wa-%data%
(i 3 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr4)
(*
(f2cl-lib:fref wa-%data%
(i 3 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci4)))
(setf (f2cl-lib:fref ch-%data%
(2 k 4 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+
(*
(f2cl-lib:fref wa-%data%
(i 3 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci4)
(*
(f2cl-lib:fref wa-%data%
(i 3 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr4)))
label104))
label105))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::c1f4kb
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4) (array double-float (*))
(fortran-to-lisp::integer4) (array double-float (*))
(fortran-to-lisp::integer4) (array double-float (*)))
:return-values '(nil nil nil nil nil nil nil nil)
:calls 'nil)))
| null | https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/fftpack5/lisp/c1f4kb.lisp | lisp | Compiled by f2cl version:
Using Lisp CMU Common Lisp snapshot-2020-04 (21D Unicode)
Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t)
(:coerce-assigns :as-needed) (:array-type ':array)
(:array-slicing t) (:declare-common nil)
(:float-format single-float)) | ( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ "
" f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ "
" f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ "
" macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " )
(in-package "FFTPACK5")
(defun c1f4kb (ido l1 na cc in1 ch in2 wa)
(declare (type (array double-float (*)) wa ch cc)
(type (f2cl-lib:integer4) in2 in1 na l1 ido))
(f2cl-lib:with-multi-array-data
((cc double-float cc-%data% cc-%offset%)
(ch double-float ch-%data% ch-%offset%)
(wa double-float wa-%data% wa-%offset%))
(prog ((ci4 0.0d0) (ci2 0.0d0) (cr4 0.0d0) (cr2 0.0d0) (ci3 0.0d0)
(cr3 0.0d0) (i 0) (tr3 0.0d0) (ti4 0.0d0) (tr2 0.0d0) (tr1 0.0d0)
(ti3 0.0d0) (tr4 0.0d0) (ti2 0.0d0) (ti1 0.0d0) (k 0))
(declare (type (f2cl-lib:integer4) k i)
(type (double-float) ti1 ti2 tr4 ti3 tr1 tr2 ti4 tr3 cr3 ci3 cr2
cr4 ci2 ci4))
(if (or (> ido 1) (= na 1)) (go label102))
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k l1) nil)
(tagbody
(setf ti1
(-
(f2cl-lib:fref cc-%data%
(2 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti2
(+
(f2cl-lib:fref cc-%data%
(2 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr4
(-
(f2cl-lib:fref cc-%data%
(2 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti3
(+
(f2cl-lib:fref cc-%data%
(2 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr1
(-
(f2cl-lib:fref cc-%data%
(1 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr2
(+
(f2cl-lib:fref cc-%data%
(1 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti4
(-
(f2cl-lib:fref cc-%data%
(1 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr3
(+
(f2cl-lib:fref cc-%data%
(1 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf (f2cl-lib:fref cc-%data%
(1 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(+ tr2 tr3))
(setf (f2cl-lib:fref cc-%data%
(1 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(- tr2 tr3))
(setf (f2cl-lib:fref cc-%data%
(2 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(+ ti2 ti3))
(setf (f2cl-lib:fref cc-%data%
(2 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(- ti2 ti3))
(setf (f2cl-lib:fref cc-%data%
(1 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(+ tr1 tr4))
(setf (f2cl-lib:fref cc-%data%
(1 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(- tr1 tr4))
(setf (f2cl-lib:fref cc-%data%
(2 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(+ ti1 ti4))
(setf (f2cl-lib:fref cc-%data%
(2 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(- ti1 ti4))
label101))
(go end_label)
label102
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k l1) nil)
(tagbody
(setf ti1
(-
(f2cl-lib:fref cc-%data%
(2 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti2
(+
(f2cl-lib:fref cc-%data%
(2 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr4
(-
(f2cl-lib:fref cc-%data%
(2 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti3
(+
(f2cl-lib:fref cc-%data%
(2 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr1
(-
(f2cl-lib:fref cc-%data%
(1 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr2
(+
(f2cl-lib:fref cc-%data%
(1 k 1 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti4
(-
(f2cl-lib:fref cc-%data%
(1 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr3
(+
(f2cl-lib:fref cc-%data%
(1 k 1 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k 1 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf (f2cl-lib:fref ch-%data%
(1 k 1 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ tr2 tr3))
(setf (f2cl-lib:fref ch-%data%
(1 k 3 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(- tr2 tr3))
(setf (f2cl-lib:fref ch-%data%
(2 k 1 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ ti2 ti3))
(setf (f2cl-lib:fref ch-%data%
(2 k 3 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(- ti2 ti3))
(setf (f2cl-lib:fref ch-%data%
(1 k 2 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ tr1 tr4))
(setf (f2cl-lib:fref ch-%data%
(1 k 4 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(- tr1 tr4))
(setf (f2cl-lib:fref ch-%data%
(2 k 2 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ ti1 ti4))
(setf (f2cl-lib:fref ch-%data%
(2 k 4 1)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(- ti1 ti4))
label103))
(if (= ido 1) (go end_label))
(f2cl-lib:fdo (i 2 (f2cl-lib:int-add i 1))
((> i ido) nil)
(tagbody
(f2cl-lib:fdo (k 1 (f2cl-lib:int-add k 1))
((> k l1) nil)
(tagbody
(setf ti1
(-
(f2cl-lib:fref cc-%data%
(2 k i 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k i 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti2
(+
(f2cl-lib:fref cc-%data%
(2 k i 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k i 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti3
(+
(f2cl-lib:fref cc-%data%
(2 k i 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k i 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr4
(-
(f2cl-lib:fref cc-%data%
(2 k i 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(2 k i 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr1
(-
(f2cl-lib:fref cc-%data%
(1 k i 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k i 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr2
(+
(f2cl-lib:fref cc-%data%
(1 k i 1)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k i 3)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf ti4
(-
(f2cl-lib:fref cc-%data%
(1 k i 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k i 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf tr3
(+
(f2cl-lib:fref cc-%data%
(1 k i 2)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)
(f2cl-lib:fref cc-%data%
(1 k i 4)
((1 in1) (1 l1) (1 ido) (1 4))
cc-%offset%)))
(setf (f2cl-lib:fref ch-%data%
(1 k 1 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ tr2 tr3))
(setf cr3 (- tr2 tr3))
(setf (f2cl-lib:fref ch-%data%
(2 k 1 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+ ti2 ti3))
(setf ci3 (- ti2 ti3))
(setf cr2 (+ tr1 tr4))
(setf cr4 (- tr1 tr4))
(setf ci2 (+ ti1 ti4))
(setf ci4 (- ti1 ti4))
(setf (f2cl-lib:fref ch-%data%
(1 k 2 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(-
(*
(f2cl-lib:fref wa-%data%
(i 1 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr2)
(*
(f2cl-lib:fref wa-%data%
(i 1 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci2)))
(setf (f2cl-lib:fref ch-%data%
(2 k 2 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+
(*
(f2cl-lib:fref wa-%data%
(i 1 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci2)
(*
(f2cl-lib:fref wa-%data%
(i 1 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr2)))
(setf (f2cl-lib:fref ch-%data%
(1 k 3 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(-
(*
(f2cl-lib:fref wa-%data%
(i 2 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr3)
(*
(f2cl-lib:fref wa-%data%
(i 2 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci3)))
(setf (f2cl-lib:fref ch-%data%
(2 k 3 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+
(*
(f2cl-lib:fref wa-%data%
(i 2 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci3)
(*
(f2cl-lib:fref wa-%data%
(i 2 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr3)))
(setf (f2cl-lib:fref ch-%data%
(1 k 4 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(-
(*
(f2cl-lib:fref wa-%data%
(i 3 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr4)
(*
(f2cl-lib:fref wa-%data%
(i 3 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci4)))
(setf (f2cl-lib:fref ch-%data%
(2 k 4 i)
((1 in2) (1 l1) (1 4) (1 ido))
ch-%offset%)
(+
(*
(f2cl-lib:fref wa-%data%
(i 3 1)
((1 ido) (1 3) (1 2))
wa-%offset%)
ci4)
(*
(f2cl-lib:fref wa-%data%
(i 3 2)
((1 ido) (1 3) (1 2))
wa-%offset%)
cr4)))
label104))
label105))
(go end_label)
end_label
(return (values nil nil nil nil nil nil nil nil)))))
(in-package #-gcl #:cl-user #+gcl "CL-USER")
#+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or))
(eval-when (:load-toplevel :compile-toplevel :execute)
(setf (gethash 'fortran-to-lisp::c1f4kb
fortran-to-lisp::*f2cl-function-info*)
(fortran-to-lisp::make-f2cl-finfo
:arg-types '((fortran-to-lisp::integer4) (fortran-to-lisp::integer4)
(fortran-to-lisp::integer4) (array double-float (*))
(fortran-to-lisp::integer4) (array double-float (*))
(fortran-to-lisp::integer4) (array double-float (*)))
:return-values '(nil nil nil nil nil nil nil nil)
:calls 'nil)))
|
87f3d24f4b767b9e532a724f7218d8d82c5a7b9779d07bc3d1a25cd6b50f02e2 | Kappa-Dev/KappaTools | ode_loggers_sig.ml | type ode_var_id = int
let int_of_ode_var_id i = i
type variable =
| Expr of int
| Init of int
| Initbis of int
| Concentration of int
| Deriv of int
| Obs of int
| Jacobian of int * int
| Jacobian_var of int * int
| Tinit
| Tend
| InitialStep
| MaxStep
| RelTol
| AbsTol
| Period_t_points
| Rate of int
| Rated of int
| Rateun of int
| Rateund of int
| Stochiometric_coef of int * int
| Jacobian_stochiometric_coef of int * int * int
| Jacobian_rate of int * int
| Jacobian_rated of int * int
| Jacobian_rateun of int * int
| Jacobian_rateund of int * int
| N_max_stoc_coef
| N_rules
| N_ode_var
| N_var
| N_obs
| N_rows
| Tmp
| Current_time
| Time_scale_factor
| NonNegative
let string_of_array_name var =
match var with
| NonNegative -> "nonnegative"
| Rate _ -> "k"
| Rated _ -> "kd"
| Rateun _ -> "kun"
| Rateund _ -> "kdun"
| Stochiometric_coef _ -> "stoc"
| Expr _ -> "var"
| Obs _ -> "obs"
| Init _ -> "init"
| Initbis _ -> "Init"
| Concentration _ -> "y"
| Deriv _ -> "dydt"
| Jacobian _ -> "jac"
| Jacobian_var _ -> "jacvar"
| Jacobian_rate _ -> "jack"
| Jacobian_rated _ -> "jackd"
| Jacobian_rateun _ -> "jackun"
| Jacobian_rateund _ -> "jackund"
| Jacobian_stochiometric_coef _ -> "jacstoc"
| Tinit -> "tinit"
| Tend -> "tend"
| InitialStep -> "initialstep"
| MaxStep -> "maxstep"
| RelTol -> "reltol"
| AbsTol -> "abstol"
| Period_t_points -> "period"
| N_ode_var -> "nodevar"
| N_var -> "nvar"
| N_obs -> "nobs"
| N_rows -> "nrows"
| N_rules -> "nrules"
| N_max_stoc_coef -> "max_stoc_coef"
| Tmp -> "tmp"
| Current_time -> "t"
| Time_scale_factor -> "t_correct_dimmension"
module StringMap = Map.Make (struct type t = string let compare = compare end)
module VarOrd =
struct
type t = variable
let compare = compare
end
module VarMap = Map.Make(VarOrd)
module VarSet = Set.Make(VarOrd)
type t =
{
logger: Loggers.t;
env: (ode_var_id,ode_var_id) Alg_expr.e Locality.annot VarMap.t ref ;
id_map: int StringMap.t ref ;
fresh_meta_id: int ref ;
fresh_reaction_id: int ref;
fresh_obs_id: int ref;
const: VarSet.t ref;
id_of_parameters: string VarMap.t ref;
dangerous_parameters: VarSet.t ref ;
idset: Mods.StringSet.t ref ;
csv_sep: string;
}
let lift f a = f a.logger
let get_encoding_format t = lift Loggers.get_encoding_format t
let fprintf t = lift Loggers.fprintf t
let print_newline t = lift Loggers.print_newline t
let print_breakable_hint t = lift Loggers.print_breakable_hint t
let flush_buffer t fmt = lift Loggers.flush_buffer t fmt
let flush_logger t = lift Loggers.flush_logger t
let formatter_of_logger t = lift Loggers.formatter_of_logger t
let string_of_un_op t = lift Loggers_string_of_op.string_of_un_op t
let string_of_bin_op t = lift Loggers_string_of_op.string_of_bin_op t
let string_of_compare_op t = lift Loggers_string_of_op.string_of_compare_op t
let string_of_un_bool_op t = lift Loggers_string_of_op.string_of_un_bool_op t
let string_of_bin_bool_op t = lift Loggers_string_of_op.string_of_bin_bool_op t
let extend_logger ~csv_sep logger =
{
logger = logger ;
id_map = ref StringMap.empty ;
fresh_meta_id = ref 1 ;
fresh_reaction_id = ref 1;
fresh_obs_id = ref 1;
env = ref VarMap.empty;
const = ref VarSet.empty;
id_of_parameters = ref VarMap.empty;
dangerous_parameters = ref VarSet.empty;
idset = ref Mods.StringSet.empty;
csv_sep ;
}
let odeFileName =
begin
List.fold_left
(fun map (key,value) ->
Loggers.FormatMap.add key (ref value) map)
Loggers.FormatMap.empty
[
Octave, "ode.m";
Matlab, "ode.m";
DOTNET, "network.net";
SBML, "network.xml";
Maple, "ode.mws";
Mathematica, "ode.nb" ;
]
end
let get_odeFileName backend =
try
Loggers.FormatMap.find backend odeFileName
with
Not_found ->
let output = ref "" in
let _ = Loggers.FormatMap.add backend output odeFileName in
output
let set_odeFileName backend name =
let reference = get_odeFileName backend in
reference:=name
let set_ode ~mode f = set_odeFileName mode f
let get_ode ~mode = !(get_odeFileName mode)
let string_of_variable_octave var =
match var with
| Rate int
| Rated int
| Rateun int
| Rateund int
| Expr int
| Obs int
| Init int
| Initbis int
| Concentration int
| Deriv int ->
Printf.sprintf "%s(%i)"
(string_of_array_name var) int
| Jacobian_rate (int1,int2)
| Jacobian_rated (int1,int2)
| Jacobian_rateun (int1,int2)
| Jacobian_rateund (int1,int2)
| Jacobian (int1,int2)
| Jacobian_var (int1,int2)
| Stochiometric_coef (int1,int2) ->
Printf.sprintf "%s(%i,%i)"
(string_of_array_name var) int1 int2
| Jacobian_stochiometric_coef (int1,int2,int3) ->
Printf.sprintf "%s(%i,%i,%i)"
(string_of_array_name var) int1 int2 int3
| MaxStep
| InitialStep
| AbsTol
| RelTol
| Tinit
| Tend
| NonNegative
| Period_t_points
| N_ode_var
| N_var
| N_obs
| N_rules
| N_rows
| N_max_stoc_coef
| Tmp
| Current_time
| Time_scale_factor -> string_of_array_name var
type side = LHS | RHS
let rem_underscore s =
let l = String.split_on_char '_' s in
String.concat "" l
let string_of_variable_mathematica ~side var =
let side_ext =
match side
with
| LHS -> "_"
| RHS -> ""
in
match var with
| Rate int
| Rated int
| Rateun int
| Rateund int
| Obs int
| Concentration int
| Deriv int
| Expr int ->
Printf.sprintf "%s%i[t%s]"
(string_of_array_name var) int side_ext
| Stochiometric_coef (int1,int2) ->
Printf.sprintf "%s%i_%i[t%s]"
(string_of_array_name var) int1 int2 side_ext
| Init int
| Initbis int ->
Printf.sprintf "%s%i"
(string_of_array_name var) int
| Jacobian_rate _
| Jacobian_rated _
| Jacobian_rateun _
| Jacobian_rateund _
| Jacobian _
| Jacobian_var _
| Jacobian_stochiometric_coef _ -> ""
| NonNegative
| Tinit
| Tend
| MaxStep
| InitialStep
| AbsTol
| RelTol
| Period_t_points
| N_ode_var
| N_var
| N_obs
| N_rules
| N_rows
| N_max_stoc_coef
| Tmp
| Current_time
| Time_scale_factor ->
rem_underscore (string_of_array_name var)
let string_of_variable_maple var =
match var with
| Rate int
| Rated int
| Rateun int
| Rateund int
| Obs int
| Concentration int
| Deriv int
| Expr int ->
Printf.sprintf "%s%i(t)"
(string_of_array_name var) int
| Init int
| Initbis int ->
Printf.sprintf "%s%i"
(string_of_array_name var) int
| Stochiometric_coef (int1,int2) ->
Printf.sprintf "%s%i_%i"
(string_of_array_name var) int1 int2
| Jacobian_rate _
| Jacobian_rated _
| Jacobian_rateun _
| Jacobian_rateund _
| Jacobian _
| Jacobian_var _
| Jacobian_stochiometric_coef _ -> ""
| NonNegative
| Tinit
| Tend
| MaxStep
| InitialStep
| AbsTol
| RelTol
| Period_t_points
| N_ode_var
| N_var
| N_obs
| N_rules
| N_rows
| N_max_stoc_coef
| Tmp
| Current_time
| Time_scale_factor ->
(string_of_array_name var)
let string_of_variable ~side loggers variable =
match
Loggers.get_encoding_format loggers.logger
with
| Loggers.Matlab
| Loggers.Octave ->
string_of_variable_octave variable
| Loggers.Mathematica ->
string_of_variable_mathematica ~side variable
| Loggers.Maple ->
string_of_variable_maple variable
| Loggers.Matrix
| Loggers.HTML_Graph
| Loggers.Js_Graph
| Loggers.HTML
| Loggers.HTML_Tabular
| Loggers.DOT
| Loggers.TXT
| Loggers.TXT_Tabular
| Loggers.XLS
| Loggers.SBML
| Loggers.DOTNET
| Loggers.GEPHI
| Loggers.Json -> ""
let variable_of_derived_variable var id =
match var with
| Rate int -> Jacobian_rate (int,id)
| Rated int -> Jacobian_rated (int,id)
| Rateun int -> Jacobian_rateun (int,id)
| Rateund int -> Jacobian_rateund (int,id)
| Expr int -> Jacobian_var (int, id)
| Concentration int -> Jacobian (int, id)
| Stochiometric_coef (int1,int2) ->
Jacobian_stochiometric_coef (int1,int2,id)
| NonNegative -> assert false
| Obs _ -> assert false
| Init _ -> assert false
| Initbis _ -> assert false
| Deriv _ -> assert false
| Jacobian_rate _ -> assert false
| Jacobian_rated _ -> assert false
| Jacobian_rateun _ -> assert false
| Jacobian_rateund _ -> assert false
| Jacobian_stochiometric_coef _ -> assert false
| Jacobian _ -> assert false
| Jacobian_var _ -> assert false
| Tinit -> assert false
| Tend -> assert false
| MaxStep -> assert false
| InitialStep -> assert false
| AbsTol -> assert false
| RelTol -> assert false
| Period_t_points -> assert false
| N_ode_var -> assert false
| N_var -> assert false
| N_obs -> assert false
| N_rules -> assert false
| N_rows -> assert false
| N_max_stoc_coef -> assert false
| Tmp -> assert false
| Current_time -> assert false
| Time_scale_factor -> assert false
let get_expr t v =
try
Some (VarMap.find v (!(t.env)))
with
| Not_found ->
None
let set_dangerous_global_parameter_name t var =
t.dangerous_parameters := VarSet.add var (!(t.dangerous_parameters))
let forbidden_char c =
match c with
'*' | '+' | '-' | '(' | ')' -> true
| _ -> false
let has_forbidden_char t string =
(match get_encoding_format t
with
DOTNET -> true
| Matrix | HTML_Graph | Js_Graph | HTML | HTML_Tabular | DOT | TXT | TXT_Tabular | XLS | GEPHI
| Octave | Matlab | Maple | Mathematica | Json | SBML -> false)
&&
let rec aux k n =
if k=n then false
else forbidden_char (string.[k]) || aux (k+1) n
in
aux 0 (String.length string)
let flag_dangerous t id string =
if has_forbidden_char t string
then
set_dangerous_global_parameter_name t id
let set_expr t v expr =
let const = Alg_expr.is_constant expr in
let () =
if not const then
t.const := VarSet.remove v (!(t.const))
else
t.const := VarSet.add v (!(t.const))
in
t.env := VarMap.add v expr (!(t.env))
let is_const t v =
VarSet.mem v (!(t.const))
let get_fresh_reaction_id t =
let output = !(t.fresh_reaction_id) in
let () = t.fresh_reaction_id:=succ output in
output
let get_id_of_global_parameter t var =
try
VarMap.find var (!(t.id_of_parameters))
with
Not_found -> ""
let set_id_of_global_parameter t var id =
let () = t.id_of_parameters := VarMap.add var id (!(t.id_of_parameters)) in
flag_dangerous t var id
let rec allocate_fresh_name t name potential_suffix =
if Mods.StringSet.mem name (!(t.idset))
then
allocate_fresh_name t (name^potential_suffix) potential_suffix
else
name
let allocate t name =
let () = t.idset := Mods.StringSet.add name (!(t.idset)) in
()
let is_dangerous_ode_variable t var =
VarSet.mem var (!(t.dangerous_parameters))
let get_fresh_meta_id logger = Tools.get_ref logger.fresh_meta_id
let get_fresh_obs_id logger = Tools.get_ref logger.fresh_obs_id
let csv_sep logger = logger.csv_sep
let lift t = t.logger
| null | https://raw.githubusercontent.com/Kappa-Dev/KappaTools/7ebbae0b0387144292b8e25dd8be6b7c9a1f6c75/core/odes/ode_loggers_sig.ml | ocaml | type ode_var_id = int
let int_of_ode_var_id i = i
type variable =
| Expr of int
| Init of int
| Initbis of int
| Concentration of int
| Deriv of int
| Obs of int
| Jacobian of int * int
| Jacobian_var of int * int
| Tinit
| Tend
| InitialStep
| MaxStep
| RelTol
| AbsTol
| Period_t_points
| Rate of int
| Rated of int
| Rateun of int
| Rateund of int
| Stochiometric_coef of int * int
| Jacobian_stochiometric_coef of int * int * int
| Jacobian_rate of int * int
| Jacobian_rated of int * int
| Jacobian_rateun of int * int
| Jacobian_rateund of int * int
| N_max_stoc_coef
| N_rules
| N_ode_var
| N_var
| N_obs
| N_rows
| Tmp
| Current_time
| Time_scale_factor
| NonNegative
let string_of_array_name var =
match var with
| NonNegative -> "nonnegative"
| Rate _ -> "k"
| Rated _ -> "kd"
| Rateun _ -> "kun"
| Rateund _ -> "kdun"
| Stochiometric_coef _ -> "stoc"
| Expr _ -> "var"
| Obs _ -> "obs"
| Init _ -> "init"
| Initbis _ -> "Init"
| Concentration _ -> "y"
| Deriv _ -> "dydt"
| Jacobian _ -> "jac"
| Jacobian_var _ -> "jacvar"
| Jacobian_rate _ -> "jack"
| Jacobian_rated _ -> "jackd"
| Jacobian_rateun _ -> "jackun"
| Jacobian_rateund _ -> "jackund"
| Jacobian_stochiometric_coef _ -> "jacstoc"
| Tinit -> "tinit"
| Tend -> "tend"
| InitialStep -> "initialstep"
| MaxStep -> "maxstep"
| RelTol -> "reltol"
| AbsTol -> "abstol"
| Period_t_points -> "period"
| N_ode_var -> "nodevar"
| N_var -> "nvar"
| N_obs -> "nobs"
| N_rows -> "nrows"
| N_rules -> "nrules"
| N_max_stoc_coef -> "max_stoc_coef"
| Tmp -> "tmp"
| Current_time -> "t"
| Time_scale_factor -> "t_correct_dimmension"
module StringMap = Map.Make (struct type t = string let compare = compare end)
module VarOrd =
struct
type t = variable
let compare = compare
end
module VarMap = Map.Make(VarOrd)
module VarSet = Set.Make(VarOrd)
type t =
{
logger: Loggers.t;
env: (ode_var_id,ode_var_id) Alg_expr.e Locality.annot VarMap.t ref ;
id_map: int StringMap.t ref ;
fresh_meta_id: int ref ;
fresh_reaction_id: int ref;
fresh_obs_id: int ref;
const: VarSet.t ref;
id_of_parameters: string VarMap.t ref;
dangerous_parameters: VarSet.t ref ;
idset: Mods.StringSet.t ref ;
csv_sep: string;
}
let lift f a = f a.logger
let get_encoding_format t = lift Loggers.get_encoding_format t
let fprintf t = lift Loggers.fprintf t
let print_newline t = lift Loggers.print_newline t
let print_breakable_hint t = lift Loggers.print_breakable_hint t
let flush_buffer t fmt = lift Loggers.flush_buffer t fmt
let flush_logger t = lift Loggers.flush_logger t
let formatter_of_logger t = lift Loggers.formatter_of_logger t
let string_of_un_op t = lift Loggers_string_of_op.string_of_un_op t
let string_of_bin_op t = lift Loggers_string_of_op.string_of_bin_op t
let string_of_compare_op t = lift Loggers_string_of_op.string_of_compare_op t
let string_of_un_bool_op t = lift Loggers_string_of_op.string_of_un_bool_op t
let string_of_bin_bool_op t = lift Loggers_string_of_op.string_of_bin_bool_op t
let extend_logger ~csv_sep logger =
{
logger = logger ;
id_map = ref StringMap.empty ;
fresh_meta_id = ref 1 ;
fresh_reaction_id = ref 1;
fresh_obs_id = ref 1;
env = ref VarMap.empty;
const = ref VarSet.empty;
id_of_parameters = ref VarMap.empty;
dangerous_parameters = ref VarSet.empty;
idset = ref Mods.StringSet.empty;
csv_sep ;
}
let odeFileName =
begin
List.fold_left
(fun map (key,value) ->
Loggers.FormatMap.add key (ref value) map)
Loggers.FormatMap.empty
[
Octave, "ode.m";
Matlab, "ode.m";
DOTNET, "network.net";
SBML, "network.xml";
Maple, "ode.mws";
Mathematica, "ode.nb" ;
]
end
let get_odeFileName backend =
try
Loggers.FormatMap.find backend odeFileName
with
Not_found ->
let output = ref "" in
let _ = Loggers.FormatMap.add backend output odeFileName in
output
let set_odeFileName backend name =
let reference = get_odeFileName backend in
reference:=name
let set_ode ~mode f = set_odeFileName mode f
let get_ode ~mode = !(get_odeFileName mode)
let string_of_variable_octave var =
match var with
| Rate int
| Rated int
| Rateun int
| Rateund int
| Expr int
| Obs int
| Init int
| Initbis int
| Concentration int
| Deriv int ->
Printf.sprintf "%s(%i)"
(string_of_array_name var) int
| Jacobian_rate (int1,int2)
| Jacobian_rated (int1,int2)
| Jacobian_rateun (int1,int2)
| Jacobian_rateund (int1,int2)
| Jacobian (int1,int2)
| Jacobian_var (int1,int2)
| Stochiometric_coef (int1,int2) ->
Printf.sprintf "%s(%i,%i)"
(string_of_array_name var) int1 int2
| Jacobian_stochiometric_coef (int1,int2,int3) ->
Printf.sprintf "%s(%i,%i,%i)"
(string_of_array_name var) int1 int2 int3
| MaxStep
| InitialStep
| AbsTol
| RelTol
| Tinit
| Tend
| NonNegative
| Period_t_points
| N_ode_var
| N_var
| N_obs
| N_rules
| N_rows
| N_max_stoc_coef
| Tmp
| Current_time
| Time_scale_factor -> string_of_array_name var
type side = LHS | RHS
let rem_underscore s =
let l = String.split_on_char '_' s in
String.concat "" l
let string_of_variable_mathematica ~side var =
let side_ext =
match side
with
| LHS -> "_"
| RHS -> ""
in
match var with
| Rate int
| Rated int
| Rateun int
| Rateund int
| Obs int
| Concentration int
| Deriv int
| Expr int ->
Printf.sprintf "%s%i[t%s]"
(string_of_array_name var) int side_ext
| Stochiometric_coef (int1,int2) ->
Printf.sprintf "%s%i_%i[t%s]"
(string_of_array_name var) int1 int2 side_ext
| Init int
| Initbis int ->
Printf.sprintf "%s%i"
(string_of_array_name var) int
| Jacobian_rate _
| Jacobian_rated _
| Jacobian_rateun _
| Jacobian_rateund _
| Jacobian _
| Jacobian_var _
| Jacobian_stochiometric_coef _ -> ""
| NonNegative
| Tinit
| Tend
| MaxStep
| InitialStep
| AbsTol
| RelTol
| Period_t_points
| N_ode_var
| N_var
| N_obs
| N_rules
| N_rows
| N_max_stoc_coef
| Tmp
| Current_time
| Time_scale_factor ->
rem_underscore (string_of_array_name var)
let string_of_variable_maple var =
match var with
| Rate int
| Rated int
| Rateun int
| Rateund int
| Obs int
| Concentration int
| Deriv int
| Expr int ->
Printf.sprintf "%s%i(t)"
(string_of_array_name var) int
| Init int
| Initbis int ->
Printf.sprintf "%s%i"
(string_of_array_name var) int
| Stochiometric_coef (int1,int2) ->
Printf.sprintf "%s%i_%i"
(string_of_array_name var) int1 int2
| Jacobian_rate _
| Jacobian_rated _
| Jacobian_rateun _
| Jacobian_rateund _
| Jacobian _
| Jacobian_var _
| Jacobian_stochiometric_coef _ -> ""
| NonNegative
| Tinit
| Tend
| MaxStep
| InitialStep
| AbsTol
| RelTol
| Period_t_points
| N_ode_var
| N_var
| N_obs
| N_rules
| N_rows
| N_max_stoc_coef
| Tmp
| Current_time
| Time_scale_factor ->
(string_of_array_name var)
let string_of_variable ~side loggers variable =
match
Loggers.get_encoding_format loggers.logger
with
| Loggers.Matlab
| Loggers.Octave ->
string_of_variable_octave variable
| Loggers.Mathematica ->
string_of_variable_mathematica ~side variable
| Loggers.Maple ->
string_of_variable_maple variable
| Loggers.Matrix
| Loggers.HTML_Graph
| Loggers.Js_Graph
| Loggers.HTML
| Loggers.HTML_Tabular
| Loggers.DOT
| Loggers.TXT
| Loggers.TXT_Tabular
| Loggers.XLS
| Loggers.SBML
| Loggers.DOTNET
| Loggers.GEPHI
| Loggers.Json -> ""
let variable_of_derived_variable var id =
match var with
| Rate int -> Jacobian_rate (int,id)
| Rated int -> Jacobian_rated (int,id)
| Rateun int -> Jacobian_rateun (int,id)
| Rateund int -> Jacobian_rateund (int,id)
| Expr int -> Jacobian_var (int, id)
| Concentration int -> Jacobian (int, id)
| Stochiometric_coef (int1,int2) ->
Jacobian_stochiometric_coef (int1,int2,id)
| NonNegative -> assert false
| Obs _ -> assert false
| Init _ -> assert false
| Initbis _ -> assert false
| Deriv _ -> assert false
| Jacobian_rate _ -> assert false
| Jacobian_rated _ -> assert false
| Jacobian_rateun _ -> assert false
| Jacobian_rateund _ -> assert false
| Jacobian_stochiometric_coef _ -> assert false
| Jacobian _ -> assert false
| Jacobian_var _ -> assert false
| Tinit -> assert false
| Tend -> assert false
| MaxStep -> assert false
| InitialStep -> assert false
| AbsTol -> assert false
| RelTol -> assert false
| Period_t_points -> assert false
| N_ode_var -> assert false
| N_var -> assert false
| N_obs -> assert false
| N_rules -> assert false
| N_rows -> assert false
| N_max_stoc_coef -> assert false
| Tmp -> assert false
| Current_time -> assert false
| Time_scale_factor -> assert false
let get_expr t v =
try
Some (VarMap.find v (!(t.env)))
with
| Not_found ->
None
let set_dangerous_global_parameter_name t var =
t.dangerous_parameters := VarSet.add var (!(t.dangerous_parameters))
let forbidden_char c =
match c with
'*' | '+' | '-' | '(' | ')' -> true
| _ -> false
let has_forbidden_char t string =
(match get_encoding_format t
with
DOTNET -> true
| Matrix | HTML_Graph | Js_Graph | HTML | HTML_Tabular | DOT | TXT | TXT_Tabular | XLS | GEPHI
| Octave | Matlab | Maple | Mathematica | Json | SBML -> false)
&&
let rec aux k n =
if k=n then false
else forbidden_char (string.[k]) || aux (k+1) n
in
aux 0 (String.length string)
let flag_dangerous t id string =
if has_forbidden_char t string
then
set_dangerous_global_parameter_name t id
let set_expr t v expr =
let const = Alg_expr.is_constant expr in
let () =
if not const then
t.const := VarSet.remove v (!(t.const))
else
t.const := VarSet.add v (!(t.const))
in
t.env := VarMap.add v expr (!(t.env))
let is_const t v =
VarSet.mem v (!(t.const))
let get_fresh_reaction_id t =
let output = !(t.fresh_reaction_id) in
let () = t.fresh_reaction_id:=succ output in
output
let get_id_of_global_parameter t var =
try
VarMap.find var (!(t.id_of_parameters))
with
Not_found -> ""
let set_id_of_global_parameter t var id =
let () = t.id_of_parameters := VarMap.add var id (!(t.id_of_parameters)) in
flag_dangerous t var id
let rec allocate_fresh_name t name potential_suffix =
if Mods.StringSet.mem name (!(t.idset))
then
allocate_fresh_name t (name^potential_suffix) potential_suffix
else
name
let allocate t name =
let () = t.idset := Mods.StringSet.add name (!(t.idset)) in
()
let is_dangerous_ode_variable t var =
VarSet.mem var (!(t.dangerous_parameters))
let get_fresh_meta_id logger = Tools.get_ref logger.fresh_meta_id
let get_fresh_obs_id logger = Tools.get_ref logger.fresh_obs_id
let csv_sep logger = logger.csv_sep
let lift t = t.logger
|
|
ad350622674f215fcd6f55f65d312df0ea4f0cdbe55f744510cd26eda43ae4a9 | agda/fix-whitespace | QuickCheck.hs | # LANGUAGE TemplateHaskell #
-- | Test 'dropWhileEnd1'.
module Main where
import Data.Maybe ( isJust )
import Test.QuickCheck.All ( allProperties )
import Test.Tasty ( defaultMain )
import Test.Tasty.QuickCheck ( testProperties )
import Data.List.Extra.Drop ( dropWhile1, dropWhileEnd1 )
| If the predicate is true for exactly one value , we can express ' dropWhileEnd1 ' in terms of ' dropWhile1 ' .
--
-- Example: predicate 'not' holds only for 'False'.
--
prop_dropWhileEnd1_Bool :: [Bool] -> Bool
prop_dropWhileEnd1_Bool xs = dropWhileEnd1 not xs == (reverse . dropWhile1 not . reverse) xs
-- | If the predicate is *not* a singleton, this relation does not hold.
--
prop_dropWhileEnd1_Maybe_Bool :: Bool
prop_dropWhileEnd1_Maybe_Bool = l /= r
where
xs = [Just True, Just False]
l = dropWhileEnd1 isJust xs -- Just True
r = (reverse . dropWhile1 isJust . reverse) xs -- Just False
Pseudo Template Haskell instruction to make $ allProperties work
return []
main :: IO ()
main = defaultMain $ testProperties "Tests" $allProperties
| null | https://raw.githubusercontent.com/agda/fix-whitespace/37220b71a7058c64f4dd7401c9755af1003f931d/test/QuickCheck.hs | haskell | | Test 'dropWhileEnd1'.
Example: predicate 'not' holds only for 'False'.
| If the predicate is *not* a singleton, this relation does not hold.
Just True
Just False | # LANGUAGE TemplateHaskell #
module Main where
import Data.Maybe ( isJust )
import Test.QuickCheck.All ( allProperties )
import Test.Tasty ( defaultMain )
import Test.Tasty.QuickCheck ( testProperties )
import Data.List.Extra.Drop ( dropWhile1, dropWhileEnd1 )
| If the predicate is true for exactly one value , we can express ' dropWhileEnd1 ' in terms of ' dropWhile1 ' .
prop_dropWhileEnd1_Bool :: [Bool] -> Bool
prop_dropWhileEnd1_Bool xs = dropWhileEnd1 not xs == (reverse . dropWhile1 not . reverse) xs
prop_dropWhileEnd1_Maybe_Bool :: Bool
prop_dropWhileEnd1_Maybe_Bool = l /= r
where
xs = [Just True, Just False]
Pseudo Template Haskell instruction to make $ allProperties work
return []
main :: IO ()
main = defaultMain $ testProperties "Tests" $allProperties
|
0995a57e9ef4a35c5517ac9c1c51cba6bca94ef490005288de4ca3d486be142b | chetmurthy/ensemble | appl_handle.mli | (**************************************************************)
(* APPL_HANDLE.MLI *)
Author : , 10/97
(**************************************************************)
open Trans
open Util
(**************************************************************)
BUG : handle and handle_gen should be opaque .
*)
type handle = { mutable endpt : Endpt.id ; mutable rank : int }
type origin = handle
type rank = handle
type dests = handle array
type handle_gen = unit
(**************************************************************)
type ('cast_msg, 'send_msg) action =
| Cast of 'cast_msg
| Send of dests * 'send_msg
| Control of Appl_intf.control
(**************************************************************)
(* Create a new handle give a handle generator and endpoint.
*)
val handle : handle_gen -> debug -> Endpt.id -> handle
(* Check if handle is valid in a view.
*)
val is_valid : handle -> View.state -> bool
val handle_hack : debug -> Endpt.id -> handle
val string_of_handle : handle -> string
val endpt_of_handle : handle -> Endpt.id
val handle_eq : handle -> handle -> bool
(**************************************************************)
module Old : sig
type (
'cast_msg,
'send_msg,
'merg_msg,
'view_msg
) full = {
recv_cast : origin -> 'cast_msg ->
('cast_msg,'send_msg) action array ;
recv_send : origin -> 'send_msg ->
('cast_msg,'send_msg) action array ;
heartbeat_rate : Time.t ;
heartbeat : Time.t ->
('cast_msg,'send_msg) action array ;
block : unit ->
('cast_msg,'send_msg) action array ;
block_recv_cast : origin -> 'cast_msg -> unit ;
block_recv_send : origin -> 'send_msg -> unit ;
block_view : View.full -> (Endpt.id * 'merg_msg) list ;
block_install_view : View.full -> 'merg_msg list -> 'view_msg ;
unblock_view : View.full -> 'view_msg ->
('cast_msg,'send_msg) action array ;
exit : unit -> unit
}
f : ( ' a,'b,'c,'d ) full - > handle_gen * ( ' a,'b,'c,'d ) Appl_intf.Old.full
end
(**************************************************************)
module New : sig
type cast_or_send = Appl_intf.New.cast_or_send = C | S
type blocked = Appl_intf.New.blocked = U | B
type 'msg naction = ('msg,'msg) action
type 'msg handlers = {
block : unit -> 'msg naction array ;
heartbeat : Time.t -> 'msg naction array ;
receive : origin -> blocked -> cast_or_send -> 'msg -> 'msg naction array ;
disable : unit -> unit
}
type 'msg full = {
heartbeat_rate : Time.t ;
install : View.full -> handle Arrayf.t -> ('msg naction array) * ('msg handlers) ;
exit : unit -> unit
}
f : ' msg full - > handle_gen * ' msg Appl_intf.New.full
end
(**************************************************************)
| null | https://raw.githubusercontent.com/chetmurthy/ensemble/8266a89e68be24a4aaa5d594662e211eeaa6dc89/ensemble/server/type/appl_handle.mli | ocaml | ************************************************************
APPL_HANDLE.MLI
************************************************************
************************************************************
************************************************************
************************************************************
Create a new handle give a handle generator and endpoint.
Check if handle is valid in a view.
************************************************************
************************************************************
************************************************************ | Author : , 10/97
open Trans
open Util
BUG : handle and handle_gen should be opaque .
*)
type handle = { mutable endpt : Endpt.id ; mutable rank : int }
type origin = handle
type rank = handle
type dests = handle array
type handle_gen = unit
type ('cast_msg, 'send_msg) action =
| Cast of 'cast_msg
| Send of dests * 'send_msg
| Control of Appl_intf.control
val handle : handle_gen -> debug -> Endpt.id -> handle
val is_valid : handle -> View.state -> bool
val handle_hack : debug -> Endpt.id -> handle
val string_of_handle : handle -> string
val endpt_of_handle : handle -> Endpt.id
val handle_eq : handle -> handle -> bool
module Old : sig
type (
'cast_msg,
'send_msg,
'merg_msg,
'view_msg
) full = {
recv_cast : origin -> 'cast_msg ->
('cast_msg,'send_msg) action array ;
recv_send : origin -> 'send_msg ->
('cast_msg,'send_msg) action array ;
heartbeat_rate : Time.t ;
heartbeat : Time.t ->
('cast_msg,'send_msg) action array ;
block : unit ->
('cast_msg,'send_msg) action array ;
block_recv_cast : origin -> 'cast_msg -> unit ;
block_recv_send : origin -> 'send_msg -> unit ;
block_view : View.full -> (Endpt.id * 'merg_msg) list ;
block_install_view : View.full -> 'merg_msg list -> 'view_msg ;
unblock_view : View.full -> 'view_msg ->
('cast_msg,'send_msg) action array ;
exit : unit -> unit
}
f : ( ' a,'b,'c,'d ) full - > handle_gen * ( ' a,'b,'c,'d ) Appl_intf.Old.full
end
module New : sig
type cast_or_send = Appl_intf.New.cast_or_send = C | S
type blocked = Appl_intf.New.blocked = U | B
type 'msg naction = ('msg,'msg) action
type 'msg handlers = {
block : unit -> 'msg naction array ;
heartbeat : Time.t -> 'msg naction array ;
receive : origin -> blocked -> cast_or_send -> 'msg -> 'msg naction array ;
disable : unit -> unit
}
type 'msg full = {
heartbeat_rate : Time.t ;
install : View.full -> handle Arrayf.t -> ('msg naction array) * ('msg handlers) ;
exit : unit -> unit
}
f : ' msg full - > handle_gen * ' msg Appl_intf.New.full
end
|
9975a714391f215b38f3c11270264746476e033a416c664552e63eb4e9f7eccc | cyverse-archive/DiscoveryEnvironmentBackend | project.clj | (use '[clojure.java.shell :only (sh)])
(require '[clojure.string :as string])
(defn git-ref
[]
(or (System/getenv "GIT_COMMIT")
(string/trim (:out (sh "git" "rev-parse" "HEAD")))
""))
(defproject template-mover "5.0.0"
:description "Utility to copy metadata templates to their new database."
:url ""
:license {:name "BSD Standard License"
:url "-LICENSE.txt"}
:manifest {"Git-Ref" ~(git-ref)}
:uberjar-name "template-mover-standalone.jar"
:dependencies [[honeysql "0.6.0"]
[org.clojure/clojure "1.6.0"]
[org.clojure/java.jdbc "0.3.7"]
[org.clojure/tools.cli "0.3.1"]
[org.clojure/tools.logging "0.3.1"]
[org.iplantc/kameleon "5.0.0"]
[postgresql "9.1-901-1.jdbc4"]]
:aot :all
:main template-mover.core)
| null | https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/tools/template-mover/project.clj | clojure | (use '[clojure.java.shell :only (sh)])
(require '[clojure.string :as string])
(defn git-ref
[]
(or (System/getenv "GIT_COMMIT")
(string/trim (:out (sh "git" "rev-parse" "HEAD")))
""))
(defproject template-mover "5.0.0"
:description "Utility to copy metadata templates to their new database."
:url ""
:license {:name "BSD Standard License"
:url "-LICENSE.txt"}
:manifest {"Git-Ref" ~(git-ref)}
:uberjar-name "template-mover-standalone.jar"
:dependencies [[honeysql "0.6.0"]
[org.clojure/clojure "1.6.0"]
[org.clojure/java.jdbc "0.3.7"]
[org.clojure/tools.cli "0.3.1"]
[org.clojure/tools.logging "0.3.1"]
[org.iplantc/kameleon "5.0.0"]
[postgresql "9.1-901-1.jdbc4"]]
:aot :all
:main template-mover.core)
|
|
8fcc9ead61e8990ab2e09fc352e08ae91bb1f112af3be83d391c38d8ab8ff7a1 | expipiplus1/vulkan | VK_KHR_external_semaphore_win32.hs | {-# language CPP #-}
-- | = Name
--
-- VK_KHR_external_semaphore_win32 - device extension
--
-- == VK_KHR_external_semaphore_win32
--
-- [__Name String__]
-- @VK_KHR_external_semaphore_win32@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 79
--
-- [__Revision__]
1
--
-- [__Extension and Version Dependencies__]
--
- Requires support for Vulkan 1.0
--
-- - Requires @VK_KHR_external_semaphore@ to be enabled for any
-- device-level functionality
--
-- [__Contact__]
--
-
-- <-Docs/issues/new?body=[VK_KHR_external_semaphore_win32] @cubanismo%0A*Here describe the issue or question you have about the VK_KHR_external_semaphore_win32 extension* >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
2016 - 10 - 21
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Contributors__]
--
- , NVIDIA
--
- , NVIDIA
--
- , NVIDIA
--
-- == Description
--
-- An application using external memory may wish to synchronize access to
-- that memory using semaphores. This extension enables an application to
export semaphore payload to and import semaphore payload from Windows
-- handles.
--
-- == New Commands
--
-- - 'getSemaphoreWin32HandleKHR'
--
-- - 'importSemaphoreWin32HandleKHR'
--
-- == New Structures
--
-- - 'ImportSemaphoreWin32HandleInfoKHR'
--
- ' SemaphoreGetWin32HandleInfoKHR '
--
- Extending ' Vulkan . Core10.QueueSemaphore . ' :
--
- ' ExportSemaphoreWin32HandleInfoKHR '
--
- Extending ' Vulkan . Core10.Queue . SubmitInfo ' :
--
-- - 'D3D12FenceSubmitInfoKHR'
--
-- == New Enum Constants
--
-- - 'KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME'
--
-- - 'KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION'
--
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR '
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR '
--
- ' Vulkan . Core10.Enums . StructureType . '
--
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR '
--
-- == Issues
--
1 ) Do applications need to call @CloseHandle@ ( ) on the values returned
from ' getSemaphoreWin32HandleKHR ' when @handleType@ is
' Vulkan . Extensions . VK_KHR_external_semaphore_capabilities . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR ' ?
--
-- __RESOLVED__: Yes, unless it is passed back in to another driver
-- instance to import the object. A successful get call transfers ownership
-- of the handle to the application. Destroying the semaphore object will
-- not destroy the handle or the handle’s reference to the underlying
-- semaphore resource.
--
2 ) Should the language regarding KMT\/Windows 7 handles be moved to a
-- separate extension so that it can be deprecated over time?
--
-- __RESOLVED__: No. Support for them can be deprecated by drivers if they
-- choose, by no longer returning them in the supported handle types of the
-- instance level queries.
--
3 ) Should applications be allowed to specify additional object
-- attributes for shared handles?
--
-- __RESOLVED__: Yes. Applications will be allowed to provide similar
-- attributes to those they would to any other handle creation API.
--
4 ) How do applications communicate the desired fence values to use with
@D3D12_FENCE@-based Vulkan semaphores ?
--
-- __RESOLVED__: There are a couple of options. The values for the signaled
-- and reset states could be communicated up front when creating the object
and remain static for the life of the Vulkan semaphore , or they could be
-- specified using auxiliary structures when submitting semaphore signal
-- and wait operations, similar to what is done with the keyed mutex
-- extensions. The latter is more flexible and consistent with the keyed
-- mutex usage, but the former is a much simpler API.
--
Since Vulkan tends to favor flexibility and consistency over simplicity ,
a new structure specifying fence acquire and release values is
added to the ' Vulkan . Core10.Queue.queueSubmit ' function .
--
-- == Version History
--
- Revision 1 , 2016 - 10 - 21 ( )
--
-- - Initial revision
--
-- == See Also
--
-- 'D3D12FenceSubmitInfoKHR', 'ExportSemaphoreWin32HandleInfoKHR',
-- 'ImportSemaphoreWin32HandleInfoKHR', 'SemaphoreGetWin32HandleInfoKHR',
-- 'getSemaphoreWin32HandleKHR', 'importSemaphoreWin32HandleKHR'
--
-- == Document Notes
--
-- For more information, see the
< -extensions/html/vkspec.html#VK_KHR_external_semaphore_win32 Vulkan Specification >
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_KHR_external_semaphore_win32 ( getSemaphoreWin32HandleKHR
, importSemaphoreWin32HandleKHR
, ImportSemaphoreWin32HandleInfoKHR(..)
, ExportSemaphoreWin32HandleInfoKHR(..)
, D3D12FenceSubmitInfoKHR(..)
, SemaphoreGetWin32HandleInfoKHR(..)
, KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION
, pattern KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION
, KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME
, pattern KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME
, HANDLE
, DWORD
, LPCWSTR
, SECURITY_ATTRIBUTES
) where
import Vulkan.Internal.Utils (traceAroundEvent)
import Control.Exception.Base (bracket)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Alloc (callocBytes)
import Foreign.Marshal.Alloc (free)
import GHC.Base (when)
import GHC.IO (throwIO)
import GHC.Ptr (nullFunPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Data.Vector (generateM)
import qualified Data.Vector (imapM_)
import qualified Data.Vector (length)
import qualified Data.Vector (null)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Control.Monad.IO.Class (MonadIO)
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import GHC.IO.Exception (IOErrorType(..))
import GHC.IO.Exception (IOException(..))
import Foreign.Ptr (FunPtr)
import Foreign.Ptr (Ptr)
import Data.Word (Word32)
import Data.Word (Word64)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Data.Vector (Vector)
import Vulkan.CStruct.Utils (advancePtrBytes)
import Vulkan.Extensions.VK_NV_external_memory_win32 (DWORD)
import Vulkan.Core10.Handles (Device)
import Vulkan.Core10.Handles (Device(..))
import Vulkan.Core10.Handles (Device(Device))
import Vulkan.Dynamic (DeviceCmds(pVkGetSemaphoreWin32HandleKHR))
import Vulkan.Dynamic (DeviceCmds(pVkImportSemaphoreWin32HandleKHR))
import Vulkan.Core10.Handles (Device_T)
import Vulkan.Core11.Enums.ExternalSemaphoreHandleTypeFlagBits (ExternalSemaphoreHandleTypeFlagBits)
import Vulkan.Extensions.VK_NV_external_memory_win32 (HANDLE)
import Vulkan.Extensions.VK_KHR_external_memory_win32 (LPCWSTR)
import Vulkan.Core10.Enums.Result (Result)
import Vulkan.Core10.Enums.Result (Result(..))
import Vulkan.Extensions.VK_NV_external_memory_win32 (SECURITY_ATTRIBUTES)
import Vulkan.Core10.Handles (Semaphore)
import Vulkan.Core11.Enums.SemaphoreImportFlagBits (SemaphoreImportFlags)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Exception (VulkanException(..))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_IMPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR))
import Vulkan.Core10.Enums.Result (Result(SUCCESS))
import Vulkan.Extensions.VK_NV_external_memory_win32 (DWORD)
import Vulkan.Extensions.VK_NV_external_memory_win32 (HANDLE)
import Vulkan.Extensions.VK_KHR_external_memory_win32 (LPCWSTR)
import Vulkan.Extensions.VK_NV_external_memory_win32 (SECURITY_ATTRIBUTES)
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkGetSemaphoreWin32HandleKHR
:: FunPtr (Ptr Device_T -> Ptr SemaphoreGetWin32HandleInfoKHR -> Ptr HANDLE -> IO Result) -> Ptr Device_T -> Ptr SemaphoreGetWin32HandleInfoKHR -> Ptr HANDLE -> IO Result
-- | vkGetSemaphoreWin32HandleKHR - Get a Windows HANDLE for a semaphore
--
-- = Description
--
-- For handle types defined as NT handles, the handles returned by
-- 'getSemaphoreWin32HandleKHR' are owned by the application. To avoid
-- leaking resources, the application /must/ release ownership of them
using the @CloseHandle@ system call when they are no longer needed .
--
-- Exporting a Windows handle from a semaphore /may/ have side effects
-- depending on the transference of the specified handle type, as described
-- in
-- <-extensions/html/vkspec.html#synchronization-semaphores-importing Importing Semaphore Payloads>.
--
-- == Return Codes
--
-- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
- ' Vulkan . Core10.Enums . Result . SUCCESS '
--
-- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
--
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
--
-- = See Also
--
< ,
' Vulkan . Core10.Handles . Device ' , ' SemaphoreGetWin32HandleInfoKHR '
getSemaphoreWin32HandleKHR :: forall io
. (MonadIO io)
=> -- | @device@ is the logical device that created the semaphore being
-- exported.
--
-- #VUID-vkGetSemaphoreWin32HandleKHR-device-parameter# @device@ /must/ be
a valid ' Vulkan . Core10.Handles . Device ' handle
Device
| @pGetWin32HandleInfo@ is a pointer to a ' SemaphoreGetWin32HandleInfoKHR '
-- structure containing parameters of the export operation.
--
-- #VUID-vkGetSemaphoreWin32HandleKHR-pGetWin32HandleInfo-parameter#
@pGetWin32HandleInfo@ /must/ be a valid pointer to a valid
' SemaphoreGetWin32HandleInfoKHR ' structure
SemaphoreGetWin32HandleInfoKHR
-> io (HANDLE)
getSemaphoreWin32HandleKHR device getWin32HandleInfo = liftIO . evalContT $ do
let vkGetSemaphoreWin32HandleKHRPtr = pVkGetSemaphoreWin32HandleKHR (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkGetSemaphoreWin32HandleKHRPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetSemaphoreWin32HandleKHR is null" Nothing Nothing
let vkGetSemaphoreWin32HandleKHR' = mkVkGetSemaphoreWin32HandleKHR vkGetSemaphoreWin32HandleKHRPtr
pGetWin32HandleInfo <- ContT $ withCStruct (getWin32HandleInfo)
pPHandle <- ContT $ bracket (callocBytes @HANDLE 8) free
r <- lift $ traceAroundEvent "vkGetSemaphoreWin32HandleKHR" (vkGetSemaphoreWin32HandleKHR'
(deviceHandle (device))
pGetWin32HandleInfo
(pPHandle))
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
pHandle <- lift $ peek @HANDLE pPHandle
pure $ (pHandle)
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkImportSemaphoreWin32HandleKHR
:: FunPtr (Ptr Device_T -> Ptr ImportSemaphoreWin32HandleInfoKHR -> IO Result) -> Ptr Device_T -> Ptr ImportSemaphoreWin32HandleInfoKHR -> IO Result
| vkImportSemaphoreWin32HandleKHR - Import a semaphore from a Windows
-- HANDLE
--
-- = Description
--
Importing a semaphore payload from Windows handles does not transfer
ownership of the handle to the Vulkan implementation . For handle types
-- defined as NT handles, the application /must/ release ownership using
the @CloseHandle@ system call when the handle is no longer needed .
--
-- Applications /can/ import the same semaphore payload into multiple
instances of Vulkan , into the same instance from which it was exported ,
and multiple times into a given Vulkan instance .
--
-- == Return Codes
--
-- [<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
--
- ' Vulkan . Core10.Enums . Result . SUCCESS '
--
-- [<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
--
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
--
- ' Vulkan . Core10.Enums . Result . ERROR_INVALID_EXTERNAL_HANDLE '
--
-- = See Also
--
< ,
' Vulkan . Core10.Handles . Device ' , ' ImportSemaphoreWin32HandleInfoKHR '
importSemaphoreWin32HandleKHR :: forall io
. (MonadIO io)
=> -- | @device@ is the logical device that created the semaphore.
--
-- #VUID-vkImportSemaphoreWin32HandleKHR-device-parameter# @device@ /must/
be a valid ' Vulkan . Core10.Handles . Device ' handle
Device
-> -- | @pImportSemaphoreWin32HandleInfo@ is a pointer to a
-- 'ImportSemaphoreWin32HandleInfoKHR' structure specifying the semaphore
-- and import parameters.
--
-- #VUID-vkImportSemaphoreWin32HandleKHR-pImportSemaphoreWin32HandleInfo-parameter#
-- @pImportSemaphoreWin32HandleInfo@ /must/ be a valid pointer to a valid
-- 'ImportSemaphoreWin32HandleInfoKHR' structure
ImportSemaphoreWin32HandleInfoKHR
-> io ()
importSemaphoreWin32HandleKHR device
importSemaphoreWin32HandleInfo = liftIO . evalContT $ do
let vkImportSemaphoreWin32HandleKHRPtr = pVkImportSemaphoreWin32HandleKHR (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkImportSemaphoreWin32HandleKHRPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkImportSemaphoreWin32HandleKHR is null" Nothing Nothing
let vkImportSemaphoreWin32HandleKHR' = mkVkImportSemaphoreWin32HandleKHR vkImportSemaphoreWin32HandleKHRPtr
pImportSemaphoreWin32HandleInfo <- ContT $ withCStruct (importSemaphoreWin32HandleInfo)
r <- lift $ traceAroundEvent "vkImportSemaphoreWin32HandleKHR" (vkImportSemaphoreWin32HandleKHR'
(deviceHandle (device))
pImportSemaphoreWin32HandleInfo)
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
| VkImportSemaphoreWin32HandleInfoKHR - Structure specifying Windows
-- handle to import to a semaphore
--
-- = Description
--
The handle types supported by @handleType@ are :
--
-- +---------------------------------------------------------------------------------------------------------------+------------------+---------------------+
-- | Handle Type | Transference | Permanence |
-- | | | Supported |
-- +===============================================================================================================+==================+=====================+
| ' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT ' | Reference | Temporary , Permanent |
-- +---------------------------------------------------------------------------------------------------------------+------------------+---------------------+
| ' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT ' | Reference | Temporary , Permanent |
-- +---------------------------------------------------------------------------------------------------------------+------------------+---------------------+
| ' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT ' | Reference | Temporary , Permanent |
-- +---------------------------------------------------------------------------------------------------------------+------------------+---------------------+
--
-- Handle Types Supported by 'ImportSemaphoreWin32HandleInfoKHR'
--
-- == Valid Usage
--
-- - #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-01140#
-- @handleType@ /must/ be a value included in the
-- <-extensions/html/vkspec.html#synchronization-semaphore-handletypes-win32 Handle Types Supported by >
-- table
--
-- - #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-01466# If
@handleType@ is not
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT '
-- or
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT ' ,
-- @name@ /must/ be @NULL@
--
-- - #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-01467# If
-- @handle@ is @NULL@, @name@ /must/ name a valid synchronization
primitive of the type specified by @handleType@
--
-- - #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-01468# If
-- @name@ is @NULL@, @handle@ /must/ be a valid handle of the type
specified by @handleType@
--
-- - #VUID-VkImportSemaphoreWin32HandleInfoKHR-handle-01469# If @handle@
-- is not @NULL@, @name@ /must/ be @NULL@
--
-- - #VUID-VkImportSemaphoreWin32HandleInfoKHR-handle-01542# If @handle@
-- is not @NULL@, it /must/ obey any requirements listed for
@handleType@ in
-- <-extensions/html/vkspec.html#external-semaphore-handle-types-compatibility external semaphore handle types compatibility>
--
- # VUID - VkImportSemaphoreWin32HandleInfoKHR - name-01543 # If @name@ is
not @NULL@ , it /must/ obey any requirements listed for @handleType@
-- in
-- <-extensions/html/vkspec.html#external-semaphore-handle-types-compatibility external semaphore handle types compatibility>
--
-- - #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-03261# If
@handleType@ is
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT '
-- or
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT ' ,
the ' Vulkan . Core10.QueueSemaphore .
-- field /must/ match that of the semaphore from which @handle@ or
-- @name@ was exported
--
-- - #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-03262# If
@handleType@ is
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT '
-- or
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT ' ,
-- the
' Vulkan . Core12.Promoted_From_VK_KHR_timeline_semaphore . SemaphoreTypeCreateInfo'::@semaphoreType@
-- field /must/ match that of the semaphore from which @handle@ or
-- @name@ was exported
--
-- - #VUID-VkImportSemaphoreWin32HandleInfoKHR-flags-03322# If @flags@
-- contains
' Vulkan . Core11.Enums . SemaphoreImportFlagBits . SEMAPHORE_IMPORT_TEMPORARY_BIT ' ,
-- the
' Vulkan . Core12.Promoted_From_VK_KHR_timeline_semaphore . SemaphoreTypeCreateInfo'::@semaphoreType@
-- field of the semaphore from which @handle@ or @name@ was exported
-- /must/ not be
' Vulkan . Core12.Enums . . SEMAPHORE_TYPE_TIMELINE '
--
-- == Valid Usage (Implicit)
--
- # VUID - VkImportSemaphoreWin32HandleInfoKHR - sType - sType # @sType@
-- /must/ be
' Vulkan . Core10.Enums . StructureType . '
--
- # VUID - VkImportSemaphoreWin32HandleInfoKHR - pNext - pNext # @pNext@
-- /must/ be @NULL@
--
-- - #VUID-VkImportSemaphoreWin32HandleInfoKHR-semaphore-parameter#
@semaphore@ /must/ be a valid ' Vulkan . Core10.Handles . Semaphore '
-- handle
--
-- - #VUID-VkImportSemaphoreWin32HandleInfoKHR-flags-parameter# @flags@
-- /must/ be a valid combination of
' Vulkan . Core11.Enums . SemaphoreImportFlagBits . SemaphoreImportFlagBits '
-- values
--
-- == Host Synchronization
--
-- - Host access to @semaphore@ /must/ be externally synchronized
--
-- = See Also
--
< ,
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits ' ,
' Vulkan . Core10.Handles . Semaphore ' ,
' Vulkan . Core11.Enums . SemaphoreImportFlagBits . SemaphoreImportFlags ' ,
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
-- 'importSemaphoreWin32HandleKHR'
data ImportSemaphoreWin32HandleInfoKHR = ImportSemaphoreWin32HandleInfoKHR
{ -- | @semaphore@ is the semaphore into which the payload will be imported.
semaphore :: Semaphore
, -- | @flags@ is a bitmask of
' Vulkan . Core11.Enums . SemaphoreImportFlagBits . SemaphoreImportFlagBits '
-- specifying additional parameters for the semaphore payload import
-- operation.
flags :: SemaphoreImportFlags
, -- | @handleType@ is a
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits '
-- value specifying the type of @handle@.
handleType :: ExternalSemaphoreHandleTypeFlagBits
, -- | @handle@ is @NULL@ or the external handle to import.
handle :: HANDLE
, -- | @name@ is @NULL@ or a null-terminated UTF-16 string naming the
-- underlying synchronization primitive to import.
name :: LPCWSTR
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (ImportSemaphoreWin32HandleInfoKHR)
#endif
deriving instance Show ImportSemaphoreWin32HandleInfoKHR
instance ToCStruct ImportSemaphoreWin32HandleInfoKHR where
withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p)
pokeCStruct p ImportSemaphoreWin32HandleInfoKHR{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Semaphore)) (semaphore)
poke ((p `plusPtr` 24 :: Ptr SemaphoreImportFlags)) (flags)
poke ((p `plusPtr` 28 :: Ptr ExternalSemaphoreHandleTypeFlagBits)) (handleType)
poke ((p `plusPtr` 32 :: Ptr HANDLE)) (handle)
poke ((p `plusPtr` 40 :: Ptr LPCWSTR)) (name)
f
cStructSize = 48
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Semaphore)) (zero)
poke ((p `plusPtr` 28 :: Ptr ExternalSemaphoreHandleTypeFlagBits)) (zero)
f
instance FromCStruct ImportSemaphoreWin32HandleInfoKHR where
peekCStruct p = do
semaphore <- peek @Semaphore ((p `plusPtr` 16 :: Ptr Semaphore))
flags <- peek @SemaphoreImportFlags ((p `plusPtr` 24 :: Ptr SemaphoreImportFlags))
handleType <- peek @ExternalSemaphoreHandleTypeFlagBits ((p `plusPtr` 28 :: Ptr ExternalSemaphoreHandleTypeFlagBits))
handle <- peek @HANDLE ((p `plusPtr` 32 :: Ptr HANDLE))
name <- peek @LPCWSTR ((p `plusPtr` 40 :: Ptr LPCWSTR))
pure $ ImportSemaphoreWin32HandleInfoKHR
semaphore flags handleType handle name
instance Storable ImportSemaphoreWin32HandleInfoKHR where
sizeOf ~_ = 48
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero ImportSemaphoreWin32HandleInfoKHR where
zero = ImportSemaphoreWin32HandleInfoKHR
zero
zero
zero
zero
zero
-- | VkExportSemaphoreWin32HandleInfoKHR - Structure specifying additional
attributes of Windows handles exported from a semaphore
--
-- = Description
--
-- If
' Vulkan . . '
-- is not included in the same @pNext@ chain, this structure is ignored.
--
-- If
' Vulkan . . '
-- is included in the @pNext@ chain of
' Vulkan . Core10.QueueSemaphore . ' with a Windows
-- @handleType@, but either 'ExportSemaphoreWin32HandleInfoKHR' is not
-- included in the @pNext@ chain, or if it is but @pAttributes@ is set to
-- @NULL@, default security descriptor values will be used, and child
-- processes created by the application will not inherit the handle, as
described in the MSDN documentation for “ Synchronization Object Security
and Access Rights”1 . Further , if the structure is not present , the
-- access rights used depend on the handle type.
--
-- For handles of the following types:
--
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT '
--
-- The implementation /must/ ensure the access rights allow both signal and
-- wait operations on the semaphore.
--
-- For handles of the following types:
--
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT '
--
-- The access rights /must/ be:
--
@GENERIC_ALL@
--
[ 1 ]
-- <-us/windows/win32/sync/synchronization-object-security-and-access-rights>
--
-- == Valid Usage
--
-- - #VUID-VkExportSemaphoreWin32HandleInfoKHR-handleTypes-01125# If
' Vulkan . Core11.Promoted_From_VK_KHR_external_semaphore . ExportSemaphoreCreateInfo'::@handleTypes@
-- does not include
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT '
-- or
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT ' ,
-- 'ExportSemaphoreWin32HandleInfoKHR' /must/ not be included in the
@pNext@ chain of ' Vulkan . Core10.QueueSemaphore . '
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkExportSemaphoreWin32HandleInfoKHR-sType-sType# @sType@
-- /must/ be
' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR '
--
-- - #VUID-VkExportSemaphoreWin32HandleInfoKHR-pAttributes-parameter# If
@pAttributes@ is not @NULL@ , @pAttributes@ /must/ be a valid pointer
-- to a valid
' Vulkan . Extensions . '
-- value
--
-- = See Also
--
< ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data ExportSemaphoreWin32HandleInfoKHR = ExportSemaphoreWin32HandleInfoKHR
| @pAttributes@ is a pointer to a Windows
' Vulkan . Extensions . '
-- structure specifying security attributes of the handle.
attributes :: Ptr SECURITY_ATTRIBUTES
| @dwAccess@ is a ' Vulkan . Extensions . VK_NV_external_memory_win32.DWORD '
-- specifying access rights of the handle.
dwAccess :: DWORD
, -- | @name@ is a null-terminated UTF-16 string to associate with the
-- underlying synchronization primitive referenced by NT handles exported
-- from the created semaphore.
name :: LPCWSTR
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (ExportSemaphoreWin32HandleInfoKHR)
#endif
deriving instance Show ExportSemaphoreWin32HandleInfoKHR
instance ToCStruct ExportSemaphoreWin32HandleInfoKHR where
withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p)
pokeCStruct p ExportSemaphoreWin32HandleInfoKHR{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr (Ptr SECURITY_ATTRIBUTES))) (attributes)
poke ((p `plusPtr` 24 :: Ptr DWORD)) (dwAccess)
poke ((p `plusPtr` 32 :: Ptr LPCWSTR)) (name)
f
cStructSize = 40
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 24 :: Ptr DWORD)) (zero)
poke ((p `plusPtr` 32 :: Ptr LPCWSTR)) (zero)
f
instance FromCStruct ExportSemaphoreWin32HandleInfoKHR where
peekCStruct p = do
pAttributes <- peek @(Ptr SECURITY_ATTRIBUTES) ((p `plusPtr` 16 :: Ptr (Ptr SECURITY_ATTRIBUTES)))
dwAccess <- peek @DWORD ((p `plusPtr` 24 :: Ptr DWORD))
name <- peek @LPCWSTR ((p `plusPtr` 32 :: Ptr LPCWSTR))
pure $ ExportSemaphoreWin32HandleInfoKHR
pAttributes dwAccess name
instance Storable ExportSemaphoreWin32HandleInfoKHR where
sizeOf ~_ = 40
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero ExportSemaphoreWin32HandleInfoKHR where
zero = ExportSemaphoreWin32HandleInfoKHR
zero
zero
zero
| VkD3D12FenceSubmitInfoKHR - Structure specifying values for Direct3D 12
-- fence-backed semaphores
--
-- = Description
--
If the semaphore in ' Vulkan . Core10.Queue . SubmitInfo'::@pWaitSemaphores@
or ' Vulkan . Core10.Queue . SubmitInfo'::@pSignalSemaphores@ corresponding
to an entry in @pWaitSemaphoreValues@ or @pSignalSemaphoreValues@
-- respectively does not currently have a
-- <-extensions/html/vkspec.html#synchronization-semaphores-payloads payload>
referring to a Direct3D 12 fence , the implementation /must/ ignore the
value in the @pWaitSemaphoreValues@ or @pSignalSemaphoreValues@ entry .
--
-- Note
--
-- As the introduction of the external semaphore handle type
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT '
-- predates that of timeline semaphores, support for importing semaphore
-- payloads from external handles of that type into semaphores created
-- (implicitly or explicitly) with a
' Vulkan . Core12.Enums . SemaphoreType . ' of
' Vulkan . Core12.Enums . SemaphoreType . SEMAPHORE_TYPE_BINARY ' is preserved
-- for backwards compatibility. However, applications /should/ prefer
-- importing such handle types into semaphores created with a
' Vulkan . Core12.Enums . SemaphoreType . ' of
' Vulkan . Core12.Enums . . , and use the
' Vulkan . Core12.Promoted_From_VK_KHR_timeline_semaphore . TimelineSemaphoreSubmitInfo '
-- structure instead of the 'D3D12FenceSubmitInfoKHR' structure to specify
-- the values to use when waiting for and signaling such semaphores.
--
-- == Valid Usage
--
-- - #VUID-VkD3D12FenceSubmitInfoKHR-waitSemaphoreValuesCount-00079#
-- @waitSemaphoreValuesCount@ /must/ be the same value as
' Vulkan . Core10.Queue . SubmitInfo'::@waitSemaphoreCount@ , where
' Vulkan . Core10.Queue . SubmitInfo ' is in the @pNext@ chain of this
-- 'D3D12FenceSubmitInfoKHR' structure
--
-- - #VUID-VkD3D12FenceSubmitInfoKHR-signalSemaphoreValuesCount-00080#
-- @signalSemaphoreValuesCount@ /must/ be the same value as
' Vulkan . Core10.Queue . SubmitInfo'::@signalSemaphoreCount@ , where
' Vulkan . Core10.Queue . SubmitInfo ' is in the @pNext@ chain of this
-- 'D3D12FenceSubmitInfoKHR' structure
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkD3D12FenceSubmitInfoKHR-sType-sType# @sType@ /must/ be
' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR '
--
-- - #VUID-VkD3D12FenceSubmitInfoKHR-pWaitSemaphoreValues-parameter# If
@waitSemaphoreValuesCount@ is not @0@ , and @pWaitSemaphoreValues@ is
-- not @NULL@, @pWaitSemaphoreValues@ /must/ be a valid pointer to an
array of @waitSemaphoreValuesCount@ @uint64_t@ values
--
-- - #VUID-VkD3D12FenceSubmitInfoKHR-pSignalSemaphoreValues-parameter# If
@signalSemaphoreValuesCount@ is not @0@ , and
@pSignalSemaphoreValues@ is not @NULL@ , @pSignalSemaphoreValues@
-- /must/ be a valid pointer to an array of
@signalSemaphoreValuesCount@ @uint64_t@ values
--
-- = See Also
--
< ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data D3D12FenceSubmitInfoKHR = D3D12FenceSubmitInfoKHR
{ -- | @waitSemaphoreValuesCount@ is the number of semaphore wait values
-- specified in @pWaitSemaphoreValues@.
waitSemaphoreValuesCount :: Word32
, -- | @pWaitSemaphoreValues@ is a pointer to an array of
-- @waitSemaphoreValuesCount@ values for the corresponding semaphores in
' Vulkan . Core10.Queue . SubmitInfo'::@pWaitSemaphores@ to wait for .
waitSemaphoreValues :: Vector Word64
, -- | @signalSemaphoreValuesCount@ is the number of semaphore signal values
-- specified in @pSignalSemaphoreValues@.
signalSemaphoreValuesCount :: Word32
, -- | @pSignalSemaphoreValues@ is a pointer to an array of
@signalSemaphoreValuesCount@ values for the corresponding semaphores in
' Vulkan . Core10.Queue . SubmitInfo'::@pSignalSemaphores@ to set when
-- signaled.
signalSemaphoreValues :: Vector Word64
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (D3D12FenceSubmitInfoKHR)
#endif
deriving instance Show D3D12FenceSubmitInfoKHR
instance ToCStruct D3D12FenceSubmitInfoKHR where
withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p)
pokeCStruct p D3D12FenceSubmitInfoKHR{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
let pWaitSemaphoreValuesLength = Data.Vector.length $ (waitSemaphoreValues)
waitSemaphoreValuesCount'' <- lift $ if (waitSemaphoreValuesCount) == 0
then pure $ fromIntegral pWaitSemaphoreValuesLength
else do
unless (fromIntegral pWaitSemaphoreValuesLength == (waitSemaphoreValuesCount) || pWaitSemaphoreValuesLength == 0) $
throwIO $ IOError Nothing InvalidArgument "" "pWaitSemaphoreValues must be empty or have 'waitSemaphoreValuesCount' elements" Nothing Nothing
pure (waitSemaphoreValuesCount)
lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) (waitSemaphoreValuesCount'')
pWaitSemaphoreValues'' <- if Data.Vector.null (waitSemaphoreValues)
then pure nullPtr
else do
pPWaitSemaphoreValues <- ContT $ allocaBytes @Word64 (((Data.Vector.length (waitSemaphoreValues))) * 8)
lift $ Data.Vector.imapM_ (\i e -> poke (pPWaitSemaphoreValues `plusPtr` (8 * (i)) :: Ptr Word64) (e)) ((waitSemaphoreValues))
pure $ pPWaitSemaphoreValues
lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr Word64))) pWaitSemaphoreValues''
let pSignalSemaphoreValuesLength = Data.Vector.length $ (signalSemaphoreValues)
signalSemaphoreValuesCount'' <- lift $ if (signalSemaphoreValuesCount) == 0
then pure $ fromIntegral pSignalSemaphoreValuesLength
else do
unless (fromIntegral pSignalSemaphoreValuesLength == (signalSemaphoreValuesCount) || pSignalSemaphoreValuesLength == 0) $
throwIO $ IOError Nothing InvalidArgument "" "pSignalSemaphoreValues must be empty or have 'signalSemaphoreValuesCount' elements" Nothing Nothing
pure (signalSemaphoreValuesCount)
lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) (signalSemaphoreValuesCount'')
pSignalSemaphoreValues'' <- if Data.Vector.null (signalSemaphoreValues)
then pure nullPtr
else do
pPSignalSemaphoreValues <- ContT $ allocaBytes @Word64 (((Data.Vector.length (signalSemaphoreValues))) * 8)
lift $ Data.Vector.imapM_ (\i e -> poke (pPSignalSemaphoreValues `plusPtr` (8 * (i)) :: Ptr Word64) (e)) ((signalSemaphoreValues))
pure $ pPSignalSemaphoreValues
lift $ poke ((p `plusPtr` 40 :: Ptr (Ptr Word64))) pSignalSemaphoreValues''
lift $ f
cStructSize = 48
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
f
instance FromCStruct D3D12FenceSubmitInfoKHR where
peekCStruct p = do
waitSemaphoreValuesCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32))
pWaitSemaphoreValues <- peek @(Ptr Word64) ((p `plusPtr` 24 :: Ptr (Ptr Word64)))
let pWaitSemaphoreValuesLength = if pWaitSemaphoreValues == nullPtr then 0 else (fromIntegral waitSemaphoreValuesCount)
pWaitSemaphoreValues' <- generateM pWaitSemaphoreValuesLength (\i -> peek @Word64 ((pWaitSemaphoreValues `advancePtrBytes` (8 * (i)) :: Ptr Word64)))
signalSemaphoreValuesCount <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32))
pSignalSemaphoreValues <- peek @(Ptr Word64) ((p `plusPtr` 40 :: Ptr (Ptr Word64)))
let pSignalSemaphoreValuesLength = if pSignalSemaphoreValues == nullPtr then 0 else (fromIntegral signalSemaphoreValuesCount)
pSignalSemaphoreValues' <- generateM pSignalSemaphoreValuesLength (\i -> peek @Word64 ((pSignalSemaphoreValues `advancePtrBytes` (8 * (i)) :: Ptr Word64)))
pure $ D3D12FenceSubmitInfoKHR
waitSemaphoreValuesCount
pWaitSemaphoreValues'
signalSemaphoreValuesCount
pSignalSemaphoreValues'
instance Zero D3D12FenceSubmitInfoKHR where
zero = D3D12FenceSubmitInfoKHR
zero
mempty
zero
mempty
-- | VkSemaphoreGetWin32HandleInfoKHR - Structure describing a Win32 handle
-- semaphore export operation
--
-- = Description
--
-- The properties of the handle returned depend on the value of
@handleType@. See
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits '
-- for a description of the properties of the defined external semaphore
-- handle types.
--
-- == Valid Usage
--
-- - #VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01126#
-- @handleType@ /must/ have been included in
' Vulkan . Core11.Promoted_From_VK_KHR_external_semaphore . ExportSemaphoreCreateInfo'::@handleTypes@
-- when the @semaphore@’s current payload was created
--
-- - #VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01127# If
@handleType@ is defined as an NT handle ,
-- 'getSemaphoreWin32HandleKHR' /must/ be called no more than once for
each valid unique combination of @semaphore@ and
--
-- - #VUID-VkSemaphoreGetWin32HandleInfoKHR-semaphore-01128# @semaphore@
-- /must/ not currently have its payload replaced by an imported
-- payload as described below in
-- <-extensions/html/vkspec.html#synchronization-semaphores-importing Importing Semaphore Payloads>
-- unless that imported payload’s handle type was included in
' Vulkan . Core11.Promoted_From_VK_KHR_external_semaphore_capabilities . ExternalSemaphoreProperties'::@exportFromImportedHandleTypes@
for
--
-- - #VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01129# If
@handleType@ refers to a handle type with copy payload transference
-- semantics, as defined below in
-- <-extensions/html/vkspec.html#synchronization-semaphores-importing Importing Semaphore Payloads>,
-- there /must/ be no queue waiting on @semaphore@
--
- # VUID - VkSemaphoreGetWin32HandleInfoKHR - handleType-01130 # If
@handleType@ refers to a handle type with copy payload transference
-- semantics, @semaphore@ /must/ be signaled, or have an associated
-- <-extensions/html/vkspec.html#synchronization-semaphores-signaling semaphore signal operation>
-- pending execution
--
-- - #VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01131#
-- @handleType@ /must/ be defined as an NT handle or a global share
-- handle
--
-- == Valid Usage (Implicit)
--
-- - #VUID-VkSemaphoreGetWin32HandleInfoKHR-sType-sType# @sType@ /must/
-- be
' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR '
--
- # VUID - VkSemaphoreGetWin32HandleInfoKHR - pNext - pNext # @pNext@ /must/
-- be @NULL@
--
- # VUID - VkSemaphoreGetWin32HandleInfoKHR - semaphore - parameter #
@semaphore@ /must/ be a valid ' Vulkan . Core10.Handles . Semaphore '
-- handle
--
-- - #VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-parameter#
-- @handleType@ /must/ be a valid
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits '
-- value
--
-- = See Also
--
< ,
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits ' ,
' Vulkan . Core10.Handles . Semaphore ' ,
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
-- 'getSemaphoreWin32HandleKHR'
data SemaphoreGetWin32HandleInfoKHR = SemaphoreGetWin32HandleInfoKHR
{ -- | @semaphore@ is the semaphore from which state will be exported.
semaphore :: Semaphore
, -- | @handleType@ is a
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits '
-- value specifying the type of handle requested.
handleType :: ExternalSemaphoreHandleTypeFlagBits
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SemaphoreGetWin32HandleInfoKHR)
#endif
deriving instance Show SemaphoreGetWin32HandleInfoKHR
instance ToCStruct SemaphoreGetWin32HandleInfoKHR where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SemaphoreGetWin32HandleInfoKHR{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Semaphore)) (semaphore)
poke ((p `plusPtr` 24 :: Ptr ExternalSemaphoreHandleTypeFlagBits)) (handleType)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Semaphore)) (zero)
poke ((p `plusPtr` 24 :: Ptr ExternalSemaphoreHandleTypeFlagBits)) (zero)
f
instance FromCStruct SemaphoreGetWin32HandleInfoKHR where
peekCStruct p = do
semaphore <- peek @Semaphore ((p `plusPtr` 16 :: Ptr Semaphore))
handleType <- peek @ExternalSemaphoreHandleTypeFlagBits ((p `plusPtr` 24 :: Ptr ExternalSemaphoreHandleTypeFlagBits))
pure $ SemaphoreGetWin32HandleInfoKHR
semaphore handleType
instance Storable SemaphoreGetWin32HandleInfoKHR where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero SemaphoreGetWin32HandleInfoKHR where
zero = SemaphoreGetWin32HandleInfoKHR
zero
zero
type KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION = 1
No documentation found for TopLevel " "
pattern KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION = 1
type KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME = "VK_KHR_external_semaphore_win32"
No documentation found for TopLevel " VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME "
pattern KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME = "VK_KHR_external_semaphore_win32"
| null | https://raw.githubusercontent.com/expipiplus1/vulkan/ebc0dde0bcd9cf251f18538de6524eb4f2ab3e9d/src/Vulkan/Extensions/VK_KHR_external_semaphore_win32.hs | haskell | # language CPP #
| = Name
VK_KHR_external_semaphore_win32 - device extension
== VK_KHR_external_semaphore_win32
[__Name String__]
@VK_KHR_external_semaphore_win32@
[__Extension Type__]
Device extension
[__Registered Extension Number__]
79
[__Revision__]
[__Extension and Version Dependencies__]
- Requires @VK_KHR_external_semaphore@ to be enabled for any
device-level functionality
[__Contact__]
<-Docs/issues/new?body=[VK_KHR_external_semaphore_win32] @cubanismo%0A*Here describe the issue or question you have about the VK_KHR_external_semaphore_win32 extension* >
== Other Extension Metadata
[__Last Modified Date__]
[__IP Status__]
No known IP claims.
[__Contributors__]
== Description
An application using external memory may wish to synchronize access to
that memory using semaphores. This extension enables an application to
handles.
== New Commands
- 'getSemaphoreWin32HandleKHR'
- 'importSemaphoreWin32HandleKHR'
== New Structures
- 'ImportSemaphoreWin32HandleInfoKHR'
- 'D3D12FenceSubmitInfoKHR'
== New Enum Constants
- 'KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME'
- 'KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION'
== Issues
__RESOLVED__: Yes, unless it is passed back in to another driver
instance to import the object. A successful get call transfers ownership
of the handle to the application. Destroying the semaphore object will
not destroy the handle or the handle’s reference to the underlying
semaphore resource.
separate extension so that it can be deprecated over time?
__RESOLVED__: No. Support for them can be deprecated by drivers if they
choose, by no longer returning them in the supported handle types of the
instance level queries.
attributes for shared handles?
__RESOLVED__: Yes. Applications will be allowed to provide similar
attributes to those they would to any other handle creation API.
__RESOLVED__: There are a couple of options. The values for the signaled
and reset states could be communicated up front when creating the object
specified using auxiliary structures when submitting semaphore signal
and wait operations, similar to what is done with the keyed mutex
extensions. The latter is more flexible and consistent with the keyed
mutex usage, but the former is a much simpler API.
== Version History
- Initial revision
== See Also
'D3D12FenceSubmitInfoKHR', 'ExportSemaphoreWin32HandleInfoKHR',
'ImportSemaphoreWin32HandleInfoKHR', 'SemaphoreGetWin32HandleInfoKHR',
'getSemaphoreWin32HandleKHR', 'importSemaphoreWin32HandleKHR'
== Document Notes
For more information, see the
This page is a generated document. Fixes and changes should be made to
the generator scripts, not directly.
| vkGetSemaphoreWin32HandleKHR - Get a Windows HANDLE for a semaphore
= Description
For handle types defined as NT handles, the handles returned by
'getSemaphoreWin32HandleKHR' are owned by the application. To avoid
leaking resources, the application /must/ release ownership of them
Exporting a Windows handle from a semaphore /may/ have side effects
depending on the transference of the specified handle type, as described
in
<-extensions/html/vkspec.html#synchronization-semaphores-importing Importing Semaphore Payloads>.
== Return Codes
[<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
[<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
= See Also
| @device@ is the logical device that created the semaphore being
exported.
#VUID-vkGetSemaphoreWin32HandleKHR-device-parameter# @device@ /must/ be
structure containing parameters of the export operation.
#VUID-vkGetSemaphoreWin32HandleKHR-pGetWin32HandleInfo-parameter#
HANDLE
= Description
defined as NT handles, the application /must/ release ownership using
Applications /can/ import the same semaphore payload into multiple
== Return Codes
[<-extensions/html/vkspec.html#fundamentals-successcodes Success>]
[<-extensions/html/vkspec.html#fundamentals-errorcodes Failure>]
= See Also
| @device@ is the logical device that created the semaphore.
#VUID-vkImportSemaphoreWin32HandleKHR-device-parameter# @device@ /must/
| @pImportSemaphoreWin32HandleInfo@ is a pointer to a
'ImportSemaphoreWin32HandleInfoKHR' structure specifying the semaphore
and import parameters.
#VUID-vkImportSemaphoreWin32HandleKHR-pImportSemaphoreWin32HandleInfo-parameter#
@pImportSemaphoreWin32HandleInfo@ /must/ be a valid pointer to a valid
'ImportSemaphoreWin32HandleInfoKHR' structure
handle to import to a semaphore
= Description
+---------------------------------------------------------------------------------------------------------------+------------------+---------------------+
| Handle Type | Transference | Permanence |
| | | Supported |
+===============================================================================================================+==================+=====================+
+---------------------------------------------------------------------------------------------------------------+------------------+---------------------+
+---------------------------------------------------------------------------------------------------------------+------------------+---------------------+
+---------------------------------------------------------------------------------------------------------------+------------------+---------------------+
Handle Types Supported by 'ImportSemaphoreWin32HandleInfoKHR'
== Valid Usage
- #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-01140#
@handleType@ /must/ be a value included in the
<-extensions/html/vkspec.html#synchronization-semaphore-handletypes-win32 Handle Types Supported by >
table
- #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-01466# If
or
@name@ /must/ be @NULL@
- #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-01467# If
@handle@ is @NULL@, @name@ /must/ name a valid synchronization
- #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-01468# If
@name@ is @NULL@, @handle@ /must/ be a valid handle of the type
- #VUID-VkImportSemaphoreWin32HandleInfoKHR-handle-01469# If @handle@
is not @NULL@, @name@ /must/ be @NULL@
- #VUID-VkImportSemaphoreWin32HandleInfoKHR-handle-01542# If @handle@
is not @NULL@, it /must/ obey any requirements listed for
<-extensions/html/vkspec.html#external-semaphore-handle-types-compatibility external semaphore handle types compatibility>
in
<-extensions/html/vkspec.html#external-semaphore-handle-types-compatibility external semaphore handle types compatibility>
- #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-03261# If
or
field /must/ match that of the semaphore from which @handle@ or
@name@ was exported
- #VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-03262# If
or
the
field /must/ match that of the semaphore from which @handle@ or
@name@ was exported
- #VUID-VkImportSemaphoreWin32HandleInfoKHR-flags-03322# If @flags@
contains
the
field of the semaphore from which @handle@ or @name@ was exported
/must/ not be
== Valid Usage (Implicit)
/must/ be
/must/ be @NULL@
- #VUID-VkImportSemaphoreWin32HandleInfoKHR-semaphore-parameter#
handle
- #VUID-VkImportSemaphoreWin32HandleInfoKHR-flags-parameter# @flags@
/must/ be a valid combination of
values
== Host Synchronization
- Host access to @semaphore@ /must/ be externally synchronized
= See Also
'importSemaphoreWin32HandleKHR'
| @semaphore@ is the semaphore into which the payload will be imported.
| @flags@ is a bitmask of
specifying additional parameters for the semaphore payload import
operation.
| @handleType@ is a
value specifying the type of @handle@.
| @handle@ is @NULL@ or the external handle to import.
| @name@ is @NULL@ or a null-terminated UTF-16 string naming the
underlying synchronization primitive to import.
| VkExportSemaphoreWin32HandleInfoKHR - Structure specifying additional
= Description
If
is not included in the same @pNext@ chain, this structure is ignored.
If
is included in the @pNext@ chain of
@handleType@, but either 'ExportSemaphoreWin32HandleInfoKHR' is not
included in the @pNext@ chain, or if it is but @pAttributes@ is set to
@NULL@, default security descriptor values will be used, and child
processes created by the application will not inherit the handle, as
access rights used depend on the handle type.
For handles of the following types:
The implementation /must/ ensure the access rights allow both signal and
wait operations on the semaphore.
For handles of the following types:
The access rights /must/ be:
<-us/windows/win32/sync/synchronization-object-security-and-access-rights>
== Valid Usage
- #VUID-VkExportSemaphoreWin32HandleInfoKHR-handleTypes-01125# If
does not include
or
'ExportSemaphoreWin32HandleInfoKHR' /must/ not be included in the
== Valid Usage (Implicit)
- #VUID-VkExportSemaphoreWin32HandleInfoKHR-sType-sType# @sType@
/must/ be
- #VUID-VkExportSemaphoreWin32HandleInfoKHR-pAttributes-parameter# If
to a valid
value
= See Also
structure specifying security attributes of the handle.
specifying access rights of the handle.
| @name@ is a null-terminated UTF-16 string to associate with the
underlying synchronization primitive referenced by NT handles exported
from the created semaphore.
fence-backed semaphores
= Description
respectively does not currently have a
<-extensions/html/vkspec.html#synchronization-semaphores-payloads payload>
Note
As the introduction of the external semaphore handle type
predates that of timeline semaphores, support for importing semaphore
payloads from external handles of that type into semaphores created
(implicitly or explicitly) with a
for backwards compatibility. However, applications /should/ prefer
importing such handle types into semaphores created with a
structure instead of the 'D3D12FenceSubmitInfoKHR' structure to specify
the values to use when waiting for and signaling such semaphores.
== Valid Usage
- #VUID-VkD3D12FenceSubmitInfoKHR-waitSemaphoreValuesCount-00079#
@waitSemaphoreValuesCount@ /must/ be the same value as
'D3D12FenceSubmitInfoKHR' structure
- #VUID-VkD3D12FenceSubmitInfoKHR-signalSemaphoreValuesCount-00080#
@signalSemaphoreValuesCount@ /must/ be the same value as
'D3D12FenceSubmitInfoKHR' structure
== Valid Usage (Implicit)
- #VUID-VkD3D12FenceSubmitInfoKHR-sType-sType# @sType@ /must/ be
- #VUID-VkD3D12FenceSubmitInfoKHR-pWaitSemaphoreValues-parameter# If
not @NULL@, @pWaitSemaphoreValues@ /must/ be a valid pointer to an
- #VUID-VkD3D12FenceSubmitInfoKHR-pSignalSemaphoreValues-parameter# If
/must/ be a valid pointer to an array of
= See Also
| @waitSemaphoreValuesCount@ is the number of semaphore wait values
specified in @pWaitSemaphoreValues@.
| @pWaitSemaphoreValues@ is a pointer to an array of
@waitSemaphoreValuesCount@ values for the corresponding semaphores in
| @signalSemaphoreValuesCount@ is the number of semaphore signal values
specified in @pSignalSemaphoreValues@.
| @pSignalSemaphoreValues@ is a pointer to an array of
signaled.
| VkSemaphoreGetWin32HandleInfoKHR - Structure describing a Win32 handle
semaphore export operation
= Description
The properties of the handle returned depend on the value of
for a description of the properties of the defined external semaphore
handle types.
== Valid Usage
- #VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01126#
@handleType@ /must/ have been included in
when the @semaphore@’s current payload was created
- #VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01127# If
'getSemaphoreWin32HandleKHR' /must/ be called no more than once for
- #VUID-VkSemaphoreGetWin32HandleInfoKHR-semaphore-01128# @semaphore@
/must/ not currently have its payload replaced by an imported
payload as described below in
<-extensions/html/vkspec.html#synchronization-semaphores-importing Importing Semaphore Payloads>
unless that imported payload’s handle type was included in
- #VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01129# If
semantics, as defined below in
<-extensions/html/vkspec.html#synchronization-semaphores-importing Importing Semaphore Payloads>,
there /must/ be no queue waiting on @semaphore@
semantics, @semaphore@ /must/ be signaled, or have an associated
<-extensions/html/vkspec.html#synchronization-semaphores-signaling semaphore signal operation>
pending execution
- #VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01131#
@handleType@ /must/ be defined as an NT handle or a global share
handle
== Valid Usage (Implicit)
- #VUID-VkSemaphoreGetWin32HandleInfoKHR-sType-sType# @sType@ /must/
be
be @NULL@
handle
- #VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-parameter#
@handleType@ /must/ be a valid
value
= See Also
'getSemaphoreWin32HandleKHR'
| @semaphore@ is the semaphore from which state will be exported.
| @handleType@ is a
value specifying the type of handle requested. | 1
- Requires support for Vulkan 1.0
-
2016 - 10 - 21
- , NVIDIA
- , NVIDIA
- , NVIDIA
export semaphore payload to and import semaphore payload from Windows
- ' SemaphoreGetWin32HandleInfoKHR '
- Extending ' Vulkan . Core10.QueueSemaphore . ' :
- ' ExportSemaphoreWin32HandleInfoKHR '
- Extending ' Vulkan . Core10.Queue . SubmitInfo ' :
- Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' :
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR '
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR '
- ' Vulkan . Core10.Enums . StructureType . '
- ' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR '
1 ) Do applications need to call @CloseHandle@ ( ) on the values returned
from ' getSemaphoreWin32HandleKHR ' when @handleType@ is
' Vulkan . Extensions . VK_KHR_external_semaphore_capabilities . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT_KHR ' ?
2 ) Should the language regarding KMT\/Windows 7 handles be moved to a
3 ) Should applications be allowed to specify additional object
4 ) How do applications communicate the desired fence values to use with
@D3D12_FENCE@-based Vulkan semaphores ?
and remain static for the life of the Vulkan semaphore , or they could be
Since Vulkan tends to favor flexibility and consistency over simplicity ,
a new structure specifying fence acquire and release values is
added to the ' Vulkan . Core10.Queue.queueSubmit ' function .
- Revision 1 , 2016 - 10 - 21 ( )
< -extensions/html/vkspec.html#VK_KHR_external_semaphore_win32 Vulkan Specification >
module Vulkan.Extensions.VK_KHR_external_semaphore_win32 ( getSemaphoreWin32HandleKHR
, importSemaphoreWin32HandleKHR
, ImportSemaphoreWin32HandleInfoKHR(..)
, ExportSemaphoreWin32HandleInfoKHR(..)
, D3D12FenceSubmitInfoKHR(..)
, SemaphoreGetWin32HandleInfoKHR(..)
, KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION
, pattern KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION
, KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME
, pattern KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME
, HANDLE
, DWORD
, LPCWSTR
, SECURITY_ATTRIBUTES
) where
import Vulkan.Internal.Utils (traceAroundEvent)
import Control.Exception.Base (bracket)
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Marshal.Alloc (callocBytes)
import Foreign.Marshal.Alloc (free)
import GHC.Base (when)
import GHC.IO (throwIO)
import GHC.Ptr (nullFunPtr)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Cont (evalContT)
import Data.Vector (generateM)
import qualified Data.Vector (imapM_)
import qualified Data.Vector (length)
import qualified Data.Vector (null)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Control.Monad.IO.Class (MonadIO)
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import GHC.IO.Exception (IOErrorType(..))
import GHC.IO.Exception (IOException(..))
import Foreign.Ptr (FunPtr)
import Foreign.Ptr (Ptr)
import Data.Word (Word32)
import Data.Word (Word64)
import Data.Kind (Type)
import Control.Monad.Trans.Cont (ContT(..))
import Data.Vector (Vector)
import Vulkan.CStruct.Utils (advancePtrBytes)
import Vulkan.Extensions.VK_NV_external_memory_win32 (DWORD)
import Vulkan.Core10.Handles (Device)
import Vulkan.Core10.Handles (Device(..))
import Vulkan.Core10.Handles (Device(Device))
import Vulkan.Dynamic (DeviceCmds(pVkGetSemaphoreWin32HandleKHR))
import Vulkan.Dynamic (DeviceCmds(pVkImportSemaphoreWin32HandleKHR))
import Vulkan.Core10.Handles (Device_T)
import Vulkan.Core11.Enums.ExternalSemaphoreHandleTypeFlagBits (ExternalSemaphoreHandleTypeFlagBits)
import Vulkan.Extensions.VK_NV_external_memory_win32 (HANDLE)
import Vulkan.Extensions.VK_KHR_external_memory_win32 (LPCWSTR)
import Vulkan.Core10.Enums.Result (Result)
import Vulkan.Core10.Enums.Result (Result(..))
import Vulkan.Extensions.VK_NV_external_memory_win32 (SECURITY_ATTRIBUTES)
import Vulkan.Core10.Handles (Semaphore)
import Vulkan.Core11.Enums.SemaphoreImportFlagBits (SemaphoreImportFlags)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Exception (VulkanException(..))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_IMPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR))
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR))
import Vulkan.Core10.Enums.Result (Result(SUCCESS))
import Vulkan.Extensions.VK_NV_external_memory_win32 (DWORD)
import Vulkan.Extensions.VK_NV_external_memory_win32 (HANDLE)
import Vulkan.Extensions.VK_KHR_external_memory_win32 (LPCWSTR)
import Vulkan.Extensions.VK_NV_external_memory_win32 (SECURITY_ATTRIBUTES)
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkGetSemaphoreWin32HandleKHR
:: FunPtr (Ptr Device_T -> Ptr SemaphoreGetWin32HandleInfoKHR -> Ptr HANDLE -> IO Result) -> Ptr Device_T -> Ptr SemaphoreGetWin32HandleInfoKHR -> Ptr HANDLE -> IO Result
using the @CloseHandle@ system call when they are no longer needed .
- ' Vulkan . Core10.Enums . Result . SUCCESS '
- ' Vulkan . Core10.Enums . Result . ERROR_TOO_MANY_OBJECTS '
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
< ,
' Vulkan . Core10.Handles . Device ' , ' SemaphoreGetWin32HandleInfoKHR '
getSemaphoreWin32HandleKHR :: forall io
. (MonadIO io)
a valid ' Vulkan . Core10.Handles . Device ' handle
Device
| @pGetWin32HandleInfo@ is a pointer to a ' SemaphoreGetWin32HandleInfoKHR '
@pGetWin32HandleInfo@ /must/ be a valid pointer to a valid
' SemaphoreGetWin32HandleInfoKHR ' structure
SemaphoreGetWin32HandleInfoKHR
-> io (HANDLE)
getSemaphoreWin32HandleKHR device getWin32HandleInfo = liftIO . evalContT $ do
let vkGetSemaphoreWin32HandleKHRPtr = pVkGetSemaphoreWin32HandleKHR (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkGetSemaphoreWin32HandleKHRPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetSemaphoreWin32HandleKHR is null" Nothing Nothing
let vkGetSemaphoreWin32HandleKHR' = mkVkGetSemaphoreWin32HandleKHR vkGetSemaphoreWin32HandleKHRPtr
pGetWin32HandleInfo <- ContT $ withCStruct (getWin32HandleInfo)
pPHandle <- ContT $ bracket (callocBytes @HANDLE 8) free
r <- lift $ traceAroundEvent "vkGetSemaphoreWin32HandleKHR" (vkGetSemaphoreWin32HandleKHR'
(deviceHandle (device))
pGetWin32HandleInfo
(pPHandle))
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
pHandle <- lift $ peek @HANDLE pPHandle
pure $ (pHandle)
foreign import ccall
#if !defined(SAFE_FOREIGN_CALLS)
unsafe
#endif
"dynamic" mkVkImportSemaphoreWin32HandleKHR
:: FunPtr (Ptr Device_T -> Ptr ImportSemaphoreWin32HandleInfoKHR -> IO Result) -> Ptr Device_T -> Ptr ImportSemaphoreWin32HandleInfoKHR -> IO Result
| vkImportSemaphoreWin32HandleKHR - Import a semaphore from a Windows
Importing a semaphore payload from Windows handles does not transfer
ownership of the handle to the Vulkan implementation . For handle types
the @CloseHandle@ system call when the handle is no longer needed .
instances of Vulkan , into the same instance from which it was exported ,
and multiple times into a given Vulkan instance .
- ' Vulkan . Core10.Enums . Result . SUCCESS '
- ' Vulkan . Core10.Enums . Result . ERROR_OUT_OF_HOST_MEMORY '
- ' Vulkan . Core10.Enums . Result . ERROR_INVALID_EXTERNAL_HANDLE '
< ,
' Vulkan . Core10.Handles . Device ' , ' ImportSemaphoreWin32HandleInfoKHR '
importSemaphoreWin32HandleKHR :: forall io
. (MonadIO io)
be a valid ' Vulkan . Core10.Handles . Device ' handle
Device
ImportSemaphoreWin32HandleInfoKHR
-> io ()
importSemaphoreWin32HandleKHR device
importSemaphoreWin32HandleInfo = liftIO . evalContT $ do
let vkImportSemaphoreWin32HandleKHRPtr = pVkImportSemaphoreWin32HandleKHR (case device of Device{deviceCmds} -> deviceCmds)
lift $ unless (vkImportSemaphoreWin32HandleKHRPtr /= nullFunPtr) $
throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkImportSemaphoreWin32HandleKHR is null" Nothing Nothing
let vkImportSemaphoreWin32HandleKHR' = mkVkImportSemaphoreWin32HandleKHR vkImportSemaphoreWin32HandleKHRPtr
pImportSemaphoreWin32HandleInfo <- ContT $ withCStruct (importSemaphoreWin32HandleInfo)
r <- lift $ traceAroundEvent "vkImportSemaphoreWin32HandleKHR" (vkImportSemaphoreWin32HandleKHR'
(deviceHandle (device))
pImportSemaphoreWin32HandleInfo)
lift $ when (r < SUCCESS) (throwIO (VulkanException r))
| VkImportSemaphoreWin32HandleInfoKHR - Structure specifying Windows
The handle types supported by @handleType@ are :
| ' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT ' | Reference | Temporary , Permanent |
| ' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT ' | Reference | Temporary , Permanent |
| ' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT ' | Reference | Temporary , Permanent |
@handleType@ is not
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT '
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT ' ,
primitive of the type specified by @handleType@
specified by @handleType@
@handleType@ in
- # VUID - VkImportSemaphoreWin32HandleInfoKHR - name-01543 # If @name@ is
not @NULL@ , it /must/ obey any requirements listed for @handleType@
@handleType@ is
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT '
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT ' ,
the ' Vulkan . Core10.QueueSemaphore .
@handleType@ is
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT '
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT ' ,
' Vulkan . Core12.Promoted_From_VK_KHR_timeline_semaphore . SemaphoreTypeCreateInfo'::@semaphoreType@
' Vulkan . Core11.Enums . SemaphoreImportFlagBits . SEMAPHORE_IMPORT_TEMPORARY_BIT ' ,
' Vulkan . Core12.Promoted_From_VK_KHR_timeline_semaphore . SemaphoreTypeCreateInfo'::@semaphoreType@
' Vulkan . Core12.Enums . . SEMAPHORE_TYPE_TIMELINE '
- # VUID - VkImportSemaphoreWin32HandleInfoKHR - sType - sType # @sType@
' Vulkan . Core10.Enums . StructureType . '
- # VUID - VkImportSemaphoreWin32HandleInfoKHR - pNext - pNext # @pNext@
@semaphore@ /must/ be a valid ' Vulkan . Core10.Handles . Semaphore '
' Vulkan . Core11.Enums . SemaphoreImportFlagBits . SemaphoreImportFlagBits '
< ,
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits ' ,
' Vulkan . Core10.Handles . Semaphore ' ,
' Vulkan . Core11.Enums . SemaphoreImportFlagBits . SemaphoreImportFlags ' ,
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
data ImportSemaphoreWin32HandleInfoKHR = ImportSemaphoreWin32HandleInfoKHR
semaphore :: Semaphore
' Vulkan . Core11.Enums . SemaphoreImportFlagBits . SemaphoreImportFlagBits '
flags :: SemaphoreImportFlags
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits '
handleType :: ExternalSemaphoreHandleTypeFlagBits
handle :: HANDLE
name :: LPCWSTR
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (ImportSemaphoreWin32HandleInfoKHR)
#endif
deriving instance Show ImportSemaphoreWin32HandleInfoKHR
instance ToCStruct ImportSemaphoreWin32HandleInfoKHR where
withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p)
pokeCStruct p ImportSemaphoreWin32HandleInfoKHR{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Semaphore)) (semaphore)
poke ((p `plusPtr` 24 :: Ptr SemaphoreImportFlags)) (flags)
poke ((p `plusPtr` 28 :: Ptr ExternalSemaphoreHandleTypeFlagBits)) (handleType)
poke ((p `plusPtr` 32 :: Ptr HANDLE)) (handle)
poke ((p `plusPtr` 40 :: Ptr LPCWSTR)) (name)
f
cStructSize = 48
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_IMPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Semaphore)) (zero)
poke ((p `plusPtr` 28 :: Ptr ExternalSemaphoreHandleTypeFlagBits)) (zero)
f
instance FromCStruct ImportSemaphoreWin32HandleInfoKHR where
peekCStruct p = do
semaphore <- peek @Semaphore ((p `plusPtr` 16 :: Ptr Semaphore))
flags <- peek @SemaphoreImportFlags ((p `plusPtr` 24 :: Ptr SemaphoreImportFlags))
handleType <- peek @ExternalSemaphoreHandleTypeFlagBits ((p `plusPtr` 28 :: Ptr ExternalSemaphoreHandleTypeFlagBits))
handle <- peek @HANDLE ((p `plusPtr` 32 :: Ptr HANDLE))
name <- peek @LPCWSTR ((p `plusPtr` 40 :: Ptr LPCWSTR))
pure $ ImportSemaphoreWin32HandleInfoKHR
semaphore flags handleType handle name
instance Storable ImportSemaphoreWin32HandleInfoKHR where
sizeOf ~_ = 48
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero ImportSemaphoreWin32HandleInfoKHR where
zero = ImportSemaphoreWin32HandleInfoKHR
zero
zero
zero
zero
zero
attributes of Windows handles exported from a semaphore
' Vulkan . . '
' Vulkan . . '
' Vulkan . Core10.QueueSemaphore . ' with a Windows
described in the MSDN documentation for “ Synchronization Object Security
and Access Rights”1 . Further , if the structure is not present , the
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT '
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT '
@GENERIC_ALL@
[ 1 ]
' Vulkan . Core11.Promoted_From_VK_KHR_external_semaphore . ExportSemaphoreCreateInfo'::@handleTypes@
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_WIN32_BIT '
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT ' ,
@pNext@ chain of ' Vulkan . Core10.QueueSemaphore . '
' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR '
@pAttributes@ is not @NULL@ , @pAttributes@ /must/ be a valid pointer
' Vulkan . Extensions . '
< ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data ExportSemaphoreWin32HandleInfoKHR = ExportSemaphoreWin32HandleInfoKHR
| @pAttributes@ is a pointer to a Windows
' Vulkan . Extensions . '
attributes :: Ptr SECURITY_ATTRIBUTES
| @dwAccess@ is a ' Vulkan . Extensions . VK_NV_external_memory_win32.DWORD '
dwAccess :: DWORD
name :: LPCWSTR
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (ExportSemaphoreWin32HandleInfoKHR)
#endif
deriving instance Show ExportSemaphoreWin32HandleInfoKHR
instance ToCStruct ExportSemaphoreWin32HandleInfoKHR where
withCStruct x f = allocaBytes 40 $ \p -> pokeCStruct p x (f p)
pokeCStruct p ExportSemaphoreWin32HandleInfoKHR{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr (Ptr SECURITY_ATTRIBUTES))) (attributes)
poke ((p `plusPtr` 24 :: Ptr DWORD)) (dwAccess)
poke ((p `plusPtr` 32 :: Ptr LPCWSTR)) (name)
f
cStructSize = 40
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 24 :: Ptr DWORD)) (zero)
poke ((p `plusPtr` 32 :: Ptr LPCWSTR)) (zero)
f
instance FromCStruct ExportSemaphoreWin32HandleInfoKHR where
peekCStruct p = do
pAttributes <- peek @(Ptr SECURITY_ATTRIBUTES) ((p `plusPtr` 16 :: Ptr (Ptr SECURITY_ATTRIBUTES)))
dwAccess <- peek @DWORD ((p `plusPtr` 24 :: Ptr DWORD))
name <- peek @LPCWSTR ((p `plusPtr` 32 :: Ptr LPCWSTR))
pure $ ExportSemaphoreWin32HandleInfoKHR
pAttributes dwAccess name
instance Storable ExportSemaphoreWin32HandleInfoKHR where
sizeOf ~_ = 40
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero ExportSemaphoreWin32HandleInfoKHR where
zero = ExportSemaphoreWin32HandleInfoKHR
zero
zero
zero
| VkD3D12FenceSubmitInfoKHR - Structure specifying values for Direct3D 12
If the semaphore in ' Vulkan . Core10.Queue . SubmitInfo'::@pWaitSemaphores@
or ' Vulkan . Core10.Queue . SubmitInfo'::@pSignalSemaphores@ corresponding
to an entry in @pWaitSemaphoreValues@ or @pSignalSemaphoreValues@
referring to a Direct3D 12 fence , the implementation /must/ ignore the
value in the @pWaitSemaphoreValues@ or @pSignalSemaphoreValues@ entry .
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . EXTERNAL_SEMAPHORE_HANDLE_TYPE_D3D12_FENCE_BIT '
' Vulkan . Core12.Enums . SemaphoreType . ' of
' Vulkan . Core12.Enums . SemaphoreType . SEMAPHORE_TYPE_BINARY ' is preserved
' Vulkan . Core12.Enums . SemaphoreType . ' of
' Vulkan . Core12.Enums . . , and use the
' Vulkan . Core12.Promoted_From_VK_KHR_timeline_semaphore . TimelineSemaphoreSubmitInfo '
' Vulkan . Core10.Queue . SubmitInfo'::@waitSemaphoreCount@ , where
' Vulkan . Core10.Queue . SubmitInfo ' is in the @pNext@ chain of this
' Vulkan . Core10.Queue . SubmitInfo'::@signalSemaphoreCount@ , where
' Vulkan . Core10.Queue . SubmitInfo ' is in the @pNext@ chain of this
' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR '
@waitSemaphoreValuesCount@ is not @0@ , and @pWaitSemaphoreValues@ is
array of @waitSemaphoreValuesCount@ @uint64_t@ values
@signalSemaphoreValuesCount@ is not @0@ , and
@pSignalSemaphoreValues@ is not @NULL@ , @pSignalSemaphoreValues@
@signalSemaphoreValuesCount@ @uint64_t@ values
< ,
' Vulkan . Core10.Enums . StructureType . StructureType '
data D3D12FenceSubmitInfoKHR = D3D12FenceSubmitInfoKHR
waitSemaphoreValuesCount :: Word32
' Vulkan . Core10.Queue . SubmitInfo'::@pWaitSemaphores@ to wait for .
waitSemaphoreValues :: Vector Word64
signalSemaphoreValuesCount :: Word32
@signalSemaphoreValuesCount@ values for the corresponding semaphores in
' Vulkan . Core10.Queue . SubmitInfo'::@pSignalSemaphores@ to set when
signalSemaphoreValues :: Vector Word64
}
deriving (Typeable)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (D3D12FenceSubmitInfoKHR)
#endif
deriving instance Show D3D12FenceSubmitInfoKHR
instance ToCStruct D3D12FenceSubmitInfoKHR where
withCStruct x f = allocaBytes 48 $ \p -> pokeCStruct p x (f p)
pokeCStruct p D3D12FenceSubmitInfoKHR{..} f = evalContT $ do
lift $ poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR)
lift $ poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
let pWaitSemaphoreValuesLength = Data.Vector.length $ (waitSemaphoreValues)
waitSemaphoreValuesCount'' <- lift $ if (waitSemaphoreValuesCount) == 0
then pure $ fromIntegral pWaitSemaphoreValuesLength
else do
unless (fromIntegral pWaitSemaphoreValuesLength == (waitSemaphoreValuesCount) || pWaitSemaphoreValuesLength == 0) $
throwIO $ IOError Nothing InvalidArgument "" "pWaitSemaphoreValues must be empty or have 'waitSemaphoreValuesCount' elements" Nothing Nothing
pure (waitSemaphoreValuesCount)
lift $ poke ((p `plusPtr` 16 :: Ptr Word32)) (waitSemaphoreValuesCount'')
pWaitSemaphoreValues'' <- if Data.Vector.null (waitSemaphoreValues)
then pure nullPtr
else do
pPWaitSemaphoreValues <- ContT $ allocaBytes @Word64 (((Data.Vector.length (waitSemaphoreValues))) * 8)
lift $ Data.Vector.imapM_ (\i e -> poke (pPWaitSemaphoreValues `plusPtr` (8 * (i)) :: Ptr Word64) (e)) ((waitSemaphoreValues))
pure $ pPWaitSemaphoreValues
lift $ poke ((p `plusPtr` 24 :: Ptr (Ptr Word64))) pWaitSemaphoreValues''
let pSignalSemaphoreValuesLength = Data.Vector.length $ (signalSemaphoreValues)
signalSemaphoreValuesCount'' <- lift $ if (signalSemaphoreValuesCount) == 0
then pure $ fromIntegral pSignalSemaphoreValuesLength
else do
unless (fromIntegral pSignalSemaphoreValuesLength == (signalSemaphoreValuesCount) || pSignalSemaphoreValuesLength == 0) $
throwIO $ IOError Nothing InvalidArgument "" "pSignalSemaphoreValues must be empty or have 'signalSemaphoreValuesCount' elements" Nothing Nothing
pure (signalSemaphoreValuesCount)
lift $ poke ((p `plusPtr` 32 :: Ptr Word32)) (signalSemaphoreValuesCount'')
pSignalSemaphoreValues'' <- if Data.Vector.null (signalSemaphoreValues)
then pure nullPtr
else do
pPSignalSemaphoreValues <- ContT $ allocaBytes @Word64 (((Data.Vector.length (signalSemaphoreValues))) * 8)
lift $ Data.Vector.imapM_ (\i e -> poke (pPSignalSemaphoreValues `plusPtr` (8 * (i)) :: Ptr Word64) (e)) ((signalSemaphoreValues))
pure $ pPSignalSemaphoreValues
lift $ poke ((p `plusPtr` 40 :: Ptr (Ptr Word64))) pSignalSemaphoreValues''
lift $ f
cStructSize = 48
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
f
instance FromCStruct D3D12FenceSubmitInfoKHR where
peekCStruct p = do
waitSemaphoreValuesCount <- peek @Word32 ((p `plusPtr` 16 :: Ptr Word32))
pWaitSemaphoreValues <- peek @(Ptr Word64) ((p `plusPtr` 24 :: Ptr (Ptr Word64)))
let pWaitSemaphoreValuesLength = if pWaitSemaphoreValues == nullPtr then 0 else (fromIntegral waitSemaphoreValuesCount)
pWaitSemaphoreValues' <- generateM pWaitSemaphoreValuesLength (\i -> peek @Word64 ((pWaitSemaphoreValues `advancePtrBytes` (8 * (i)) :: Ptr Word64)))
signalSemaphoreValuesCount <- peek @Word32 ((p `plusPtr` 32 :: Ptr Word32))
pSignalSemaphoreValues <- peek @(Ptr Word64) ((p `plusPtr` 40 :: Ptr (Ptr Word64)))
let pSignalSemaphoreValuesLength = if pSignalSemaphoreValues == nullPtr then 0 else (fromIntegral signalSemaphoreValuesCount)
pSignalSemaphoreValues' <- generateM pSignalSemaphoreValuesLength (\i -> peek @Word64 ((pSignalSemaphoreValues `advancePtrBytes` (8 * (i)) :: Ptr Word64)))
pure $ D3D12FenceSubmitInfoKHR
waitSemaphoreValuesCount
pWaitSemaphoreValues'
signalSemaphoreValuesCount
pSignalSemaphoreValues'
instance Zero D3D12FenceSubmitInfoKHR where
zero = D3D12FenceSubmitInfoKHR
zero
mempty
zero
mempty
@handleType@. See
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits '
' Vulkan . Core11.Promoted_From_VK_KHR_external_semaphore . ExportSemaphoreCreateInfo'::@handleTypes@
@handleType@ is defined as an NT handle ,
each valid unique combination of @semaphore@ and
' Vulkan . Core11.Promoted_From_VK_KHR_external_semaphore_capabilities . ExternalSemaphoreProperties'::@exportFromImportedHandleTypes@
for
@handleType@ refers to a handle type with copy payload transference
- # VUID - VkSemaphoreGetWin32HandleInfoKHR - handleType-01130 # If
@handleType@ refers to a handle type with copy payload transference
' Vulkan . Core10.Enums . StructureType . STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR '
- # VUID - VkSemaphoreGetWin32HandleInfoKHR - pNext - pNext # @pNext@ /must/
- # VUID - VkSemaphoreGetWin32HandleInfoKHR - semaphore - parameter #
@semaphore@ /must/ be a valid ' Vulkan . Core10.Handles . Semaphore '
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits '
< ,
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits ' ,
' Vulkan . Core10.Handles . Semaphore ' ,
' Vulkan . Core10.Enums . StructureType . StructureType ' ,
data SemaphoreGetWin32HandleInfoKHR = SemaphoreGetWin32HandleInfoKHR
semaphore :: Semaphore
' Vulkan . Core11.Enums . ExternalSemaphoreHandleTypeFlagBits . ExternalSemaphoreHandleTypeFlagBits '
handleType :: ExternalSemaphoreHandleTypeFlagBits
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (SemaphoreGetWin32HandleInfoKHR)
#endif
deriving instance Show SemaphoreGetWin32HandleInfoKHR
instance ToCStruct SemaphoreGetWin32HandleInfoKHR where
withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p)
pokeCStruct p SemaphoreGetWin32HandleInfoKHR{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Semaphore)) (semaphore)
poke ((p `plusPtr` 24 :: Ptr ExternalSemaphoreHandleTypeFlagBits)) (handleType)
f
cStructSize = 32
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Semaphore)) (zero)
poke ((p `plusPtr` 24 :: Ptr ExternalSemaphoreHandleTypeFlagBits)) (zero)
f
instance FromCStruct SemaphoreGetWin32HandleInfoKHR where
peekCStruct p = do
semaphore <- peek @Semaphore ((p `plusPtr` 16 :: Ptr Semaphore))
handleType <- peek @ExternalSemaphoreHandleTypeFlagBits ((p `plusPtr` 24 :: Ptr ExternalSemaphoreHandleTypeFlagBits))
pure $ SemaphoreGetWin32HandleInfoKHR
semaphore handleType
instance Storable SemaphoreGetWin32HandleInfoKHR where
sizeOf ~_ = 32
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero SemaphoreGetWin32HandleInfoKHR where
zero = SemaphoreGetWin32HandleInfoKHR
zero
zero
type KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION = 1
No documentation found for TopLevel " "
pattern KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION :: forall a . Integral a => a
pattern KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION = 1
type KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME = "VK_KHR_external_semaphore_win32"
No documentation found for TopLevel " VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME "
pattern KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME = "VK_KHR_external_semaphore_win32"
|
262ad2867a237744be9fbf141d14c794a46b9706ff949ff20b48f72edda289fd | clash-lang/clash-compiler | WarnAlways.hs | # LANGUAGE DataKinds #
{-# LANGUAGE OverloadedStrings #-}
module WarnAlways where
import Clash.Prelude hiding (Text)
import Clash.Annotations.Primitive (warnAlways)
import Clash.Netlist.Types (BlackBox(BBTemplate))
import Clash.Netlist.BlackBox.Types (BlackBoxFunction, emptyBlackBoxMeta, Element(ArgGen,Text))
import Clash.Annotations.Primitive (Primitive(InlinePrimitive), HDL(VHDL))
primitiveTF :: BlackBoxFunction
primitiveTF isD primName args ty = pure $
Right ( emptyBlackBoxMeta, BBTemplate [Text "5 + ", ArgGen 0 0])
primitive
:: Signal System Int
-> Signal System Int
primitive =
(+5)
# NOINLINE primitive #
# ANN primitive ( warnAlways " You should n't use ' primitive ' ! " ) #
{-# ANN primitive (InlinePrimitive [VHDL] "[ { \"BlackBoxHaskell\" : { \"name\" : \"WarnAlways.primitive\", \"templateFunction\" : \"WarnAlways.primitiveTF\"}} ]") #-}
topEntity = primitive
| null | https://raw.githubusercontent.com/clash-lang/clash-compiler/8e461a910f2f37c900705a0847a9b533bce4d2ea/tests/shouldwork/PrimitiveGuards/WarnAlways.hs | haskell | # LANGUAGE OverloadedStrings #
# ANN primitive (InlinePrimitive [VHDL] "[ { \"BlackBoxHaskell\" : { \"name\" : \"WarnAlways.primitive\", \"templateFunction\" : \"WarnAlways.primitiveTF\"}} ]") # | # LANGUAGE DataKinds #
module WarnAlways where
import Clash.Prelude hiding (Text)
import Clash.Annotations.Primitive (warnAlways)
import Clash.Netlist.Types (BlackBox(BBTemplate))
import Clash.Netlist.BlackBox.Types (BlackBoxFunction, emptyBlackBoxMeta, Element(ArgGen,Text))
import Clash.Annotations.Primitive (Primitive(InlinePrimitive), HDL(VHDL))
primitiveTF :: BlackBoxFunction
primitiveTF isD primName args ty = pure $
Right ( emptyBlackBoxMeta, BBTemplate [Text "5 + ", ArgGen 0 0])
primitive
:: Signal System Int
-> Signal System Int
primitive =
(+5)
# NOINLINE primitive #
# ANN primitive ( warnAlways " You should n't use ' primitive ' ! " ) #
topEntity = primitive
|
2aa7ea341273a3e157d92f535308400bd3f0543b6270bf9c72fb3d5d2c10c224 | 2600hz-archive/whistle | riak_core_apl.erl | %% -------------------------------------------------------------------
%%
riak_core : Core Active Preference Lists
%%
Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
%% Get active preference list - preference list with secondary nodes
%% substituted.
%% -------------------------------------------------------------------
-module(riak_core_apl).
-export([active_owners/1, active_owners/2,
get_apl/3, get_apl/4, get_apl_ann/4,
get_primary_apl/3, get_primary_apl/4
]).
-export_type([preflist/0, preflist2/0]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-type index() :: non_neg_integer().
-type n_val() :: non_neg_integer().
-type ring() :: riak_core_ring:riak_core_ring().
-type preflist() :: [{index(), node()}].
-type preflist2() :: [{{index(), node()}, primary|fallback}].
%% Return preflist of all active primary nodes (with no
%% substituion of fallbacks). Used to simulate a
%% preflist with N=ring_size
-spec active_owners(atom()) -> preflist().
active_owners(Service) ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
active_owners(Ring, riak_core_node_watcher:nodes(Service)).
-spec active_owners(ring(), [node()]) -> preflist().
active_owners(Ring, UpNodes) ->
UpNodes1 = ordsets:from_list(UpNodes),
Primaries = riak_core_ring:all_owners(Ring),
{Up, _Pangs} = check_up(Primaries, UpNodes1, [], []),
lists:reverse(Up).
%% Get the active preflist taking account of which nodes are up
-spec get_apl(binary(), n_val(), atom()) -> preflist().
get_apl(DocIdx, N, Service) ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
get_apl(DocIdx, N, Ring, riak_core_node_watcher:nodes(Service)).
%% Get the active preflist taking account of which nodes are up
%% for a given ring/upnodes list
-spec get_apl(binary(), n_val(), ring(), [node()]) -> preflist().
get_apl(DocIdx, N, Ring, UpNodes) ->
[{Partition, Node} || {{Partition, Node}, _Type} <-
get_apl_ann(DocIdx, N, Ring, UpNodes)].
%% Get the active preflist taking account of which nodes are up
%% for a given ring/upnodes list and annotate each node with type of
%% primary/fallback
-spec get_apl_ann(binary(), n_val(), ring(), [node()]) -> preflist2().
get_apl_ann(DocIdx, N, Ring, UpNodes) ->
UpNodes1 = ordsets:from_list(UpNodes),
Preflist = riak_core_ring:preflist(DocIdx, Ring),
{Primaries, Fallbacks} = lists:split(N, Preflist),
{Up, Pangs} = check_up(Primaries, UpNodes1, [], []),
lists:reverse(Up) ++ find_fallbacks(Pangs, Fallbacks, UpNodes1, []).
%% Same as get_apl, but returns only the primaries.
-spec get_primary_apl(binary(), n_val(), atom()) -> preflist().
get_primary_apl(DocIdx, N, Service) ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
get_primary_apl(DocIdx, N, Ring, riak_core_node_watcher:nodes(Service)).
%% Same as get_apl, but returns only the primaries.
-spec get_primary_apl(binary(), n_val(), ring(), [node()]) -> preflist().
get_primary_apl(DocIdx, N, Ring, UpNodes) ->
UpNodes1 = ordsets:from_list(UpNodes),
Preflist = riak_core_ring:preflist(DocIdx, Ring),
{Primaries, _} = lists:split(N, Preflist),
{Up, _} = check_up(Primaries, UpNodes1, [], []),
lists:reverse(Up).
%% Split a preference list into up and down lists
-spec check_up(preflist(), [node()], preflist2(), preflist()) -> {preflist2(), preflist()}.
check_up([], _UpNodes, Up, Pangs) ->
{Up, Pangs};
check_up([{Partition,Node}|Rest], UpNodes, Up, Pangs) ->
case is_up(Node, UpNodes) of
true ->
check_up(Rest, UpNodes, [{{Partition, Node}, primary} | Up], Pangs);
false ->
check_up(Rest, UpNodes, Up, [{Partition, Node} | Pangs])
end.
%% Find fallbacks for downed nodes in the preference list
-spec find_fallbacks(preflist(), preflist(), [node()], preflist2()) -> preflist2().
find_fallbacks(_Pangs, [], _UpNodes, Secondaries) ->
Secondaries;
find_fallbacks([], _Fallbacks, _UpNodes, Secondaries) ->
Secondaries;
find_fallbacks([{Partition, _Node}|Rest]=Pangs, [{_,FN}|Fallbacks], UpNodes, Secondaries) ->
case is_up(FN, UpNodes) of
true ->
find_fallbacks(Rest, Fallbacks, UpNodes,
[{{Partition, FN}, fallback} | Secondaries]);
false ->
find_fallbacks(Pangs, Fallbacks, UpNodes, Secondaries)
end.
%% Return true if a node is up
is_up(Node, UpNodes) ->
ordsets:is_element(Node, UpNodes).
-ifdef(TEST).
smallest_test() ->
Ring = riak_core_ring:fresh(1,node()),
?assertEqual([{0,node()}], get_apl(last_in_ring(), 1, Ring, [node()])).
four_node_test() ->
Nodes = [nodea, nodeb, nodec, noded],
Ring = perfect_ring(8, Nodes),
?assertEqual([{0,nodea},
{182687704666362864775460604089535377456991567872,nodeb},
{365375409332725729550921208179070754913983135744,nodec}],
get_apl(last_in_ring(), 3, Ring, Nodes)),
%% With a node down
?assertEqual([{182687704666362864775460604089535377456991567872,nodeb},
{365375409332725729550921208179070754913983135744,nodec},
{0,noded}],
get_apl(last_in_ring(), 3, Ring, [nodeb, nodec, noded])),
With two nodes down
?assertEqual([{365375409332725729550921208179070754913983135744,nodec},
{0,nodec},
{182687704666362864775460604089535377456991567872,noded}],
get_apl(last_in_ring(), 3, Ring, [nodec, noded])),
With the other two nodes down
?assertEqual([{0,nodea},
{182687704666362864775460604089535377456991567872,nodeb},
{365375409332725729550921208179070754913983135744,nodea}],
get_apl(last_in_ring(), 3, Ring, [nodea, nodeb])).
%% Create a perfect ring - RingSize must be a multiple of nodes
perfect_ring(RingSize, Nodes) when RingSize rem length(Nodes) =:= 0 ->
Ring = riak_core_ring:fresh(RingSize,node()),
Owners = riak_core_ring:all_owners(Ring),
TransferNode =
fun({Idx,_CurOwner}, {Ring0, [NewOwner|Rest]}) ->
{riak_core_ring:transfer_node(Idx, NewOwner, Ring0), Rest ++ [NewOwner]}
end,
{PerfectRing, _} = lists:foldl(TransferNode, {Ring, Nodes}, Owners),
PerfectRing.
last_in_ring() ->
<<1461501637330902918203684832716283019655932542975:160/unsigned>>.
-endif.
| null | https://raw.githubusercontent.com/2600hz-archive/whistle/1a256604f0d037fac409ad5a55b6b17e545dcbf9/lib/riak_core-0.14.0/src/riak_core_apl.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
Get active preference list - preference list with secondary nodes
substituted.
-------------------------------------------------------------------
Return preflist of all active primary nodes (with no
substituion of fallbacks). Used to simulate a
preflist with N=ring_size
Get the active preflist taking account of which nodes are up
Get the active preflist taking account of which nodes are up
for a given ring/upnodes list
Get the active preflist taking account of which nodes are up
for a given ring/upnodes list and annotate each node with type of
primary/fallback
Same as get_apl, but returns only the primaries.
Same as get_apl, but returns only the primaries.
Split a preference list into up and down lists
Find fallbacks for downed nodes in the preference list
Return true if a node is up
With a node down
Create a perfect ring - RingSize must be a multiple of nodes | riak_core : Core Active Preference Lists
Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(riak_core_apl).
-export([active_owners/1, active_owners/2,
get_apl/3, get_apl/4, get_apl_ann/4,
get_primary_apl/3, get_primary_apl/4
]).
-export_type([preflist/0, preflist2/0]).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-type index() :: non_neg_integer().
-type n_val() :: non_neg_integer().
-type ring() :: riak_core_ring:riak_core_ring().
-type preflist() :: [{index(), node()}].
-type preflist2() :: [{{index(), node()}, primary|fallback}].
-spec active_owners(atom()) -> preflist().
active_owners(Service) ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
active_owners(Ring, riak_core_node_watcher:nodes(Service)).
-spec active_owners(ring(), [node()]) -> preflist().
active_owners(Ring, UpNodes) ->
UpNodes1 = ordsets:from_list(UpNodes),
Primaries = riak_core_ring:all_owners(Ring),
{Up, _Pangs} = check_up(Primaries, UpNodes1, [], []),
lists:reverse(Up).
-spec get_apl(binary(), n_val(), atom()) -> preflist().
get_apl(DocIdx, N, Service) ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
get_apl(DocIdx, N, Ring, riak_core_node_watcher:nodes(Service)).
-spec get_apl(binary(), n_val(), ring(), [node()]) -> preflist().
get_apl(DocIdx, N, Ring, UpNodes) ->
[{Partition, Node} || {{Partition, Node}, _Type} <-
get_apl_ann(DocIdx, N, Ring, UpNodes)].
-spec get_apl_ann(binary(), n_val(), ring(), [node()]) -> preflist2().
get_apl_ann(DocIdx, N, Ring, UpNodes) ->
UpNodes1 = ordsets:from_list(UpNodes),
Preflist = riak_core_ring:preflist(DocIdx, Ring),
{Primaries, Fallbacks} = lists:split(N, Preflist),
{Up, Pangs} = check_up(Primaries, UpNodes1, [], []),
lists:reverse(Up) ++ find_fallbacks(Pangs, Fallbacks, UpNodes1, []).
-spec get_primary_apl(binary(), n_val(), atom()) -> preflist().
get_primary_apl(DocIdx, N, Service) ->
{ok, Ring} = riak_core_ring_manager:get_my_ring(),
get_primary_apl(DocIdx, N, Ring, riak_core_node_watcher:nodes(Service)).
-spec get_primary_apl(binary(), n_val(), ring(), [node()]) -> preflist().
get_primary_apl(DocIdx, N, Ring, UpNodes) ->
UpNodes1 = ordsets:from_list(UpNodes),
Preflist = riak_core_ring:preflist(DocIdx, Ring),
{Primaries, _} = lists:split(N, Preflist),
{Up, _} = check_up(Primaries, UpNodes1, [], []),
lists:reverse(Up).
-spec check_up(preflist(), [node()], preflist2(), preflist()) -> {preflist2(), preflist()}.
check_up([], _UpNodes, Up, Pangs) ->
{Up, Pangs};
check_up([{Partition,Node}|Rest], UpNodes, Up, Pangs) ->
case is_up(Node, UpNodes) of
true ->
check_up(Rest, UpNodes, [{{Partition, Node}, primary} | Up], Pangs);
false ->
check_up(Rest, UpNodes, Up, [{Partition, Node} | Pangs])
end.
-spec find_fallbacks(preflist(), preflist(), [node()], preflist2()) -> preflist2().
find_fallbacks(_Pangs, [], _UpNodes, Secondaries) ->
Secondaries;
find_fallbacks([], _Fallbacks, _UpNodes, Secondaries) ->
Secondaries;
find_fallbacks([{Partition, _Node}|Rest]=Pangs, [{_,FN}|Fallbacks], UpNodes, Secondaries) ->
case is_up(FN, UpNodes) of
true ->
find_fallbacks(Rest, Fallbacks, UpNodes,
[{{Partition, FN}, fallback} | Secondaries]);
false ->
find_fallbacks(Pangs, Fallbacks, UpNodes, Secondaries)
end.
is_up(Node, UpNodes) ->
ordsets:is_element(Node, UpNodes).
-ifdef(TEST).
smallest_test() ->
Ring = riak_core_ring:fresh(1,node()),
?assertEqual([{0,node()}], get_apl(last_in_ring(), 1, Ring, [node()])).
four_node_test() ->
Nodes = [nodea, nodeb, nodec, noded],
Ring = perfect_ring(8, Nodes),
?assertEqual([{0,nodea},
{182687704666362864775460604089535377456991567872,nodeb},
{365375409332725729550921208179070754913983135744,nodec}],
get_apl(last_in_ring(), 3, Ring, Nodes)),
?assertEqual([{182687704666362864775460604089535377456991567872,nodeb},
{365375409332725729550921208179070754913983135744,nodec},
{0,noded}],
get_apl(last_in_ring(), 3, Ring, [nodeb, nodec, noded])),
With two nodes down
?assertEqual([{365375409332725729550921208179070754913983135744,nodec},
{0,nodec},
{182687704666362864775460604089535377456991567872,noded}],
get_apl(last_in_ring(), 3, Ring, [nodec, noded])),
With the other two nodes down
?assertEqual([{0,nodea},
{182687704666362864775460604089535377456991567872,nodeb},
{365375409332725729550921208179070754913983135744,nodea}],
get_apl(last_in_ring(), 3, Ring, [nodea, nodeb])).
perfect_ring(RingSize, Nodes) when RingSize rem length(Nodes) =:= 0 ->
Ring = riak_core_ring:fresh(RingSize,node()),
Owners = riak_core_ring:all_owners(Ring),
TransferNode =
fun({Idx,_CurOwner}, {Ring0, [NewOwner|Rest]}) ->
{riak_core_ring:transfer_node(Idx, NewOwner, Ring0), Rest ++ [NewOwner]}
end,
{PerfectRing, _} = lists:foldl(TransferNode, {Ring, Nodes}, Owners),
PerfectRing.
last_in_ring() ->
<<1461501637330902918203684832716283019655932542975:160/unsigned>>.
-endif.
|
68e3429d11f333147ba3548fa72152551c86a505db39bc0bd334e757d62d7d79 | mythical-linux/rktfetch | logo.rkt | #!/usr/bin/env racket
#lang racket/base
(require
"helpers/logos.rkt"
(only-in "helpers/string.rkt" string-remove)
(only-in racket/string string-contains?)
)
(provide get-logo)
(define (get-logo os distro)
(let
(
[dist (string-remove (string-downcase distro) "linux")]
;; initial logo
[logo (if (string-contains? distro "linux")
(hash-ref system-logos "linux")
(case os
(("unix") (hash-ref system-logos "unix"))
(("windows") (hash-ref system-logos "windows"))
(else (hash-ref system-logos "other"))
)
)]
)
(for ([i (hash-keys system-logos)])
(when (string-contains? dist i)
(set! logo (hash-ref system-logos i))
)
)
logo
)
)
| null | https://raw.githubusercontent.com/mythical-linux/rktfetch/b4e7aa6030b09d32e6e8dbee1ad5197b73a8139b/rktfetch/private/get/logo.rkt | racket | initial logo | #!/usr/bin/env racket
#lang racket/base
(require
"helpers/logos.rkt"
(only-in "helpers/string.rkt" string-remove)
(only-in racket/string string-contains?)
)
(provide get-logo)
(define (get-logo os distro)
(let
(
[dist (string-remove (string-downcase distro) "linux")]
[logo (if (string-contains? distro "linux")
(hash-ref system-logos "linux")
(case os
(("unix") (hash-ref system-logos "unix"))
(("windows") (hash-ref system-logos "windows"))
(else (hash-ref system-logos "other"))
)
)]
)
(for ([i (hash-keys system-logos)])
(when (string-contains? dist i)
(set! logo (hash-ref system-logos i))
)
)
logo
)
)
|
e10b92697c3777ed787f5383262a873cd248c1dff9ae4e27644ec13151d3b674 | screenshotbot/screenshotbot-oss | object.lisp | MOP based object subsystem for the BKNR datastore
Internal slots should have a different slot descriptor class , ( setf
;; slot-value-using-class) should only be defined for
;; application-defined slots, not internal slots (like ID, maybe
;; others).
;; get-internal-real-time, get-internal-run-time, get-universal-time
;; need to be shadowed and disallowed.
(in-package :bknr.datastore)
(define-condition inconsistent-slot-persistence-definition (store-error)
((class :initarg :class)
(slot-name :initarg :slot-name))
(:report (lambda (e stream)
(with-slots (slot-name class) e
(format stream "Slot ~A in class ~A declared as both transient and persistent"
slot-name class)))))
(define-condition object-subsystem-not-found-in-store (store-error)
((store :initarg :store))
(:report (lambda (e stream)
(with-slots (store) e
(format stream "Could not find a store-object-subsystem in the current store ~A" store)))))
(define-condition persistent-slot-modified-outside-of-transaction (store-error)
((slot-name :initarg :slot-name)
(object :initarg :object))
(:report (lambda (e stream)
(with-slots (slot-name object) e
(format stream "Attempt to modify persistent slot ~A of ~A outside of a transaction"
slot-name object)))))
(defclass store-object-subsystem ()
((next-object-id :initform 0
:accessor next-object-id
:documentation "Next object ID to assign to a new object")))
(defun store-object-subsystem ()
(let ((subsystem (find-if (alexandria:rcurry #'typep 'store-object-subsystem)
(store-subsystems *store*))))
(unless subsystem
(error 'object-subsystem-not-found-in-store :store *store*))
subsystem))
(eval-when (:compile-toplevel :load-toplevel :execute)
(finalize-inheritance
(defclass persistent-class (indexed-class)
())))
(defmethod validate-superclass ((sub persistent-class) (super indexed-class))
t)
(defvar *suppress-schema-warnings* nil)
(deftransaction update-instances-for-changed-class (class)
(let ((instance-count (length (class-instances class))))
(when (plusp instance-count)
(unless *suppress-schema-warnings*
(report-progress "~&; updating ~A instances of ~A for class changes~%"
instance-count class))
(mapc #'reinitialize-instance (class-instances class)))))
(defmethod reinitialize-instance :after ((class persistent-class) &key)
(when (and (boundp '*store*) *store*)
(update-instances-for-changed-class (class-name class))
(unless *suppress-schema-warnings*
(report-progress "~&; class ~A has been changed. To ensure correct schema ~
evolution, please snapshot your datastore.~%"
(class-name class)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass persistent-direct-slot-definition (index-direct-slot-definition)
((relaxed-object-reference :initarg :relaxed-object-reference
:initform nil)
(transient :initarg :transient
:initform nil)))
(defclass persistent-effective-slot-definition (index-effective-slot-definition)
((relaxed-object-reference :initarg :relaxed-object-reference
:initform nil)
(transient :initarg :transient
:initform nil)))
(defgeneric transient-slot-p (slotd)
(:method ((slotd t))
t)
(:method ((slotd persistent-direct-slot-definition))
(slot-value slotd 'transient))
(:method ((slotd persistent-effective-slot-definition))
(slot-value slotd 'transient)))
(defgeneric relaxed-object-reference-slot-p (slotd)
(:method ((slotd t))
nil)
(:method ((slotd persistent-effective-slot-definition))
(slot-value slotd 'relaxed-object-reference))
(:method ((slotd persistent-direct-slot-definition))
(slot-value slotd 'relaxed-object-reference))
(:documentation "Return whether the given slot definition specifies
that the slot is relaxed. If a relaxed slot holds a pointer to
another persistent object and the pointed-to object is deleted, slot
reads will return nil.")))
(defun undo-set-slot (object slot-name value)
(if (eq value 'unbound)
(slot-makunbound object slot-name)
(setf (slot-value object slot-name) value)))
(defmethod (setf slot-value-using-class) :before ((newval t)
(class persistent-class)
object
(slotd persistent-effective-slot-definition))
(unless (transient-slot-p slotd)
(let ((slot-name (slot-definition-name slotd)))
(unless (or (in-transaction-p)
(member slot-name '(last-change id)))
(error 'persistent-slot-modified-outside-of-transaction :slot-name slot-name :object object))
(when (in-anonymous-transaction-p)
(push (list #'undo-set-slot
object
(slot-definition-name slotd)
(if (slot-boundp object (slot-definition-name slotd))
(slot-value object (slot-definition-name slotd))
'unbound))
(anonymous-transaction-undo-log *current-transaction*)))
(when (and (not (eq :restore (store-state *store*)))
(not (member slot-name '(last-change id))))
(setf (slot-value object 'last-change) (current-transaction-timestamp))))))
(defmethod (setf slot-value-using-class) :after (newval
(class persistent-class)
object
(slotd persistent-effective-slot-definition))
(when (and (not (transient-slot-p slotd))
(in-anonymous-transaction-p)
(not (member (slot-definition-name slotd) '(last-change id))))
(encode (make-instance 'transaction
:timestamp (transaction-timestamp *current-transaction*)
:function-symbol 'tx-change-slot-values
:args (list object (slot-definition-name slotd) newval))
(anonymous-transaction-log-buffer *current-transaction*))))
(define-condition transient-slot-cannot-have-initarg (store-error)
((class :initarg :class)
(slot-name :initarg :slot-name))
(:documentation "A transient slot may not have an :initarg
specified, as initialize-instance is only used for persistent
initialization.")
(:report (lambda (e stream)
(with-slots (class slot-name) e
(format stream "The transient slot ~A in class ~A was defined as having an initarg, which is not supported"
slot-name (class-name class))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod direct-slot-definition-class ((class persistent-class) &key initargs transient name &allow-other-keys)
;; It might be better to do the error checking in an
;; initialize-instance method of persistent-direct-slot-definition
(when (and initargs transient)
(error 'transient-slot-cannot-have-initarg :class class :slot-name name))
'persistent-direct-slot-definition))
(defmethod effective-slot-definition-class ((class persistent-class) &key &allow-other-keys)
'persistent-effective-slot-definition)
(defmethod compute-effective-slot-definition :around ((class persistent-class) name direct-slots)
(unless (or (every #'transient-slot-p direct-slots)
(notany #'transient-slot-p direct-slots))
(error 'inconsistent-slot-persistence-definition :class class :slot-name name))
(let ((effective-slot-definition (call-next-method)))
(when (typep effective-slot-definition 'persistent-effective-slot-definition)
(with-slots (relaxed-object-reference transient) effective-slot-definition
(setf relaxed-object-reference (some #'relaxed-object-reference-slot-p direct-slots)
transient (slot-value (first direct-slots) 'transient))))
effective-slot-definition))
(defmethod class-persistent-slots ((class standard-class))
(remove-if #'transient-slot-p (class-slots class)))
(defclass store-object ()
((id :initarg :id
:reader store-object-id
:type integer
:index-type unique-index
:index-initargs (:test #'eql)
:index-reader store-object-with-id :index-values all-store-objects
:index-mapvalues map-store-objects)
(last-change :initform (get-universal-time)
:initarg :last-change))
(:metaclass persistent-class)
(:class-indices (all-class :index-type class-skip-index
:index-subclasses t
:index-initargs (:index-superclasses t)
:index-keys all-store-classes
:index-reader store-objects-with-class
:slots (id))))
(defun class-instances (class)
(find-class class) ; make sure that the class exists
(store-objects-with-class class))
(deftransaction store-object-touch (object)
"Update the LAST-CHANGE slot to reflect the current transaction timestamp."
(setf (slot-value object 'last-change) (current-transaction-timestamp)))
(defgeneric store-object-last-change (object depth)
(:documentation "Return the last change time of the OBJECT. DEPTH
determines how deep the object graph will be traversed.")
(:method ((object t) (depth integer))
0)
(:method ((object store-object) (depth (eql 0)))
(slot-value object 'last-change))
(:method ((object store-object) depth)
(let ((last-change (slot-value object 'last-change)))
(dolist (slotd (class-slots (class-of object)))
(let* ((slot-name (slot-definition-name slotd))
(child (and (slot-boundp object slot-name)
(slot-value object slot-name))))
(setf last-change
(cond
((null child)
last-change)
((typep child 'store-object)
(max last-change (store-object-last-change child (1- depth))))
((listp child)
(reduce #'max child
:key (alexandria:rcurry 'store-object-last-change (1- depth))
:initial-value last-change))
(t
last-change)))))
last-change)))
#+allegro
(aclmop::finalize-inheritance (find-class 'store-object))
(defmethod initialize-instance :around ((object store-object) &rest initargs &key)
(setf (slot-value object 'id) (allocate-next-object-id))
(cond
((not (in-transaction-p))
(with-store-guard ()
(let ((transaction (make-instance 'transaction
:function-symbol 'make-instance
:timestamp (get-universal-time)
:args (cons (class-name (class-of object))
(append (list :id (slot-value object 'id))
initargs)))))
(with-statistics-log (*transaction-statistics* (transaction-function-symbol transaction))
(with-transaction-log (transaction)
(call-next-method))))))
((in-anonymous-transaction-p)
(encode (make-instance 'transaction
:function-symbol 'make-instance
:timestamp (transaction-timestamp *current-transaction*)
:args (cons (class-name (class-of object)) initargs))
(anonymous-transaction-log-buffer *current-transaction*))
(call-next-method))
(t
(call-next-method))))
(defvar *allocate-object-id-lock* (bt:make-lock "Persistent Object ID Creation"))
(defun allocate-next-object-id ()
(mp-with-lock-held (*allocate-object-id-lock*)
(let ((id (next-object-id (store-object-subsystem))))
(incf (next-object-id (store-object-subsystem)))
id)))
(defun initialize-transient-slots (object)
(dolist (slotd (class-slots (class-of object)))
(when (and (typep slotd 'persistent-effective-slot-definition)
(transient-slot-p slotd)
(slot-definition-initfunction slotd))
(setf (slot-value object (slot-definition-name slotd))
(funcall (slot-definition-initfunction slotd))))))
(defmethod initialize-instance :after ((object store-object) &key)
;; This is called only when initially creating the (persistent)
;; instance, not during restore. During restore, the
INITIALIZE - TRANSIENT - INSTANCE function is called for all
;; persistent objects after the snapshot has been read, but before
;; running the transaction log.
(initialize-transient-instance object))
(defmacro print-store-object ((object stream &key type) &body body)
;; variable capture accepted here.
`(print-unreadable-object (,object ,stream :type ,type)
(format stream "ID: ~D " (store-object-id ,object))
,@body))
(defmethod print-object ((object store-object) stream)
(print-unreadable-object (object stream :type t)
(format stream "ID: ~D" (store-object-id object))))
(defmethod print-object :around ((object store-object) stream)
(if (object-destroyed-p object)
(print-unreadable-object (object stream :type t)
(princ "DESTROYED" stream))
(call-next-method)))
(defmethod change-class :before ((object store-object) class &rest args)
(declare (ignore class args))
(when (not (in-transaction-p))
(error "Can't change class of persistent object ~A using change-class ~
outside of transaction, please use PERSISTENT-CHANGE-CLASS instead" object)))
(defun tx-persistent-change-class (object class-name &rest args)
(warn "TX-PERSISTENT-CHANGE-CLASS does not maintain class indices, ~
please snapshot and restore to recover indices")
(apply #'change-class object (find-class class-name) args))
(defun persistent-change-class (object class &rest args)
(execute (make-instance 'transaction :function-symbol 'tx-persistent-change-class
:timestamp (get-universal-time)
:args (append (list object (if (symbolp class) class (class-name class))) args))))
(defgeneric initialize-transient-instance (store-object)
(:documentation
"Initializes the transient aspects of a persistent object. This
method is called after a persistent object has been initialized, also
when the object is loaded from a snapshot, but before reading the
transaction log."))
(defmethod initialize-transient-instance ((object store-object)))
(defmethod store-object-persistent-slots ((object store-object))
(mapcar #'slot-definition-name (class-persistent-slots (class-of object))))
(defmethod store-object-relaxed-object-reference-p ((object store-object) slot-name)
(let ((slot (find slot-name (class-slots (class-of object)) :key #'slot-definition-name)))
(when slot
(relaxed-object-reference-slot-p slot))))
(defmacro define-persistent-class (class (&rest superclasses) slots &rest class-options)
(let ((superclasses (or superclasses '(store-object)))
(metaclass (cadr (assoc :metaclass class-options))))
(when (and metaclass
(not (validate-superclass (find-class metaclass)
(find-class 'persistent-class))))
(error "Can not define a persistent class with metaclass ~A." metaclass))
`(define-bknr-class ,class ,superclasses ,slots
,@(unless metaclass '((:metaclass persistent-class)))
,@class-options)))
(defmacro defpersistent-class (class (&rest superclasses) slots &rest class-options)
(let ((superclasses (or superclasses '(store-object)))
(metaclass (cadr (assoc :metaclass class-options))))
(when (and metaclass
(not (validate-superclass (find-class metaclass)
(find-class 'persistent-class))))
(error "Can not define a persistent class with metaclass ~A." metaclass))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass ,class ,superclasses ,slots
,@(unless metaclass '((:metaclass persistent-class)))
,@class-options))))
;;; binary snapshot
(defvar *current-object-slot* nil)
(defvar *current-slot-relaxed-p* nil)
(defun encode-layout (id class slots stream)
(%write-tag #\L stream)
(%encode-integer id stream)
(%encode-symbol (class-name class) stream)
(%encode-integer (length slots) stream)
(dolist (slot slots)
(%encode-symbol slot stream)))
(defun %encode-set-slots (slots object stream)
(dolist (slot slots)
(let ((*current-object-slot* (list object slot))
(*current-slot-relaxed-p* (store-object-relaxed-object-reference-p object slot)))
(encode (if (slot-boundp object slot)
(slot-value object slot)
'unbound)
stream))))
(defun encode-create-object (class-layouts object stream)
(let* ((class (class-of object))
(layout (gethash class class-layouts)))
(unless layout
(setf layout
(cons (hash-table-count class-layouts)
XXX layout muss konstant
(sort (remove 'id (store-object-persistent-slots object))
#'string< :key #'symbol-name)))
(encode-layout (car layout) class (cdr layout) stream)
(setf (gethash class class-layouts) layout))
(destructuring-bind (layout-id &rest slots) layout
(declare (ignore slots))
(%write-tag #\O stream)
(%encode-integer layout-id stream)
(%encode-integer (store-object-id object) stream))))
(defun encode-set-slots (class-layouts object stream)
(destructuring-bind (layout-id &rest slots)
(gethash (class-of object) class-layouts)
(%write-tag #\S stream)
(%encode-integer layout-id stream)
(%encode-integer (store-object-id object) stream)
(%encode-set-slots slots object stream)))
(defun find-class-with-interactive-renaming (class-name)
(loop until (or (null class-name)
(find-class class-name nil))
do (progn
(format *query-io* "Class ~A not found, enter new class or enter ~
NIL to ignore objects of this class: "
class-name)
(finish-output *query-io*)
(setq class-name (read *query-io*))))
(and class-name
(find-class class-name)))
(defun find-slot-name-with-interactive-rename (class slot-name)
(loop until (find slot-name (class-slots class) :key #'slot-definition-name)
do (format *query-io* "Slot ~S not found in class ~S, enter new slot name: "
slot-name (class-name class))
do (setq slot-name (read *query-io*))
finally (return slot-name)))
(defvar *slot-name-map*)
(defun rename-slot (class slot-name)
(or (caddr (find (list (class-name class) slot-name) *slot-name-map*
:key #'(lambda (entry) (subseq entry 0 2)) :test #'equal))
(find (symbol-name slot-name)
(mapcar #'slot-definition-name (class-slots class)) :key #'symbol-name :test #'equal)))
(defgeneric convert-slot-value-while-restoring (object slot-name value)
(:documentation "Generic function to be called to convert a slot's
value from a previous snapshot layout. OBJECT is the object that is
being restored, SLOT-NAME is the name of the slot in the old schema,
VALUE is the value of the slot in the old schema.")
(:method (object slot-name value)
(setf (slot-value object slot-name) value)))
(defun find-slot-name-with-automatic-rename (class slot-name)
(if (find slot-name (class-slots class) :key #'slot-definition-name)
slot-name
(restart-case
(let ((new-slot-name (rename-slot class slot-name)))
(cond
(new-slot-name
(warn "slot ~S not found in class ~S, automatically renamed to ~S"
slot-name (class-name class) new-slot-name)
new-slot-name)
(t
(error "can't find a slot in class ~A which matches the name ~A used in the store snapshot"
(class-name class) slot-name))))
(convert-values ()
:report "Convert slot values using CONVERT-SLOT-VALUE-WHILE-RESTORING"
(cons 'convert-slot-values slot-name))
(ignore-slot ()
:report "Ignore slot, discarding values found in the snapshot file"
nil))))
(defun find-class-slots-with-interactive-renaming (class slot-names)
#+(or)
(format t "; verifying class layout for class ~A~%; slots:~{ ~S~}~%" (class-name class)
(mapcar #'slot-definition-name (class-slots class)))
(loop for slot-name in slot-names
collect (find-slot-name-with-automatic-rename class slot-name)))
(defun snapshot-read-layout (stream layouts)
(let* ((id (%decode-integer stream))
(class-name (%decode-symbol stream :usage "class"))
(nslots (%decode-integer stream))
(class (find-class-with-interactive-renaming class-name))
(slot-names (loop repeat nslots collect (%decode-symbol stream
:intern (not (null class))
:usage "slot")))
(slots (if class
(find-class-slots-with-interactive-renaming class slot-names)
slot-names)))
(setf (gethash id layouts)
(cons class slots))))
(defun %read-slots (stream object slots)
"Read the OBJECT from STREAM. The individual slots of the object
are expected in the order of the list SLOTS. If the OBJECT is NIL,
the slots are read from the snapshot and ignored."
(declare (optimize (speed 3)))
(dolist (slot-name slots)
(let ((value (decode stream)))
(cond
((consp slot-name)
(assert (eq 'convert-slot-values (car slot-name)))
(convert-slot-value-while-restoring object (cdr slot-name) value))
((null slot-name)
;; ignore value
)
(t
(restart-case
(let ((*current-object-slot* (list object slot-name))
(*current-slot-relaxed-p* (or (null object)
(store-object-relaxed-object-reference-p object slot-name))))
(when object
(let ((bknr.indices::*indices-remove-p* nil))
(if (eq value 'unbound)
(slot-makunbound object slot-name)
(convert-slot-value-while-restoring object slot-name value)))))
(set-slot-nil ()
:report "Set slot to NIL."
(setf (slot-value object slot-name) nil))
(make-slot-unbound ()
:report "Make slot unbound."
(slot-makunbound object slot-name))))))))
(defun snapshot-read-object (stream layouts)
(declare (optimize (speed 3)))
(with-simple-restart (skip-object "Skip the object.")
(let* ((layout-id (%decode-integer stream))
(object-id (%decode-integer stream))
(class (first (gethash layout-id layouts))))
;; If the class is NIL, it was not found in the currently
;; running Lisp image and objects of this class will be ignored.
(when class
(let ((object (allocate-instance class)))
(setf (slot-value object 'id) object-id
(next-object-id (store-object-subsystem)) (max (1+ object-id)
(next-object-id (store-object-subsystem))))
(dolist (index (class-slot-indices class 'id))
(index-add index object)))))))
(defun snapshot-read-slots (stream layouts)
(let* ((layout-id (%decode-integer stream))
(object-id (%decode-integer stream))
(object (store-object-with-id object-id)))
(restart-case
(%read-slots stream object (cdr (gethash layout-id layouts)))
(skip-object-initialization ()
:report "Skip object initialization.")
(delete-object ()
:report "Delete the object."
(delete-object object)))))
(define-condition encoding-destroyed-object (error)
((id :initarg :id)
(slot :initarg :slot)
(container :initarg :container))
(:report (lambda (e out)
(with-slots (slot container id) e
(format out
"Encoding reference to destroyed object with ID ~A from slot ~A of object ~A with ID ~A."
id slot (type-of container) (store-object-id container))))))
(defmethod encode-object ((object store-object) stream)
(if (object-destroyed-p object)
(let* ((*indexed-class-override* t)
(id (store-object-id object))
(container (first *current-object-slot*))
(slot (second *current-object-slot*)))
;; if we are not encoding slot values, something has gone
;; wrong with the indices
(unless (and container slot)
(warn "Encoding destroyed object with ID ~A." id)
(%write-tag #\o stream)
(%encode-integer id stream)
(return-from encode-object))
(flet ((encode-relaxed ()
(warn "Encoding reference to destroyed object with ID ~A from slot ~A of object ~A with ID ~A."
id slot (type-of container) (store-object-id container))
(%write-tag #\o stream)
(%encode-integer id stream)))
(if *current-slot-relaxed-p*
;; the slot can contain references to deleted objects, just warn
(encode-relaxed)
;; the slot can't contain references to deleted objects, throw an error
(restart-case
(error 'encoding-destroyed-object
:id id
:slot slot
:container container)
(encode-relaxed-slot ()
(encode-relaxed))
(make-slot-unbound-and-encode-relaxed ()
(encode-relaxed)
(slot-makunbound container slot))))))
;; Go ahead and serialize the object reference
(progn (%write-tag #\o stream)
(%encode-integer (store-object-id object) stream))))
(defmethod decode-object ((tag (eql #\o)) stream)
(let ((*current-object-slot* nil))
(%decode-store-object stream)))
(define-condition invalid-reference (warning)
((id :initarg :id))
(:report (lambda (e stream)
(format stream "internal inconsistency during restore - store object with ID ~A could not be found"
(slot-value e 'id)))))
(defun %decode-store-object (stream)
This is actually called in two contexts , when a slot - value is to
;; be filled with a reference to a store object and when a list of
;; store objects is read from the transaction log (%decode-list).
In the former case , references two deleted objects are accepted
;; when the slot pointing to the object is marked as being a
;; "relaxed-object-reference", in the latter case, no such
;; information is available. To ensure maximum restorability of
;; transaction logs, object references stored in lists are always
;; considered to be relaxed references, which means that references
to deleted objects are restored as NIL . Applications must be
;; prepared to cope with NIL entries in such object lists (usually
;; lists in slots).
(let* ((id (%decode-integer stream))
(object (or (store-object-with-id id)
(warn 'invalid-reference :id id)))
(container (first *current-object-slot*))
(slot-name (second *current-object-slot*)))
(cond (object object)
((or *current-slot-relaxed-p* (not container))
(if container
(warn "Reference to inexistent object with id ~A in relaxed slot ~A of object ~
with class ~A with ID ~A."
id slot-name (type-of container) (store-object-id container))
(warn "Reference to inexistent object with id ~A from unnamed container, returning NIL." id))
;; Possibly determine new "current object id"
(when (>= id (next-object-id (store-object-subsystem)))
(setf (next-object-id (store-object-subsystem)) (1+ id)))
nil)
(t (error "Reference to inexistent object with id ~A from slot ~A of object ~A with ID ~A."
id slot-name (type-of container)
(if container (store-object-id container) "unknown object"))))))
(defun encode-current-object-id (stream)
(%write-tag #\I stream)
(%encode-integer (next-object-id (store-object-subsystem)) stream))
(defmethod snapshot-subsystem ((store store) (subsystem store-object-subsystem))
(let ((snapshot (store-subsystem-snapshot-pathname store subsystem)))
(with-open-file (s snapshot
:direction :output
:element-type '(unsigned-byte 8)
:if-does-not-exist :create
:if-exists :supersede)
(let ((class-layouts (make-hash-table)))
(with-transaction (:prepare-for-snapshot)
(map-store-objects #'prepare-for-snapshot))
(encode-current-object-id s)
(map-store-objects (lambda (object) (when (subtypep (type-of object) 'store-object)
(encode-create-object class-layouts object s))))
(map-store-objects (lambda (object) (when (subtypep (type-of object) 'store-object)
(encode-set-slots class-layouts object s))))
t))))
(defmethod close-subsystem ((store store) (subsystem store-object-subsystem))
(dolist (class-name (all-store-classes))
(clear-class-indices (find-class class-name))))
(defmethod restore-subsystem ((store store) (subsystem store-object-subsystem) &key until)
;; XXX check that until > snapshot time
(declare (ignore until))
(let ((snapshot (store-subsystem-snapshot-pathname store subsystem)))
;; not all indices that should be cleared are cleared. maybe
check on first instatiation of a class ?
(dolist (class-name (cons 'store-object (all-store-classes)))
(clear-class-indices (find-class class-name)))
(setf (next-object-id subsystem) 0)
(when (probe-file snapshot)
(report-progress "~&; loading snapshot file ~A~%" snapshot)
(with-open-file (s snapshot
:element-type '(unsigned-byte 8)
:direction :input)
(let ((class-layouts (make-hash-table))
(created-objects 0)
(reported-objects-count 0)
(read-slots 0)
(error t)
(*slot-name-map* nil))
(unwind-protect
(progn
(with-simple-restart
(finalize-object-subsystem "Finalize the object subsystem.")
(loop
(when (and (plusp created-objects)
(zerop (mod created-objects 10000))
(not (= created-objects reported-objects-count)))
#+nil (format t "Snapshot position ~A~%" (file-position s))
(report-progress "~A objects created.~%" created-objects)
(setf reported-objects-count created-objects)
(force-output))
(when (and (plusp read-slots)
(zerop (mod read-slots 10000)))
(report-progress "~A of ~A objects initialized.~%" read-slots created-objects)
(force-output))
(let ((char (%read-tag s nil nil)))
(unless (member char '(#\I #\L #\O #\S nil))
(error "unknown char ~A at offset ~A~%" char (file-position s)))
(ecase char
((nil) (return))
(#\I (setf (next-object-id (store-object-subsystem)) (%decode-integer s)))
(#\L (snapshot-read-layout s class-layouts))
(#\O (snapshot-read-object s class-layouts) (incf created-objects))
(#\S (snapshot-read-slots s class-layouts) (incf read-slots))))))
(map-store-objects #'initialize-transient-slots)
(map-store-objects #'initialize-transient-instance)
(setf error nil))
(when error
(maphash #'(lambda (key val)
(declare (ignore key))
(let ((class-name (car val)))
(report-progress "clearing indices for class ~A~%" (class-name class-name))
(clear-class-indices class-name)))
class-layouts))))))))
(defun tx-delete-object (id)
(destroy-object (store-object-with-id id)))
(defun delete-object (object)
(if (and (in-transaction-p)
(not (in-anonymous-transaction-p)))
(destroy-object object)
(execute (make-instance 'transaction :function-symbol 'tx-delete-object
:timestamp (get-universal-time)
:args (list (store-object-id object))))))
(defun tx-delete-objects (&rest object-ids)
(mapc #'(lambda (id) (destroy-object (store-object-with-id id))) object-ids))
(defun delete-objects (&rest objects)
(if (in-transaction-p)
(mapc #'destroy-object objects)
(execute (make-instance 'transaction :function-symbol 'tx-delete-objects
:timestamp (get-universal-time)
:args (mapcar #'store-object-id objects)))))
(defgeneric cascade-delete-p (object referencing-object)
(:method (object referencing-object)
(declare (ignore object referencing-object))
nil)
(:documentation "return non-nil if the REFERENCING-OBJECT should be deleted when the OBJECT is deleted"))
(defun partition-list (list predicate)
"Return two list values, the first containing all elements from LIST
that satisfy PREDICATE, the second those that don't"
(let (do dont)
(dolist (element list)
(if (funcall predicate element)
(push element do)
(push element dont)))
(values do dont)))
(defun cascading-delete-object (object)
"Delete the OBJECT and all objects that reference it and that are eligible to cascading deletes, as indicated by
the result of calling CASCADE-DELETE-P. Generate error if there are references to the objects that are not eligible
to cascading deletes."
(multiple-value-bind (cascading-delete-refs
remaining-refs)
(partition-list (find-refs object) (alexandria:curry #'cascade-delete-p object))
(when remaining-refs
(error "Cannot delete object ~A because there are references ~
to this object in the system, please consult a system administrator!"
object))
(apply #'delete-objects object cascading-delete-refs)))
(defun tx-change-slot-values (object &rest slots-and-values)
"Called by the MOP to change a persistent slot's value."
(unless (in-transaction-p)
(error 'not-in-transaction))
(when object
(loop for (slot value) on slots-and-values by #'cddr
do (setf (slot-value object slot) value))))
(defun change-slot-values (object &rest slots-and-values)
"This function is the deprecated way to set slots of persistent
objects."
(warn "CHANGE-SLOT-VALUES is deprecated - use WITH-TRANSACTION and standard accessors!")
(execute (make-instance 'transaction
:function-symbol 'tx-change-slot-values
:timestamp (get-universal-time)
:args (list* object slots-and-values))))
(defgeneric prepare-for-snapshot (object)
(:method ((object store-object))
nil)
(:documentation "Called for every store object before a snapshot is
written."))
(defun find-store-object (id-or-name &key (class 'store-object) query-function key-slot-name)
"Mock up implementation of find-store-object API as in the old datastore.
Note: QUERY-FUNCTION will only be used if ID-OR-NAME is neither an integer nor a
string designating an integer."
(unless id-or-name
(error "can't search a store object with null key"))
(when (stringp id-or-name)
(multiple-value-bind (value end) (parse-integer id-or-name :junk-allowed t)
(when (and value
(eql end (length id-or-name)))
(setq id-or-name value))))
(let ((result (cond
((numberp id-or-name)
(store-object-with-id id-or-name))
(t
(cond
(query-function
(funcall query-function id-or-name))
((eq class 't)
(error "can't search for store object by name without class specified"))
(t
(let ((index (bknr.indices::class-slot-index (find-class class) key-slot-name)))
(when index
(index-get index id-or-name)))))))))
(unless (or (null result)
(typep result class))
(error "Object ~A is not of wanted type ~A." result class))
result))
(deftransaction store-object-add-keywords (object slot keywords)
(setf (slot-value object slot)
(union (slot-value object slot)
keywords)))
(deftransaction store-object-remove-keywords (object slot keywords)
(setf (slot-value object slot)
(set-difference (slot-value object slot) keywords)))
(deftransaction store-object-set-keywords (object slot keywords)
(setf (slot-value object slot) keywords))
(defmethod find-refs ((object store-object))
"Find references to the given OBJECT in all store-objects, traversing both single valued and list valued slots."
(remove-if-not
(lambda (candidate)
(find-if (lambda (slotd)
(and (slot-boundp candidate (slot-definition-name slotd))
(let ((slot-value (slot-value candidate (slot-definition-name slotd))))
(or (eq object slot-value)
(and (alexandria:proper-list-p slot-value)
(find object slot-value))))))
(class-slots (class-of candidate))))
(class-instances 'store-object)))
(pushnew :mop-store cl:*features*)
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/3eaa883800031a1b041cc81ee58f1f2ca8c40bde/third-party/bknr.datastore/src/data/object.lisp | lisp | slot-value-using-class) should only be defined for
application-defined slots, not internal slots (like ID, maybe
others).
get-internal-real-time, get-internal-run-time, get-universal-time
need to be shadowed and disallowed.
class ~A has been changed. To ensure correct schema ~
It might be better to do the error checking in an
initialize-instance method of persistent-direct-slot-definition
make sure that the class exists
This is called only when initially creating the (persistent)
instance, not during restore. During restore, the
persistent objects after the snapshot has been read, but before
running the transaction log.
variable capture accepted here.
binary snapshot
ignore value
If the class is NIL, it was not found in the currently
running Lisp image and objects of this class will be ignored.
if we are not encoding slot values, something has gone
wrong with the indices
the slot can contain references to deleted objects, just warn
the slot can't contain references to deleted objects, throw an error
Go ahead and serialize the object reference
be filled with a reference to a store object and when a list of
store objects is read from the transaction log (%decode-list).
when the slot pointing to the object is marked as being a
"relaxed-object-reference", in the latter case, no such
information is available. To ensure maximum restorability of
transaction logs, object references stored in lists are always
considered to be relaxed references, which means that references
prepared to cope with NIL entries in such object lists (usually
lists in slots).
Possibly determine new "current object id"
XXX check that until > snapshot time
not all indices that should be cleared are cleared. maybe | MOP based object subsystem for the BKNR datastore
Internal slots should have a different slot descriptor class , ( setf
(in-package :bknr.datastore)
(define-condition inconsistent-slot-persistence-definition (store-error)
((class :initarg :class)
(slot-name :initarg :slot-name))
(:report (lambda (e stream)
(with-slots (slot-name class) e
(format stream "Slot ~A in class ~A declared as both transient and persistent"
slot-name class)))))
(define-condition object-subsystem-not-found-in-store (store-error)
((store :initarg :store))
(:report (lambda (e stream)
(with-slots (store) e
(format stream "Could not find a store-object-subsystem in the current store ~A" store)))))
(define-condition persistent-slot-modified-outside-of-transaction (store-error)
((slot-name :initarg :slot-name)
(object :initarg :object))
(:report (lambda (e stream)
(with-slots (slot-name object) e
(format stream "Attempt to modify persistent slot ~A of ~A outside of a transaction"
slot-name object)))))
(defclass store-object-subsystem ()
((next-object-id :initform 0
:accessor next-object-id
:documentation "Next object ID to assign to a new object")))
(defun store-object-subsystem ()
(let ((subsystem (find-if (alexandria:rcurry #'typep 'store-object-subsystem)
(store-subsystems *store*))))
(unless subsystem
(error 'object-subsystem-not-found-in-store :store *store*))
subsystem))
(eval-when (:compile-toplevel :load-toplevel :execute)
(finalize-inheritance
(defclass persistent-class (indexed-class)
())))
(defmethod validate-superclass ((sub persistent-class) (super indexed-class))
t)
(defvar *suppress-schema-warnings* nil)
(deftransaction update-instances-for-changed-class (class)
(let ((instance-count (length (class-instances class))))
(when (plusp instance-count)
(unless *suppress-schema-warnings*
(report-progress "~&; updating ~A instances of ~A for class changes~%"
instance-count class))
(mapc #'reinitialize-instance (class-instances class)))))
(defmethod reinitialize-instance :after ((class persistent-class) &key)
(when (and (boundp '*store*) *store*)
(update-instances-for-changed-class (class-name class))
(unless *suppress-schema-warnings*
evolution, please snapshot your datastore.~%"
(class-name class)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass persistent-direct-slot-definition (index-direct-slot-definition)
((relaxed-object-reference :initarg :relaxed-object-reference
:initform nil)
(transient :initarg :transient
:initform nil)))
(defclass persistent-effective-slot-definition (index-effective-slot-definition)
((relaxed-object-reference :initarg :relaxed-object-reference
:initform nil)
(transient :initarg :transient
:initform nil)))
(defgeneric transient-slot-p (slotd)
(:method ((slotd t))
t)
(:method ((slotd persistent-direct-slot-definition))
(slot-value slotd 'transient))
(:method ((slotd persistent-effective-slot-definition))
(slot-value slotd 'transient)))
(defgeneric relaxed-object-reference-slot-p (slotd)
(:method ((slotd t))
nil)
(:method ((slotd persistent-effective-slot-definition))
(slot-value slotd 'relaxed-object-reference))
(:method ((slotd persistent-direct-slot-definition))
(slot-value slotd 'relaxed-object-reference))
(:documentation "Return whether the given slot definition specifies
that the slot is relaxed. If a relaxed slot holds a pointer to
another persistent object and the pointed-to object is deleted, slot
reads will return nil.")))
(defun undo-set-slot (object slot-name value)
(if (eq value 'unbound)
(slot-makunbound object slot-name)
(setf (slot-value object slot-name) value)))
(defmethod (setf slot-value-using-class) :before ((newval t)
(class persistent-class)
object
(slotd persistent-effective-slot-definition))
(unless (transient-slot-p slotd)
(let ((slot-name (slot-definition-name slotd)))
(unless (or (in-transaction-p)
(member slot-name '(last-change id)))
(error 'persistent-slot-modified-outside-of-transaction :slot-name slot-name :object object))
(when (in-anonymous-transaction-p)
(push (list #'undo-set-slot
object
(slot-definition-name slotd)
(if (slot-boundp object (slot-definition-name slotd))
(slot-value object (slot-definition-name slotd))
'unbound))
(anonymous-transaction-undo-log *current-transaction*)))
(when (and (not (eq :restore (store-state *store*)))
(not (member slot-name '(last-change id))))
(setf (slot-value object 'last-change) (current-transaction-timestamp))))))
(defmethod (setf slot-value-using-class) :after (newval
(class persistent-class)
object
(slotd persistent-effective-slot-definition))
(when (and (not (transient-slot-p slotd))
(in-anonymous-transaction-p)
(not (member (slot-definition-name slotd) '(last-change id))))
(encode (make-instance 'transaction
:timestamp (transaction-timestamp *current-transaction*)
:function-symbol 'tx-change-slot-values
:args (list object (slot-definition-name slotd) newval))
(anonymous-transaction-log-buffer *current-transaction*))))
(define-condition transient-slot-cannot-have-initarg (store-error)
((class :initarg :class)
(slot-name :initarg :slot-name))
(:documentation "A transient slot may not have an :initarg
specified, as initialize-instance is only used for persistent
initialization.")
(:report (lambda (e stream)
(with-slots (class slot-name) e
(format stream "The transient slot ~A in class ~A was defined as having an initarg, which is not supported"
slot-name (class-name class))))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod direct-slot-definition-class ((class persistent-class) &key initargs transient name &allow-other-keys)
(when (and initargs transient)
(error 'transient-slot-cannot-have-initarg :class class :slot-name name))
'persistent-direct-slot-definition))
(defmethod effective-slot-definition-class ((class persistent-class) &key &allow-other-keys)
'persistent-effective-slot-definition)
(defmethod compute-effective-slot-definition :around ((class persistent-class) name direct-slots)
(unless (or (every #'transient-slot-p direct-slots)
(notany #'transient-slot-p direct-slots))
(error 'inconsistent-slot-persistence-definition :class class :slot-name name))
(let ((effective-slot-definition (call-next-method)))
(when (typep effective-slot-definition 'persistent-effective-slot-definition)
(with-slots (relaxed-object-reference transient) effective-slot-definition
(setf relaxed-object-reference (some #'relaxed-object-reference-slot-p direct-slots)
transient (slot-value (first direct-slots) 'transient))))
effective-slot-definition))
(defmethod class-persistent-slots ((class standard-class))
(remove-if #'transient-slot-p (class-slots class)))
(defclass store-object ()
((id :initarg :id
:reader store-object-id
:type integer
:index-type unique-index
:index-initargs (:test #'eql)
:index-reader store-object-with-id :index-values all-store-objects
:index-mapvalues map-store-objects)
(last-change :initform (get-universal-time)
:initarg :last-change))
(:metaclass persistent-class)
(:class-indices (all-class :index-type class-skip-index
:index-subclasses t
:index-initargs (:index-superclasses t)
:index-keys all-store-classes
:index-reader store-objects-with-class
:slots (id))))
(defun class-instances (class)
(store-objects-with-class class))
(deftransaction store-object-touch (object)
"Update the LAST-CHANGE slot to reflect the current transaction timestamp."
(setf (slot-value object 'last-change) (current-transaction-timestamp)))
(defgeneric store-object-last-change (object depth)
(:documentation "Return the last change time of the OBJECT. DEPTH
determines how deep the object graph will be traversed.")
(:method ((object t) (depth integer))
0)
(:method ((object store-object) (depth (eql 0)))
(slot-value object 'last-change))
(:method ((object store-object) depth)
(let ((last-change (slot-value object 'last-change)))
(dolist (slotd (class-slots (class-of object)))
(let* ((slot-name (slot-definition-name slotd))
(child (and (slot-boundp object slot-name)
(slot-value object slot-name))))
(setf last-change
(cond
((null child)
last-change)
((typep child 'store-object)
(max last-change (store-object-last-change child (1- depth))))
((listp child)
(reduce #'max child
:key (alexandria:rcurry 'store-object-last-change (1- depth))
:initial-value last-change))
(t
last-change)))))
last-change)))
#+allegro
(aclmop::finalize-inheritance (find-class 'store-object))
(defmethod initialize-instance :around ((object store-object) &rest initargs &key)
(setf (slot-value object 'id) (allocate-next-object-id))
(cond
((not (in-transaction-p))
(with-store-guard ()
(let ((transaction (make-instance 'transaction
:function-symbol 'make-instance
:timestamp (get-universal-time)
:args (cons (class-name (class-of object))
(append (list :id (slot-value object 'id))
initargs)))))
(with-statistics-log (*transaction-statistics* (transaction-function-symbol transaction))
(with-transaction-log (transaction)
(call-next-method))))))
((in-anonymous-transaction-p)
(encode (make-instance 'transaction
:function-symbol 'make-instance
:timestamp (transaction-timestamp *current-transaction*)
:args (cons (class-name (class-of object)) initargs))
(anonymous-transaction-log-buffer *current-transaction*))
(call-next-method))
(t
(call-next-method))))
(defvar *allocate-object-id-lock* (bt:make-lock "Persistent Object ID Creation"))
(defun allocate-next-object-id ()
(mp-with-lock-held (*allocate-object-id-lock*)
(let ((id (next-object-id (store-object-subsystem))))
(incf (next-object-id (store-object-subsystem)))
id)))
(defun initialize-transient-slots (object)
(dolist (slotd (class-slots (class-of object)))
(when (and (typep slotd 'persistent-effective-slot-definition)
(transient-slot-p slotd)
(slot-definition-initfunction slotd))
(setf (slot-value object (slot-definition-name slotd))
(funcall (slot-definition-initfunction slotd))))))
(defmethod initialize-instance :after ((object store-object) &key)
INITIALIZE - TRANSIENT - INSTANCE function is called for all
(initialize-transient-instance object))
(defmacro print-store-object ((object stream &key type) &body body)
`(print-unreadable-object (,object ,stream :type ,type)
(format stream "ID: ~D " (store-object-id ,object))
,@body))
(defmethod print-object ((object store-object) stream)
(print-unreadable-object (object stream :type t)
(format stream "ID: ~D" (store-object-id object))))
(defmethod print-object :around ((object store-object) stream)
(if (object-destroyed-p object)
(print-unreadable-object (object stream :type t)
(princ "DESTROYED" stream))
(call-next-method)))
(defmethod change-class :before ((object store-object) class &rest args)
(declare (ignore class args))
(when (not (in-transaction-p))
(error "Can't change class of persistent object ~A using change-class ~
outside of transaction, please use PERSISTENT-CHANGE-CLASS instead" object)))
(defun tx-persistent-change-class (object class-name &rest args)
(warn "TX-PERSISTENT-CHANGE-CLASS does not maintain class indices, ~
please snapshot and restore to recover indices")
(apply #'change-class object (find-class class-name) args))
(defun persistent-change-class (object class &rest args)
(execute (make-instance 'transaction :function-symbol 'tx-persistent-change-class
:timestamp (get-universal-time)
:args (append (list object (if (symbolp class) class (class-name class))) args))))
(defgeneric initialize-transient-instance (store-object)
(:documentation
"Initializes the transient aspects of a persistent object. This
method is called after a persistent object has been initialized, also
when the object is loaded from a snapshot, but before reading the
transaction log."))
(defmethod initialize-transient-instance ((object store-object)))
(defmethod store-object-persistent-slots ((object store-object))
(mapcar #'slot-definition-name (class-persistent-slots (class-of object))))
(defmethod store-object-relaxed-object-reference-p ((object store-object) slot-name)
(let ((slot (find slot-name (class-slots (class-of object)) :key #'slot-definition-name)))
(when slot
(relaxed-object-reference-slot-p slot))))
(defmacro define-persistent-class (class (&rest superclasses) slots &rest class-options)
(let ((superclasses (or superclasses '(store-object)))
(metaclass (cadr (assoc :metaclass class-options))))
(when (and metaclass
(not (validate-superclass (find-class metaclass)
(find-class 'persistent-class))))
(error "Can not define a persistent class with metaclass ~A." metaclass))
`(define-bknr-class ,class ,superclasses ,slots
,@(unless metaclass '((:metaclass persistent-class)))
,@class-options)))
(defmacro defpersistent-class (class (&rest superclasses) slots &rest class-options)
(let ((superclasses (or superclasses '(store-object)))
(metaclass (cadr (assoc :metaclass class-options))))
(when (and metaclass
(not (validate-superclass (find-class metaclass)
(find-class 'persistent-class))))
(error "Can not define a persistent class with metaclass ~A." metaclass))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(defclass ,class ,superclasses ,slots
,@(unless metaclass '((:metaclass persistent-class)))
,@class-options))))
(defvar *current-object-slot* nil)
(defvar *current-slot-relaxed-p* nil)
(defun encode-layout (id class slots stream)
(%write-tag #\L stream)
(%encode-integer id stream)
(%encode-symbol (class-name class) stream)
(%encode-integer (length slots) stream)
(dolist (slot slots)
(%encode-symbol slot stream)))
(defun %encode-set-slots (slots object stream)
(dolist (slot slots)
(let ((*current-object-slot* (list object slot))
(*current-slot-relaxed-p* (store-object-relaxed-object-reference-p object slot)))
(encode (if (slot-boundp object slot)
(slot-value object slot)
'unbound)
stream))))
(defun encode-create-object (class-layouts object stream)
(let* ((class (class-of object))
(layout (gethash class class-layouts)))
(unless layout
(setf layout
(cons (hash-table-count class-layouts)
XXX layout muss konstant
(sort (remove 'id (store-object-persistent-slots object))
#'string< :key #'symbol-name)))
(encode-layout (car layout) class (cdr layout) stream)
(setf (gethash class class-layouts) layout))
(destructuring-bind (layout-id &rest slots) layout
(declare (ignore slots))
(%write-tag #\O stream)
(%encode-integer layout-id stream)
(%encode-integer (store-object-id object) stream))))
(defun encode-set-slots (class-layouts object stream)
(destructuring-bind (layout-id &rest slots)
(gethash (class-of object) class-layouts)
(%write-tag #\S stream)
(%encode-integer layout-id stream)
(%encode-integer (store-object-id object) stream)
(%encode-set-slots slots object stream)))
(defun find-class-with-interactive-renaming (class-name)
(loop until (or (null class-name)
(find-class class-name nil))
do (progn
(format *query-io* "Class ~A not found, enter new class or enter ~
NIL to ignore objects of this class: "
class-name)
(finish-output *query-io*)
(setq class-name (read *query-io*))))
(and class-name
(find-class class-name)))
(defun find-slot-name-with-interactive-rename (class slot-name)
(loop until (find slot-name (class-slots class) :key #'slot-definition-name)
do (format *query-io* "Slot ~S not found in class ~S, enter new slot name: "
slot-name (class-name class))
do (setq slot-name (read *query-io*))
finally (return slot-name)))
(defvar *slot-name-map*)
(defun rename-slot (class slot-name)
(or (caddr (find (list (class-name class) slot-name) *slot-name-map*
:key #'(lambda (entry) (subseq entry 0 2)) :test #'equal))
(find (symbol-name slot-name)
(mapcar #'slot-definition-name (class-slots class)) :key #'symbol-name :test #'equal)))
(defgeneric convert-slot-value-while-restoring (object slot-name value)
(:documentation "Generic function to be called to convert a slot's
value from a previous snapshot layout. OBJECT is the object that is
being restored, SLOT-NAME is the name of the slot in the old schema,
VALUE is the value of the slot in the old schema.")
(:method (object slot-name value)
(setf (slot-value object slot-name) value)))
(defun find-slot-name-with-automatic-rename (class slot-name)
(if (find slot-name (class-slots class) :key #'slot-definition-name)
slot-name
(restart-case
(let ((new-slot-name (rename-slot class slot-name)))
(cond
(new-slot-name
(warn "slot ~S not found in class ~S, automatically renamed to ~S"
slot-name (class-name class) new-slot-name)
new-slot-name)
(t
(error "can't find a slot in class ~A which matches the name ~A used in the store snapshot"
(class-name class) slot-name))))
(convert-values ()
:report "Convert slot values using CONVERT-SLOT-VALUE-WHILE-RESTORING"
(cons 'convert-slot-values slot-name))
(ignore-slot ()
:report "Ignore slot, discarding values found in the snapshot file"
nil))))
(defun find-class-slots-with-interactive-renaming (class slot-names)
#+(or)
(format t "; verifying class layout for class ~A~%; slots:~{ ~S~}~%" (class-name class)
(mapcar #'slot-definition-name (class-slots class)))
(loop for slot-name in slot-names
collect (find-slot-name-with-automatic-rename class slot-name)))
(defun snapshot-read-layout (stream layouts)
(let* ((id (%decode-integer stream))
(class-name (%decode-symbol stream :usage "class"))
(nslots (%decode-integer stream))
(class (find-class-with-interactive-renaming class-name))
(slot-names (loop repeat nslots collect (%decode-symbol stream
:intern (not (null class))
:usage "slot")))
(slots (if class
(find-class-slots-with-interactive-renaming class slot-names)
slot-names)))
(setf (gethash id layouts)
(cons class slots))))
(defun %read-slots (stream object slots)
"Read the OBJECT from STREAM. The individual slots of the object
are expected in the order of the list SLOTS. If the OBJECT is NIL,
the slots are read from the snapshot and ignored."
(declare (optimize (speed 3)))
(dolist (slot-name slots)
(let ((value (decode stream)))
(cond
((consp slot-name)
(assert (eq 'convert-slot-values (car slot-name)))
(convert-slot-value-while-restoring object (cdr slot-name) value))
((null slot-name)
)
(t
(restart-case
(let ((*current-object-slot* (list object slot-name))
(*current-slot-relaxed-p* (or (null object)
(store-object-relaxed-object-reference-p object slot-name))))
(when object
(let ((bknr.indices::*indices-remove-p* nil))
(if (eq value 'unbound)
(slot-makunbound object slot-name)
(convert-slot-value-while-restoring object slot-name value)))))
(set-slot-nil ()
:report "Set slot to NIL."
(setf (slot-value object slot-name) nil))
(make-slot-unbound ()
:report "Make slot unbound."
(slot-makunbound object slot-name))))))))
(defun snapshot-read-object (stream layouts)
(declare (optimize (speed 3)))
(with-simple-restart (skip-object "Skip the object.")
(let* ((layout-id (%decode-integer stream))
(object-id (%decode-integer stream))
(class (first (gethash layout-id layouts))))
(when class
(let ((object (allocate-instance class)))
(setf (slot-value object 'id) object-id
(next-object-id (store-object-subsystem)) (max (1+ object-id)
(next-object-id (store-object-subsystem))))
(dolist (index (class-slot-indices class 'id))
(index-add index object)))))))
(defun snapshot-read-slots (stream layouts)
(let* ((layout-id (%decode-integer stream))
(object-id (%decode-integer stream))
(object (store-object-with-id object-id)))
(restart-case
(%read-slots stream object (cdr (gethash layout-id layouts)))
(skip-object-initialization ()
:report "Skip object initialization.")
(delete-object ()
:report "Delete the object."
(delete-object object)))))
(define-condition encoding-destroyed-object (error)
((id :initarg :id)
(slot :initarg :slot)
(container :initarg :container))
(:report (lambda (e out)
(with-slots (slot container id) e
(format out
"Encoding reference to destroyed object with ID ~A from slot ~A of object ~A with ID ~A."
id slot (type-of container) (store-object-id container))))))
(defmethod encode-object ((object store-object) stream)
(if (object-destroyed-p object)
(let* ((*indexed-class-override* t)
(id (store-object-id object))
(container (first *current-object-slot*))
(slot (second *current-object-slot*)))
(unless (and container slot)
(warn "Encoding destroyed object with ID ~A." id)
(%write-tag #\o stream)
(%encode-integer id stream)
(return-from encode-object))
(flet ((encode-relaxed ()
(warn "Encoding reference to destroyed object with ID ~A from slot ~A of object ~A with ID ~A."
id slot (type-of container) (store-object-id container))
(%write-tag #\o stream)
(%encode-integer id stream)))
(if *current-slot-relaxed-p*
(encode-relaxed)
(restart-case
(error 'encoding-destroyed-object
:id id
:slot slot
:container container)
(encode-relaxed-slot ()
(encode-relaxed))
(make-slot-unbound-and-encode-relaxed ()
(encode-relaxed)
(slot-makunbound container slot))))))
(progn (%write-tag #\o stream)
(%encode-integer (store-object-id object) stream))))
(defmethod decode-object ((tag (eql #\o)) stream)
(let ((*current-object-slot* nil))
(%decode-store-object stream)))
(define-condition invalid-reference (warning)
((id :initarg :id))
(:report (lambda (e stream)
(format stream "internal inconsistency during restore - store object with ID ~A could not be found"
(slot-value e 'id)))))
(defun %decode-store-object (stream)
This is actually called in two contexts , when a slot - value is to
In the former case , references two deleted objects are accepted
to deleted objects are restored as NIL . Applications must be
(let* ((id (%decode-integer stream))
(object (or (store-object-with-id id)
(warn 'invalid-reference :id id)))
(container (first *current-object-slot*))
(slot-name (second *current-object-slot*)))
(cond (object object)
((or *current-slot-relaxed-p* (not container))
(if container
(warn "Reference to inexistent object with id ~A in relaxed slot ~A of object ~
with class ~A with ID ~A."
id slot-name (type-of container) (store-object-id container))
(warn "Reference to inexistent object with id ~A from unnamed container, returning NIL." id))
(when (>= id (next-object-id (store-object-subsystem)))
(setf (next-object-id (store-object-subsystem)) (1+ id)))
nil)
(t (error "Reference to inexistent object with id ~A from slot ~A of object ~A with ID ~A."
id slot-name (type-of container)
(if container (store-object-id container) "unknown object"))))))
(defun encode-current-object-id (stream)
(%write-tag #\I stream)
(%encode-integer (next-object-id (store-object-subsystem)) stream))
(defmethod snapshot-subsystem ((store store) (subsystem store-object-subsystem))
(let ((snapshot (store-subsystem-snapshot-pathname store subsystem)))
(with-open-file (s snapshot
:direction :output
:element-type '(unsigned-byte 8)
:if-does-not-exist :create
:if-exists :supersede)
(let ((class-layouts (make-hash-table)))
(with-transaction (:prepare-for-snapshot)
(map-store-objects #'prepare-for-snapshot))
(encode-current-object-id s)
(map-store-objects (lambda (object) (when (subtypep (type-of object) 'store-object)
(encode-create-object class-layouts object s))))
(map-store-objects (lambda (object) (when (subtypep (type-of object) 'store-object)
(encode-set-slots class-layouts object s))))
t))))
(defmethod close-subsystem ((store store) (subsystem store-object-subsystem))
(dolist (class-name (all-store-classes))
(clear-class-indices (find-class class-name))))
(defmethod restore-subsystem ((store store) (subsystem store-object-subsystem) &key until)
(declare (ignore until))
(let ((snapshot (store-subsystem-snapshot-pathname store subsystem)))
check on first instatiation of a class ?
(dolist (class-name (cons 'store-object (all-store-classes)))
(clear-class-indices (find-class class-name)))
(setf (next-object-id subsystem) 0)
(when (probe-file snapshot)
(report-progress "~&; loading snapshot file ~A~%" snapshot)
(with-open-file (s snapshot
:element-type '(unsigned-byte 8)
:direction :input)
(let ((class-layouts (make-hash-table))
(created-objects 0)
(reported-objects-count 0)
(read-slots 0)
(error t)
(*slot-name-map* nil))
(unwind-protect
(progn
(with-simple-restart
(finalize-object-subsystem "Finalize the object subsystem.")
(loop
(when (and (plusp created-objects)
(zerop (mod created-objects 10000))
(not (= created-objects reported-objects-count)))
#+nil (format t "Snapshot position ~A~%" (file-position s))
(report-progress "~A objects created.~%" created-objects)
(setf reported-objects-count created-objects)
(force-output))
(when (and (plusp read-slots)
(zerop (mod read-slots 10000)))
(report-progress "~A of ~A objects initialized.~%" read-slots created-objects)
(force-output))
(let ((char (%read-tag s nil nil)))
(unless (member char '(#\I #\L #\O #\S nil))
(error "unknown char ~A at offset ~A~%" char (file-position s)))
(ecase char
((nil) (return))
(#\I (setf (next-object-id (store-object-subsystem)) (%decode-integer s)))
(#\L (snapshot-read-layout s class-layouts))
(#\O (snapshot-read-object s class-layouts) (incf created-objects))
(#\S (snapshot-read-slots s class-layouts) (incf read-slots))))))
(map-store-objects #'initialize-transient-slots)
(map-store-objects #'initialize-transient-instance)
(setf error nil))
(when error
(maphash #'(lambda (key val)
(declare (ignore key))
(let ((class-name (car val)))
(report-progress "clearing indices for class ~A~%" (class-name class-name))
(clear-class-indices class-name)))
class-layouts))))))))
(defun tx-delete-object (id)
(destroy-object (store-object-with-id id)))
(defun delete-object (object)
(if (and (in-transaction-p)
(not (in-anonymous-transaction-p)))
(destroy-object object)
(execute (make-instance 'transaction :function-symbol 'tx-delete-object
:timestamp (get-universal-time)
:args (list (store-object-id object))))))
(defun tx-delete-objects (&rest object-ids)
(mapc #'(lambda (id) (destroy-object (store-object-with-id id))) object-ids))
(defun delete-objects (&rest objects)
(if (in-transaction-p)
(mapc #'destroy-object objects)
(execute (make-instance 'transaction :function-symbol 'tx-delete-objects
:timestamp (get-universal-time)
:args (mapcar #'store-object-id objects)))))
(defgeneric cascade-delete-p (object referencing-object)
(:method (object referencing-object)
(declare (ignore object referencing-object))
nil)
(:documentation "return non-nil if the REFERENCING-OBJECT should be deleted when the OBJECT is deleted"))
(defun partition-list (list predicate)
"Return two list values, the first containing all elements from LIST
that satisfy PREDICATE, the second those that don't"
(let (do dont)
(dolist (element list)
(if (funcall predicate element)
(push element do)
(push element dont)))
(values do dont)))
(defun cascading-delete-object (object)
"Delete the OBJECT and all objects that reference it and that are eligible to cascading deletes, as indicated by
the result of calling CASCADE-DELETE-P. Generate error if there are references to the objects that are not eligible
to cascading deletes."
(multiple-value-bind (cascading-delete-refs
remaining-refs)
(partition-list (find-refs object) (alexandria:curry #'cascade-delete-p object))
(when remaining-refs
(error "Cannot delete object ~A because there are references ~
to this object in the system, please consult a system administrator!"
object))
(apply #'delete-objects object cascading-delete-refs)))
(defun tx-change-slot-values (object &rest slots-and-values)
"Called by the MOP to change a persistent slot's value."
(unless (in-transaction-p)
(error 'not-in-transaction))
(when object
(loop for (slot value) on slots-and-values by #'cddr
do (setf (slot-value object slot) value))))
(defun change-slot-values (object &rest slots-and-values)
"This function is the deprecated way to set slots of persistent
objects."
(warn "CHANGE-SLOT-VALUES is deprecated - use WITH-TRANSACTION and standard accessors!")
(execute (make-instance 'transaction
:function-symbol 'tx-change-slot-values
:timestamp (get-universal-time)
:args (list* object slots-and-values))))
(defgeneric prepare-for-snapshot (object)
(:method ((object store-object))
nil)
(:documentation "Called for every store object before a snapshot is
written."))
(defun find-store-object (id-or-name &key (class 'store-object) query-function key-slot-name)
"Mock up implementation of find-store-object API as in the old datastore.
Note: QUERY-FUNCTION will only be used if ID-OR-NAME is neither an integer nor a
string designating an integer."
(unless id-or-name
(error "can't search a store object with null key"))
(when (stringp id-or-name)
(multiple-value-bind (value end) (parse-integer id-or-name :junk-allowed t)
(when (and value
(eql end (length id-or-name)))
(setq id-or-name value))))
(let ((result (cond
((numberp id-or-name)
(store-object-with-id id-or-name))
(t
(cond
(query-function
(funcall query-function id-or-name))
((eq class 't)
(error "can't search for store object by name without class specified"))
(t
(let ((index (bknr.indices::class-slot-index (find-class class) key-slot-name)))
(when index
(index-get index id-or-name)))))))))
(unless (or (null result)
(typep result class))
(error "Object ~A is not of wanted type ~A." result class))
result))
(deftransaction store-object-add-keywords (object slot keywords)
(setf (slot-value object slot)
(union (slot-value object slot)
keywords)))
(deftransaction store-object-remove-keywords (object slot keywords)
(setf (slot-value object slot)
(set-difference (slot-value object slot) keywords)))
(deftransaction store-object-set-keywords (object slot keywords)
(setf (slot-value object slot) keywords))
(defmethod find-refs ((object store-object))
"Find references to the given OBJECT in all store-objects, traversing both single valued and list valued slots."
(remove-if-not
(lambda (candidate)
(find-if (lambda (slotd)
(and (slot-boundp candidate (slot-definition-name slotd))
(let ((slot-value (slot-value candidate (slot-definition-name slotd))))
(or (eq object slot-value)
(and (alexandria:proper-list-p slot-value)
(find object slot-value))))))
(class-slots (class-of candidate))))
(class-instances 'store-object)))
(pushnew :mop-store cl:*features*)
|
ebe9ac9a244f458fbc1d146ec2ac3a6c462ba29aca7ab0ddc193dc5343d7794b | SRI-CSL/f3d | lcl-pkg.lisp | (in-package :cl-user)
The minimal package definition for : LCL to support QFFI
(defpackage :lcl (:use #+sbcl :common-lisp #-sbcl :lisp)
(:import-from :asdf asdf::getenv)
#+cmu (:import-from :ext memq assq)
#+sbcl (:import-from :SB-INT memq assq)
#+allegro (:import-from excl memq assq)
)
(in-package :lcl)
This does n't really belong here , but these functions are defined by qffi .
(export '(underlying-simple-vector array-simple-vector with-interrupts-deferred
def-foreign-function def-foreign-callable def-foreign-synonym-type
def-foreign-struct
foreign-variable-value foreign-variable-pointer foreign-pointer-address
foreign-string-value dummy-pointer register-all-callbacks
make-foreign-pointer
environment-variable setenv getenv
%POINTER MEMQ ASSQ COMMAND-LINE-ARGUMENT WITHOUT-FLOATING-UNDERFLOW-TRAPS
)
:lcl)
| null | https://raw.githubusercontent.com/SRI-CSL/f3d/93285f582198bfbab33ca96ff71efda539b1bec7/f3d-core/lcl/lcl-pkg.lisp | lisp | (in-package :cl-user)
The minimal package definition for : LCL to support QFFI
(defpackage :lcl (:use #+sbcl :common-lisp #-sbcl :lisp)
(:import-from :asdf asdf::getenv)
#+cmu (:import-from :ext memq assq)
#+sbcl (:import-from :SB-INT memq assq)
#+allegro (:import-from excl memq assq)
)
(in-package :lcl)
This does n't really belong here , but these functions are defined by qffi .
(export '(underlying-simple-vector array-simple-vector with-interrupts-deferred
def-foreign-function def-foreign-callable def-foreign-synonym-type
def-foreign-struct
foreign-variable-value foreign-variable-pointer foreign-pointer-address
foreign-string-value dummy-pointer register-all-callbacks
make-foreign-pointer
environment-variable setenv getenv
%POINTER MEMQ ASSQ COMMAND-LINE-ARGUMENT WITHOUT-FLOATING-UNDERFLOW-TRAPS
)
:lcl)
|
|
ac48b59e309fdea9475db7ee13252aaff96b0f2657a591b1fcb6f1d4c885ad9f | ucsd-progsys/liquidhaskell | Vector0a.hs | {-@ LIQUID "--expect-any-error" @-}
module Vector0a () where
import Language.Haskell.Liquid.Prelude
import Data.Vector hiding(map, concat, zipWith, filter, foldl, foldr, (++))
xs = [1,2,3,4] :: [Int]
vs = fromList xs
prop0 = liquidAssertB ( x > = 0 )
where x = Prelude.head xs
--
prop1 = liquidAssertB ( n > 0 )
-- where n = Prelude.length xs
--
prop2 = liquidAssertB ( Data.Vector.length vs > 0 )
prop3 = liquidAssertB ( Data.Vector.length vs > 3 )
prop6 = crash (0 == 1)
x0 = vs ! 0
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/neg/Vector0a.hs | haskell | @ LIQUID "--expect-any-error" @
where n = Prelude.length xs
| module Vector0a () where
import Language.Haskell.Liquid.Prelude
import Data.Vector hiding(map, concat, zipWith, filter, foldl, foldr, (++))
xs = [1,2,3,4] :: [Int]
vs = fromList xs
prop0 = liquidAssertB ( x > = 0 )
where x = Prelude.head xs
prop1 = liquidAssertB ( n > 0 )
prop2 = liquidAssertB ( Data.Vector.length vs > 0 )
prop3 = liquidAssertB ( Data.Vector.length vs > 3 )
prop6 = crash (0 == 1)
x0 = vs ! 0
|
0004ba8bb7e85ea80c163e1ad3c47dafa3d66d3303e3f69b712b81d1bc7a3398 | ruhler/smten | Char.hs |
module Smten.Base.GHC.Char (chr) where
import GHC.Base
TODO : Bounds check this like does .
chr :: Int -> Char
chr = unsafeChr
| null | https://raw.githubusercontent.com/ruhler/smten/16dd37fb0ee3809408803d4be20401211b6c4027/smten-base/Smten/Base/GHC/Char.hs | haskell |
module Smten.Base.GHC.Char (chr) where
import GHC.Base
TODO : Bounds check this like does .
chr :: Int -> Char
chr = unsafeChr
|
|
3809ab28a2838b431db7e482e5af52d9d3e9d99ff78d66c6ce76219f12b7c798 | arthur-adjedj/proof_assistant | parser_read.ml |
module MenhirBasics = struct
exception Error
type token =
| RPAREN
| REDUC
| ORG
| ORD
| OR
| NOTG
| NOTD
| NOT
| NAME of (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)
| LPAREN
| INT of (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 25 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)
| IMPG
| IMPD
| IMP
| EXT
| EOL
| EOF
| CONTRG
| CONTRD
| CHAR of (
# 8 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Formule.formule)
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)
| BEGIN
| AXIOM
| ANDG
| ANDD
| AND
| AFFG
| AFFD
end
include MenhirBasics
let _eRR =
MenhirBasics.Error
type _menhir_env = {
_menhir_lexer: Lexing.lexbuf -> token;
_menhir_lexbuf: Lexing.lexbuf;
_menhir_token: token;
mutable _menhir_error: bool
}
and _menhir_state =
| MenhirState56
| MenhirState29
| MenhirState17
| MenhirState12
| MenhirState10
| MenhirState8
| MenhirState4
| MenhirState3
| MenhirState2
# 1 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
open Proof_build.Formule
# 77 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
let rec _menhir_goto_tacts : _menhir_env -> 'ttv_tail -> _menhir_state -> (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 82 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s _v ->
match _menhir_s with
| MenhirState17 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv195) * (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 91 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let (_menhir_s : _menhir_state) = _menhir_s in
let (_v : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 97 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv193) * (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 103 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let (_ : _menhir_state) = _menhir_s in
let ((_3 : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 109 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 113 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, (_2 : (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 118 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 123 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 45 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( ( _2 , _3 ) )
# 127 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv191) = _menhir_stack in
let (_v : (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 134 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv189) = Obj.magic _menhir_stack in
let (_v : (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 141 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv187) = Obj.magic _menhir_stack in
let ((_1 : (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 148 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 152 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
(Obj.magic _1 : 'freshtv188)) : 'freshtv190)) : 'freshtv192)) : 'freshtv194)) : 'freshtv196)
| MenhirState56 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv199 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 160 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = Obj.magic _menhir_stack in
let (_menhir_s : _menhir_state) = _menhir_s in
let (_v : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 166 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv197 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 172 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = Obj.magic _menhir_stack in
let (_ : _menhir_state) = _menhir_s in
let ((_3 : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 178 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 182 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s, (_1 : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 187 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 192 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 72 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(_1::_3)
# 196 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tacts _menhir_env _menhir_stack _menhir_s _v) : 'freshtv198)) : 'freshtv200)
| _ ->
_menhir_fail ()
and _menhir_goto_tact : _menhir_env -> 'ttv_tail -> _menhir_state -> (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 205 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s _v ->
let _menhir_stack = (_menhir_stack, _menhir_s, _v) in
match _menhir_s with
| MenhirState29 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv175 * _menhir_state) * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 215 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| RPAREN ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv171 * _menhir_state) * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 225 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv169 * _menhir_state) * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 232 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _, (_2 : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 237 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 242 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 67 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(_2)
# 246 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv170)) : 'freshtv172)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv173 * _menhir_state) * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 256 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv174)) : 'freshtv176)
| MenhirState56 | MenhirState17 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv185 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 265 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| EOF ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv179 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 275 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv177 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 281 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, (_1 : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 286 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 291 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 71 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
([_1])
# 295 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tacts _menhir_env _menhir_stack _menhir_s _v) : 'freshtv178)) : 'freshtv180)
| EOL ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv181 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 303 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| AFFD ->
_menhir_run49 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| AFFG ->
_menhir_run47 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| ANDD ->
_menhir_run45 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| ANDG ->
_menhir_run43 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| AXIOM ->
_menhir_run42 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| CONTRD ->
_menhir_run39 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| CONTRG ->
_menhir_run36 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| EOF ->
_menhir_run53 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| EXT ->
_menhir_run34 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| IMPD ->
_menhir_run32 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| IMPG ->
_menhir_run30 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| LPAREN ->
_menhir_run29 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| NOTD ->
_menhir_run27 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| NOTG ->
_menhir_run25 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| ORD ->
_menhir_run23 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| ORG ->
_menhir_run21 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| REDUC ->
_menhir_run18 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState56) : 'freshtv182)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv183 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 353 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv184)) : 'freshtv186)
| _ ->
_menhir_fail ()
and _menhir_run18 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv165 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 372 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_stack = (_menhir_stack, _v) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv161 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 383 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 388 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv159 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 395 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let ((_3 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 400 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 404 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let ((_menhir_stack, _menhir_s), (_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 409 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 414 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 53 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.reduc _2 _3)
# 418 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv160)) : 'freshtv162)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv163 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 428 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv164)) : 'freshtv166)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv167 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv168)
and _menhir_run21 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv155 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 452 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv153 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 460 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 464 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 470 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 63 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.or_left _2)
# 474 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv154)) : 'freshtv156)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv157 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv158)
and _menhir_run23 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv149 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 497 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv147 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 505 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 509 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 515 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 64 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.or_right _2)
# 519 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv148)) : 'freshtv150)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv151 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv152)
and _menhir_run25 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv143 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 542 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv141 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 550 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 554 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 560 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 59 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.not_left _2)
# 564 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv142)) : 'freshtv144)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv145 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv146)
and _menhir_run27 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv137 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 587 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv135 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 595 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 599 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 605 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 60 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.not_right _2)
# 609 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv136)) : 'freshtv138)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv139 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv140)
and _menhir_run29 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| AFFD ->
_menhir_run49 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| AFFG ->
_menhir_run47 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| ANDD ->
_menhir_run45 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| ANDG ->
_menhir_run43 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| AXIOM ->
_menhir_run42 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| CONTRD ->
_menhir_run39 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| CONTRG ->
_menhir_run36 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| EXT ->
_menhir_run34 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| IMPD ->
_menhir_run32 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| IMPG ->
_menhir_run30 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| LPAREN ->
_menhir_run29 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| NOTD ->
_menhir_run27 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| NOTG ->
_menhir_run25 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| ORD ->
_menhir_run23 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| ORG ->
_menhir_run21 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| REDUC ->
_menhir_run18 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState29
and _menhir_run30 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv131 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 675 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv129 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 683 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 687 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 693 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 65 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.imp_left _2)
# 697 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv130)) : 'freshtv132)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv133 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv134)
and _menhir_run32 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv125 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 720 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv123 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 728 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 732 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 738 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 66 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.imp_right _2)
# 742 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv124)) : 'freshtv126)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv127 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv128)
and _menhir_run34 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| NAME _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv119 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 765 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv117 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 773 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 777 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 783 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 54 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_store.Ext_props.ext _2)
# 787 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv118)) : 'freshtv120)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv121 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv122)
and _menhir_run53 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv115) = Obj.magic _menhir_stack in
let (_menhir_s : _menhir_state) = _menhir_s in
((let _v : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 806 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 70 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
([])
# 810 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tacts _menhir_env _menhir_stack _menhir_s _v) : 'freshtv116)
and _menhir_run36 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv111 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 826 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_stack = (_menhir_stack, _v) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv107 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 837 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 842 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv105 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 849 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let ((_3 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 854 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 858 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let ((_menhir_stack, _menhir_s), (_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 863 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 868 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 57 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.contr_left _2 _3)
# 872 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv106)) : 'freshtv108)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv109 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 882 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv110)) : 'freshtv112)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv113 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv114)
and _menhir_run39 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv101 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 906 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_stack = (_menhir_stack, _v) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv97 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 917 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 922 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv95 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 929 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let ((_3 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 934 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 938 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let ((_menhir_stack, _menhir_s), (_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 943 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 948 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 58 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.contr_right _2 _3)
# 952 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv96)) : 'freshtv98)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv99 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 962 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv100)) : 'freshtv102)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv103 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv104)
and _menhir_run42 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv93) = Obj.magic _menhir_stack in
let (_menhir_s : _menhir_state) = _menhir_s in
((let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 983 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 52 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.axiom)
# 987 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv94)
and _menhir_run43 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv89 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1003 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv87 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1011 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1015 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 1021 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 61 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.and_left _2)
# 1025 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv88)) : 'freshtv90)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv91 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv92)
and _menhir_run45 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv83 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1048 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv81 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1056 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1060 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 1066 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 62 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.and_right _2)
# 1070 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv82)) : 'freshtv84)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv85 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv86)
and _menhir_run47 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv77 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1093 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv75 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1101 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1105 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 1111 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 55 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.aff_left _2)
# 1115 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv76)) : 'freshtv78)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv79 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv80)
and _menhir_run49 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv71 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1138 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv69 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1146 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1150 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 1156 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 56 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.aff_right _2)
# 1160 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv70)) : 'freshtv72)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv73 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv74)
and _menhir_fail : unit -> 'a =
fun () ->
Printf.fprintf stderr "Internal failure -- please contact the parser generator's developers.\n%!";
assert false
and _menhir_goto_start : _menhir_env -> 'ttv_tail -> (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 1179 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) -> 'ttv_return =
fun _menhir_env _menhir_stack _v ->
let _menhir_stack = (_menhir_stack, _v) in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv67) * (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 1187 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| AFFD ->
_menhir_run49 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| AFFG ->
_menhir_run47 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| ANDD ->
_menhir_run45 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| ANDG ->
_menhir_run43 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| AXIOM ->
_menhir_run42 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| CONTRD ->
_menhir_run39 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| CONTRG ->
_menhir_run36 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| EOF ->
_menhir_run53 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| EXT ->
_menhir_run34 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| IMPD ->
_menhir_run32 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| IMPG ->
_menhir_run30 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| LPAREN ->
_menhir_run29 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| NOTD ->
_menhir_run27 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| NOTG ->
_menhir_run25 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| ORD ->
_menhir_run23 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| ORG ->
_menhir_run21 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| REDUC ->
_menhir_run18 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState17) : 'freshtv68)
and _menhir_run8 : _menhir_env -> 'ttv_tail * _menhir_state * 'tv_prop -> 'ttv_return =
fun _menhir_env _menhir_stack ->
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState8 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState8
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState8
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState8
and _menhir_run10 : _menhir_env -> 'ttv_tail * _menhir_state * 'tv_prop -> 'ttv_return =
fun _menhir_env _menhir_stack ->
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState10 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState10
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState10
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState10
and _menhir_run12 : _menhir_env -> 'ttv_tail * _menhir_state * 'tv_prop -> 'ttv_return =
fun _menhir_env _menhir_stack ->
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState12 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState12
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState12
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState12
and _menhir_goto_prop : _menhir_env -> 'ttv_tail -> _menhir_state -> 'tv_prop -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s _v ->
let _menhir_stack = (_menhir_stack, _menhir_s, _v) in
match _menhir_s with
| MenhirState4 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv37 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| AND ->
_menhir_run12 _menhir_env (Obj.magic _menhir_stack)
| IMP ->
_menhir_run10 _menhir_env (Obj.magic _menhir_stack)
| OR ->
_menhir_run8 _menhir_env (Obj.magic _menhir_stack)
| RPAREN ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv33 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv31 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _, (_2 : 'tv_prop)) = _menhir_stack in
let _v : 'tv_prop =
# 76 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( _2 )
# 1305 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv32)) : 'freshtv34)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv35 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv36)) : 'freshtv38)
| MenhirState8 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv41 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv39 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s, (_1 : 'tv_prop)), _, (_3 : 'tv_prop)) = _menhir_stack in
let _v : 'tv_prop =
# 79 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( Or(_1,_3) )
# 1324 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv40)) : 'freshtv42)
| MenhirState10 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv47 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| AND ->
_menhir_run12 _menhir_env (Obj.magic _menhir_stack)
| OR ->
_menhir_run8 _menhir_env (Obj.magic _menhir_stack)
| AFFD | AFFG | ANDD | ANDG | AXIOM | CONTRD | CONTRG | EOF | EOL | EXT | IMP | IMPD | IMPG | LPAREN | NOTD | NOTG | ORD | ORG | REDUC | RPAREN ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv43 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s, (_1 : 'tv_prop)), _, (_3 : 'tv_prop)) = _menhir_stack in
let _v : 'tv_prop =
# 77 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( Imp(_1,_3) )
# 1344 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv44)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv45 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv46)) : 'freshtv48)
| MenhirState12 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv51 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv49 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s, (_1 : 'tv_prop)), _, (_3 : 'tv_prop)) = _menhir_stack in
let _v : 'tv_prop =
# 78 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( And(_1,_3) )
# 1363 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv50)) : 'freshtv52)
| MenhirState3 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv55 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv53 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _, (_2 : 'tv_prop)) = _menhir_stack in
let _v : 'tv_prop =
# 80 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( Not _2)
# 1375 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv54)) : 'freshtv56)
| MenhirState2 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv65 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1383 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| AND ->
_menhir_run12 _menhir_env (Obj.magic _menhir_stack)
| EOL ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv59 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1395 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv57 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1402 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, (_1 : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1407 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))), _, (_2 : 'tv_prop)) = _menhir_stack in
let _v : (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 1412 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 48 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( ( _1 , _2 ) )
# 1416 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_start _menhir_env _menhir_stack _v) : 'freshtv58)) : 'freshtv60)
| IMP ->
_menhir_run10 _menhir_env (Obj.magic _menhir_stack)
| OR ->
_menhir_run8 _menhir_env (Obj.magic _menhir_stack)
| AFFD | AFFG | ANDD | ANDG | AXIOM | CONTRD | CONTRG | EOF | EXT | IMPD | IMPG | LPAREN | NOTD | NOTG | ORD | ORG | REDUC ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv61 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1428 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, (_1 : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1433 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))), _, (_2 : 'tv_prop)) = _menhir_stack in
let _v : (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 1438 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 49 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( ( _1 , _2 ) )
# 1442 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_start _menhir_env _menhir_stack _v) : 'freshtv62)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv63 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1452 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv64)) : 'freshtv66)
| _ ->
_menhir_fail ()
and _menhir_errorcase : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
match _menhir_s with
| MenhirState56 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv13 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 1467 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv14)
| MenhirState29 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv15 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv16)
| MenhirState17 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv17) * (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 1481 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
(raise _eRR : 'freshtv18)
| MenhirState12 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv19 * _menhir_state * 'tv_prop)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv20)
| MenhirState10 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv21 * _menhir_state * 'tv_prop)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv22)
| MenhirState8 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv23 * _menhir_state * 'tv_prop)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv24)
| MenhirState4 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv25 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv26)
| MenhirState3 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv27 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv28)
| MenhirState2 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv29 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1514 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
(raise _eRR : 'freshtv30)
and _menhir_run3 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState3 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState3
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState3
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState3
and _menhir_run4 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState4 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState4
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState4
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState4
and _menhir_run5 : _menhir_env -> 'ttv_tail -> _menhir_state -> (
# 8 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Formule.formule)
# 1555 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s _v ->
let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv11) = Obj.magic _menhir_stack in
let (_menhir_s : _menhir_state) = _menhir_s in
let ((_1 : (
# 8 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Formule.formule)
# 1565 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 8 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Formule.formule)
# 1569 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _v : 'tv_prop =
# 75 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( _1 )
# 1574 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv12)
and _menhir_discard : _menhir_env -> _menhir_env =
fun _menhir_env ->
let lexer = _menhir_env._menhir_lexer in
let lexbuf = _menhir_env._menhir_lexbuf in
let _tok = lexer lexbuf in
{
_menhir_lexer = lexer;
_menhir_lexbuf = lexbuf;
_menhir_token = _tok;
_menhir_error = false;
}
and main : (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 1593 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
fun lexer lexbuf ->
let _menhir_env = {
_menhir_lexer = lexer;
_menhir_lexbuf = lexbuf;
_menhir_token = Obj.magic ();
_menhir_error = false;
} in
Obj.magic (let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv9) = ((), _menhir_env._menhir_lexbuf.Lexing.lex_curr_p) in
((let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| BEGIN ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv5) = Obj.magic _menhir_stack in
((let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| NAME _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv1) = Obj.magic _menhir_stack in
let (_v : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1619 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_stack = (_menhir_stack, _v) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState2 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState2
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState2
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState2) : 'freshtv2)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv3) = Obj.magic _menhir_stack in
(raise _eRR : 'freshtv4)) : 'freshtv6)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv7) = Obj.magic _menhir_stack in
(raise _eRR : 'freshtv8)) : 'freshtv10))
# 269 "<standard.mly>"
# 1651 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
| null | https://raw.githubusercontent.com/arthur-adjedj/proof_assistant/a47ae2e1012e77ed810de0f8c99a957571ad5c27/pr_assistant/proof_read/parser_read.ml | ocaml |
module MenhirBasics = struct
exception Error
type token =
| RPAREN
| REDUC
| ORG
| ORD
| OR
| NOTG
| NOTD
| NOT
| NAME of (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)
| LPAREN
| INT of (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 25 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)
| IMPG
| IMPD
| IMP
| EXT
| EOL
| EOF
| CONTRG
| CONTRD
| CHAR of (
# 8 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Formule.formule)
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)
| BEGIN
| AXIOM
| ANDG
| ANDD
| AND
| AFFG
| AFFD
end
include MenhirBasics
let _eRR =
MenhirBasics.Error
type _menhir_env = {
_menhir_lexer: Lexing.lexbuf -> token;
_menhir_lexbuf: Lexing.lexbuf;
_menhir_token: token;
mutable _menhir_error: bool
}
and _menhir_state =
| MenhirState56
| MenhirState29
| MenhirState17
| MenhirState12
| MenhirState10
| MenhirState8
| MenhirState4
| MenhirState3
| MenhirState2
# 1 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
open Proof_build.Formule
# 77 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
let rec _menhir_goto_tacts : _menhir_env -> 'ttv_tail -> _menhir_state -> (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 82 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s _v ->
match _menhir_s with
| MenhirState17 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv195) * (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 91 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let (_menhir_s : _menhir_state) = _menhir_s in
let (_v : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 97 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv193) * (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 103 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let (_ : _menhir_state) = _menhir_s in
let ((_3 : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 109 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 113 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, (_2 : (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 118 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 123 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 45 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( ( _2 , _3 ) )
# 127 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv191) = _menhir_stack in
let (_v : (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 134 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv189) = Obj.magic _menhir_stack in
let (_v : (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 141 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv187) = Obj.magic _menhir_stack in
let ((_1 : (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 148 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 152 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
(Obj.magic _1 : 'freshtv188)) : 'freshtv190)) : 'freshtv192)) : 'freshtv194)) : 'freshtv196)
| MenhirState56 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv199 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 160 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = Obj.magic _menhir_stack in
let (_menhir_s : _menhir_state) = _menhir_s in
let (_v : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 166 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv197 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 172 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = Obj.magic _menhir_stack in
let (_ : _menhir_state) = _menhir_s in
let ((_3 : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 178 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 182 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s, (_1 : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 187 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 192 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 72 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(_1::_3)
# 196 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tacts _menhir_env _menhir_stack _menhir_s _v) : 'freshtv198)) : 'freshtv200)
| _ ->
_menhir_fail ()
and _menhir_goto_tact : _menhir_env -> 'ttv_tail -> _menhir_state -> (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 205 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s _v ->
let _menhir_stack = (_menhir_stack, _menhir_s, _v) in
match _menhir_s with
| MenhirState29 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv175 * _menhir_state) * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 215 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| RPAREN ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv171 * _menhir_state) * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 225 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv169 * _menhir_state) * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 232 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _, (_2 : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 237 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 242 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 67 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(_2)
# 246 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv170)) : 'freshtv172)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv173 * _menhir_state) * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 256 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv174)) : 'freshtv176)
| MenhirState56 | MenhirState17 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv185 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 265 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| EOF ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv179 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 275 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv177 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 281 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, (_1 : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 286 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 291 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 71 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
([_1])
# 295 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tacts _menhir_env _menhir_stack _menhir_s _v) : 'freshtv178)) : 'freshtv180)
| EOL ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv181 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 303 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| AFFD ->
_menhir_run49 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| AFFG ->
_menhir_run47 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| ANDD ->
_menhir_run45 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| ANDG ->
_menhir_run43 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| AXIOM ->
_menhir_run42 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| CONTRD ->
_menhir_run39 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| CONTRG ->
_menhir_run36 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| EOF ->
_menhir_run53 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| EXT ->
_menhir_run34 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| IMPD ->
_menhir_run32 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| IMPG ->
_menhir_run30 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| LPAREN ->
_menhir_run29 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| NOTD ->
_menhir_run27 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| NOTG ->
_menhir_run25 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| ORD ->
_menhir_run23 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| ORG ->
_menhir_run21 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| REDUC ->
_menhir_run18 _menhir_env (Obj.magic _menhir_stack) MenhirState56
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState56) : 'freshtv182)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv183 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 353 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv184)) : 'freshtv186)
| _ ->
_menhir_fail ()
and _menhir_run18 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv165 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 372 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_stack = (_menhir_stack, _v) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv161 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 383 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 388 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv159 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 395 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let ((_3 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 400 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 404 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let ((_menhir_stack, _menhir_s), (_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 409 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 414 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 53 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.reduc _2 _3)
# 418 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv160)) : 'freshtv162)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv163 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 428 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv164)) : 'freshtv166)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv167 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv168)
and _menhir_run21 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv155 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 452 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv153 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 460 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 464 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 470 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 63 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.or_left _2)
# 474 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv154)) : 'freshtv156)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv157 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv158)
and _menhir_run23 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv149 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 497 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv147 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 505 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 509 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 515 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 64 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.or_right _2)
# 519 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv148)) : 'freshtv150)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv151 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv152)
and _menhir_run25 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv143 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 542 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv141 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 550 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 554 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 560 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 59 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.not_left _2)
# 564 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv142)) : 'freshtv144)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv145 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv146)
and _menhir_run27 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv137 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 587 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv135 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 595 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 599 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 605 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 60 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.not_right _2)
# 609 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv136)) : 'freshtv138)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv139 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv140)
and _menhir_run29 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| AFFD ->
_menhir_run49 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| AFFG ->
_menhir_run47 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| ANDD ->
_menhir_run45 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| ANDG ->
_menhir_run43 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| AXIOM ->
_menhir_run42 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| CONTRD ->
_menhir_run39 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| CONTRG ->
_menhir_run36 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| EXT ->
_menhir_run34 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| IMPD ->
_menhir_run32 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| IMPG ->
_menhir_run30 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| LPAREN ->
_menhir_run29 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| NOTD ->
_menhir_run27 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| NOTG ->
_menhir_run25 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| ORD ->
_menhir_run23 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| ORG ->
_menhir_run21 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| REDUC ->
_menhir_run18 _menhir_env (Obj.magic _menhir_stack) MenhirState29
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState29
and _menhir_run30 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv131 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 675 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv129 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 683 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 687 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 693 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 65 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.imp_left _2)
# 697 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv130)) : 'freshtv132)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv133 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv134)
and _menhir_run32 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv125 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 720 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv123 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 728 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 732 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 738 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 66 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.imp_right _2)
# 742 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv124)) : 'freshtv126)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv127 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv128)
and _menhir_run34 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| NAME _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv119 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 765 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv117 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 773 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 777 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 783 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 54 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_store.Ext_props.ext _2)
# 787 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv118)) : 'freshtv120)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv121 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv122)
and _menhir_run53 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv115) = Obj.magic _menhir_stack in
let (_menhir_s : _menhir_state) = _menhir_s in
((let _v : (
# 40 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique list)
# 806 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 70 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
([])
# 810 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tacts _menhir_env _menhir_stack _menhir_s _v) : 'freshtv116)
and _menhir_run36 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv111 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 826 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_stack = (_menhir_stack, _v) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv107 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 837 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 842 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv105 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 849 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let ((_3 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 854 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 858 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let ((_menhir_stack, _menhir_s), (_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 863 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 868 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 57 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.contr_left _2 _3)
# 872 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv106)) : 'freshtv108)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv109 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 882 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv110)) : 'freshtv112)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv113 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv114)
and _menhir_run39 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv101 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 906 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_stack = (_menhir_stack, _v) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv97 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 917 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 922 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv95 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 929 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
let ((_3 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 934 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 938 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let ((_menhir_stack, _menhir_s), (_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 943 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 948 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 58 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.contr_right _2 _3)
# 952 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv96)) : 'freshtv98)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv99 * _menhir_state) * (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 962 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv100)) : 'freshtv102)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv103 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv104)
and _menhir_run42 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv93) = Obj.magic _menhir_stack in
let (_menhir_s : _menhir_state) = _menhir_s in
((let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 983 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 52 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.axiom)
# 987 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv94)
and _menhir_run43 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv89 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1003 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv87 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1011 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1015 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 1021 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 61 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.and_left _2)
# 1025 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv88)) : 'freshtv90)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv91 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv92)
and _menhir_run45 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv83 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1048 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv81 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1056 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1060 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 1066 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 62 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.and_right _2)
# 1070 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv82)) : 'freshtv84)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv85 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv86)
and _menhir_run47 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv77 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1093 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv75 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1101 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1105 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 1111 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 55 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.aff_left _2)
# 1115 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv76)) : 'freshtv78)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv79 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv80)
and _menhir_run49 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| INT _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv71 * _menhir_state) = Obj.magic _menhir_stack in
let (_v : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1138 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv69 * _menhir_state) = Obj.magic _menhir_stack in
let ((_2 : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1146 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 19 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(int)
# 1150 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
let _v : (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 1156 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 56 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.aff_right _2)
# 1160 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_tact _menhir_env _menhir_stack _menhir_s _v) : 'freshtv70)) : 'freshtv72)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv73 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv74)
and _menhir_fail : unit -> 'a =
fun () ->
Printf.fprintf stderr "Internal failure -- please contact the parser generator's developers.\n%!";
assert false
and _menhir_goto_start : _menhir_env -> 'ttv_tail -> (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 1179 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) -> 'ttv_return =
fun _menhir_env _menhir_stack _v ->
let _menhir_stack = (_menhir_stack, _v) in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv67) * (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 1187 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| AFFD ->
_menhir_run49 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| AFFG ->
_menhir_run47 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| ANDD ->
_menhir_run45 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| ANDG ->
_menhir_run43 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| AXIOM ->
_menhir_run42 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| CONTRD ->
_menhir_run39 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| CONTRG ->
_menhir_run36 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| EOF ->
_menhir_run53 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| EXT ->
_menhir_run34 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| IMPD ->
_menhir_run32 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| IMPG ->
_menhir_run30 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| LPAREN ->
_menhir_run29 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| NOTD ->
_menhir_run27 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| NOTG ->
_menhir_run25 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| ORD ->
_menhir_run23 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| ORG ->
_menhir_run21 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| REDUC ->
_menhir_run18 _menhir_env (Obj.magic _menhir_stack) MenhirState17
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState17) : 'freshtv68)
and _menhir_run8 : _menhir_env -> 'ttv_tail * _menhir_state * 'tv_prop -> 'ttv_return =
fun _menhir_env _menhir_stack ->
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState8 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState8
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState8
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState8
and _menhir_run10 : _menhir_env -> 'ttv_tail * _menhir_state * 'tv_prop -> 'ttv_return =
fun _menhir_env _menhir_stack ->
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState10 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState10
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState10
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState10
and _menhir_run12 : _menhir_env -> 'ttv_tail * _menhir_state * 'tv_prop -> 'ttv_return =
fun _menhir_env _menhir_stack ->
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState12 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState12
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState12
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState12
and _menhir_goto_prop : _menhir_env -> 'ttv_tail -> _menhir_state -> 'tv_prop -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s _v ->
let _menhir_stack = (_menhir_stack, _menhir_s, _v) in
match _menhir_s with
| MenhirState4 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv37 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| AND ->
_menhir_run12 _menhir_env (Obj.magic _menhir_stack)
| IMP ->
_menhir_run10 _menhir_env (Obj.magic _menhir_stack)
| OR ->
_menhir_run8 _menhir_env (Obj.magic _menhir_stack)
| RPAREN ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv33 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv31 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _, (_2 : 'tv_prop)) = _menhir_stack in
let _v : 'tv_prop =
# 76 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( _2 )
# 1305 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv32)) : 'freshtv34)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv35 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv36)) : 'freshtv38)
| MenhirState8 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv41 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv39 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s, (_1 : 'tv_prop)), _, (_3 : 'tv_prop)) = _menhir_stack in
let _v : 'tv_prop =
# 79 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( Or(_1,_3) )
# 1324 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv40)) : 'freshtv42)
| MenhirState10 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv47 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| AND ->
_menhir_run12 _menhir_env (Obj.magic _menhir_stack)
| OR ->
_menhir_run8 _menhir_env (Obj.magic _menhir_stack)
| AFFD | AFFG | ANDD | ANDG | AXIOM | CONTRD | CONTRG | EOF | EOL | EXT | IMP | IMPD | IMPG | LPAREN | NOTD | NOTG | ORD | ORG | REDUC | RPAREN ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv43 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s, (_1 : 'tv_prop)), _, (_3 : 'tv_prop)) = _menhir_stack in
let _v : 'tv_prop =
# 77 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( Imp(_1,_3) )
# 1344 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv44)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv45 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv46)) : 'freshtv48)
| MenhirState12 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv51 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : (('freshtv49 * _menhir_state * 'tv_prop)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s, (_1 : 'tv_prop)), _, (_3 : 'tv_prop)) = _menhir_stack in
let _v : 'tv_prop =
# 78 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( And(_1,_3) )
# 1363 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv50)) : 'freshtv52)
| MenhirState3 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv55 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv53 * _menhir_state) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, _menhir_s), _, (_2 : 'tv_prop)) = _menhir_stack in
let _v : 'tv_prop =
# 80 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( Not _2)
# 1375 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv54)) : 'freshtv56)
| MenhirState2 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv65 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1383 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((assert (not _menhir_env._menhir_error);
let _tok = _menhir_env._menhir_token in
match _tok with
| AND ->
_menhir_run12 _menhir_env (Obj.magic _menhir_stack)
| EOL ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv59 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1395 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv57 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1402 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, (_1 : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1407 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))), _, (_2 : 'tv_prop)) = _menhir_stack in
let _v : (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 1412 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 48 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( ( _1 , _2 ) )
# 1416 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_start _menhir_env _menhir_stack _v) : 'freshtv58)) : 'freshtv60)
| IMP ->
_menhir_run10 _menhir_env (Obj.magic _menhir_stack)
| OR ->
_menhir_run8 _menhir_env (Obj.magic _menhir_stack)
| AFFD | AFFG | ANDD | ANDG | AXIOM | CONTRD | CONTRG | EOF | EXT | IMPD | IMPG | LPAREN | NOTD | NOTG | ORD | ORG | REDUC ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv61 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1428 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let ((_menhir_stack, (_1 : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1433 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))), _, (_2 : 'tv_prop)) = _menhir_stack in
let _v : (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 1438 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
# 49 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( ( _1 , _2 ) )
# 1442 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_start _menhir_env _menhir_stack _v) : 'freshtv62)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv63 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1452 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) * _menhir_state * 'tv_prop) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv64)) : 'freshtv66)
| _ ->
_menhir_fail ()
and _menhir_errorcase : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
match _menhir_s with
| MenhirState56 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv13 * _menhir_state * (
# 41 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Tactiques.tactique)
# 1467 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
))) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv14)
| MenhirState29 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv15 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv16)
| MenhirState17 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv17) * (
# 39 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string * Proof_build.Formule.formule)
# 1481 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
(raise _eRR : 'freshtv18)
| MenhirState12 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv19 * _menhir_state * 'tv_prop)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv20)
| MenhirState10 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv21 * _menhir_state * 'tv_prop)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv22)
| MenhirState8 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : ('freshtv23 * _menhir_state * 'tv_prop)) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s, _) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv24)
| MenhirState4 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv25 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv26)
| MenhirState3 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv27 * _menhir_state) = Obj.magic _menhir_stack in
((let (_menhir_stack, _menhir_s) = _menhir_stack in
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) _menhir_s) : 'freshtv28)
| MenhirState2 ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv29 * (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1514 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = Obj.magic _menhir_stack in
(raise _eRR : 'freshtv30)
and _menhir_run3 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState3 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState3
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState3
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState3
and _menhir_run4 : _menhir_env -> 'ttv_tail -> _menhir_state -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s ->
let _menhir_stack = (_menhir_stack, _menhir_s) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState4 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState4
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState4
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState4
and _menhir_run5 : _menhir_env -> 'ttv_tail -> _menhir_state -> (
# 8 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Formule.formule)
# 1555 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) -> 'ttv_return =
fun _menhir_env _menhir_stack _menhir_s _v ->
let _menhir_env = _menhir_discard _menhir_env in
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv11) = Obj.magic _menhir_stack in
let (_menhir_s : _menhir_state) = _menhir_s in
let ((_1 : (
# 8 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Formule.formule)
# 1565 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) : (
# 8 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(Proof_build.Formule.formule)
# 1569 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _v : 'tv_prop =
# 75 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
( _1 )
# 1574 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
in
_menhir_goto_prop _menhir_env _menhir_stack _menhir_s _v) : 'freshtv12)
and _menhir_discard : _menhir_env -> _menhir_env =
fun _menhir_env ->
let lexer = _menhir_env._menhir_lexer in
let lexbuf = _menhir_env._menhir_lexbuf in
let _tok = lexer lexbuf in
{
_menhir_lexer = lexer;
_menhir_lexbuf = lexbuf;
_menhir_token = _tok;
_menhir_error = false;
}
and main : (Lexing.lexbuf -> token) -> Lexing.lexbuf -> (
# 38 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
((string * Proof_build.Formule.formule) * (Proof_build.Tactiques.tactique list))
# 1593 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
) =
fun lexer lexbuf ->
let _menhir_env = {
_menhir_lexer = lexer;
_menhir_lexbuf = lexbuf;
_menhir_token = Obj.magic ();
_menhir_error = false;
} in
Obj.magic (let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv9) = ((), _menhir_env._menhir_lexbuf.Lexing.lex_curr_p) in
((let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| BEGIN ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv5) = Obj.magic _menhir_stack in
((let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| NAME _v ->
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv1) = Obj.magic _menhir_stack in
let (_v : (
# 6 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.mly"
(string)
# 1619 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
)) = _v in
((let _menhir_stack = (_menhir_stack, _v) in
let _menhir_env = _menhir_discard _menhir_env in
let _tok = _menhir_env._menhir_token in
match _tok with
| CHAR _v ->
_menhir_run5 _menhir_env (Obj.magic _menhir_stack) MenhirState2 _v
| LPAREN ->
_menhir_run4 _menhir_env (Obj.magic _menhir_stack) MenhirState2
| NOT ->
_menhir_run3 _menhir_env (Obj.magic _menhir_stack) MenhirState2
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
_menhir_errorcase _menhir_env (Obj.magic _menhir_stack) MenhirState2) : 'freshtv2)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv3) = Obj.magic _menhir_stack in
(raise _eRR : 'freshtv4)) : 'freshtv6)
| _ ->
assert (not _menhir_env._menhir_error);
_menhir_env._menhir_error <- true;
let (_menhir_env : _menhir_env) = _menhir_env in
let (_menhir_stack : 'freshtv7) = Obj.magic _menhir_stack in
(raise _eRR : 'freshtv8)) : 'freshtv10))
# 269 "<standard.mly>"
# 1651 "C:\Users\aarth\IdeaProjects\Theorem_prover\pr_assistant\proof_read\parser_read.ml"
|
|
a76892436ddf2f586777bb323d8d9eeb61d6e7eeb6133bb13524055b60ddb711 | cloojure/tupelo | snip.cljc | (ns tst.tupelo.core.snip
(:use tupelo.core tupelo.test)
(:require
[clojure.pprint :as pprint]
[tupelo.core :as t]
)
#?(:clj
(:require
[flatland.ordered.map :as omap]
[flatland.ordered.set :as oset]
)))
#?(:clj
(do
(verify
(let [r10 (range 10)
m10 {:a 1 :b 2 :c 3 :d 4 :e 5 :f 6 :g 7 :h 8 :i 9 :j 10}
m10-seq (seq (t/->sorted-map-generic m10))
s10 #{:a :b :c :d :e :f :g :h :i :j}]
(throws? (snip-seq-heads [] r10))
(is= (snip-seq-heads [0] r10) [t/SNIP-TOKEN])
(is= (snip-seq-heads [1] r10) [0 t/SNIP-TOKEN])
(is= (snip-seq-heads [2] r10) [0 1 t/SNIP-TOKEN])
(is= (snip-seq-heads [1 1] r10) [0 t/SNIP-TOKEN 5 t/SNIP-TOKEN])
(is= (snip-seq-heads [2 3] r10) [0 1 t/SNIP-TOKEN 5 6 7 t/SNIP-TOKEN])
(is= (snip-seq-heads [3 3 3] r10) [0 1 2 t/SNIP-TOKEN 3 4 5 t/SNIP-TOKEN 6 7 8 t/SNIP-TOKEN])
(is= (snip-seq-heads [4 9] r10) [0 1 2 3 4 5 6 7 8 9])
(is= (snip-seq-tail 0 r10) [])
(is= (snip-seq-tail 1 r10) [9])
(is= (snip-seq-tail 2 r10) [8 9])
(throws? (snip-seq [0] r10))
(is= (snip-seq [1] r10) [0 t/SNIP-TOKEN])
(is= (snip-seq [1 1] r10) [0 t/SNIP-TOKEN 9])
(is= (snip-seq [1 1 1] r10) [0 t/SNIP-TOKEN 4 t/SNIP-TOKEN 9])
(is= (snip-seq [2 3 2] r10) [0 1 t/SNIP-TOKEN 4 5 6 t/SNIP-TOKEN 8 9])
(is= (snip-seq [3 3 3] r10) [0 1 2 t/SNIP-TOKEN 3 4 5 t/SNIP-TOKEN 7 8 9])
;---------------------------------------------------------------------------------------------------
(throws? (snip-seq-heads [] m10-seq))
(is= (snip-seq-heads [0] m10-seq) [t/SNIP-TOKEN])
(is= (snip-seq-heads [1] m10-seq) [[:a 1] t/SNIP-TOKEN])
(is= (snip-seq-heads [2] m10-seq) [[:a 1] [:b 2] t/SNIP-TOKEN])
(is= (snip-seq-heads [1 1] m10-seq) [[:a 1] t/SNIP-TOKEN [:f 6] t/SNIP-TOKEN])
(is= (snip-seq-heads [2 3] m10-seq) [[:a 1] [:b 2] t/SNIP-TOKEN [:f 6] [:g 7] [:h 8] t/SNIP-TOKEN])
(is= (snip-seq-heads [3 3 3] m10-seq) [[:a 1] [:b 2] [:c 3] t/SNIP-TOKEN [:d 4] [:e 5] [:f 6] t/SNIP-TOKEN [:g 7] [:h 8] [:i 9] t/SNIP-TOKEN])
(is= (snip-seq-heads [4 9] m10-seq) [[:a 1] [:b 2] [:c 3] [:d 4] [:e 5] [:f 6] [:g 7] [:h 8] [:i 9] [:j 10]])
;---------------------------------------------------------------------------------------------------
(is= (snip-impl {:snip-sizes [1 1 1] :data r10}) [0 t/SNIP-TOKEN 4 t/SNIP-TOKEN 9])
(is= (snip-impl {:snip-sizes [2 3 2] :data r10}) [0 1 t/SNIP-TOKEN 4 5 6 t/SNIP-TOKEN 8 9])
(is= (snip-impl {:snip-sizes [1 1] :data m10})
{:a 1, :<snip-key-0> :<snip-val-0>, :j 10})
(is= (snip-impl {:snip-sizes [2 3] :data m10})
{:a 1, :b 2,
:<snip-key-0> :<snip-val-0>,
:h 8, :i 9, :j 10})
(is= (snip-impl {:snip-sizes [2 1 2] :data m10})
{:a 1,
:b 2,
:<snip-key-0> :<snip-val-0>,
:e 5,
:<snip-key-1> :<snip-val-1>,
:i 9,
:j 10})
; ***** must use `spyx-pretty` or `pprint` to avoid `#ordered-map (...)` syntax *****
(is= (snip-impl {:snip-sizes [1 1], :data s10}) #{:a :<snip-0> :j})
(is= (snip-impl {:snip-sizes [2 3], :data s10}) #{:a :b :<snip-0> :h :i :j})
; ***** Enable debug code to see default printout put like `#ordered-map (...)`
(when false
(nl)
(spyx "hello")
(spyx-pretty "hello")
(nl)
(let [om (omap/ordered-map :a 1 :b 2)]
(spyx-pretty om)
(println :println om)
(println :pr-str (pr-str om))
(prn :prn om)
(pprint/pprint [:pprint om]))
(nl)
(let [os (oset/ordered-set 1 2 3)]
(spyx os)
(spyx-pretty os)
(println :println os)
(println :pr-str (pr-str os))
(prn :prn os)
(pprint/pprint [:pprint os]))
(nl)
(let [os10 (into (oset/ordered-set) (range 20))]
(spyx :coerce-before os10)
(coerce-flatland-ordered->normal-print!)
(spyx :coerce-after os10)
(spyx :plain-set (into #{} os10))))
))
(verify
(let [e1 [{:date "2020-10-01", :value 116.5888}
{:date "2020-10-02", :value 112.8253}
{:date "2020-10-05", :value 116.2993}
{:date "2020-10-06", :value 112.9651}
{:date "2020-10-07", :value 114.8818}
{:date "2020-10-08", :value 114.7719}
{:date "2020-10-09", :value 116.7685}
{:date "2020-10-12", :value 124.1857}
{:date "2020-10-13", :value 120.8914}
{:date "2020-10-14", :value 120.9812}
{:date "2020-10-15", :value 120.5021}]
e2 [{:date "2020-10-01", :value 116.5888}
{:date "2020-10-02", :value 112.8253}
{:date "2020-10-05", :value 116.2993}
{:date "2020-10-06", :value 112.9651}
{:date "2020-10-07", :value 114.8818}
{:date "2020-10-08", :value 114.7719}
{:date "2020-10-09", :value 116.7685}
{:date "2020-10-12", :value 124.1857}
{:date "2020-10-13", :value 120.8914}
{:date "2020-10-14", :value 120.9812}
{:date "2020-10-15", :value 120.5021}]
sn1 (snip e1)
sn2 (snip e2)]
(is= sn1
[{:date "2020-10-01", :value 116.5888}
{:date "2020-10-02", :value 112.8253}
{:date "2020-10-05", :value 116.2993}
{:date "2020-10-06", :value 112.9651}
t/SNIP-TOKEN
{:date "2020-10-13", :value 120.8914}
{:date "2020-10-14", :value 120.9812}
{:date "2020-10-15", :value 120.5021}])
(is (deep-rel= e1 e2))
(is (deep-rel= sn1 sn2))))
(verify
(let [v312 (forv [i (thru 1 9)]
(forv [j (thru 1 12)]
(->kw (format "%d-%d" i j))))
v312-snip (snip v312)]
(is= v312
[[:1-1 :1-2 :1-3 :1-4 :1-5 :1-6 :1-7 :1-8 :1-9 :1-10 :1-11 :1-12]
[:2-1 :2-2 :2-3 :2-4 :2-5 :2-6 :2-7 :2-8 :2-9 :2-10 :2-11 :2-12]
[:3-1 :3-2 :3-3 :3-4 :3-5 :3-6 :3-7 :3-8 :3-9 :3-10 :3-11 :3-12]
[:4-1 :4-2 :4-3 :4-4 :4-5 :4-6 :4-7 :4-8 :4-9 :4-10 :4-11 :4-12]
[:5-1 :5-2 :5-3 :5-4 :5-5 :5-6 :5-7 :5-8 :5-9 :5-10 :5-11 :5-12]
[:6-1 :6-2 :6-3 :6-4 :6-5 :6-6 :6-7 :6-8 :6-9 :6-10 :6-11 :6-12]
[:7-1 :7-2 :7-3 :7-4 :7-5 :7-6 :7-7 :7-8 :7-9 :7-10 :7-11 :7-12]
[:8-1 :8-2 :8-3 :8-4 :8-5 :8-6 :8-7 :8-8 :8-9 :8-10 :8-11 :8-12]
[:9-1 :9-2 :9-3 :9-4 :9-5 :9-6 :9-7 :9-8 :9-9 :9-10 :9-11 :9-12]])
(is= v312-snip
[[:1-1 :1-2 :1-3 :1-4 t/SNIP-TOKEN :1-10 :1-11 :1-12]
[:2-1 :2-2 :2-3 :2-4 t/SNIP-TOKEN :2-10 :2-11 :2-12]
[:3-1 :3-2 :3-3 :3-4 t/SNIP-TOKEN :3-10 :3-11 :3-12]
[:4-1 :4-2 :4-3 :4-4 t/SNIP-TOKEN :4-10 :4-11 :4-12]
t/SNIP-TOKEN
[:7-1 :7-2 :7-3 :7-4 t/SNIP-TOKEN :7-10 :7-11 :7-12]
[:8-1 :8-2 :8-3 :8-4 t/SNIP-TOKEN :8-10 :8-11 :8-12]
[:9-1 :9-2 :9-3 :9-4 t/SNIP-TOKEN :9-10 :9-11 :9-12]])))
(verify
(let [data (apply glue
(forv [x (chars-thru \a \k)]
{(->kw (str x))
(forv [j (thru 1 12)]
(->kw (format "%s-%d" x j)))}))
data-snip (snip data)]
(is= data
{:e [:e-1 :e-2 :e-3 :e-4 :e-5 :e-6 :e-7 :e-8 :e-9 :e-10 :e-11 :e-12],
:k [:k-1 :k-2 :k-3 :k-4 :k-5 :k-6 :k-7 :k-8 :k-9 :k-10 :k-11 :k-12],
:g [:g-1 :g-2 :g-3 :g-4 :g-5 :g-6 :g-7 :g-8 :g-9 :g-10 :g-11 :g-12],
:c [:c-1 :c-2 :c-3 :c-4 :c-5 :c-6 :c-7 :c-8 :c-9 :c-10 :c-11 :c-12],
:j [:j-1 :j-2 :j-3 :j-4 :j-5 :j-6 :j-7 :j-8 :j-9 :j-10 :j-11 :j-12],
:h [:h-1 :h-2 :h-3 :h-4 :h-5 :h-6 :h-7 :h-8 :h-9 :h-10 :h-11 :h-12],
:b [:b-1 :b-2 :b-3 :b-4 :b-5 :b-6 :b-7 :b-8 :b-9 :b-10 :b-11 :b-12],
:d [:d-1 :d-2 :d-3 :d-4 :d-5 :d-6 :d-7 :d-8 :d-9 :d-10 :d-11 :d-12],
:f [:f-1 :f-2 :f-3 :f-4 :f-5 :f-6 :f-7 :f-8 :f-9 :f-10 :f-11 :f-12],
:i [:i-1 :i-2 :i-3 :i-4 :i-5 :i-6 :i-7 :i-8 :i-9 :i-10 :i-11 :i-12],
:a [:a-1 :a-2 :a-3 :a-4 :a-5 :a-6 :a-7 :a-8 :a-9 :a-10 :a-11 :a-12]})
(is= data-snip
{:a [:a-1 :a-2 :a-3 :a-4 t/SNIP-TOKEN :a-10 :a-11 :a-12],
:b [:b-1 :b-2 :b-3 :b-4 t/SNIP-TOKEN :b-10 :b-11 :b-12],
:c [:c-1 :c-2 :c-3 :c-4 t/SNIP-TOKEN :c-10 :c-11 :c-12],
:d [:d-1 :d-2 :d-3 :d-4 t/SNIP-TOKEN :d-10 :d-11 :d-12],
:<snip-key-0> :<snip-val-0>,
:i [:i-1 :i-2 :i-3 :i-4 t/SNIP-TOKEN :i-10 :i-11 :i-12],
:j [:j-1 :j-2 :j-3 :j-4 t/SNIP-TOKEN :j-10 :j-11 :j-12],
:k [:k-1 :k-2 :k-3 :k-4 t/SNIP-TOKEN :k-10 :k-11 :k-12]})))
(verify
(let [data (apply glue
(forv [x (chars-thru \a \c)]
{(->kw (str x))
(apply glue
(forv [j (thru 1 12)]
{j (->kw (format "%s-%d" x j))}))}))
data-snip (snip data)]
(is= data-snip
{:a {1 :a-1,
2 :a-2,
3 :a-3,
4 :a-4,
:<snip-key-0> :<snip-val-0>,
10 :a-10,
11 :a-11,
12 :a-12},
:b {1 :b-1,
2 :b-2,
3 :b-3,
4 :b-4,
:<snip-key-0> :<snip-val-0>,
10 :b-10,
11 :b-11,
12 :b-12},
:c {1 :c-1,
2 :c-2,
3 :c-3,
4 :c-4,
:<snip-key-0> :<snip-val-0>,
10 :c-10,
11 :c-11,
12 :c-12}})))
))
| null | https://raw.githubusercontent.com/cloojure/tupelo/dbb4b12fd6f379803a74a6bdcf54726597ec0fdf/test/cljc/tst/tupelo/core/snip.cljc | clojure | ---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
***** must use `spyx-pretty` or `pprint` to avoid `#ordered-map (...)` syntax *****
***** Enable debug code to see default printout put like `#ordered-map (...)` | (ns tst.tupelo.core.snip
(:use tupelo.core tupelo.test)
(:require
[clojure.pprint :as pprint]
[tupelo.core :as t]
)
#?(:clj
(:require
[flatland.ordered.map :as omap]
[flatland.ordered.set :as oset]
)))
#?(:clj
(do
(verify
(let [r10 (range 10)
m10 {:a 1 :b 2 :c 3 :d 4 :e 5 :f 6 :g 7 :h 8 :i 9 :j 10}
m10-seq (seq (t/->sorted-map-generic m10))
s10 #{:a :b :c :d :e :f :g :h :i :j}]
(throws? (snip-seq-heads [] r10))
(is= (snip-seq-heads [0] r10) [t/SNIP-TOKEN])
(is= (snip-seq-heads [1] r10) [0 t/SNIP-TOKEN])
(is= (snip-seq-heads [2] r10) [0 1 t/SNIP-TOKEN])
(is= (snip-seq-heads [1 1] r10) [0 t/SNIP-TOKEN 5 t/SNIP-TOKEN])
(is= (snip-seq-heads [2 3] r10) [0 1 t/SNIP-TOKEN 5 6 7 t/SNIP-TOKEN])
(is= (snip-seq-heads [3 3 3] r10) [0 1 2 t/SNIP-TOKEN 3 4 5 t/SNIP-TOKEN 6 7 8 t/SNIP-TOKEN])
(is= (snip-seq-heads [4 9] r10) [0 1 2 3 4 5 6 7 8 9])
(is= (snip-seq-tail 0 r10) [])
(is= (snip-seq-tail 1 r10) [9])
(is= (snip-seq-tail 2 r10) [8 9])
(throws? (snip-seq [0] r10))
(is= (snip-seq [1] r10) [0 t/SNIP-TOKEN])
(is= (snip-seq [1 1] r10) [0 t/SNIP-TOKEN 9])
(is= (snip-seq [1 1 1] r10) [0 t/SNIP-TOKEN 4 t/SNIP-TOKEN 9])
(is= (snip-seq [2 3 2] r10) [0 1 t/SNIP-TOKEN 4 5 6 t/SNIP-TOKEN 8 9])
(is= (snip-seq [3 3 3] r10) [0 1 2 t/SNIP-TOKEN 3 4 5 t/SNIP-TOKEN 7 8 9])
(throws? (snip-seq-heads [] m10-seq))
(is= (snip-seq-heads [0] m10-seq) [t/SNIP-TOKEN])
(is= (snip-seq-heads [1] m10-seq) [[:a 1] t/SNIP-TOKEN])
(is= (snip-seq-heads [2] m10-seq) [[:a 1] [:b 2] t/SNIP-TOKEN])
(is= (snip-seq-heads [1 1] m10-seq) [[:a 1] t/SNIP-TOKEN [:f 6] t/SNIP-TOKEN])
(is= (snip-seq-heads [2 3] m10-seq) [[:a 1] [:b 2] t/SNIP-TOKEN [:f 6] [:g 7] [:h 8] t/SNIP-TOKEN])
(is= (snip-seq-heads [3 3 3] m10-seq) [[:a 1] [:b 2] [:c 3] t/SNIP-TOKEN [:d 4] [:e 5] [:f 6] t/SNIP-TOKEN [:g 7] [:h 8] [:i 9] t/SNIP-TOKEN])
(is= (snip-seq-heads [4 9] m10-seq) [[:a 1] [:b 2] [:c 3] [:d 4] [:e 5] [:f 6] [:g 7] [:h 8] [:i 9] [:j 10]])
(is= (snip-impl {:snip-sizes [1 1 1] :data r10}) [0 t/SNIP-TOKEN 4 t/SNIP-TOKEN 9])
(is= (snip-impl {:snip-sizes [2 3 2] :data r10}) [0 1 t/SNIP-TOKEN 4 5 6 t/SNIP-TOKEN 8 9])
(is= (snip-impl {:snip-sizes [1 1] :data m10})
{:a 1, :<snip-key-0> :<snip-val-0>, :j 10})
(is= (snip-impl {:snip-sizes [2 3] :data m10})
{:a 1, :b 2,
:<snip-key-0> :<snip-val-0>,
:h 8, :i 9, :j 10})
(is= (snip-impl {:snip-sizes [2 1 2] :data m10})
{:a 1,
:b 2,
:<snip-key-0> :<snip-val-0>,
:e 5,
:<snip-key-1> :<snip-val-1>,
:i 9,
:j 10})
(is= (snip-impl {:snip-sizes [1 1], :data s10}) #{:a :<snip-0> :j})
(is= (snip-impl {:snip-sizes [2 3], :data s10}) #{:a :b :<snip-0> :h :i :j})
(when false
(nl)
(spyx "hello")
(spyx-pretty "hello")
(nl)
(let [om (omap/ordered-map :a 1 :b 2)]
(spyx-pretty om)
(println :println om)
(println :pr-str (pr-str om))
(prn :prn om)
(pprint/pprint [:pprint om]))
(nl)
(let [os (oset/ordered-set 1 2 3)]
(spyx os)
(spyx-pretty os)
(println :println os)
(println :pr-str (pr-str os))
(prn :prn os)
(pprint/pprint [:pprint os]))
(nl)
(let [os10 (into (oset/ordered-set) (range 20))]
(spyx :coerce-before os10)
(coerce-flatland-ordered->normal-print!)
(spyx :coerce-after os10)
(spyx :plain-set (into #{} os10))))
))
(verify
(let [e1 [{:date "2020-10-01", :value 116.5888}
{:date "2020-10-02", :value 112.8253}
{:date "2020-10-05", :value 116.2993}
{:date "2020-10-06", :value 112.9651}
{:date "2020-10-07", :value 114.8818}
{:date "2020-10-08", :value 114.7719}
{:date "2020-10-09", :value 116.7685}
{:date "2020-10-12", :value 124.1857}
{:date "2020-10-13", :value 120.8914}
{:date "2020-10-14", :value 120.9812}
{:date "2020-10-15", :value 120.5021}]
e2 [{:date "2020-10-01", :value 116.5888}
{:date "2020-10-02", :value 112.8253}
{:date "2020-10-05", :value 116.2993}
{:date "2020-10-06", :value 112.9651}
{:date "2020-10-07", :value 114.8818}
{:date "2020-10-08", :value 114.7719}
{:date "2020-10-09", :value 116.7685}
{:date "2020-10-12", :value 124.1857}
{:date "2020-10-13", :value 120.8914}
{:date "2020-10-14", :value 120.9812}
{:date "2020-10-15", :value 120.5021}]
sn1 (snip e1)
sn2 (snip e2)]
(is= sn1
[{:date "2020-10-01", :value 116.5888}
{:date "2020-10-02", :value 112.8253}
{:date "2020-10-05", :value 116.2993}
{:date "2020-10-06", :value 112.9651}
t/SNIP-TOKEN
{:date "2020-10-13", :value 120.8914}
{:date "2020-10-14", :value 120.9812}
{:date "2020-10-15", :value 120.5021}])
(is (deep-rel= e1 e2))
(is (deep-rel= sn1 sn2))))
(verify
(let [v312 (forv [i (thru 1 9)]
(forv [j (thru 1 12)]
(->kw (format "%d-%d" i j))))
v312-snip (snip v312)]
(is= v312
[[:1-1 :1-2 :1-3 :1-4 :1-5 :1-6 :1-7 :1-8 :1-9 :1-10 :1-11 :1-12]
[:2-1 :2-2 :2-3 :2-4 :2-5 :2-6 :2-7 :2-8 :2-9 :2-10 :2-11 :2-12]
[:3-1 :3-2 :3-3 :3-4 :3-5 :3-6 :3-7 :3-8 :3-9 :3-10 :3-11 :3-12]
[:4-1 :4-2 :4-3 :4-4 :4-5 :4-6 :4-7 :4-8 :4-9 :4-10 :4-11 :4-12]
[:5-1 :5-2 :5-3 :5-4 :5-5 :5-6 :5-7 :5-8 :5-9 :5-10 :5-11 :5-12]
[:6-1 :6-2 :6-3 :6-4 :6-5 :6-6 :6-7 :6-8 :6-9 :6-10 :6-11 :6-12]
[:7-1 :7-2 :7-3 :7-4 :7-5 :7-6 :7-7 :7-8 :7-9 :7-10 :7-11 :7-12]
[:8-1 :8-2 :8-3 :8-4 :8-5 :8-6 :8-7 :8-8 :8-9 :8-10 :8-11 :8-12]
[:9-1 :9-2 :9-3 :9-4 :9-5 :9-6 :9-7 :9-8 :9-9 :9-10 :9-11 :9-12]])
(is= v312-snip
[[:1-1 :1-2 :1-3 :1-4 t/SNIP-TOKEN :1-10 :1-11 :1-12]
[:2-1 :2-2 :2-3 :2-4 t/SNIP-TOKEN :2-10 :2-11 :2-12]
[:3-1 :3-2 :3-3 :3-4 t/SNIP-TOKEN :3-10 :3-11 :3-12]
[:4-1 :4-2 :4-3 :4-4 t/SNIP-TOKEN :4-10 :4-11 :4-12]
t/SNIP-TOKEN
[:7-1 :7-2 :7-3 :7-4 t/SNIP-TOKEN :7-10 :7-11 :7-12]
[:8-1 :8-2 :8-3 :8-4 t/SNIP-TOKEN :8-10 :8-11 :8-12]
[:9-1 :9-2 :9-3 :9-4 t/SNIP-TOKEN :9-10 :9-11 :9-12]])))
(verify
(let [data (apply glue
(forv [x (chars-thru \a \k)]
{(->kw (str x))
(forv [j (thru 1 12)]
(->kw (format "%s-%d" x j)))}))
data-snip (snip data)]
(is= data
{:e [:e-1 :e-2 :e-3 :e-4 :e-5 :e-6 :e-7 :e-8 :e-9 :e-10 :e-11 :e-12],
:k [:k-1 :k-2 :k-3 :k-4 :k-5 :k-6 :k-7 :k-8 :k-9 :k-10 :k-11 :k-12],
:g [:g-1 :g-2 :g-3 :g-4 :g-5 :g-6 :g-7 :g-8 :g-9 :g-10 :g-11 :g-12],
:c [:c-1 :c-2 :c-3 :c-4 :c-5 :c-6 :c-7 :c-8 :c-9 :c-10 :c-11 :c-12],
:j [:j-1 :j-2 :j-3 :j-4 :j-5 :j-6 :j-7 :j-8 :j-9 :j-10 :j-11 :j-12],
:h [:h-1 :h-2 :h-3 :h-4 :h-5 :h-6 :h-7 :h-8 :h-9 :h-10 :h-11 :h-12],
:b [:b-1 :b-2 :b-3 :b-4 :b-5 :b-6 :b-7 :b-8 :b-9 :b-10 :b-11 :b-12],
:d [:d-1 :d-2 :d-3 :d-4 :d-5 :d-6 :d-7 :d-8 :d-9 :d-10 :d-11 :d-12],
:f [:f-1 :f-2 :f-3 :f-4 :f-5 :f-6 :f-7 :f-8 :f-9 :f-10 :f-11 :f-12],
:i [:i-1 :i-2 :i-3 :i-4 :i-5 :i-6 :i-7 :i-8 :i-9 :i-10 :i-11 :i-12],
:a [:a-1 :a-2 :a-3 :a-4 :a-5 :a-6 :a-7 :a-8 :a-9 :a-10 :a-11 :a-12]})
(is= data-snip
{:a [:a-1 :a-2 :a-3 :a-4 t/SNIP-TOKEN :a-10 :a-11 :a-12],
:b [:b-1 :b-2 :b-3 :b-4 t/SNIP-TOKEN :b-10 :b-11 :b-12],
:c [:c-1 :c-2 :c-3 :c-4 t/SNIP-TOKEN :c-10 :c-11 :c-12],
:d [:d-1 :d-2 :d-3 :d-4 t/SNIP-TOKEN :d-10 :d-11 :d-12],
:<snip-key-0> :<snip-val-0>,
:i [:i-1 :i-2 :i-3 :i-4 t/SNIP-TOKEN :i-10 :i-11 :i-12],
:j [:j-1 :j-2 :j-3 :j-4 t/SNIP-TOKEN :j-10 :j-11 :j-12],
:k [:k-1 :k-2 :k-3 :k-4 t/SNIP-TOKEN :k-10 :k-11 :k-12]})))
(verify
(let [data (apply glue
(forv [x (chars-thru \a \c)]
{(->kw (str x))
(apply glue
(forv [j (thru 1 12)]
{j (->kw (format "%s-%d" x j))}))}))
data-snip (snip data)]
(is= data-snip
{:a {1 :a-1,
2 :a-2,
3 :a-3,
4 :a-4,
:<snip-key-0> :<snip-val-0>,
10 :a-10,
11 :a-11,
12 :a-12},
:b {1 :b-1,
2 :b-2,
3 :b-3,
4 :b-4,
:<snip-key-0> :<snip-val-0>,
10 :b-10,
11 :b-11,
12 :b-12},
:c {1 :c-1,
2 :c-2,
3 :c-3,
4 :c-4,
:<snip-key-0> :<snip-val-0>,
10 :c-10,
11 :c-11,
12 :c-12}})))
))
|
79774cbfaafb960beb8c246b02e0a0060da870eb0d7830e8bbf5b31994264a4f | nd/sicp | 5.9.scm | (define (make-operation-exp exp machine labels operations)
(let ((op (lookup-prim (operation-exp-op exp) operations))
(aprocs (map (lambda (e)
(if (label-exp? e)
(error "Label as argument to operation -- make-operation-exp" e)
(make-primitive-exp e machine labels)))
(operation-exp-operands exp))))
(lambda () (apply op (map (lambda (p) (p)) aprocs))))) | null | https://raw.githubusercontent.com/nd/sicp/d8587a0403d95af7c7bcf59b812f98c4f8550afd/ch05/5.9.scm | scheme | (define (make-operation-exp exp machine labels operations)
(let ((op (lookup-prim (operation-exp-op exp) operations))
(aprocs (map (lambda (e)
(if (label-exp? e)
(error "Label as argument to operation -- make-operation-exp" e)
(make-primitive-exp e machine labels)))
(operation-exp-operands exp))))
(lambda () (apply op (map (lambda (p) (p)) aprocs))))) |
|
da9cd89bac360d61a5f6b3a72177e98e5ce5e0173997782878605ef4e0d374a3 | roterski/syncrate-fulcro | post_form.cljs | (ns app.posts.ui.post-form
(:require
[app.posts.validations]
[app.routing :refer [route-to!]]
[app.ui.components :refer [field]]
[clojure.set :refer [intersection subset?]]
[com.fulcrologic.fulcro.dom :as dom :refer [div ul li p h1 h3 button]]
[com.fulcrologic.fulcro.dom.events :as evt]
[com.fulcrologic.fulcro.components :as prim :refer [defsc]]
[com.fulcrologic.fulcro.components :as comp]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.algorithms.tempid :refer [tempid]]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro-css.css :as css]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]))
(declare PostForm)
(defn add-post*
[state-map {:post/keys [id] :as props}]
(let [post-ident [:post/id id]]
(-> state-map
(assoc-in post-ident props)
(assoc-in [:component/id :new-post-page :new-post-page/post] post-ident))))
(defmutation add-post-form
[props]
(action [{:keys [state]}]
(let [post-id (tempid)]
(log/info "Adding post form")
(swap! state (fn [s]
(-> s
(add-post* (merge {:post/id post-id :post/body "" :post/title ""} props))
(fs/add-form-config* PostForm [:post/id post-id])))))))
(defn clear-post-form*
[state-map id]
(let [post-ident [:post/id id]
form-ident {:table :post/id :row id}]
(-> state-map
(update-in post-ident
merge
{:post/title ""
:post/body ""})
(assoc-in [::fs/forms-by-ident form-ident ::fs/complete?] #{}))))
(defmutation clear-post-form [{:keys [id]}]
(action [{:keys [state]}]
(swap! state (fn [s]
(-> s
(clear-post-form* id))))))
(defmutation create-post! [{:post/keys [tempid]}]
(action [{:keys [state]}]
(log/info "Creating post..."))
(ok-action [{:keys [app state result] :as params}]
(log/info "...post created successfully!")
(swap! state (fn [s]
(-> s
(update-in [::fs/forms-by-ident] dissoc {:table :post/id :row tempid})
(assoc-in [:component/id :new-post-page :new-post-page/post] nil))))
(route-to! "/posts/all/page/1"))
(error-action [env]
(log/error "...creating post failed!")
(log/error env))
(remote [{:keys [state] :as env}] true))
(def not-empty? (complement empty?))
(defsc PostForm [this {:post/keys [id title body] :as props}]
{:query [:post/id :post/title :post/body fs/form-config-join]
:initial-state (fn [_]
(fs/add-form-config PostForm
{:post/title ""
:post/body ""}))
:form-fields #{:post/title :post/body}
:ident :post/id}
(let [title-validity (fs/get-spec-validity props :post/title)
body-validity (fs/get-spec-validity props :post/body)
validity (conj #{} title-validity body-validity)
submit! (fn [evt]
(when (or (identical? true evt) (evt/enter-key? evt))
(comp/transact! this `[(fs/mark-complete! {})])
(when (= #{:valid} validity)
(comp/transact! this `[(create-post! {:post/tempid ~id :post/title ~title :post/body ~body})]))))
cancel #(comp/transact! this [(clear-post-form {:id id})])]
(div :.ui.form {:classes [(when (subset? #{:invalid} validity) "error")]}
(field {:label "Title"
:value (or title "")
:valid? (contains? #{:valid :unchecked} title-validity)
:error-message "Must be at least 3 char long"
:autoComplete "off"
:onBlur #(comp/transact! this `[(fs/mark-complete! {:field :post/title})])
:onKeyDown submit!
:onChange #(do
(m/set-string! this :post/title :event %))})
(field {:label "Body"
:value (or body "")
:valid? (contains? #{:valid :unchecked} body-validity)
:error-message "Cannot be blank"
:onKeyDown submit!
:autoComplete "off"
:onChange #(do
(comp/transact! this `[(fs/mark-complete! {:field :post/body})])
(m/set-string! this :post/body :event %))})
(dom/button :.ui.primary.button {:onClick #(submit! true) :disabled (->> validity
(intersection #{:invalid :unchecked})
not-empty?)}
"Create")
(dom/button :.ui.secondary.button {:onClick cancel} "Cancel"))))
(def ui-post-form (comp/factory PostForm))
| null | https://raw.githubusercontent.com/roterski/syncrate-fulcro/3fda40b12973e64c7ff976174498ec512b411323/src/main/app/posts/ui/post_form.cljs | clojure | (ns app.posts.ui.post-form
(:require
[app.posts.validations]
[app.routing :refer [route-to!]]
[app.ui.components :refer [field]]
[clojure.set :refer [intersection subset?]]
[com.fulcrologic.fulcro.dom :as dom :refer [div ul li p h1 h3 button]]
[com.fulcrologic.fulcro.dom.events :as evt]
[com.fulcrologic.fulcro.components :as prim :refer [defsc]]
[com.fulcrologic.fulcro.components :as comp]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[com.fulcrologic.fulcro.algorithms.tempid :refer [tempid]]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro-css.css :as css]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[com.fulcrologic.fulcro.algorithms.form-state :as fs]))
(declare PostForm)
(defn add-post*
[state-map {:post/keys [id] :as props}]
(let [post-ident [:post/id id]]
(-> state-map
(assoc-in post-ident props)
(assoc-in [:component/id :new-post-page :new-post-page/post] post-ident))))
(defmutation add-post-form
[props]
(action [{:keys [state]}]
(let [post-id (tempid)]
(log/info "Adding post form")
(swap! state (fn [s]
(-> s
(add-post* (merge {:post/id post-id :post/body "" :post/title ""} props))
(fs/add-form-config* PostForm [:post/id post-id])))))))
(defn clear-post-form*
[state-map id]
(let [post-ident [:post/id id]
form-ident {:table :post/id :row id}]
(-> state-map
(update-in post-ident
merge
{:post/title ""
:post/body ""})
(assoc-in [::fs/forms-by-ident form-ident ::fs/complete?] #{}))))
(defmutation clear-post-form [{:keys [id]}]
(action [{:keys [state]}]
(swap! state (fn [s]
(-> s
(clear-post-form* id))))))
(defmutation create-post! [{:post/keys [tempid]}]
(action [{:keys [state]}]
(log/info "Creating post..."))
(ok-action [{:keys [app state result] :as params}]
(log/info "...post created successfully!")
(swap! state (fn [s]
(-> s
(update-in [::fs/forms-by-ident] dissoc {:table :post/id :row tempid})
(assoc-in [:component/id :new-post-page :new-post-page/post] nil))))
(route-to! "/posts/all/page/1"))
(error-action [env]
(log/error "...creating post failed!")
(log/error env))
(remote [{:keys [state] :as env}] true))
(def not-empty? (complement empty?))
(defsc PostForm [this {:post/keys [id title body] :as props}]
{:query [:post/id :post/title :post/body fs/form-config-join]
:initial-state (fn [_]
(fs/add-form-config PostForm
{:post/title ""
:post/body ""}))
:form-fields #{:post/title :post/body}
:ident :post/id}
(let [title-validity (fs/get-spec-validity props :post/title)
body-validity (fs/get-spec-validity props :post/body)
validity (conj #{} title-validity body-validity)
submit! (fn [evt]
(when (or (identical? true evt) (evt/enter-key? evt))
(comp/transact! this `[(fs/mark-complete! {})])
(when (= #{:valid} validity)
(comp/transact! this `[(create-post! {:post/tempid ~id :post/title ~title :post/body ~body})]))))
cancel #(comp/transact! this [(clear-post-form {:id id})])]
(div :.ui.form {:classes [(when (subset? #{:invalid} validity) "error")]}
(field {:label "Title"
:value (or title "")
:valid? (contains? #{:valid :unchecked} title-validity)
:error-message "Must be at least 3 char long"
:autoComplete "off"
:onBlur #(comp/transact! this `[(fs/mark-complete! {:field :post/title})])
:onKeyDown submit!
:onChange #(do
(m/set-string! this :post/title :event %))})
(field {:label "Body"
:value (or body "")
:valid? (contains? #{:valid :unchecked} body-validity)
:error-message "Cannot be blank"
:onKeyDown submit!
:autoComplete "off"
:onChange #(do
(comp/transact! this `[(fs/mark-complete! {:field :post/body})])
(m/set-string! this :post/body :event %))})
(dom/button :.ui.primary.button {:onClick #(submit! true) :disabled (->> validity
(intersection #{:invalid :unchecked})
not-empty?)}
"Create")
(dom/button :.ui.secondary.button {:onClick cancel} "Cancel"))))
(def ui-post-form (comp/factory PostForm))
|
|
5283b74427aa11e90f17d97245967923dfbe1cd3846dfea39af6a59936a2da2f | garipovroma/hi | Action.hs | # LANGUAGE DeriveFunctor #
module HW3.Action
(HiPermission(..), PermissionException(..), HIO(..))
where
import Control.Exception (Exception, throwIO)
import Control.Monad (ap)
import Data.ByteString (readFile, writeFile)
import Data.Sequence (fromList)
import Data.Set (Set, member)
import Data.Text (pack, unpack)
import Data.Text.Encoding (decodeUtf8')
import Data.Time (getCurrentTime)
import HW3.Base (HiAction (..), HiMonad (runAction), HiValue (..))
import System.Directory (createDirectory, doesFileExist, getCurrentDirectory, listDirectory,
setCurrentDirectory)
import System.Random (getStdRandom, uniformR)
data HiPermission =
AllowRead
| AllowWrite
| AllowTime deriving (Eq, Ord, Show)
data PermissionException =
PermissionRequired HiPermission deriving Show
instance Exception PermissionException
newtype HIO a = HIO { runHIO :: Set HiPermission -> IO a } deriving Functor
instance Applicative HIO where
pure = return
x <*> y = do { a <- x; a <$> y;}
instance Monad HIO where
return x = HIO (\_ -> return x)
h >>= x = HIO (\perms -> do
y <- runHIO h perms
runHIO (x y) perms)
instance HiMonad HIO where
runAction (HiActionRead path) =
HIO $ \perms ->
if not (member AllowRead perms) then
throwIO $ PermissionRequired AllowRead
else
do
flag <- doesFileExist path
(if flag then do
content <- Data.ByteString.readFile path
case decodeUtf8' content of
Left exception -> return $ HiValueBytes content
Right value -> return $ HiValueString value
else
do
kek <- listDirectory path
return $ HiValueList $ (fromList . map (HiValueString . pack)) kek)
runAction (HiActionWrite path bytes) =
HIO $ \perms ->
if not (member AllowWrite perms) then
throwIO $ PermissionRequired AllowWrite
else
do
Data.ByteString.writeFile path bytes
return HiValueNull
runAction HiActionCwd =
HIO $ \perms ->
if not (member AllowRead perms)
then throwIO $ PermissionRequired AllowRead
else
HiValueString . pack <$> getCurrentDirectory
runAction (HiActionChDir path) =
HIO $ \perms ->
if not (member AllowRead perms)
then throwIO $ PermissionRequired AllowRead
else
do
setCurrentDirectory path
return HiValueNull
runAction (HiActionMkDir path) =
HIO $ \perms ->
if not (member AllowWrite perms)
then throwIO $ PermissionRequired AllowWrite
else
do
createDirectory path
return HiValueNull
runAction HiActionNow =
HIO $ \perms ->
if not (member AllowTime perms)
then throwIO $ PermissionRequired AllowTime
else
HiValueTime <$> getCurrentTime
runAction (HiActionRand x y) =
HIO $ \perms ->
do
value <- getStdRandom (uniformR (x, y))
return $ HiValueNumber $ toRational value
runAction (HiActionEcho x) =
HIO $ \perms ->
if not (member AllowWrite perms)
then throwIO $ PermissionRequired AllowWrite
else
do
putStrLn $ unpack x
return HiValueNull
| null | https://raw.githubusercontent.com/garipovroma/hi/8fd0db19afa260083c6c3b39a622ff491c32013a/hw3/src/HW3/Action.hs | haskell | # LANGUAGE DeriveFunctor #
module HW3.Action
(HiPermission(..), PermissionException(..), HIO(..))
where
import Control.Exception (Exception, throwIO)
import Control.Monad (ap)
import Data.ByteString (readFile, writeFile)
import Data.Sequence (fromList)
import Data.Set (Set, member)
import Data.Text (pack, unpack)
import Data.Text.Encoding (decodeUtf8')
import Data.Time (getCurrentTime)
import HW3.Base (HiAction (..), HiMonad (runAction), HiValue (..))
import System.Directory (createDirectory, doesFileExist, getCurrentDirectory, listDirectory,
setCurrentDirectory)
import System.Random (getStdRandom, uniformR)
data HiPermission =
AllowRead
| AllowWrite
| AllowTime deriving (Eq, Ord, Show)
data PermissionException =
PermissionRequired HiPermission deriving Show
instance Exception PermissionException
newtype HIO a = HIO { runHIO :: Set HiPermission -> IO a } deriving Functor
instance Applicative HIO where
pure = return
x <*> y = do { a <- x; a <$> y;}
instance Monad HIO where
return x = HIO (\_ -> return x)
h >>= x = HIO (\perms -> do
y <- runHIO h perms
runHIO (x y) perms)
instance HiMonad HIO where
runAction (HiActionRead path) =
HIO $ \perms ->
if not (member AllowRead perms) then
throwIO $ PermissionRequired AllowRead
else
do
flag <- doesFileExist path
(if flag then do
content <- Data.ByteString.readFile path
case decodeUtf8' content of
Left exception -> return $ HiValueBytes content
Right value -> return $ HiValueString value
else
do
kek <- listDirectory path
return $ HiValueList $ (fromList . map (HiValueString . pack)) kek)
runAction (HiActionWrite path bytes) =
HIO $ \perms ->
if not (member AllowWrite perms) then
throwIO $ PermissionRequired AllowWrite
else
do
Data.ByteString.writeFile path bytes
return HiValueNull
runAction HiActionCwd =
HIO $ \perms ->
if not (member AllowRead perms)
then throwIO $ PermissionRequired AllowRead
else
HiValueString . pack <$> getCurrentDirectory
runAction (HiActionChDir path) =
HIO $ \perms ->
if not (member AllowRead perms)
then throwIO $ PermissionRequired AllowRead
else
do
setCurrentDirectory path
return HiValueNull
runAction (HiActionMkDir path) =
HIO $ \perms ->
if not (member AllowWrite perms)
then throwIO $ PermissionRequired AllowWrite
else
do
createDirectory path
return HiValueNull
runAction HiActionNow =
HIO $ \perms ->
if not (member AllowTime perms)
then throwIO $ PermissionRequired AllowTime
else
HiValueTime <$> getCurrentTime
runAction (HiActionRand x y) =
HIO $ \perms ->
do
value <- getStdRandom (uniformR (x, y))
return $ HiValueNumber $ toRational value
runAction (HiActionEcho x) =
HIO $ \perms ->
if not (member AllowWrite perms)
then throwIO $ PermissionRequired AllowWrite
else
do
putStrLn $ unpack x
return HiValueNull
|
|
62ef6379de27c46767ad2439ab2bff4fc3cfab1c202452a29a471ee48b658898 | google/rysim | parsers.erl | %%%-------------------------------------------------------------------
Copyright 2014 The RySim Authors . All rights reserved .
%%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%% -2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%%
%%% @doc
%%% Wrapper that allows other modules to call into the parsing code without
%%% having to know the horrible internals of the parsing functions.
%%% @end
%%%-------------------------------------------------------------------
-module(parsers).
%% API
-export([init/0, process_experiment/1, process_model/1]).
%% ===================================================================
%% API
%% ===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Make the calls that are needed to get the application that the
%% parsing code depends initialized.
@spec init ( ) - > ok
%% @end
%% --------------------------------------------------------------------
init() ->
application:load(jsx),
application:start(jsx),
ok.
%%--------------------------------------------------------------------
%% @doc
%% Call into the appropriate module to parse the given experiment file.
process_experiment(File : : string ( ) ) - > ExperimentConfig
%% Experiment = record(experiment_config)
%% @end
%% --------------------------------------------------------------------
process_experiment(File) ->
parsers_experiment:process(File).
%%--------------------------------------------------------------------
%% @doc
%% Call into the appropriate module to parse the given model
%% file. Currently only SEIR is implemented.
process_model(File : : string ( ) ) - > Model
%% Model = record(model_config)
%% @end
%% --------------------------------------------------------------------
process_model(File) ->
parsers_model:process(File). | null | https://raw.githubusercontent.com/google/rysim/afe19cea6415eb9d17e97f2f67280cf0b92eaa6e/erlang/rysim_des_actor_smp/src/parsers.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
Wrapper that allows other modules to call into the parsing code without
having to know the horrible internals of the parsing functions.
@end
-------------------------------------------------------------------
API
===================================================================
API
===================================================================
--------------------------------------------------------------------
@doc
Make the calls that are needed to get the application that the
parsing code depends initialized.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Call into the appropriate module to parse the given experiment file.
Experiment = record(experiment_config)
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Call into the appropriate module to parse the given model
file. Currently only SEIR is implemented.
Model = record(model_config)
@end
-------------------------------------------------------------------- | Copyright 2014 The RySim Authors . 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(parsers).
-export([init/0, process_experiment/1, process_model/1]).
@spec init ( ) - > ok
init() ->
application:load(jsx),
application:start(jsx),
ok.
process_experiment(File : : string ( ) ) - > ExperimentConfig
process_experiment(File) ->
parsers_experiment:process(File).
process_model(File : : string ( ) ) - > Model
process_model(File) ->
parsers_model:process(File). |
c1c1c1d13637ad065ec821a9492779b6e6789243eec7ada8aa550c41dcb5f918 | lpeterse/haskell-ssh | Client.hs | {-# LANGUAGE OverloadedStrings #-}
module Spec.Client ( tests ) where
import Test.Tasty
tests :: TestTree
tests = testGroup "Network.SSH.Client" []
| null | https://raw.githubusercontent.com/lpeterse/haskell-ssh/d1a614b6bf30c4932ee5a66efcae6e71680b4819/test/Spec/Client.hs | haskell | # LANGUAGE OverloadedStrings # | module Spec.Client ( tests ) where
import Test.Tasty
tests :: TestTree
tests = testGroup "Network.SSH.Client" []
|
5302f058675e2656dc0877d6f83ec5f2de4e5b9885b247c9c7ae6df285c74b6b | 3b/3bgl-misc | test-shader.lisp | (cl:defpackage #:scenegraph-test-shaders
(:use :3bgl-glsl/cl))
(cl:in-package #:scenegraph-test-shaders)
(input position :vec4 :location 0)
(input normal :vec3 :location 1)
(input color :vec4 :location 2)
;; final output
(output out-color :vec4 :stage :fragment)
(uniform mv :mat4)
(uniform mvp :mat4)
(interface varyings (:out (:vertex outs)
:in (:fragment ins))
(color :vec4))
(defun vertex ()
(setf gl-position (* mvp position))
#++(setf (@ outs color) (vec4 normal 1.0))
(setf (@ outs color) color))
(defun fragment ()
(let ((a (.a (@ ins color))))
(setf out-color (vec4 (* a (.xyz (@ ins color))) a))))
| null | https://raw.githubusercontent.com/3b/3bgl-misc/e3bf2781d603feb6b44e5c4ec20f06225648ffd9/scenegraph/test-shader.lisp | lisp | final output | (cl:defpackage #:scenegraph-test-shaders
(:use :3bgl-glsl/cl))
(cl:in-package #:scenegraph-test-shaders)
(input position :vec4 :location 0)
(input normal :vec3 :location 1)
(input color :vec4 :location 2)
(output out-color :vec4 :stage :fragment)
(uniform mv :mat4)
(uniform mvp :mat4)
(interface varyings (:out (:vertex outs)
:in (:fragment ins))
(color :vec4))
(defun vertex ()
(setf gl-position (* mvp position))
#++(setf (@ outs color) (vec4 normal 1.0))
(setf (@ outs color) color))
(defun fragment ()
(let ((a (.a (@ ins color))))
(setf out-color (vec4 (* a (.xyz (@ ins color))) a))))
|
376beab80d6c37ad85b7ef683d9c28229df1925ae2a4880283f6cf8c0534ecc0 | ocaml/ocaml-re | posix.mli |
RE - A regular expression library
Copyright ( C ) 2001
email :
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation , with
linking exception ; either version 2.1 of the License , or ( at
your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
RE - A regular expression library
Copyright (C) 2001 Jerome Vouillon
email:
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, with
linking exception; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
*
References :
- { { : } re }
- { { : } regcomp }
Example of how to use this module ( to parse some IRC logs ):
{ [
type msg = {
time : string ;
author : string ;
content : string ;
}
let re = Core.compile ( " ( [ ^:].*:[^:]*:[^:]{2})<.([^>]+ ) > ( .+)$ " )
( * parse a line
References:
- {{: } re}
- {{: } regcomp}
Example of how to use this module (to parse some IRC logs):
{[
type msg = {
time:string;
author:string;
content:string;
}
let re = Core.compile (Re_posix.re "([^:].*:[^:]*:[^:]{2})<.([^>]+)> (.+)$")
(* parse a line *)
let match_line line =
try
let substrings = Core.exec re line in
let groups = Core.get_all substrings in
(* groups can be obtained directly by index within [substrings] *)
Some {time=groups.(1); author=groups.(2); content=groups.(3)}
with Not_found ->
None (* regex didn't match *)
]}
*)
(* XXX Character classes *)
exception Parse_error
exception Not_supported
(** Errors that can be raised during the parsing of the regular expression *)
type opt = [`ICase | `NoSub | `Newline]
val re : ?opts:(opt list) -> string -> Core.t
* Parsing of a extended regular expression
val compile : Core.t -> Core.re
(** [compile r] is defined as [Core.compile (Core.longest r)] *)
val compile_pat : ?opts:(opt list) -> string -> Core.re
* [ compile_pat ? opts regex ] compiles the extended regular expression [ regexp ]
Deviation from the standard / ambiguities in the standard
---------------------------------------------------------
We tested the behavior of the Linux library ( glibc ) and the Solaris
library .
( 1 ) An expression [ efg ] should be parsed as [ ( ef)g ] .
All implementations parse it as [ e(fg ) ] .
( 2 ) When matching the pattern " ( ( a)|b ) * " against the string " ab " ,
the sub - expression " ( ( a)|b ) " should match " b " , and the
sub - expression " ( a ) " should not match anything .
In both implementation , the sub - expression " ( a ) " matches " a " .
( 3 ) When matching the pattern " ( aa ? ) * " against the string " aaa " , it is
not clear whether the final match of the sub - expression " ( aa ? ) " is
the last " a " ( all matches of the sub - expression are successively
maximized ) , or " aa " ( the final match is maximized ) .
Both implementations implements the first case .
( 4 ) When matching the pattern " ( ( a?)|b ) * " against the string " ab " ,
the sub - expression " ( ( a?)|b ) " should match the empty string at the
end of the string ( it is better to match the empty string than to
match nothing ) .
In both implementations , this sub - expression matches " b " .
( Strangely , in the Linux implementation , the sub - expression " ( a ? ) "
correctly matches the empty string at the end of the string )
This library behaves the same way as the other libraries for all
points , except for ( 2 ) and ( 4 ) where it follows the standard .
The behavior of this library in theses four cases may change in future
releases .
Deviation from the standard / ambiguities in the standard
---------------------------------------------------------
We tested the behavior of the Linux library (glibc) and the Solaris
library.
(1) An expression [efg] should be parsed as [(ef)g].
All implementations parse it as [e(fg)].
(2) When matching the pattern "((a)|b)*" against the string "ab",
the sub-expression "((a)|b)" should match "b", and the
sub-expression "(a)" should not match anything.
In both implementation, the sub-expression "(a)" matches "a".
(3) When matching the pattern "(aa?)*" against the string "aaa", it is
not clear whether the final match of the sub-expression "(aa?)" is
the last "a" (all matches of the sub-expression are successively
maximized), or "aa" (the final match is maximized).
Both implementations implements the first case.
(4) When matching the pattern "((a?)|b)*" against the string "ab",
the sub-expression "((a?)|b)" should match the empty string at the
end of the string (it is better to match the empty string than to
match nothing).
In both implementations, this sub-expression matches "b".
(Strangely, in the Linux implementation, the sub-expression "(a?)"
correctly matches the empty string at the end of the string)
This library behaves the same way as the other libraries for all
points, except for (2) and (4) where it follows the standard.
The behavior of this library in theses four cases may change in future
releases.
*)
| null | https://raw.githubusercontent.com/ocaml/ocaml-re/55f9478e64cb65ce583e586f2ed3837677530ddb/lib/posix.mli | ocaml | parse a line
groups can be obtained directly by index within [substrings]
regex didn't match
XXX Character classes
* Errors that can be raised during the parsing of the regular expression
* [compile r] is defined as [Core.compile (Core.longest r)] |
RE - A regular expression library
Copyright ( C ) 2001
email :
This library is free software ; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation , with
linking exception ; either version 2.1 of the License , or ( at
your option ) any later version .
This library is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
RE - A regular expression library
Copyright (C) 2001 Jerome Vouillon
email:
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, with
linking exception; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
*
References :
- { { : } re }
- { { : } regcomp }
Example of how to use this module ( to parse some IRC logs ):
{ [
type msg = {
time : string ;
author : string ;
content : string ;
}
let re = Core.compile ( " ( [ ^:].*:[^:]*:[^:]{2})<.([^>]+ ) > ( .+)$ " )
( * parse a line
References:
- {{: } re}
- {{: } regcomp}
Example of how to use this module (to parse some IRC logs):
{[
type msg = {
time:string;
author:string;
content:string;
}
let re = Core.compile (Re_posix.re "([^:].*:[^:]*:[^:]{2})<.([^>]+)> (.+)$")
let match_line line =
try
let substrings = Core.exec re line in
let groups = Core.get_all substrings in
Some {time=groups.(1); author=groups.(2); content=groups.(3)}
with Not_found ->
]}
*)
exception Parse_error
exception Not_supported
type opt = [`ICase | `NoSub | `Newline]
val re : ?opts:(opt list) -> string -> Core.t
* Parsing of a extended regular expression
val compile : Core.t -> Core.re
val compile_pat : ?opts:(opt list) -> string -> Core.re
* [ compile_pat ? opts regex ] compiles the extended regular expression [ regexp ]
Deviation from the standard / ambiguities in the standard
---------------------------------------------------------
We tested the behavior of the Linux library ( glibc ) and the Solaris
library .
( 1 ) An expression [ efg ] should be parsed as [ ( ef)g ] .
All implementations parse it as [ e(fg ) ] .
( 2 ) When matching the pattern " ( ( a)|b ) * " against the string " ab " ,
the sub - expression " ( ( a)|b ) " should match " b " , and the
sub - expression " ( a ) " should not match anything .
In both implementation , the sub - expression " ( a ) " matches " a " .
( 3 ) When matching the pattern " ( aa ? ) * " against the string " aaa " , it is
not clear whether the final match of the sub - expression " ( aa ? ) " is
the last " a " ( all matches of the sub - expression are successively
maximized ) , or " aa " ( the final match is maximized ) .
Both implementations implements the first case .
( 4 ) When matching the pattern " ( ( a?)|b ) * " against the string " ab " ,
the sub - expression " ( ( a?)|b ) " should match the empty string at the
end of the string ( it is better to match the empty string than to
match nothing ) .
In both implementations , this sub - expression matches " b " .
( Strangely , in the Linux implementation , the sub - expression " ( a ? ) "
correctly matches the empty string at the end of the string )
This library behaves the same way as the other libraries for all
points , except for ( 2 ) and ( 4 ) where it follows the standard .
The behavior of this library in theses four cases may change in future
releases .
Deviation from the standard / ambiguities in the standard
---------------------------------------------------------
We tested the behavior of the Linux library (glibc) and the Solaris
library.
(1) An expression [efg] should be parsed as [(ef)g].
All implementations parse it as [e(fg)].
(2) When matching the pattern "((a)|b)*" against the string "ab",
the sub-expression "((a)|b)" should match "b", and the
sub-expression "(a)" should not match anything.
In both implementation, the sub-expression "(a)" matches "a".
(3) When matching the pattern "(aa?)*" against the string "aaa", it is
not clear whether the final match of the sub-expression "(aa?)" is
the last "a" (all matches of the sub-expression are successively
maximized), or "aa" (the final match is maximized).
Both implementations implements the first case.
(4) When matching the pattern "((a?)|b)*" against the string "ab",
the sub-expression "((a?)|b)" should match the empty string at the
end of the string (it is better to match the empty string than to
match nothing).
In both implementations, this sub-expression matches "b".
(Strangely, in the Linux implementation, the sub-expression "(a?)"
correctly matches the empty string at the end of the string)
This library behaves the same way as the other libraries for all
points, except for (2) and (4) where it follows the standard.
The behavior of this library in theses four cases may change in future
releases.
*)
|
37a717983ecc47160a0899e8043dae3d0cdbd273dbb5dc0664ed9653558fd1c3 | c-cube/tiny_httpd | Tiny_httpd_buf.mli |
* Simple buffer .
These buffers are used to avoid allocating too many byte arrays when
processing streams and parsing requests .
@since 0.12
These buffers are used to avoid allocating too many byte arrays when
processing streams and parsing requests.
@since 0.12
*)
type t
val size : t -> int
val clear : t -> unit
val create : ?size:int -> unit -> t
val contents : t -> string
val bytes_slice : t -> bytes
* Access underlying slice of bytes .
@since 0.5
@since 0.5 *)
val contents_and_clear : t -> string
* Get contents of the buffer and clear it .
@since 0.5
@since 0.5 *)
val add_bytes : t -> bytes -> int -> int -> unit
* Append given bytes slice to the buffer .
@since 0.5
@since 0.5 *)
| null | https://raw.githubusercontent.com/c-cube/tiny_httpd/211d40a4b76a10a3d827fd11b2fa6db5dcc05772/src/Tiny_httpd_buf.mli | ocaml |
* Simple buffer .
These buffers are used to avoid allocating too many byte arrays when
processing streams and parsing requests .
@since 0.12
These buffers are used to avoid allocating too many byte arrays when
processing streams and parsing requests.
@since 0.12
*)
type t
val size : t -> int
val clear : t -> unit
val create : ?size:int -> unit -> t
val contents : t -> string
val bytes_slice : t -> bytes
* Access underlying slice of bytes .
@since 0.5
@since 0.5 *)
val contents_and_clear : t -> string
* Get contents of the buffer and clear it .
@since 0.5
@since 0.5 *)
val add_bytes : t -> bytes -> int -> int -> unit
* Append given bytes slice to the buffer .
@since 0.5
@since 0.5 *)
|
|
ade04fe39fbecef02afde996a3462ce5aba1db16df7ad8ac36462ad5531e3fc6 | roterski/syncrate-fulcro | post_show_page.cljs | (ns app.posts.ui.post-show-page
(:require
[app.posts.ui.post :refer [Post ui-post]]
[app.profiles.ui.profile :refer [Profile]]
[app.auth.ui.session :refer [Session]]
[app.comments.ui.new-comment-button :refer [ui-new-comment-button]]
[app.comments.ui.comment :refer [ui-comment Comment]]
[app.comments.ui.comment-form :refer [ui-comment-form]]
[app.application :refer [SPA]]
[com.fulcrologic.fulcro.application :as app]
[com.fulcrologic.fulcro.algorithms.denormalize :as dn]
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]
[com.fulcrologic.fulcro.dom :as dom :refer [div h1 h2 button]]
[com.fulcrologic.fulcro.components :as prim :refer [defsc]]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.components :as comp]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro-css.css :as css]))
(defsc PostShowPage [this {:post/keys [id title body profile new-comment comments] :keys [current-session] :as props}]
{:query [:post/id :post/title :post/body {:post/profile (comp/get-query Profile)}
{:post/comments (comp/get-query Comment)}
{:post/new-comment (comp/get-query Comment)}
{[:current-session '_] (comp/get-query Session)}]
:ident :post/id
:route-segment ["posts" :id]
:will-enter (fn [app {:keys [id]}]
(dr/route-deferred [:post/id id]
#(df/load app [:post/id id] PostShowPage
{:without #{[:current-session '_]}
:post-mutation `dr/target-ready
:post-mutation-params {:target [:post/id id]}})))}
(div :.ui.container.segment
(h1 "Post")
(ui-post props)
(when (:session/valid? current-session)
(ui-new-comment-button this {:new-comment new-comment :post id :parent nil}))
(h2 "Comments")
(map ui-comment comments)))
(comment
(let [state (app/current-state SPA)
query (comp/get-query PostShow)
post-id "5f7133f2-8701-46b6-9d30-a4f08e7f2e58"
ident [:post/id (keyword "post.id" post-id)]
post (dn/db->tree query ident state)
comments (:post/comments post)
comment-id (:comment/id (first comments))
filter-fn (fn [comment] (tempid/tempid? (:comment/id comment)))
temp-comments (filter filter-fn comments)
temp-comment (first (filter filter-fn comments))
saved-comments (filter (fn [comment] (not (filter-fn comment))) comments)]
(def st state)))
| null | https://raw.githubusercontent.com/roterski/syncrate-fulcro/3fda40b12973e64c7ff976174498ec512b411323/src/main/app/posts/ui/post_show_page.cljs | clojure | (ns app.posts.ui.post-show-page
(:require
[app.posts.ui.post :refer [Post ui-post]]
[app.profiles.ui.profile :refer [Profile]]
[app.auth.ui.session :refer [Session]]
[app.comments.ui.new-comment-button :refer [ui-new-comment-button]]
[app.comments.ui.comment :refer [ui-comment Comment]]
[app.comments.ui.comment-form :refer [ui-comment-form]]
[app.application :refer [SPA]]
[com.fulcrologic.fulcro.application :as app]
[com.fulcrologic.fulcro.algorithms.denormalize :as dn]
[com.fulcrologic.fulcro.algorithms.tempid :as tempid]
[com.fulcrologic.fulcro.dom :as dom :refer [div h1 h2 button]]
[com.fulcrologic.fulcro.components :as prim :refer [defsc]]
[com.fulcrologic.fulcro.routing.dynamic-routing :as dr]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.components :as comp]
[com.fulcrologic.fulcro.mutations :as m :refer [defmutation]]
[taoensso.timbre :as log]
[com.fulcrologic.fulcro-css.css :as css]))
(defsc PostShowPage [this {:post/keys [id title body profile new-comment comments] :keys [current-session] :as props}]
{:query [:post/id :post/title :post/body {:post/profile (comp/get-query Profile)}
{:post/comments (comp/get-query Comment)}
{:post/new-comment (comp/get-query Comment)}
{[:current-session '_] (comp/get-query Session)}]
:ident :post/id
:route-segment ["posts" :id]
:will-enter (fn [app {:keys [id]}]
(dr/route-deferred [:post/id id]
#(df/load app [:post/id id] PostShowPage
{:without #{[:current-session '_]}
:post-mutation `dr/target-ready
:post-mutation-params {:target [:post/id id]}})))}
(div :.ui.container.segment
(h1 "Post")
(ui-post props)
(when (:session/valid? current-session)
(ui-new-comment-button this {:new-comment new-comment :post id :parent nil}))
(h2 "Comments")
(map ui-comment comments)))
(comment
(let [state (app/current-state SPA)
query (comp/get-query PostShow)
post-id "5f7133f2-8701-46b6-9d30-a4f08e7f2e58"
ident [:post/id (keyword "post.id" post-id)]
post (dn/db->tree query ident state)
comments (:post/comments post)
comment-id (:comment/id (first comments))
filter-fn (fn [comment] (tempid/tempid? (:comment/id comment)))
temp-comments (filter filter-fn comments)
temp-comment (first (filter filter-fn comments))
saved-comments (filter (fn [comment] (not (filter-fn comment))) comments)]
(def st state)))
|
|
df53f61914bd8b5e58065d43a701cdd39483ecf0bfa797828f72dd747b69390b | haskell-opengl/OpenGLRaw | Subtexture.hs | --------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.Subtexture
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer : < >
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.Subtexture (
-- * Extension Support
glGetEXTSubtexture,
gl_EXT_subtexture,
-- * Functions
glTexSubImage1DEXT,
glTexSubImage2DEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Functions
| null | https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/EXT/Subtexture.hs | haskell | ------------------------------------------------------------------------------
|
Module : Graphics.GL.EXT.Subtexture
License : BSD3
Stability : stable
Portability : portable
------------------------------------------------------------------------------
* Extension Support
* Functions | Copyright : ( c ) 2019
Maintainer : < >
module Graphics.GL.EXT.Subtexture (
glGetEXTSubtexture,
gl_EXT_subtexture,
glTexSubImage1DEXT,
glTexSubImage2DEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Functions
|
9b100ea0f2f3d9d6e474dca56a3f513de2dce93246f6982557810bacfc4c00f9 | janestreet/memtrace_viewer_with_deps | unit.ml | module Stable = struct
open Base.Export
open Bin_prot.Std
module V1 = struct
module T = struct
type t = unit [@@deriving bin_io, compare, sexp]
end
include T
include Comparator.Stable.V1.Make (T)
let%expect_test _ =
print_endline [%bin_digest: t];
[%expect {| 86ba5df747eec837f0b391dd49f33f9e |}]
;;
end
end
open! Import
include Identifiable.Extend
(Base.Unit)
(struct
type t = unit [@@deriving bin_io]
end)
include Base.Unit
type t = unit [@@deriving typerep]
let quickcheck_generator = Base_quickcheck.Generator.unit
let quickcheck_observer = Base_quickcheck.Observer.unit
let quickcheck_shrinker = Base_quickcheck.Shrinker.unit
module type S = sig end
type m = (module S)
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/core_kernel/src/unit.ml | ocaml | module Stable = struct
open Base.Export
open Bin_prot.Std
module V1 = struct
module T = struct
type t = unit [@@deriving bin_io, compare, sexp]
end
include T
include Comparator.Stable.V1.Make (T)
let%expect_test _ =
print_endline [%bin_digest: t];
[%expect {| 86ba5df747eec837f0b391dd49f33f9e |}]
;;
end
end
open! Import
include Identifiable.Extend
(Base.Unit)
(struct
type t = unit [@@deriving bin_io]
end)
include Base.Unit
type t = unit [@@deriving typerep]
let quickcheck_generator = Base_quickcheck.Generator.unit
let quickcheck_observer = Base_quickcheck.Observer.unit
let quickcheck_shrinker = Base_quickcheck.Shrinker.unit
module type S = sig end
type m = (module S)
|
|
b6f0f9efa6c19cd11069ac843f9e7e1e588e197d0853de1ece494ba371f89a0c | yminer/libml | check.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[ LibML - Machine Learning Library ]
Copyright ( C ) 2002 - 2003 LAGACHERIE
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
of the License , or ( at your option ) any later version . This
program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details . You should have
received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 ,
USA .
SPECIAL NOTE ( the beerware clause ):
This software is free software . However , it also falls under the beerware
special category . That is , if you find this software useful , or use it
every day , or want to grant us for our modest contribution to the
free software community , feel free to send us a beer from one of
your local brewery . Our preference goes to Belgium abbey beers and
irish stout ( Guiness for strength ! ) , but we like to try new stuffs .
Authors :
E - mail : RICORDEAU
E - mail :
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[LibML - Machine Learning Library]
Copyright (C) 2002 - 2003 LAGACHERIE Matthieu RICORDEAU Olivier
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version. This
program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. You should have
received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.
SPECIAL NOTE (the beerware clause):
This software is free software. However, it also falls under the beerware
special category. That is, if you find this software useful, or use it
every day, or want to grant us for our modest contribution to the
free software community, feel free to send us a beer from one of
your local brewery. Our preference goes to Belgium abbey beers and
irish stout (Guiness for strength!), but we like to try new stuffs.
Authors:
Matthieu LAGACHERIE
E-mail :
Olivier RICORDEAU
E-mail :
****************************************************************)
*
Test program for the init module .
@author
@since 09/11/2003
Test program for the init module.
@author Matthieu Lagacherie
@since 09/11/2003
*)
open Env
open Pattern
open MlpNN
open TdNN
open InitTdnnVisitor
open InputTdnnVisitor
open PropagateTdnnVisitor
let tdnn = new tdNN;;
let initTdnn = new initTdnnVisitor;;
let inputTdnn = new inputTdnnVisitor;;
let pTdnn = new propagateTdnnVisitor;;
let pat = new pattern [|[|0.3;0.7;0.2;0.3;0.7;0.2;0.8;0.7;0.1;0.3;0.7;0.9|]|] [|[|0.42;0.2;0.1|]|];;
tdnn#addPattern pat;;
tdnn#setLayerNb 3;;
tdnn#setDelay [|1;1|];;
tdnn#setTimeNb [|12;10;6|];;
tdnn#setFeaturesNb [|1;8;4|];;
tdnn#setFieldSize [|3;5|];;
tdnn#accept initTdnn;;
tdnn#accept inputTdnn;;
tdnn#accept pTdnn;;
| null | https://raw.githubusercontent.com/yminer/libml/1475dd87c2c16983366fab62124e8bbfbbf2161b/src/nn/propagate/check.ml | ocaml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[ LibML - Machine Learning Library ]
Copyright ( C ) 2002 - 2003 LAGACHERIE
This program is free software ; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version 2
of the License , or ( at your option ) any later version . This
program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details . You should have
received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 ,
USA .
SPECIAL NOTE ( the beerware clause ):
This software is free software . However , it also falls under the beerware
special category . That is , if you find this software useful , or use it
every day , or want to grant us for our modest contribution to the
free software community , feel free to send us a beer from one of
your local brewery . Our preference goes to Belgium abbey beers and
irish stout ( Guiness for strength ! ) , but we like to try new stuffs .
Authors :
E - mail : RICORDEAU
E - mail :
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
[LibML - Machine Learning Library]
Copyright (C) 2002 - 2003 LAGACHERIE Matthieu RICORDEAU Olivier
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version. This
program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. You should have
received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.
SPECIAL NOTE (the beerware clause):
This software is free software. However, it also falls under the beerware
special category. That is, if you find this software useful, or use it
every day, or want to grant us for our modest contribution to the
free software community, feel free to send us a beer from one of
your local brewery. Our preference goes to Belgium abbey beers and
irish stout (Guiness for strength!), but we like to try new stuffs.
Authors:
Matthieu LAGACHERIE
E-mail :
Olivier RICORDEAU
E-mail :
****************************************************************)
*
Test program for the init module .
@author
@since 09/11/2003
Test program for the init module.
@author Matthieu Lagacherie
@since 09/11/2003
*)
open Env
open Pattern
open MlpNN
open TdNN
open InitTdnnVisitor
open InputTdnnVisitor
open PropagateTdnnVisitor
let tdnn = new tdNN;;
let initTdnn = new initTdnnVisitor;;
let inputTdnn = new inputTdnnVisitor;;
let pTdnn = new propagateTdnnVisitor;;
let pat = new pattern [|[|0.3;0.7;0.2;0.3;0.7;0.2;0.8;0.7;0.1;0.3;0.7;0.9|]|] [|[|0.42;0.2;0.1|]|];;
tdnn#addPattern pat;;
tdnn#setLayerNb 3;;
tdnn#setDelay [|1;1|];;
tdnn#setTimeNb [|12;10;6|];;
tdnn#setFeaturesNb [|1;8;4|];;
tdnn#setFieldSize [|3;5|];;
tdnn#accept initTdnn;;
tdnn#accept inputTdnn;;
tdnn#accept pTdnn;;
|
|
804f0df1521b3fb206f84b799636acd7c899d126e7fa30bd8606d706a2f58b82 | vseloved/cl-nlp | math.lisp | ( c ) 2013 - 2017 Vsevolod Dyomkin
(in-package #:nlp.util)
(named-readtables:in-readtable rutilsx-readtable)
(defparameter +inf most-positive-fixnum)
(defun argmax (fn vals
&key (test #'>) (key #'identity) (min (- most-positive-fixnum)))
"Return the val from VALS which is the argument for maximum value of FN under TEST.
If KEY is provided it's applied to VAL before feeding it to FN.
Also, MIN can be provided to correspond with the TEST fucntion (default: 0).
Also return the value of FN at VAL as a second value."
(let ((max min)
arg)
(dolist (v vals)
(let ((cur (or (funcall fn (funcall key v))
min)))
(when (funcall test cur max)
(setf max cur
arg v))))
(values arg
max)))
(defun keymax (ht
&key (test #'>) (key #'identity) (min (- most-positive-fixnum)))
"Return the key corresponding to the maximum of hash-table HT under TEST.
If KEY is provided it's applied to VAL before feeding it to FN.
Also, MIN can be provided to correspond with the TEST fucntion (default: 0).
Also return the value at this key as a second value."
(let ((max min)
arg)
(dotable (k v ht)
(let ((cur (or (funcall key v)
min)))
(when (funcall test cur max)
(:= max cur
arg k))))
(values arg
max)))
(defun bin-search (val vec test-less &key (start 0) end key test)
"Binary search for VAL in sorted vector VEC (the order property isn't checked).
Needs to specify TEST-LESS predicate. Handles START, END, KEY as usual.
It TEST is provided tests the value at the found position against VAL,
and returns nil if it returns nil."
(let ((low start)
(high (or end (1- (length vec)))))
(do ()
((= low high) (when (or (null test)
(funcall test val (svref vec high)))
(elt vec high)))
(let ((mid (floor (+ low high) 2)))
(if (funcall test-less (if key
(funcall key (svref vec mid))
(svref vec mid))
val)
(setf low (1+ mid))
(setf high mid))))))
(defun sum (fn xs &optional ys)
"Sum result of application of FN to each of XS (and optionally YS)."
(reduce '+ (if ys
(map 'list fn xs ys)
(map 'list fn xs))
:initial-value 0))
(defun frobenius-norm (m)
"Frobenius norm of matrix M."
(let ((rez 0))
(dotimes (i (array-dimension m 0))
(dotimes (j (array-dimension m 1))
(:+ rez (expt (aref m i j) 2))))))
(defun ~= (x y &key (epsilon 0.01))
"Approximately equality between X & Y to the margin EPSILON."
(< (abs (- x y)) epsilon))
(defun log-likelihood-ratio (ab a~b ~ab ~a~b)
"Calculate log-likelihood ratio between event A and B given
probabilites of A and B occurring together and separately."
(let ((total (+ ab a~b ~ab ~a~b)))
(* 2 total (- (entropy (list ab a~b ~ab ~a~b) total)
(entropy (list (+ ab a~b) (+ ~ab ~a~b)) total)
(entropy (list (+ ab ~ab) (+ a~b ~a~b)) total)))))
(defun sample (data n &key (with-replacement? t))
"Sample N elements from DATA (by default, WITH-REPLACEMENT?)."
(if (zerop n)
#()
(with ((vec (coerce data 'vector))
(len (length vec))
(int rem (floor n len)))
(if (plusp int)
(progn
(warn "Sample size exceeds data length: ~A > ~A" n len)
(nshuffle (apply 'concatenate 'vector
(sample data rem
:with-replacement? with-replacement?)
(loop :repeat int :collect vec))))
(coerce (if with-replacement?
(let ((rez (make-array n)))
(dotimes (i n)
(:= (? rez i) (? vec (random len))))
rez)
(subseq (nshuffle vec) 0 n))
(type-of data))))))
(defun resample (data label new &key key)
"Resample DATA so that the number of items with LABEL (determined by KEY)
equals to NEW (a number or a reference to another label,
in which case the number of items by it is used)."
(with ((sample (keep label data :key key))
(len (length sample)))
(coerce (nshuffle
(concatenate 'vector
(coerce (remove label data :key key) 'vector)
(coerce (loop :repeat
(if (numberp new) new
(let ((cc (count new data :key key)))
(when (zerop cc)
(warn "Label '~A' not found in data by ~A."
new key))
cc))
:collect (? sample (random len)))
'vector)))
'vector)))
(defun normal-random (&optional (mean 0.0) (std-dev 1.0))
"Generate a normal random number with the given MEAN and STD-DEV."
(do* ((rand-u (* 2 (- 0.5 (random 1.0))) (* 2 (- 0.5 (random 1.0))))
(rand-v (* 2 (- 0.5 (random 1.0))) (* 2 (- 0.5 (random 1.0))))
(rand-s (+ (* rand-u rand-u) (* rand-v rand-v))
(+ (* rand-u rand-u) (* rand-v rand-v))))
((not (or (= 0 rand-s) (>= rand-s 1)))
(+ mean
(* std-dev
(* rand-u (sqrt (/ (* -2.0 (log rand-s)) rand-s))))))))
| null | https://raw.githubusercontent.com/vseloved/cl-nlp/f180b6c3c0b9a3614ae43f53a11bc500767307d0/src/util/math.lisp | lisp | ( c ) 2013 - 2017 Vsevolod Dyomkin
(in-package #:nlp.util)
(named-readtables:in-readtable rutilsx-readtable)
(defparameter +inf most-positive-fixnum)
(defun argmax (fn vals
&key (test #'>) (key #'identity) (min (- most-positive-fixnum)))
"Return the val from VALS which is the argument for maximum value of FN under TEST.
If KEY is provided it's applied to VAL before feeding it to FN.
Also, MIN can be provided to correspond with the TEST fucntion (default: 0).
Also return the value of FN at VAL as a second value."
(let ((max min)
arg)
(dolist (v vals)
(let ((cur (or (funcall fn (funcall key v))
min)))
(when (funcall test cur max)
(setf max cur
arg v))))
(values arg
max)))
(defun keymax (ht
&key (test #'>) (key #'identity) (min (- most-positive-fixnum)))
"Return the key corresponding to the maximum of hash-table HT under TEST.
If KEY is provided it's applied to VAL before feeding it to FN.
Also, MIN can be provided to correspond with the TEST fucntion (default: 0).
Also return the value at this key as a second value."
(let ((max min)
arg)
(dotable (k v ht)
(let ((cur (or (funcall key v)
min)))
(when (funcall test cur max)
(:= max cur
arg k))))
(values arg
max)))
(defun bin-search (val vec test-less &key (start 0) end key test)
"Binary search for VAL in sorted vector VEC (the order property isn't checked).
Needs to specify TEST-LESS predicate. Handles START, END, KEY as usual.
It TEST is provided tests the value at the found position against VAL,
and returns nil if it returns nil."
(let ((low start)
(high (or end (1- (length vec)))))
(do ()
((= low high) (when (or (null test)
(funcall test val (svref vec high)))
(elt vec high)))
(let ((mid (floor (+ low high) 2)))
(if (funcall test-less (if key
(funcall key (svref vec mid))
(svref vec mid))
val)
(setf low (1+ mid))
(setf high mid))))))
(defun sum (fn xs &optional ys)
"Sum result of application of FN to each of XS (and optionally YS)."
(reduce '+ (if ys
(map 'list fn xs ys)
(map 'list fn xs))
:initial-value 0))
(defun frobenius-norm (m)
"Frobenius norm of matrix M."
(let ((rez 0))
(dotimes (i (array-dimension m 0))
(dotimes (j (array-dimension m 1))
(:+ rez (expt (aref m i j) 2))))))
(defun ~= (x y &key (epsilon 0.01))
"Approximately equality between X & Y to the margin EPSILON."
(< (abs (- x y)) epsilon))
(defun log-likelihood-ratio (ab a~b ~ab ~a~b)
"Calculate log-likelihood ratio between event A and B given
probabilites of A and B occurring together and separately."
(let ((total (+ ab a~b ~ab ~a~b)))
(* 2 total (- (entropy (list ab a~b ~ab ~a~b) total)
(entropy (list (+ ab a~b) (+ ~ab ~a~b)) total)
(entropy (list (+ ab ~ab) (+ a~b ~a~b)) total)))))
(defun sample (data n &key (with-replacement? t))
"Sample N elements from DATA (by default, WITH-REPLACEMENT?)."
(if (zerop n)
#()
(with ((vec (coerce data 'vector))
(len (length vec))
(int rem (floor n len)))
(if (plusp int)
(progn
(warn "Sample size exceeds data length: ~A > ~A" n len)
(nshuffle (apply 'concatenate 'vector
(sample data rem
:with-replacement? with-replacement?)
(loop :repeat int :collect vec))))
(coerce (if with-replacement?
(let ((rez (make-array n)))
(dotimes (i n)
(:= (? rez i) (? vec (random len))))
rez)
(subseq (nshuffle vec) 0 n))
(type-of data))))))
(defun resample (data label new &key key)
"Resample DATA so that the number of items with LABEL (determined by KEY)
equals to NEW (a number or a reference to another label,
in which case the number of items by it is used)."
(with ((sample (keep label data :key key))
(len (length sample)))
(coerce (nshuffle
(concatenate 'vector
(coerce (remove label data :key key) 'vector)
(coerce (loop :repeat
(if (numberp new) new
(let ((cc (count new data :key key)))
(when (zerop cc)
(warn "Label '~A' not found in data by ~A."
new key))
cc))
:collect (? sample (random len)))
'vector)))
'vector)))
(defun normal-random (&optional (mean 0.0) (std-dev 1.0))
"Generate a normal random number with the given MEAN and STD-DEV."
(do* ((rand-u (* 2 (- 0.5 (random 1.0))) (* 2 (- 0.5 (random 1.0))))
(rand-v (* 2 (- 0.5 (random 1.0))) (* 2 (- 0.5 (random 1.0))))
(rand-s (+ (* rand-u rand-u) (* rand-v rand-v))
(+ (* rand-u rand-u) (* rand-v rand-v))))
((not (or (= 0 rand-s) (>= rand-s 1)))
(+ mean
(* std-dev
(* rand-u (sqrt (/ (* -2.0 (log rand-s)) rand-s))))))))
|
|
af847ed1a1963c30c9e610d1c01e75d880a5bd20366ff1a56859dcfc276b5f8e | mark-watson/loving-common-lisp | package.lisp | (defpackage #:wolfram
(:use #:cl #:uiop)
(:export #:wolfram #:cleanup-lists #:find-answer-in-text #:entities))
| null | https://raw.githubusercontent.com/mark-watson/loving-common-lisp/32f6abf3d2e500baeffd15c085a502b03399a074/src/wolfram/package.lisp | lisp | (defpackage #:wolfram
(:use #:cl #:uiop)
(:export #:wolfram #:cleanup-lists #:find-answer-in-text #:entities))
|
|
b78994b3eca1ba9812fcb15cef8a93e8849ff2ce1e5f3dfd8c62aca1c358a34d | NB-Iot/emqx-hw-coap | emqx_hw_coap_resource.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2016 - 2017 EMQ Enterprise , Inc. ( )
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_hw_coap_resource).
-behaviour(lwm2m_coap_resource).
-include("emqx_hw_coap.hrl").
-include_lib("lwm2m_coap/include/coap.hrl").
-include_lib("emqx/include/emqx.hrl").
-include_lib("emqx/include/emqx_mqtt.hrl").
-export([coap_discover/2, coap_get/4, coap_post/4, coap_put/4, coap_delete/3,
coap_observe/4, coap_unobserve/1, handle_info/2, coap_ack/2]).
-ifdef(TEST).
-export([topic/1]).
-endif.
-define(MQTT_PREFIX, [<<"mqtt">>]).
-define(NB_PREFIX, [<<"t">>]).
-define(NB_CLIENT_ID_PREFIX, <<"imei_">>).
-define(NB_TOPIC_PREFIX, <<"nbiot_dev/">>).
-define(NB_SUB_TOPIC_SUFFIX, <<"/in">>).
-define(NB_PUB_TOPIC_SUFFIX, <<"/out">>).
-define(LOG(Level, Format, Args),
lager:Level("CoAP-RES: " ++ Format, Args)).
% resource operations
coap_discover(_Prefix, _Args) ->
[{absolute, "mqtt", []}].
coap_get(ChId, ?MQTT_PREFIX, Name, Query) ->
?LOG(debug, "coap_get() ChId=~p, Name=~p, Query=~p~n", [ChId, Name, Query]),
#coap_mqtt_auth{clientid = Clientid, username = Usr, password = Passwd} = get_auth(Query),
case emqx_hw_coap_mqtt_adapter:client_pid(Clientid, Usr, Passwd, ChId) of
{ok, Pid} ->
put(mqtt_client_pid, Pid),
emqx_hw_coap_mqtt_adapter:keepalive(Pid),
#coap_content{};
{error, auth_failure} ->
put(mqtt_client_pid, undefined),
{error, uauthorized};
{error, bad_request} ->
put(mqtt_client_pid, undefined),
{error, bad_request};
{error, _Other} ->
put(mqtt_client_pid, undefined),
{error, internal_server_error}
end;
coap_get(ChId, ?NB_PREFIX, Name, Query) ->
?LOG(debug, "coap_get() Name=~p, Query=~p~n", [Name, Query]),
case Name of
[<<"r">>] ->
#coap_mqtt_auth{clientid = Clientid, username = Usr, password = Passwd} = get_auth(Query),
NewClientid = <<?NB_CLIENT_ID_PREFIX/binary, Clientid/binary>>,
case emqx_hw_coap_mqtt_adapter:client_pid(NewClientid, Usr, Passwd, ChId) of
{ok, Pid} ->
put(mqtt_client_pid, Pid),
emqx_hw_coap_mqtt_adapter:keepalive(Pid),
?LOG(debug, "coap_get() will send observe_nb_device~n", []),
Pid ! {observe_nb_device, self()},
SubTopic = <<?NB_TOPIC_PREFIX/binary, NewClientid/binary, ?NB_SUB_TOPIC_SUFFIX/binary>>,
emqx_hw_coap_mqtt_adapter:subscribe(Pid, SubTopic),
#coap_content{};
{error, auth_failure} ->
put(mqtt_client_pid, undefined),
{error, uauthorized};
{error, bad_request} ->
put(mqtt_client_pid, undefined),
{error, bad_request};
{error, _Other} ->
put(mqtt_client_pid, undefined),
{error, internal_server_error}
end;
[<<"d">>] ->
?LOG(debug, "coap_get() receives Name=~p, Query=~p~n", [Name, Query]),
case get(mqtt_client_pid) of
undefined ->
?LOG(debug, "mqtt_client_pid is undefined, the device from ~p is not registered before, ignore the request~n", [ChId]),
{error, uauthorized};
_Pid ->
#coap_content{}
end;
_else ->
?LOG(debug, "coap_get() receives unknown Name=~p, Query=~p~n", [Name, Query]),
{error, bad_request}
end;
coap_get(ChId, Prefix, Name, Query) ->
?LOG(error, "ignore bad put request ChId=~p, Prefix=~p, Name=~p, Query=~p", [ChId, Prefix, Name, Query]),
{error, bad_request}.
coap_post(ChId, ?NB_PREFIX, [Topic = <<"r">>], Content = #coap_content{}) ->
?LOG(debug, "post message, ChId =~p, Topic=~p, Content=~p~n", [ChId, Topic, Content]),
{ok, valid, Content};
coap_post(ChId, ?NB_PREFIX, [Topic], Content = #coap_content{payload = Payload}) ->
?LOG(debug, "post message, ChId =~p, Topic=~p, Content=~p~n", [ChId, Topic, Content]),
Pid = get(mqtt_client_pid),
emqx_coap_mqtt_adapter:publish(Pid, topic(Topic), Payload),
{ok, valid, Content};
coap_post(_ChId, _Prefix, _Name, _Content) ->
{error, method_not_allowed}.
coap_put(_ChId, ?MQTT_PREFIX, [Topic], #coap_content{payload = Payload}) ->
?LOG(debug, "put message, Topic=~p, Payload=~p~n", [Topic, Payload]),
Pid = get(mqtt_client_pid),
emqx_hw_coap_mqtt_adapter:publish(Pid, topic(Topic), Payload),
ok;
coap_put(_ChId, Prefix, Name, Content) ->
?LOG(error, "put has error, Prefix=~p, Name=~p, Content=~p", [Prefix, Name, Content]),
{error, bad_request}.
coap_delete(_ChId, _Prefix, _Name) ->
{error, method_not_allowed}.
coap_observe(ChId, ?MQTT_PREFIX, [Topic], Ack) ->
TrueTopic = topic(Topic),
?LOG(debug, "observe Topic=~p, Ack=~p", [TrueTopic, Ack]),
Pid = get(mqtt_client_pid),
emqx_hw_coap_mqtt_adapter:subscribe(Pid, TrueTopic),
{ok, {state, ChId, ?MQTT_PREFIX, [TrueTopic]}};
coap_observe(ChId, Prefix, Name, Ack) ->
?LOG(error, "unknown observe request ChId=~p, Prefix=~p, Name=~p, Ack=~p", [ChId, Prefix, Name, Ack]),
{error, bad_request}.
coap_unobserve({state, _ChId, ?MQTT_PREFIX, [Topic]}) ->
?LOG(debug, "unobserve ~p", [Topic]),
Pid = get(mqtt_client_pid),
emqx_hw_coap_mqtt_adapter:unsubscribe(Pid, Topic),
ok;
coap_unobserve({state, ChId, Prefix, Name}) ->
?LOG(error, "ignore unknown unobserve request ChId=~p, Prefix=~p, Name=~p", [ChId, Prefix, Name]),
ok.
handle_info({dispatch, Topic, Payload}, State) ->
?LOG(debug, "dispatch Topic=~p, Payload=~p", [Topic, Payload]),
{notify, [], #coap_content{format = <<"application/octet-stream">>, payload = Payload}, State};
handle_info({dispatch_request, CoapRequest, Ref}, _State) ->
?LOG(debug, "dispatch_request CoapRequest=~p, Ref=~p", [CoapRequest, Ref]),
{send_request, CoapRequest, Ref};
handle_info({coap_response, _ChId, _Channel, Ref, Msg=#coap_message{type = Type, id = MsgId, method = _Method, options = _Options, payload = Payload}}, ObState) ->
?LOG(debug, "receive coap response from device ~p, Ref = ~p~n", [Msg, Ref]),
Pid = get(mqtt_client_pid),
case process_response(Type, Payload, Ref, Pid) of
ok ->
{noreply, ObState};
error ->
BinReset = lwm2m_coap_message_parser:encode(#coap_message{type=reset, id=MsgId}),
{error, BinReset}
end;
handle_info(Message, State) ->
?LOG(error, "Unknown Message ~p", [Message]),
{noreply, State}.
coap_ack(_Ref, State) -> {ok, State}.
get_auth(Query) ->
get_auth(Query, #coap_mqtt_auth{}).
get_auth([], Auth=#coap_mqtt_auth{}) ->
Auth;
get_auth([<<$c, $=, Rest/binary>>|T], Auth=#coap_mqtt_auth{}) ->
get_auth(T, Auth#coap_mqtt_auth{clientid = Rest});
get_auth([<<$u, $=, Rest/binary>>|T], Auth=#coap_mqtt_auth{}) ->
get_auth(T, Auth#coap_mqtt_auth{username = Rest});
get_auth([<<$p, $=, Rest/binary>>|T], Auth=#coap_mqtt_auth{}) ->
get_auth(T, Auth#coap_mqtt_auth{password = Rest});
get_auth([<<$e, $p, $=, Rest/binary>>|T], Auth=#coap_mqtt_auth{}) ->
get_auth(T, Auth#coap_mqtt_auth{clientid = Rest, username = <<"nbuser">>, password = <<"nbpass">>});
get_auth([Param|T], Auth=#coap_mqtt_auth{}) ->
?LOG(error, "ignore unknown parameter ~p", [Param]),
get_auth(T, Auth).
process_response(non, Payload, Ref, Pid) when is_binary(Payload), is_binary(Ref)->
case is_process_alive(Pid) of
true ->
PubTopic = <<?NB_TOPIC_PREFIX/binary, Ref/binary, ?NB_PUB_TOPIC_SUFFIX/binary>>,
?LOG(debug, "process response will publish to topic=~p, Payload=~p, Ref=~p~n", [PubTopic, Payload, Ref]),
emqx_hw_coap_mqtt_adapter:publish(Pid, PubTopic, Payload),
ok;
false ->
?LOG(error, "coap_adapter process not alive, ignore the response~n", []),
error
end;
process_response(ack, _Payload, _Ref, _Pid) ->
ok;
process_response(_Other, _Payload, _Ref, _Pid) ->
?LOG(error, "process illegal response, just ignore or may be supported later~n", []),
ok.
topic(TopicBinary) ->
RFC 7252 section 6.4 . Decomposing URIs into Options
%% Note that these rules completely resolve any percent-encoding.
That is to say : URI may have percent - encoding . But coap options has no percent - encoding at all .
TopicBinary.
| null | https://raw.githubusercontent.com/NB-Iot/emqx-hw-coap/76436492a22eaa0cd6560b4f135275ecf16245d0/src/emqx_hw_coap_resource.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.
--------------------------------------------------------------------
resource operations
Note that these rules completely resolve any percent-encoding. | Copyright ( c ) 2016 - 2017 EMQ Enterprise , Inc. ( )
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_hw_coap_resource).
-behaviour(lwm2m_coap_resource).
-include("emqx_hw_coap.hrl").
-include_lib("lwm2m_coap/include/coap.hrl").
-include_lib("emqx/include/emqx.hrl").
-include_lib("emqx/include/emqx_mqtt.hrl").
-export([coap_discover/2, coap_get/4, coap_post/4, coap_put/4, coap_delete/3,
coap_observe/4, coap_unobserve/1, handle_info/2, coap_ack/2]).
-ifdef(TEST).
-export([topic/1]).
-endif.
-define(MQTT_PREFIX, [<<"mqtt">>]).
-define(NB_PREFIX, [<<"t">>]).
-define(NB_CLIENT_ID_PREFIX, <<"imei_">>).
-define(NB_TOPIC_PREFIX, <<"nbiot_dev/">>).
-define(NB_SUB_TOPIC_SUFFIX, <<"/in">>).
-define(NB_PUB_TOPIC_SUFFIX, <<"/out">>).
-define(LOG(Level, Format, Args),
lager:Level("CoAP-RES: " ++ Format, Args)).
coap_discover(_Prefix, _Args) ->
[{absolute, "mqtt", []}].
coap_get(ChId, ?MQTT_PREFIX, Name, Query) ->
?LOG(debug, "coap_get() ChId=~p, Name=~p, Query=~p~n", [ChId, Name, Query]),
#coap_mqtt_auth{clientid = Clientid, username = Usr, password = Passwd} = get_auth(Query),
case emqx_hw_coap_mqtt_adapter:client_pid(Clientid, Usr, Passwd, ChId) of
{ok, Pid} ->
put(mqtt_client_pid, Pid),
emqx_hw_coap_mqtt_adapter:keepalive(Pid),
#coap_content{};
{error, auth_failure} ->
put(mqtt_client_pid, undefined),
{error, uauthorized};
{error, bad_request} ->
put(mqtt_client_pid, undefined),
{error, bad_request};
{error, _Other} ->
put(mqtt_client_pid, undefined),
{error, internal_server_error}
end;
coap_get(ChId, ?NB_PREFIX, Name, Query) ->
?LOG(debug, "coap_get() Name=~p, Query=~p~n", [Name, Query]),
case Name of
[<<"r">>] ->
#coap_mqtt_auth{clientid = Clientid, username = Usr, password = Passwd} = get_auth(Query),
NewClientid = <<?NB_CLIENT_ID_PREFIX/binary, Clientid/binary>>,
case emqx_hw_coap_mqtt_adapter:client_pid(NewClientid, Usr, Passwd, ChId) of
{ok, Pid} ->
put(mqtt_client_pid, Pid),
emqx_hw_coap_mqtt_adapter:keepalive(Pid),
?LOG(debug, "coap_get() will send observe_nb_device~n", []),
Pid ! {observe_nb_device, self()},
SubTopic = <<?NB_TOPIC_PREFIX/binary, NewClientid/binary, ?NB_SUB_TOPIC_SUFFIX/binary>>,
emqx_hw_coap_mqtt_adapter:subscribe(Pid, SubTopic),
#coap_content{};
{error, auth_failure} ->
put(mqtt_client_pid, undefined),
{error, uauthorized};
{error, bad_request} ->
put(mqtt_client_pid, undefined),
{error, bad_request};
{error, _Other} ->
put(mqtt_client_pid, undefined),
{error, internal_server_error}
end;
[<<"d">>] ->
?LOG(debug, "coap_get() receives Name=~p, Query=~p~n", [Name, Query]),
case get(mqtt_client_pid) of
undefined ->
?LOG(debug, "mqtt_client_pid is undefined, the device from ~p is not registered before, ignore the request~n", [ChId]),
{error, uauthorized};
_Pid ->
#coap_content{}
end;
_else ->
?LOG(debug, "coap_get() receives unknown Name=~p, Query=~p~n", [Name, Query]),
{error, bad_request}
end;
coap_get(ChId, Prefix, Name, Query) ->
?LOG(error, "ignore bad put request ChId=~p, Prefix=~p, Name=~p, Query=~p", [ChId, Prefix, Name, Query]),
{error, bad_request}.
coap_post(ChId, ?NB_PREFIX, [Topic = <<"r">>], Content = #coap_content{}) ->
?LOG(debug, "post message, ChId =~p, Topic=~p, Content=~p~n", [ChId, Topic, Content]),
{ok, valid, Content};
coap_post(ChId, ?NB_PREFIX, [Topic], Content = #coap_content{payload = Payload}) ->
?LOG(debug, "post message, ChId =~p, Topic=~p, Content=~p~n", [ChId, Topic, Content]),
Pid = get(mqtt_client_pid),
emqx_coap_mqtt_adapter:publish(Pid, topic(Topic), Payload),
{ok, valid, Content};
coap_post(_ChId, _Prefix, _Name, _Content) ->
{error, method_not_allowed}.
coap_put(_ChId, ?MQTT_PREFIX, [Topic], #coap_content{payload = Payload}) ->
?LOG(debug, "put message, Topic=~p, Payload=~p~n", [Topic, Payload]),
Pid = get(mqtt_client_pid),
emqx_hw_coap_mqtt_adapter:publish(Pid, topic(Topic), Payload),
ok;
coap_put(_ChId, Prefix, Name, Content) ->
?LOG(error, "put has error, Prefix=~p, Name=~p, Content=~p", [Prefix, Name, Content]),
{error, bad_request}.
coap_delete(_ChId, _Prefix, _Name) ->
{error, method_not_allowed}.
coap_observe(ChId, ?MQTT_PREFIX, [Topic], Ack) ->
TrueTopic = topic(Topic),
?LOG(debug, "observe Topic=~p, Ack=~p", [TrueTopic, Ack]),
Pid = get(mqtt_client_pid),
emqx_hw_coap_mqtt_adapter:subscribe(Pid, TrueTopic),
{ok, {state, ChId, ?MQTT_PREFIX, [TrueTopic]}};
coap_observe(ChId, Prefix, Name, Ack) ->
?LOG(error, "unknown observe request ChId=~p, Prefix=~p, Name=~p, Ack=~p", [ChId, Prefix, Name, Ack]),
{error, bad_request}.
coap_unobserve({state, _ChId, ?MQTT_PREFIX, [Topic]}) ->
?LOG(debug, "unobserve ~p", [Topic]),
Pid = get(mqtt_client_pid),
emqx_hw_coap_mqtt_adapter:unsubscribe(Pid, Topic),
ok;
coap_unobserve({state, ChId, Prefix, Name}) ->
?LOG(error, "ignore unknown unobserve request ChId=~p, Prefix=~p, Name=~p", [ChId, Prefix, Name]),
ok.
handle_info({dispatch, Topic, Payload}, State) ->
?LOG(debug, "dispatch Topic=~p, Payload=~p", [Topic, Payload]),
{notify, [], #coap_content{format = <<"application/octet-stream">>, payload = Payload}, State};
handle_info({dispatch_request, CoapRequest, Ref}, _State) ->
?LOG(debug, "dispatch_request CoapRequest=~p, Ref=~p", [CoapRequest, Ref]),
{send_request, CoapRequest, Ref};
handle_info({coap_response, _ChId, _Channel, Ref, Msg=#coap_message{type = Type, id = MsgId, method = _Method, options = _Options, payload = Payload}}, ObState) ->
?LOG(debug, "receive coap response from device ~p, Ref = ~p~n", [Msg, Ref]),
Pid = get(mqtt_client_pid),
case process_response(Type, Payload, Ref, Pid) of
ok ->
{noreply, ObState};
error ->
BinReset = lwm2m_coap_message_parser:encode(#coap_message{type=reset, id=MsgId}),
{error, BinReset}
end;
handle_info(Message, State) ->
?LOG(error, "Unknown Message ~p", [Message]),
{noreply, State}.
coap_ack(_Ref, State) -> {ok, State}.
get_auth(Query) ->
get_auth(Query, #coap_mqtt_auth{}).
get_auth([], Auth=#coap_mqtt_auth{}) ->
Auth;
get_auth([<<$c, $=, Rest/binary>>|T], Auth=#coap_mqtt_auth{}) ->
get_auth(T, Auth#coap_mqtt_auth{clientid = Rest});
get_auth([<<$u, $=, Rest/binary>>|T], Auth=#coap_mqtt_auth{}) ->
get_auth(T, Auth#coap_mqtt_auth{username = Rest});
get_auth([<<$p, $=, Rest/binary>>|T], Auth=#coap_mqtt_auth{}) ->
get_auth(T, Auth#coap_mqtt_auth{password = Rest});
get_auth([<<$e, $p, $=, Rest/binary>>|T], Auth=#coap_mqtt_auth{}) ->
get_auth(T, Auth#coap_mqtt_auth{clientid = Rest, username = <<"nbuser">>, password = <<"nbpass">>});
get_auth([Param|T], Auth=#coap_mqtt_auth{}) ->
?LOG(error, "ignore unknown parameter ~p", [Param]),
get_auth(T, Auth).
process_response(non, Payload, Ref, Pid) when is_binary(Payload), is_binary(Ref)->
case is_process_alive(Pid) of
true ->
PubTopic = <<?NB_TOPIC_PREFIX/binary, Ref/binary, ?NB_PUB_TOPIC_SUFFIX/binary>>,
?LOG(debug, "process response will publish to topic=~p, Payload=~p, Ref=~p~n", [PubTopic, Payload, Ref]),
emqx_hw_coap_mqtt_adapter:publish(Pid, PubTopic, Payload),
ok;
false ->
?LOG(error, "coap_adapter process not alive, ignore the response~n", []),
error
end;
process_response(ack, _Payload, _Ref, _Pid) ->
ok;
process_response(_Other, _Payload, _Ref, _Pid) ->
?LOG(error, "process illegal response, just ignore or may be supported later~n", []),
ok.
topic(TopicBinary) ->
RFC 7252 section 6.4 . Decomposing URIs into Options
That is to say : URI may have percent - encoding . But coap options has no percent - encoding at all .
TopicBinary.
|
05706bf29ecf3cb9b85989210044fef6007f39a6622e4e0f5b7a1782176b564e | ocsigen/js_of_ocaml | intersectionObserver.mli | (** The Intersection Observer API provides a way to asynchronously observe
changes in the intersection of a target element with an ancestor element or
with a top-level document's viewport.
-US/docs/Web/API/Intersection_Observer_API *)
class type intersectionObserverEntry =
object
method target : Dom.node Js.t Js.readonly_prop
method boundingClientRect : Dom_html.clientRect Js.t Js.readonly_prop
method rootBounds : Dom_html.clientRect Js.t Js.opt Js.readonly_prop
method intersectionRect : Dom_html.clientRect Js.t Js.readonly_prop
method intersectionRatio : float Js.readonly_prop
method isIntersecting : bool Js.t Js.readonly_prop
method time : float Js.readonly_prop
end
class type intersectionObserverOptions =
object
method root : Dom.node Js.t Js.writeonly_prop
method rootMargin : Js.js_string Js.t Js.writeonly_prop
method threshold : float Js.js_array Js.t Js.writeonly_prop
end
class type intersectionObserver =
object
method root : Dom.node Js.t Js.opt Js.readonly_prop
method rootMargin : Js.js_string Js.t Js.readonly_prop
method thresholds : float Js.js_array Js.t Js.readonly_prop
method observe : #Dom.node Js.t -> unit Js.meth
method unobserve : #Dom.node Js.t -> unit Js.meth
method disconnect : unit Js.meth
method takeRecords : intersectionObserverEntry Js.t Js.js_array Js.meth
end
val empty_intersection_observer_options : unit -> intersectionObserverOptions Js.t
val is_supported : unit -> bool
val intersectionObserver :
( ( intersectionObserverEntry Js.t Js.js_array Js.t
-> intersectionObserver Js.t
-> unit)
Js.callback
-> intersectionObserverOptions Js.t
-> intersectionObserver Js.t)
Js.constr
| null | https://raw.githubusercontent.com/ocsigen/js_of_ocaml/58210fabc947c4839b6e71ffbbf353a4ede0dbb7/lib/js_of_ocaml/intersectionObserver.mli | ocaml | * The Intersection Observer API provides a way to asynchronously observe
changes in the intersection of a target element with an ancestor element or
with a top-level document's viewport.
-US/docs/Web/API/Intersection_Observer_API |
class type intersectionObserverEntry =
object
method target : Dom.node Js.t Js.readonly_prop
method boundingClientRect : Dom_html.clientRect Js.t Js.readonly_prop
method rootBounds : Dom_html.clientRect Js.t Js.opt Js.readonly_prop
method intersectionRect : Dom_html.clientRect Js.t Js.readonly_prop
method intersectionRatio : float Js.readonly_prop
method isIntersecting : bool Js.t Js.readonly_prop
method time : float Js.readonly_prop
end
class type intersectionObserverOptions =
object
method root : Dom.node Js.t Js.writeonly_prop
method rootMargin : Js.js_string Js.t Js.writeonly_prop
method threshold : float Js.js_array Js.t Js.writeonly_prop
end
class type intersectionObserver =
object
method root : Dom.node Js.t Js.opt Js.readonly_prop
method rootMargin : Js.js_string Js.t Js.readonly_prop
method thresholds : float Js.js_array Js.t Js.readonly_prop
method observe : #Dom.node Js.t -> unit Js.meth
method unobserve : #Dom.node Js.t -> unit Js.meth
method disconnect : unit Js.meth
method takeRecords : intersectionObserverEntry Js.t Js.js_array Js.meth
end
val empty_intersection_observer_options : unit -> intersectionObserverOptions Js.t
val is_supported : unit -> bool
val intersectionObserver :
( ( intersectionObserverEntry Js.t Js.js_array Js.t
-> intersectionObserver Js.t
-> unit)
Js.callback
-> intersectionObserverOptions Js.t
-> intersectionObserver Js.t)
Js.constr
|
31f58c60edd33ff2cd57da63c919787be94da90f712ce8ac8679390d4c0e15ea | mirage/irmin | schema.mli |
* Copyright ( c ) 2018 - 2022 Tarides < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2018-2022 Tarides <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
include
Irmin.Schema.Extended
with type Contents.t = bytes
and type Metadata.t = unit
and type Path.t = string list
and type Path.step = string
and type Branch.t = string
and module Info = Irmin.Info.Default
| null | https://raw.githubusercontent.com/mirage/irmin/abeee121a6db7b085b3c68af50ef24a8d8f9ed05/src/irmin-tezos/schema.mli | ocaml |
* Copyright ( c ) 2018 - 2022 Tarides < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2018-2022 Tarides <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
include
Irmin.Schema.Extended
with type Contents.t = bytes
and type Metadata.t = unit
and type Path.t = string list
and type Path.step = string
and type Branch.t = string
and module Info = Irmin.Info.Default
|
|
f39e6b5147d3bad8c0f7509ec5cde5025986cc38ddc4269fabd6b36296295b75 | pfdietz/ansi-test | format-goto.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Tue Aug 24 06:56:13 2004
;;;; Contains: Tests of the ~* format directive
;;; ~*
(def-format-test format.*.1
"~A~*~A" (1 2 3) "13")
(def-format-test format.*.2
"~A~0*~A" (1 2 3) "12" 1)
(def-format-test format.*.3
"~A~v*~A" (1 0 2) "12")
(def-format-test format.*.4
"~A~v*~A" (1 1 2 3) "13")
(def-format-test format.*.5
"~A~v*~A" (1 nil 2 3) "13")
(def-format-test format.*.6
"~A~1{~A~*~A~}~A" (0 '(1 2 3) 4) "0134")
(def-format-test format.*.7
"~A~1{~A~0*~A~}~A" (0 '(1 2 3) 4) "0124")
(def-format-test format.*.8
"~A~{~A~*~A~}~A" (0 '(1 2 3 4 5 6) 7) "013467")
(def-format-test format.*.9
"~A~{~A~A~A~A~v*~^~A~A~A~A~}~A" (0 '(1 2 3 4 nil 6 7 8 9 #\A) 5)
"01234789A5")
;;; ~:*
(def-format-test format.\:*.1
"~A~:*~A" (1 2 3) "11" 2)
(def-format-test format.\:*.2
"~A~A~:*~A" (1 2 3) "122" 1)
(def-format-test format.\:*.3
"~A~A~0:*~A" (1 2 3) "123")
(def-format-test format.\:*.4
"~A~A~2:*~A" (1 2 3) "121" 2)
(def-format-test format.\:*.5
"~A~A~v:*~A" (1 2 0 3) "123")
(def-format-test format.\:*.6
"~A~A~v:*~A" (6 7 2 3) "677" 2)
(def-format-test format.\:*.7
"~A~A~v:*~A" (6 7 nil 3) "67NIL" 1)
(def-format-test format.\:*.8
"~A~1{~A~:*~A~}~A" (0 '(1 2 3) 4) "0114")
(def-format-test format.\:*.9
"~A~1{~A~A~A~:*~A~}~A" (0 '(1 2 3 4) 5) "012335")
(def-format-test format.\:*.10
"~A~1{~A~A~A~2:*~A~A~}~A" (0 '(1 2 3 4) 5) "0123235")
(def-format-test format.\:*.11
"~A~{~A~A~A~3:*~A~A~A~A~}~A" (0 '(1 2 3 4) 5) "012312345")
(def-format-test format.\:*.12
"~A~{~A~A~A~A~4:*~^~A~A~A~A~}~A" (0 '(1 2 3 4) 5) "0123412345")
(def-format-test format.\:*.13
"~A~{~A~A~A~A~v:*~^~A~}~A" (0 '(1 2 3 4 nil) 5) "01234NIL5")
;;; ~@*
(def-format-test format.@*.1
"~A~A~@*~A~A" (1 2 3 4) "1212" 2)
(def-format-test format.@*.2
"~A~A~1@*~A~A" (1 2 3 4) "1223" 1)
(def-format-test format.@*.3
"~A~A~2@*~A~A" (1 2 3 4) "1234")
(def-format-test format.@*.4
"~A~A~3@*~A~A" (1 2 3 4 5) "1245")
(def-format-test format.@*.5
"~A~A~v@*~A~A" (1 2 nil 3 4) "1212" 3)
(def-format-test format.@*.6
"~A~A~v@*~A~A" (1 2 1 3 4) "1221" 2)
(def-format-test format.@*.7
"~A~A~v@*~A~A" (6 7 2 3 4) "6723" 1)
(def-format-test format.@*.8
"~A~{~A~A~@*~A~A~}~A" (0 '(1 2) 9) "012129")
(def-format-test format.@*.9
"~A~{~A~A~0@*~A~A~}~A" (0 '(1 2) 9) "012129")
(def-format-test format.@*.10
"~A~1{~A~A~v@*~A~A~}~A" (0 '(1 2 nil) 9) "012129")
(def-format-test format.@*.11
"~A~{~A~A~1@*~A~}~A" (0 '(1 2) 9) "01229")
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/printer/format/format-goto.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of the ~* format directive
~*
~:*
~@* | Author :
Created : Tue Aug 24 06:56:13 2004
(def-format-test format.*.1
"~A~*~A" (1 2 3) "13")
(def-format-test format.*.2
"~A~0*~A" (1 2 3) "12" 1)
(def-format-test format.*.3
"~A~v*~A" (1 0 2) "12")
(def-format-test format.*.4
"~A~v*~A" (1 1 2 3) "13")
(def-format-test format.*.5
"~A~v*~A" (1 nil 2 3) "13")
(def-format-test format.*.6
"~A~1{~A~*~A~}~A" (0 '(1 2 3) 4) "0134")
(def-format-test format.*.7
"~A~1{~A~0*~A~}~A" (0 '(1 2 3) 4) "0124")
(def-format-test format.*.8
"~A~{~A~*~A~}~A" (0 '(1 2 3 4 5 6) 7) "013467")
(def-format-test format.*.9
"~A~{~A~A~A~A~v*~^~A~A~A~A~}~A" (0 '(1 2 3 4 nil 6 7 8 9 #\A) 5)
"01234789A5")
(def-format-test format.\:*.1
"~A~:*~A" (1 2 3) "11" 2)
(def-format-test format.\:*.2
"~A~A~:*~A" (1 2 3) "122" 1)
(def-format-test format.\:*.3
"~A~A~0:*~A" (1 2 3) "123")
(def-format-test format.\:*.4
"~A~A~2:*~A" (1 2 3) "121" 2)
(def-format-test format.\:*.5
"~A~A~v:*~A" (1 2 0 3) "123")
(def-format-test format.\:*.6
"~A~A~v:*~A" (6 7 2 3) "677" 2)
(def-format-test format.\:*.7
"~A~A~v:*~A" (6 7 nil 3) "67NIL" 1)
(def-format-test format.\:*.8
"~A~1{~A~:*~A~}~A" (0 '(1 2 3) 4) "0114")
(def-format-test format.\:*.9
"~A~1{~A~A~A~:*~A~}~A" (0 '(1 2 3 4) 5) "012335")
(def-format-test format.\:*.10
"~A~1{~A~A~A~2:*~A~A~}~A" (0 '(1 2 3 4) 5) "0123235")
(def-format-test format.\:*.11
"~A~{~A~A~A~3:*~A~A~A~A~}~A" (0 '(1 2 3 4) 5) "012312345")
(def-format-test format.\:*.12
"~A~{~A~A~A~A~4:*~^~A~A~A~A~}~A" (0 '(1 2 3 4) 5) "0123412345")
(def-format-test format.\:*.13
"~A~{~A~A~A~A~v:*~^~A~}~A" (0 '(1 2 3 4 nil) 5) "01234NIL5")
(def-format-test format.@*.1
"~A~A~@*~A~A" (1 2 3 4) "1212" 2)
(def-format-test format.@*.2
"~A~A~1@*~A~A" (1 2 3 4) "1223" 1)
(def-format-test format.@*.3
"~A~A~2@*~A~A" (1 2 3 4) "1234")
(def-format-test format.@*.4
"~A~A~3@*~A~A" (1 2 3 4 5) "1245")
(def-format-test format.@*.5
"~A~A~v@*~A~A" (1 2 nil 3 4) "1212" 3)
(def-format-test format.@*.6
"~A~A~v@*~A~A" (1 2 1 3 4) "1221" 2)
(def-format-test format.@*.7
"~A~A~v@*~A~A" (6 7 2 3 4) "6723" 1)
(def-format-test format.@*.8
"~A~{~A~A~@*~A~A~}~A" (0 '(1 2) 9) "012129")
(def-format-test format.@*.9
"~A~{~A~A~0@*~A~A~}~A" (0 '(1 2) 9) "012129")
(def-format-test format.@*.10
"~A~1{~A~A~v@*~A~A~}~A" (0 '(1 2 nil) 9) "012129")
(def-format-test format.@*.11
"~A~{~A~A~1@*~A~}~A" (0 '(1 2) 9) "01229")
|
ee7e416a435104584805a08c735bb34a3916e9dae2b2afad40a5b58c42804022 | PowerMeMobile/smppload | smppload_lazy_messages.erl | -module(smppload_lazy_messages).
-export([
init/2,
deinit/1,
get_next/1
]).
-include("smppload_lazy_messages.hrl").
-include("message.hrl").
-export([behaviour_info/1]).
-spec behaviour_info(atom()) -> [{atom(), arity()}] | undefined.
behaviour_info(callbacks) ->
[{init, 1}, {deinit, 1}, {get_next, 1}];
behaviour_info(_) ->
undefined.
-record(state, {
mod,
mod_state
}).
-spec init(module(), config()) -> {ok, state()} | {error, reason()}.
init(Module, Config) ->
case Module:init(Config) of
{ok, ModState} ->
{ok, #state{mod = Module, mod_state = ModState}};
Error ->
Error
end.
-spec deinit(state()) -> ok.
deinit(State) ->
Module = State#state.mod,
ModState = State#state.mod_state,
Module:deinit(ModState).
-spec get_next(state()) -> {ok, #message{}, state()} | {no_more, state()}.
get_next(State) ->
Module = State#state.mod,
ModState0 = State#state.mod_state,
case Module:get_next(ModState0) of
{ok, Message, ModState1} ->
{ok, Message, State#state{mod_state = ModState1}};
{no_more, ModState1} ->
{no_more, State#state{mod_state = ModState1}}
end.
| null | https://raw.githubusercontent.com/PowerMeMobile/smppload/3130eaa95ed1e69ace551dc7be9c9509d05fde2a/src/smppload_lazy_messages.erl | erlang | -module(smppload_lazy_messages).
-export([
init/2,
deinit/1,
get_next/1
]).
-include("smppload_lazy_messages.hrl").
-include("message.hrl").
-export([behaviour_info/1]).
-spec behaviour_info(atom()) -> [{atom(), arity()}] | undefined.
behaviour_info(callbacks) ->
[{init, 1}, {deinit, 1}, {get_next, 1}];
behaviour_info(_) ->
undefined.
-record(state, {
mod,
mod_state
}).
-spec init(module(), config()) -> {ok, state()} | {error, reason()}.
init(Module, Config) ->
case Module:init(Config) of
{ok, ModState} ->
{ok, #state{mod = Module, mod_state = ModState}};
Error ->
Error
end.
-spec deinit(state()) -> ok.
deinit(State) ->
Module = State#state.mod,
ModState = State#state.mod_state,
Module:deinit(ModState).
-spec get_next(state()) -> {ok, #message{}, state()} | {no_more, state()}.
get_next(State) ->
Module = State#state.mod,
ModState0 = State#state.mod_state,
case Module:get_next(ModState0) of
{ok, Message, ModState1} ->
{ok, Message, State#state{mod_state = ModState1}};
{no_more, ModState1} ->
{no_more, State#state{mod_state = ModState1}}
end.
|
|
4d205b1e24a0745e8dc7dfde4ecd39afc817c4de0fe78b127bc762c968f9aa2e | dmjio/miso | Element.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE NoImplicitPrelude #
-----------------------------------------------------------------------------
-- |
Module : Miso . . Element
Copyright : ( C ) 2016 - 2018
-- License : BSD3-style (see the file LICENSE)
Maintainer : < >
-- Stability : experimental
-- Portability : non-portable
----------------------------------------------------------------------------
module Miso.Mathml.Element
( -- * Construct an Element
nodeMathml
) where
import Miso.Html.Types
import Miso.String (MisoString)
import qualified Prelude as P
-- | Used to construct `VNode`'s in `View`
nodeMathml :: MisoString -> [Attribute action] -> [View action] -> View action
nodeMathml = P.flip (node MATHML) P.Nothing
| null | https://raw.githubusercontent.com/dmjio/miso/339505587fd8576c7f89484d3a4244732a9f00e6/src/Miso/Mathml/Element.hs | haskell | # LANGUAGE OverloadedStrings #
---------------------------------------------------------------------------
|
License : BSD3-style (see the file LICENSE)
Stability : experimental
Portability : non-portable
--------------------------------------------------------------------------
* Construct an Element
| Used to construct `VNode`'s in `View` | # LANGUAGE NoImplicitPrelude #
Module : Miso . . Element
Copyright : ( C ) 2016 - 2018
Maintainer : < >
module Miso.Mathml.Element
nodeMathml
) where
import Miso.Html.Types
import Miso.String (MisoString)
import qualified Prelude as P
nodeMathml :: MisoString -> [Attribute action] -> [View action] -> View action
nodeMathml = P.flip (node MATHML) P.Nothing
|
17fddd88ef0a76a1ece6b78ffb8752e0f9b973b88b8f27daed6d2ce890971ce0 | tek/polysemy-log | DataLog.hs | {-# options_haddock prune #-}
-- |Description: Internal
module Polysemy.Log.Effect.DataLog where
import Polysemy.Time (GhcTime)
import Prelude hiding (local)
import Polysemy.Log.Data.LogEntry (LogEntry, annotate)
import Polysemy.Log.Data.LogMessage (LogMessage (LogMessage))
import Polysemy.Log.Data.Severity (Severity (Crit, Debug, Error, Info, Trace, Warn))
|Structural logs , used as a backend for the simpler ' Text ' log effect , ' Polysemy . Log . Log ' .
--
-- Can also be used on its own, or reinterpreted into an effect like those from /co-log/ or /di/.
data DataLog a :: Effect where
-- |Schedule an arbitrary value for logging.
DataLog :: a -> DataLog a m ()
-- |Stores the provided function in the interpreter and applies it to all log messages emitted within the higher-order
thunk that 's the second argument .
Local :: (a -> a) -> m b -> DataLog a m b
makeSem ''DataLog
|Alias for the logger with the default message type used by ' Polysemy . Log . Log ' .
type Logger =
DataLog (LogEntry LogMessage)
-- |Log a text message with the given severity.
-- Basic 'Sem' constructor.
log ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Severity ->
Text ->
Sem r ()
log severity message =
withFrozenCallStack do
send . DataLog =<< annotate (LogMessage severity message)
# inline log #
-- |Log a text message with the 'Trace' severity.
trace ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
trace =
withFrozenCallStack (log Trace)
{-# inline trace #-}
-- |Log a text message with the 'Debug' severity.
debug ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
debug =
withFrozenCallStack (log Debug)
{-# inline debug #-}
-- |Log a text message with the 'Info' severity.
info ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
info =
withFrozenCallStack (log Info)
# inline info #
-- |Log a text message with the 'Warn' severity.
warn ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
warn =
withFrozenCallStack (log Warn)
{-# inline warn #-}
|Log a text message with the ' Polysemy . Log . Data . Severity . Error ' severity .
error ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
error =
withFrozenCallStack (log Error)
{-# inline error #-}
-- |Log a text message with the 'Crit' severity.
crit ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
crit =
withFrozenCallStack (log Crit)
# inline crit #
| null | https://raw.githubusercontent.com/tek/polysemy-log/e4a8b494a88809b60b8298b3a345382f750a6ed4/packages/polysemy-log/lib/Polysemy/Log/Effect/DataLog.hs | haskell | # options_haddock prune #
|Description: Internal
Can also be used on its own, or reinterpreted into an effect like those from /co-log/ or /di/.
|Schedule an arbitrary value for logging.
|Stores the provided function in the interpreter and applies it to all log messages emitted within the higher-order
|Log a text message with the given severity.
Basic 'Sem' constructor.
|Log a text message with the 'Trace' severity.
# inline trace #
|Log a text message with the 'Debug' severity.
# inline debug #
|Log a text message with the 'Info' severity.
|Log a text message with the 'Warn' severity.
# inline warn #
# inline error #
|Log a text message with the 'Crit' severity. |
module Polysemy.Log.Effect.DataLog where
import Polysemy.Time (GhcTime)
import Prelude hiding (local)
import Polysemy.Log.Data.LogEntry (LogEntry, annotate)
import Polysemy.Log.Data.LogMessage (LogMessage (LogMessage))
import Polysemy.Log.Data.Severity (Severity (Crit, Debug, Error, Info, Trace, Warn))
|Structural logs , used as a backend for the simpler ' Text ' log effect , ' Polysemy . Log . Log ' .
data DataLog a :: Effect where
DataLog :: a -> DataLog a m ()
thunk that 's the second argument .
Local :: (a -> a) -> m b -> DataLog a m b
makeSem ''DataLog
|Alias for the logger with the default message type used by ' Polysemy . Log . Log ' .
type Logger =
DataLog (LogEntry LogMessage)
log ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Severity ->
Text ->
Sem r ()
log severity message =
withFrozenCallStack do
send . DataLog =<< annotate (LogMessage severity message)
# inline log #
trace ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
trace =
withFrozenCallStack (log Trace)
debug ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
debug =
withFrozenCallStack (log Debug)
info ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
info =
withFrozenCallStack (log Info)
# inline info #
warn ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
warn =
withFrozenCallStack (log Warn)
|Log a text message with the ' Polysemy . Log . Data . Severity . Error ' severity .
error ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
error =
withFrozenCallStack (log Error)
crit ::
HasCallStack =>
Members [Logger, GhcTime] r =>
Text ->
Sem r ()
crit =
withFrozenCallStack (log Crit)
# inline crit #
|
c2b92c85dde2337b344d03ab141396d4c6a76c7678afce679d5441072c0d23b6 | xvw/ocamlectron | Size.mli | (** Describe a Size *)
open Js_of_ocaml
open Js
class type size = object
method width : int readonly_prop
method height : int readonly_prop
end
type t = size Js.t
| null | https://raw.githubusercontent.com/xvw/ocamlectron/3e0cb9575975e69ab34cb7e0e3549d31c07141c2/lib/electron_plumbing/Size.mli | ocaml | * Describe a Size |
open Js_of_ocaml
open Js
class type size = object
method width : int readonly_prop
method height : int readonly_prop
end
type t = size Js.t
|
afad2458ce0351c30159b0540fbd0aa275e8eb488cc4feb030f281f34cef1cd2 | AbstractMachinesLab/caramel | mconfig.ml | open Std
(** {1 OCaml commandline parsing} *)
let {Logger. log} = Logger.for_section "Mconfig"
type ocaml = {
include_dirs : string list;
no_std_include : bool;
unsafe : bool;
classic : bool;
principal : bool;
real_paths : bool;
threads : [ `None | `Threads | `Vmthreads ];
recursive_types : bool;
strict_sequence : bool;
applicative_functors : bool;
unsafe_string : bool;
nopervasives : bool;
strict_formats : bool;
open_modules : string list;
ppx : string with_workdir list;
pp : string with_workdir option;
warnings : Warnings.state;
}
let dump_warnings st =
let st' = Warnings.backup () in
Warnings.restore st;
Misc.try_finally Warnings.dump
~always:(fun () -> Warnings.restore st')
let dump_ocaml x = `Assoc [
"include_dirs" , `List (List.map ~f:Json.string x.include_dirs);
"no_std_include" , `Bool x.no_std_include;
"unsafe" , `Bool x.unsafe;
"classic" , `Bool x.classic;
"principal" , `Bool x.principal;
"real_paths" , `Bool x.real_paths;
"recursive_types" , `Bool x.recursive_types;
"strict_sequence" , `Bool x.strict_sequence;
"applicative_functors" , `Bool x.applicative_functors;
"unsafe_string" , `Bool x.unsafe_string;
"nopervasives" , `Bool x.nopervasives;
"strict_formats" , `Bool x.strict_formats;
"open_modules" , Json.list Json.string x.open_modules;
"ppx" , Json.list (dump_with_workdir Json.string) x.ppx;
"pp" , Json.option (dump_with_workdir Json.string) x.pp;
"warnings" , dump_warnings x.warnings;
]
(** Some paths can be resolved relative to a current working directory *)
let cwd = ref None
let unsafe_get_cwd () = match !cwd with
| None -> assert false
| Some cwd -> cwd
let canonicalize_filename path =
Misc.canonicalize_filename ?cwd:!cwd path
let marg_path f =
Marg.param "path" (fun path acc -> f (canonicalize_filename path) acc)
let marg_commandline f =
Marg.param "command"
(fun workval acc -> f {workdir = unsafe_get_cwd (); workval} acc)
(** {1 Merlin high-level settings} *)
type merlin = {
build_path : string list;
source_path : string list;
cmi_path : string list;
cmt_path : string list;
extensions : string list;
suffixes : (string * string) list;
stdlib : string option;
reader : string list;
protocol : [`Json | `Sexp];
log_file : string option;
log_sections : string list;
config_path : string option;
exclude_query_dir : bool;
flags_to_apply : string list with_workdir list;
flags_applied : string list with_workdir list;
failures : string list;
extension_to_reader : (string * string) list
}
let dump_merlin x =
let dump_flag_list flags =
dump_with_workdir (Json.list Json.string) flags
in
`Assoc [
"build_path" , `List (List.map ~f:Json.string x.build_path);
"source_path" , `List (List.map ~f:Json.string x.source_path);
"cmi_path" , `List (List.map ~f:Json.string x.cmi_path);
"cmt_path" , `List (List.map ~f:Json.string x.cmt_path);
"flags_applied", `List (List.map ~f:dump_flag_list x.flags_applied);
"extensions" , `List (List.map ~f:Json.string x.extensions);
"suffixes" , `List (
List.map ~f:(fun (impl,intf) -> `Assoc [
"impl", `String impl;
"intf", `String intf;
]) x.suffixes
);
"stdlib" , Json.option Json.string x.stdlib;
"reader" , `List (List.map ~f:Json.string x.reader);
"protocol" , (match x.protocol with
| `Json -> `String "json"
| `Sexp -> `String "sexp"
);
"log_file" , Json.option Json.string x.log_file;
"log_sections" , Json.list Json.string x.log_sections;
"flags_to_apply" , `List (List.map ~f:dump_flag_list x.flags_to_apply);
"failures" , `List (List.map ~f:Json.string x.failures);
"assoc_suffixes" , `List (
List.map ~f:(fun (suffix,reader) -> `Assoc [
"extension", `String suffix;
"reader", `String reader;
]) x.extension_to_reader
)
]
type query = {
filename : string;
directory : string;
printer_width : int;
verbosity : int;
}
let dump_query x = `Assoc [
"filename" , `String x.filename;
"directory" , `String x.directory;
"printer_width", `Int x.printer_width;
"verbosity" , `Int x.verbosity;
]
type t = {
ocaml : ocaml;
merlin : merlin;
query : query;
}
let dump x = `Assoc [
"ocaml" , dump_ocaml x.ocaml;
"merlin" , dump_merlin x.merlin;
"query" , dump_query x.query;
]
let arguments_table = Hashtbl.create 67
let stdlib =
let env =
try Some (Sys.getenv "OCAMLLIB")
with Not_found ->
try Some (Sys.getenv "CAMLLIB")
with Not_found -> None
in
fun config ->
match config.merlin.stdlib with
| Some stdlib -> stdlib
| None -> match env with
| Some stdlib -> stdlib
| None -> Standard_library.path
let normalize_step t =
let merlin = t.merlin in
if merlin.flags_to_apply <> [] then
let flagss = merlin.flags_to_apply in
let t = {t with merlin = { merlin with
flags_to_apply = [];
flags_applied = flagss @ merlin.flags_applied;
} }
in
let failures = ref [] in
let warning failure = failures := failure :: !failures in
let t = List.fold_left ~f:(fun t {workdir; workval} -> fst (
let_ref cwd (Some workdir)
(Marg.parse_all ~warning arguments_table [] workval t)
)) ~init:t flagss
in
{t with merlin = {t.merlin with failures = !failures @ t.merlin.failures}}
else
t
let is_normalized t =
let merlin = t.merlin in
merlin.flags_to_apply = []
let rec normalize t =
if is_normalized t then (
log ~title:"normalize" "%a" Logger.json (fun () -> dump t);
t
) else
normalize (normalize_step t)
let get_external_config path t =
let path = Misc.canonicalize_filename path in
let directory = Filename.dirname path in
match Mconfig_dot.find_project_context directory with
| None -> t
| Some (ctxt, config_path) ->
let dot, failures = Mconfig_dot.get_config ctxt path in
let merlin = t.merlin in
let merlin = {
merlin with
build_path = dot.build_path @ merlin.build_path;
source_path = dot.source_path @ merlin.source_path;
cmi_path = dot.cmi_path @ merlin.cmi_path;
cmt_path = dot.cmt_path @ merlin.cmt_path;
exclude_query_dir = dot.exclude_query_dir || merlin.exclude_query_dir;
extensions = dot.extensions @ merlin.extensions;
suffixes = dot.suffixes @ merlin.suffixes;
stdlib = (if dot.stdlib = None then merlin.stdlib else dot.stdlib);
reader =
if dot.reader = []
then merlin.reader
else dot.reader;
flags_to_apply = dot.flags @ merlin.flags_to_apply;
failures = failures @ merlin.failures;
config_path = Some config_path;
} in
normalize { t with merlin }
let merlin_flags = [
(
"-build-path",
marg_path (fun dir merlin ->
{merlin with build_path = dir :: merlin.build_path}),
"<dir> Add <dir> to merlin build path"
);
(
"-source-path",
marg_path (fun dir merlin ->
{merlin with source_path = dir :: merlin.source_path}),
"<dir> Add <dir> to merlin source path"
);
(
"-cmi-path",
marg_path (fun dir merlin ->
{merlin with cmi_path = dir :: merlin.cmi_path}),
"<dir> Add <dir> to merlin cmi path"
);
(
"-cmt-path",
marg_path (fun dir merlin ->
{merlin with build_path = dir :: merlin.cmt_path}),
"<dir> Add <dir> to merlin cmt path"
);
(
"-reader",
Marg.param "command" (fun reader merlin ->
{merlin with reader = Shell.split_command reader }),
"<command> Use <command> as a merlin reader"
);
(
"-assocsuffix",
Marg.param "suffix:reader"
(fun assoc_pair merlin ->
match Misc.rev_string_split ~on:':' assoc_pair with
| [reader;suffix] ->
{merlin with
extension_to_reader = (suffix,reader)::merlin.extension_to_reader}
| _ -> merlin
),
"Associate suffix with reader"
);
(
"-addsuffix",
Marg.param "implementation Suffix, interface Suffix"
(fun suffix_pair merlin ->
match Misc.rev_string_split ~on:':' suffix_pair with
| [intf;impl] ->
{merlin with suffixes = (impl,intf)::merlin.suffixes}
| _ -> merlin
),
"Add a suffix implementation,interface pair"
);
(
"-extension",
Marg.param "extension" (fun extension merlin ->
match Extension.lookup extension with
| None -> invalid_arg "Unknown extension"
| Some _ ->
{merlin with extensions = extension :: merlin.extensions}),
"<extension> Load merlin syntax extension"
);
(
"-flags",
Marg.param "string" (fun flags merlin ->
let flags =
{ workdir = unsafe_get_cwd (); workval = Shell.split_command flags }
in
{merlin with flags_to_apply = flags :: merlin.flags_to_apply}),
"<quoted flags> Unescape argument and interpret it as more flags"
);
(
"-protocol",
Marg.param "protocol" (fun prot merlin ->
match prot with
| "json" -> {merlin with protocol = `Json}
| "sexp" -> {merlin with protocol = `Sexp}
| _ -> invalid_arg "Valid protocols are 'json' and 'sexp'";
),
"<protocol> Select frontend protocol ('json' or 'sexp')"
);
(
"-log-file",
Marg.param "file" (fun file merlin -> {merlin with log_file = Some file}),
"<file> Log messages to specified file ('' for disabling, '-' for stderr)"
);
(
"-log-section",
Marg.param "file" (fun section merlin ->
let sections = String.split_on_char_ ',' section in
{merlin with log_sections = sections @ merlin.log_sections}),
"<section,...> Only log specific sections (separated by comma)"
);
(
"-ocamllib-path",
marg_path (fun path merlin -> {merlin with stdlib = Some path}),
"<path> Change path of ocaml standard library"
);
(
Legacy support for janestreet . Ignored . To be removed soon .
"-attributes-allowed",
Marg.unit_ignore,
" DEPRECATED"
);
]
let query_flags = [
(
"-verbosity",
Marg.param "integer" (fun verbosity query ->
let verbosity =
try int_of_string verbosity
with _ -> invalid_arg "argument should be an integer"
in
{query with verbosity}),
"<integer> Verbosity determines the number of expansions of aliases in answers"
);
(
"-printer-width",
Marg.param "integer" (fun width query ->
let printer_width =
try int_of_string width
with _ -> invalid_arg "argument should be an integer"
in
{query with printer_width}),
"<integer> Optimal width for formatting types, signatures, etc"
)
]
let ocaml_ignored_flags = [
"-a"; "-absname"; "-alias-deps"; "-annot"; "-app-funct"; "-bin-annot";
"-c"; "-compact"; "-compat-32"; "-config"; "-custom"; "-dalloc";
"-dclambda"; "-dcmm"; "-dcombine"; "-dcse"; "-dflambda";
"-dflambda-no-invariants"; "-dflambda-verbose"; "-dinstr"; "-dinterf";
"-dlambda"; "-dlinear"; "-dlive"; "-dparsetree"; "-dprefer";
"-drawclambda"; "-drawflambda"; "-drawlambda"; "-dreload"; "-dscheduling";
"-dsel"; "-dsource"; "-dspill"; "-dsplit"; "-dstartup"; "-dtimings";
"-dtypedtree"; "-dtypes"; "-dump-pass"; "-fno-PIC"; "-fPIC"; "-g"; "-i";
"-inlining-report"; "-keep-docs"; "-keep-docs"; "-keep-locs"; "-linkall";
"-make_runtime"; "-make-runtime"; "-modern"; "-no-alias-deps"; "-noassert";
"-noautolink"; "-no-check-prims"; "-nodynlink"; "-no-float-const-prop";
"-no-keep-locs"; "-no-principal"; "-no-rectypes"; "-no-strict-formats";
"-no-strict-sequence"; "-no-unbox-free-vars-of-clos";
"-no-unbox-specialised-args"; "-O2"; "-O3"; "-Oclassic"; "-opaque";
"-output-complete-obj"; "-output-obj"; "-p"; "-pack";
"-remove-unused-arguments"; "-S"; "-shared"; "-unbox-closures"; "-v";
"-verbose"; "-where";
]
let ocaml_ignored_parametrized_flags = [
"-cc"; "-cclib"; "-ccopt"; "-color"; "-dflambda-let"; "-dllib"; "-dllpath";
"-for-pack"; "-impl"; "-inline-alloc-cost"; "-inline-branch-cost";
"-inline-branch-factor"; "-inline-call-cost"; "-inline-indirect-cost";
"-inline-lifting-benefit"; "-inline-max-depth"; "-inline-max-unroll";
"-inline"; "-inline-prim-cost"; "-inline-toplevel"; "-intf";
"-intf_suffix"; "-intf-suffix"; "-o"; "-rounds"; "-runtime-variant";
"-unbox-closures-factor"; "-use-prims"; "-use_runtime"; "-use-runtime";
]
let ocaml_warnings_spec ~error =
Marg.param "warning specification" (fun spec ocaml ->
let b' = Warnings.backup () in
Warnings.restore ocaml.warnings;
Misc.try_finally (fun () ->
Warnings.parse_options error spec;
{ ocaml with warnings = Warnings.backup () })
~always:(fun () -> Warnings.restore b'))
let ocaml_flags = [
(
"-I",
marg_path (fun dir ocaml ->
{ocaml with include_dirs = dir :: ocaml.include_dirs}),
"<dir> Add <dir> to the list of include directories"
);
(
"-nostdlib",
Marg.unit (fun ocaml -> {ocaml with no_std_include = true}),
" Do not add default directory to the list of include directories"
);
(
"-unsafe",
Marg.unit (fun ocaml -> {ocaml with unsafe = true}),
" Do not compile bounds checking on array and string access"
);
(
"-labels",
Marg.unit (fun ocaml -> {ocaml with classic = false}),
" Use commuting label mode"
);
(
"-nolabels",
Marg.unit (fun ocaml -> {ocaml with classic = true}),
" Ignore non-optional labels in types"
);
(
"-principal",
Marg.unit (fun ocaml -> {ocaml with principal = true}),
" Check principality of type inference"
);
(
"-real-paths",
Marg.unit (fun ocaml -> {ocaml with real_paths = true}),
" Display real paths in types rather than short ones"
);
(
"-short-paths",
Marg.unit (fun ocaml -> {ocaml with real_paths = false}),
" Shorten paths in types"
);
(
"-rectypes",
Marg.unit (fun ocaml -> {ocaml with recursive_types = true}),
" Allow arbitrary recursive types"
);
(
"-strict-sequence",
Marg.unit (fun ocaml -> {ocaml with strict_sequence = true}),
" Left-hand part of a sequence must have type unit"
);
(
"-no-app-funct",
Marg.unit (fun ocaml -> {ocaml with applicative_functors = false}),
" Deactivate applicative functors"
);
(
"-thread",
Marg.unit (fun ocaml -> {ocaml with threads = `Threads}),
" Add support for system threads library"
);
(
"-vmthread",
Marg.unit (fun ocaml -> {ocaml with threads = `None}),
" Add support for VM-scheduled threads library"
);
(
"-unsafe-string",
Marg.unit (fun ocaml -> {ocaml with unsafe_string = true}),
Printf.sprintf
" Make strings mutable (default: %B)"
(not Config.safe_string)
);
(
"-safe-string",
Marg.unit (fun ocaml -> {ocaml with unsafe_string = false}),
Printf.sprintf
" Make strings immutable (default: %B)"
Config.safe_string
);
(
"-nopervasives",
Marg.unit (fun ocaml -> {ocaml with nopervasives = true}),
" Don't open Pervasives module (advanced)"
);
(
"-strict-formats",
Marg.unit (fun ocaml -> {ocaml with strict_formats = true}),
" Reject invalid formats accepted by legacy implementations"
);
(
"-open",
Marg.param "module" (fun md ocaml ->
{ocaml with open_modules = md :: ocaml.open_modules}),
"<module> Opens the module <module> before typing"
);
(
"-ppx",
marg_commandline (fun command ocaml ->
{ocaml with ppx = command :: ocaml.ppx}),
"<command> Pipe abstract syntax trees through preprocessor <command>"
);
(
"-pp",
marg_commandline (fun pp ocaml -> {ocaml with pp = Some pp}),
"<command> Pipe sources through preprocessor <command>"
);
( "-w",
ocaml_warnings_spec ~error:false,
Printf.sprintf
"<list> Enable or disable warnings according to <list>:\n\
\ +<spec> enable warnings in <spec>\n\
\ -<spec> disable warnings in <spec>\n\
\ @<spec> enable warnings in <spec> and treat them as errors\n\
\ <spec> can be:\n\
\ <num> a single warning number\n\
\ <num1>..<num2> a range of consecutive warning numbers\n\
\ <letter> a predefined set\n\
\ default setting is %S"
Warnings.defaults_w
);
( "-warn-error",
ocaml_warnings_spec ~error:true,
Printf.sprintf
"<list> Enable or disable error status for warnings according\n\
\ to <list>. See option -w for the syntax of <list>.\n\
\ Default setting is %S"
Warnings.defaults_warn_error
);
]
* { 1 Main configuration }
let initial = {
ocaml = {
include_dirs = [];
no_std_include = false;
unsafe = false;
classic = false;
principal = false;
real_paths = true;
threads = `None;
recursive_types = false;
strict_sequence = false;
applicative_functors = true;
unsafe_string = not Config.safe_string;
nopervasives = false;
strict_formats = false;
open_modules = [];
ppx = [];
pp = None;
warnings = Warnings.backup ();
};
merlin = {
build_path = [];
source_path = [];
cmi_path = [];
cmt_path = [];
extensions = [];
suffixes = [(".ml", ".mli"); (".re", ".rei")];
stdlib = None;
reader = [];
protocol = `Json;
log_file = None;
log_sections = [];
config_path = None;
exclude_query_dir = false;
flags_to_apply = [];
flags_applied = [];
failures = [];
extension_to_reader = [(".re","reason");(".rei","reason")];
};
query = {
filename = "*buffer*";
directory = Sys.getcwd ();
verbosity = 0;
printer_width = 0;
}
}
let parse_arguments ~wd ~warning local_spec args t local =
let_ref cwd (Some wd) @@ fun () ->
Marg.parse_all ~warning arguments_table local_spec args t local
let global_flags = [
(
"-filename",
marg_path (fun path t ->
let query = t.query in
let path = Misc.canonicalize_filename path in
let filename = Filename.basename path in
let directory = Filename.dirname path in
let t = {t with query = {query with filename; directory}} in
Logger.with_log_file t.merlin.log_file
~sections:t.merlin.log_sections @@ fun () ->
get_external_config path t),
"<path> Path of the buffer; \
extension determines the kind of file (interface or implementation), \
basename is used as name of the module being definer, \
directory is used to resolve other relative paths"
);
(
"-dot-merlin",
marg_path (fun dotmerlin t -> get_external_config dotmerlin t),
"<path> Load <path> as a .merlin; if it is a directory, \
look for .merlin here or in a parent directory"
);
]
let () =
List.iter ~f:(fun name -> Hashtbl.add arguments_table name Marg.unit_ignore)
ocaml_ignored_flags;
List.iter ~f:(fun name -> Hashtbl.add arguments_table name Marg.param_ignore)
ocaml_ignored_parametrized_flags;
let lens prj upd flag : _ Marg.t = fun args a ->
let cwd' = match !cwd with
| None when a.query.directory <> "" -> Some a.query.directory
| cwd -> cwd
in
let_ref cwd cwd' @@ fun () ->
let args, b = flag args (prj a) in
args, (upd a b)
in
let add prj upd (name,flag,_doc) =
assert (not (Hashtbl.mem arguments_table name));
Hashtbl.add arguments_table name (lens prj upd flag)
in
List.iter
~f:(add (fun x -> x.ocaml) (fun x ocaml -> {x with ocaml}))
ocaml_flags;
List.iter
~f:(add (fun x -> x.merlin) (fun x merlin -> {x with merlin}))
merlin_flags;
List.iter
~f:(add (fun x -> x.query) (fun x query -> {x with query}))
query_flags;
List.iter
~f:(add (fun x -> x) (fun _ x -> x))
global_flags
let flags_for_completion () =
List.sort ~cmp:compare (
"-dot-merlin" :: "-reader" ::
List.map ~f:(fun (x,_,_) -> x) ocaml_flags
)
let document_arguments oc =
let print_doc flags =
List.iter ~f:(fun (name,_flag,doc) -> Printf.fprintf oc " %s\t%s\n" name doc)
flags
in
output_string oc "Flags affecting Merlin:\n";
print_doc merlin_flags;
print_doc query_flags;
output_string oc "Flags affecting OCaml frontend:\n";
print_doc ocaml_flags;
output_string oc "Flags accepted by ocamlc and ocamlopt but not affecting merlin will be ignored.\n"
let source_path config =
let stdlib = if config.ocaml.no_std_include then [] else [stdlib config] in
List.concat
[[config.query.directory];
stdlib;
config.merlin.source_path]
let build_path config = (
let dirs =
match config.ocaml.threads with
| `None -> config.ocaml.include_dirs
| `Threads -> "+threads" :: config.ocaml.include_dirs
| `Vmthreads -> "+vmthreads" :: config.ocaml.include_dirs
in
let dirs =
config.merlin.cmi_path @
config.merlin.build_path @
dirs
in
let stdlib = stdlib config in
let exp_dirs =
List.map ~f:(Misc.expand_directory stdlib) dirs
in
let stdlib = if config.ocaml.no_std_include then [] else [stdlib] in
let dirs = List.rev_append exp_dirs stdlib in
let result =
if config.merlin.exclude_query_dir
then dirs
else config.query.directory :: dirs
in
let result' = List.filter_dup result in
log ~title:"build_path" "%d items in path, %d after deduplication"
(List.length result) (List.length result');
result'
)
let cmt_path config = (
let dirs =
match config.ocaml.threads with
| `None -> config.ocaml.include_dirs
| `Threads -> "+threads" :: config.ocaml.include_dirs
| `Vmthreads -> "+vmthreads" :: config.ocaml.include_dirs
in
let dirs =
config.merlin.cmt_path @
config.merlin.build_path @
dirs
in
let stdlib = stdlib config in
let exp_dirs =
List.map ~f:(Misc.expand_directory stdlib) dirs
in
let stdlib = if config.ocaml.no_std_include then [] else [stdlib] in
config.query.directory :: List.rev_append exp_dirs stdlib
)
let global_modules ?(include_current=false) config = (
let modules = Misc.modules_in_path ~ext:".cmi" (build_path config) in
if include_current then modules
else match config.query.filename with
| "" -> modules
| filename -> List.remove (Misc.unitname filename) modules
)
* { 1 Accessors for other information }
let filename t = t.query.filename
let unitname t = Misc.unitname t.query.filename
| null | https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/src/kernel/mconfig.ml | ocaml | * {1 OCaml commandline parsing}
* Some paths can be resolved relative to a current working directory
* {1 Merlin high-level settings} | open Std
let {Logger. log} = Logger.for_section "Mconfig"
type ocaml = {
include_dirs : string list;
no_std_include : bool;
unsafe : bool;
classic : bool;
principal : bool;
real_paths : bool;
threads : [ `None | `Threads | `Vmthreads ];
recursive_types : bool;
strict_sequence : bool;
applicative_functors : bool;
unsafe_string : bool;
nopervasives : bool;
strict_formats : bool;
open_modules : string list;
ppx : string with_workdir list;
pp : string with_workdir option;
warnings : Warnings.state;
}
let dump_warnings st =
let st' = Warnings.backup () in
Warnings.restore st;
Misc.try_finally Warnings.dump
~always:(fun () -> Warnings.restore st')
let dump_ocaml x = `Assoc [
"include_dirs" , `List (List.map ~f:Json.string x.include_dirs);
"no_std_include" , `Bool x.no_std_include;
"unsafe" , `Bool x.unsafe;
"classic" , `Bool x.classic;
"principal" , `Bool x.principal;
"real_paths" , `Bool x.real_paths;
"recursive_types" , `Bool x.recursive_types;
"strict_sequence" , `Bool x.strict_sequence;
"applicative_functors" , `Bool x.applicative_functors;
"unsafe_string" , `Bool x.unsafe_string;
"nopervasives" , `Bool x.nopervasives;
"strict_formats" , `Bool x.strict_formats;
"open_modules" , Json.list Json.string x.open_modules;
"ppx" , Json.list (dump_with_workdir Json.string) x.ppx;
"pp" , Json.option (dump_with_workdir Json.string) x.pp;
"warnings" , dump_warnings x.warnings;
]
let cwd = ref None
let unsafe_get_cwd () = match !cwd with
| None -> assert false
| Some cwd -> cwd
let canonicalize_filename path =
Misc.canonicalize_filename ?cwd:!cwd path
let marg_path f =
Marg.param "path" (fun path acc -> f (canonicalize_filename path) acc)
let marg_commandline f =
Marg.param "command"
(fun workval acc -> f {workdir = unsafe_get_cwd (); workval} acc)
type merlin = {
build_path : string list;
source_path : string list;
cmi_path : string list;
cmt_path : string list;
extensions : string list;
suffixes : (string * string) list;
stdlib : string option;
reader : string list;
protocol : [`Json | `Sexp];
log_file : string option;
log_sections : string list;
config_path : string option;
exclude_query_dir : bool;
flags_to_apply : string list with_workdir list;
flags_applied : string list with_workdir list;
failures : string list;
extension_to_reader : (string * string) list
}
let dump_merlin x =
let dump_flag_list flags =
dump_with_workdir (Json.list Json.string) flags
in
`Assoc [
"build_path" , `List (List.map ~f:Json.string x.build_path);
"source_path" , `List (List.map ~f:Json.string x.source_path);
"cmi_path" , `List (List.map ~f:Json.string x.cmi_path);
"cmt_path" , `List (List.map ~f:Json.string x.cmt_path);
"flags_applied", `List (List.map ~f:dump_flag_list x.flags_applied);
"extensions" , `List (List.map ~f:Json.string x.extensions);
"suffixes" , `List (
List.map ~f:(fun (impl,intf) -> `Assoc [
"impl", `String impl;
"intf", `String intf;
]) x.suffixes
);
"stdlib" , Json.option Json.string x.stdlib;
"reader" , `List (List.map ~f:Json.string x.reader);
"protocol" , (match x.protocol with
| `Json -> `String "json"
| `Sexp -> `String "sexp"
);
"log_file" , Json.option Json.string x.log_file;
"log_sections" , Json.list Json.string x.log_sections;
"flags_to_apply" , `List (List.map ~f:dump_flag_list x.flags_to_apply);
"failures" , `List (List.map ~f:Json.string x.failures);
"assoc_suffixes" , `List (
List.map ~f:(fun (suffix,reader) -> `Assoc [
"extension", `String suffix;
"reader", `String reader;
]) x.extension_to_reader
)
]
type query = {
filename : string;
directory : string;
printer_width : int;
verbosity : int;
}
let dump_query x = `Assoc [
"filename" , `String x.filename;
"directory" , `String x.directory;
"printer_width", `Int x.printer_width;
"verbosity" , `Int x.verbosity;
]
type t = {
ocaml : ocaml;
merlin : merlin;
query : query;
}
let dump x = `Assoc [
"ocaml" , dump_ocaml x.ocaml;
"merlin" , dump_merlin x.merlin;
"query" , dump_query x.query;
]
let arguments_table = Hashtbl.create 67
let stdlib =
let env =
try Some (Sys.getenv "OCAMLLIB")
with Not_found ->
try Some (Sys.getenv "CAMLLIB")
with Not_found -> None
in
fun config ->
match config.merlin.stdlib with
| Some stdlib -> stdlib
| None -> match env with
| Some stdlib -> stdlib
| None -> Standard_library.path
let normalize_step t =
let merlin = t.merlin in
if merlin.flags_to_apply <> [] then
let flagss = merlin.flags_to_apply in
let t = {t with merlin = { merlin with
flags_to_apply = [];
flags_applied = flagss @ merlin.flags_applied;
} }
in
let failures = ref [] in
let warning failure = failures := failure :: !failures in
let t = List.fold_left ~f:(fun t {workdir; workval} -> fst (
let_ref cwd (Some workdir)
(Marg.parse_all ~warning arguments_table [] workval t)
)) ~init:t flagss
in
{t with merlin = {t.merlin with failures = !failures @ t.merlin.failures}}
else
t
let is_normalized t =
let merlin = t.merlin in
merlin.flags_to_apply = []
let rec normalize t =
if is_normalized t then (
log ~title:"normalize" "%a" Logger.json (fun () -> dump t);
t
) else
normalize (normalize_step t)
let get_external_config path t =
let path = Misc.canonicalize_filename path in
let directory = Filename.dirname path in
match Mconfig_dot.find_project_context directory with
| None -> t
| Some (ctxt, config_path) ->
let dot, failures = Mconfig_dot.get_config ctxt path in
let merlin = t.merlin in
let merlin = {
merlin with
build_path = dot.build_path @ merlin.build_path;
source_path = dot.source_path @ merlin.source_path;
cmi_path = dot.cmi_path @ merlin.cmi_path;
cmt_path = dot.cmt_path @ merlin.cmt_path;
exclude_query_dir = dot.exclude_query_dir || merlin.exclude_query_dir;
extensions = dot.extensions @ merlin.extensions;
suffixes = dot.suffixes @ merlin.suffixes;
stdlib = (if dot.stdlib = None then merlin.stdlib else dot.stdlib);
reader =
if dot.reader = []
then merlin.reader
else dot.reader;
flags_to_apply = dot.flags @ merlin.flags_to_apply;
failures = failures @ merlin.failures;
config_path = Some config_path;
} in
normalize { t with merlin }
let merlin_flags = [
(
"-build-path",
marg_path (fun dir merlin ->
{merlin with build_path = dir :: merlin.build_path}),
"<dir> Add <dir> to merlin build path"
);
(
"-source-path",
marg_path (fun dir merlin ->
{merlin with source_path = dir :: merlin.source_path}),
"<dir> Add <dir> to merlin source path"
);
(
"-cmi-path",
marg_path (fun dir merlin ->
{merlin with cmi_path = dir :: merlin.cmi_path}),
"<dir> Add <dir> to merlin cmi path"
);
(
"-cmt-path",
marg_path (fun dir merlin ->
{merlin with build_path = dir :: merlin.cmt_path}),
"<dir> Add <dir> to merlin cmt path"
);
(
"-reader",
Marg.param "command" (fun reader merlin ->
{merlin with reader = Shell.split_command reader }),
"<command> Use <command> as a merlin reader"
);
(
"-assocsuffix",
Marg.param "suffix:reader"
(fun assoc_pair merlin ->
match Misc.rev_string_split ~on:':' assoc_pair with
| [reader;suffix] ->
{merlin with
extension_to_reader = (suffix,reader)::merlin.extension_to_reader}
| _ -> merlin
),
"Associate suffix with reader"
);
(
"-addsuffix",
Marg.param "implementation Suffix, interface Suffix"
(fun suffix_pair merlin ->
match Misc.rev_string_split ~on:':' suffix_pair with
| [intf;impl] ->
{merlin with suffixes = (impl,intf)::merlin.suffixes}
| _ -> merlin
),
"Add a suffix implementation,interface pair"
);
(
"-extension",
Marg.param "extension" (fun extension merlin ->
match Extension.lookup extension with
| None -> invalid_arg "Unknown extension"
| Some _ ->
{merlin with extensions = extension :: merlin.extensions}),
"<extension> Load merlin syntax extension"
);
(
"-flags",
Marg.param "string" (fun flags merlin ->
let flags =
{ workdir = unsafe_get_cwd (); workval = Shell.split_command flags }
in
{merlin with flags_to_apply = flags :: merlin.flags_to_apply}),
"<quoted flags> Unescape argument and interpret it as more flags"
);
(
"-protocol",
Marg.param "protocol" (fun prot merlin ->
match prot with
| "json" -> {merlin with protocol = `Json}
| "sexp" -> {merlin with protocol = `Sexp}
| _ -> invalid_arg "Valid protocols are 'json' and 'sexp'";
),
"<protocol> Select frontend protocol ('json' or 'sexp')"
);
(
"-log-file",
Marg.param "file" (fun file merlin -> {merlin with log_file = Some file}),
"<file> Log messages to specified file ('' for disabling, '-' for stderr)"
);
(
"-log-section",
Marg.param "file" (fun section merlin ->
let sections = String.split_on_char_ ',' section in
{merlin with log_sections = sections @ merlin.log_sections}),
"<section,...> Only log specific sections (separated by comma)"
);
(
"-ocamllib-path",
marg_path (fun path merlin -> {merlin with stdlib = Some path}),
"<path> Change path of ocaml standard library"
);
(
Legacy support for janestreet . Ignored . To be removed soon .
"-attributes-allowed",
Marg.unit_ignore,
" DEPRECATED"
);
]
let query_flags = [
(
"-verbosity",
Marg.param "integer" (fun verbosity query ->
let verbosity =
try int_of_string verbosity
with _ -> invalid_arg "argument should be an integer"
in
{query with verbosity}),
"<integer> Verbosity determines the number of expansions of aliases in answers"
);
(
"-printer-width",
Marg.param "integer" (fun width query ->
let printer_width =
try int_of_string width
with _ -> invalid_arg "argument should be an integer"
in
{query with printer_width}),
"<integer> Optimal width for formatting types, signatures, etc"
)
]
let ocaml_ignored_flags = [
"-a"; "-absname"; "-alias-deps"; "-annot"; "-app-funct"; "-bin-annot";
"-c"; "-compact"; "-compat-32"; "-config"; "-custom"; "-dalloc";
"-dclambda"; "-dcmm"; "-dcombine"; "-dcse"; "-dflambda";
"-dflambda-no-invariants"; "-dflambda-verbose"; "-dinstr"; "-dinterf";
"-dlambda"; "-dlinear"; "-dlive"; "-dparsetree"; "-dprefer";
"-drawclambda"; "-drawflambda"; "-drawlambda"; "-dreload"; "-dscheduling";
"-dsel"; "-dsource"; "-dspill"; "-dsplit"; "-dstartup"; "-dtimings";
"-dtypedtree"; "-dtypes"; "-dump-pass"; "-fno-PIC"; "-fPIC"; "-g"; "-i";
"-inlining-report"; "-keep-docs"; "-keep-docs"; "-keep-locs"; "-linkall";
"-make_runtime"; "-make-runtime"; "-modern"; "-no-alias-deps"; "-noassert";
"-noautolink"; "-no-check-prims"; "-nodynlink"; "-no-float-const-prop";
"-no-keep-locs"; "-no-principal"; "-no-rectypes"; "-no-strict-formats";
"-no-strict-sequence"; "-no-unbox-free-vars-of-clos";
"-no-unbox-specialised-args"; "-O2"; "-O3"; "-Oclassic"; "-opaque";
"-output-complete-obj"; "-output-obj"; "-p"; "-pack";
"-remove-unused-arguments"; "-S"; "-shared"; "-unbox-closures"; "-v";
"-verbose"; "-where";
]
let ocaml_ignored_parametrized_flags = [
"-cc"; "-cclib"; "-ccopt"; "-color"; "-dflambda-let"; "-dllib"; "-dllpath";
"-for-pack"; "-impl"; "-inline-alloc-cost"; "-inline-branch-cost";
"-inline-branch-factor"; "-inline-call-cost"; "-inline-indirect-cost";
"-inline-lifting-benefit"; "-inline-max-depth"; "-inline-max-unroll";
"-inline"; "-inline-prim-cost"; "-inline-toplevel"; "-intf";
"-intf_suffix"; "-intf-suffix"; "-o"; "-rounds"; "-runtime-variant";
"-unbox-closures-factor"; "-use-prims"; "-use_runtime"; "-use-runtime";
]
let ocaml_warnings_spec ~error =
Marg.param "warning specification" (fun spec ocaml ->
let b' = Warnings.backup () in
Warnings.restore ocaml.warnings;
Misc.try_finally (fun () ->
Warnings.parse_options error spec;
{ ocaml with warnings = Warnings.backup () })
~always:(fun () -> Warnings.restore b'))
let ocaml_flags = [
(
"-I",
marg_path (fun dir ocaml ->
{ocaml with include_dirs = dir :: ocaml.include_dirs}),
"<dir> Add <dir> to the list of include directories"
);
(
"-nostdlib",
Marg.unit (fun ocaml -> {ocaml with no_std_include = true}),
" Do not add default directory to the list of include directories"
);
(
"-unsafe",
Marg.unit (fun ocaml -> {ocaml with unsafe = true}),
" Do not compile bounds checking on array and string access"
);
(
"-labels",
Marg.unit (fun ocaml -> {ocaml with classic = false}),
" Use commuting label mode"
);
(
"-nolabels",
Marg.unit (fun ocaml -> {ocaml with classic = true}),
" Ignore non-optional labels in types"
);
(
"-principal",
Marg.unit (fun ocaml -> {ocaml with principal = true}),
" Check principality of type inference"
);
(
"-real-paths",
Marg.unit (fun ocaml -> {ocaml with real_paths = true}),
" Display real paths in types rather than short ones"
);
(
"-short-paths",
Marg.unit (fun ocaml -> {ocaml with real_paths = false}),
" Shorten paths in types"
);
(
"-rectypes",
Marg.unit (fun ocaml -> {ocaml with recursive_types = true}),
" Allow arbitrary recursive types"
);
(
"-strict-sequence",
Marg.unit (fun ocaml -> {ocaml with strict_sequence = true}),
" Left-hand part of a sequence must have type unit"
);
(
"-no-app-funct",
Marg.unit (fun ocaml -> {ocaml with applicative_functors = false}),
" Deactivate applicative functors"
);
(
"-thread",
Marg.unit (fun ocaml -> {ocaml with threads = `Threads}),
" Add support for system threads library"
);
(
"-vmthread",
Marg.unit (fun ocaml -> {ocaml with threads = `None}),
" Add support for VM-scheduled threads library"
);
(
"-unsafe-string",
Marg.unit (fun ocaml -> {ocaml with unsafe_string = true}),
Printf.sprintf
" Make strings mutable (default: %B)"
(not Config.safe_string)
);
(
"-safe-string",
Marg.unit (fun ocaml -> {ocaml with unsafe_string = false}),
Printf.sprintf
" Make strings immutable (default: %B)"
Config.safe_string
);
(
"-nopervasives",
Marg.unit (fun ocaml -> {ocaml with nopervasives = true}),
" Don't open Pervasives module (advanced)"
);
(
"-strict-formats",
Marg.unit (fun ocaml -> {ocaml with strict_formats = true}),
" Reject invalid formats accepted by legacy implementations"
);
(
"-open",
Marg.param "module" (fun md ocaml ->
{ocaml with open_modules = md :: ocaml.open_modules}),
"<module> Opens the module <module> before typing"
);
(
"-ppx",
marg_commandline (fun command ocaml ->
{ocaml with ppx = command :: ocaml.ppx}),
"<command> Pipe abstract syntax trees through preprocessor <command>"
);
(
"-pp",
marg_commandline (fun pp ocaml -> {ocaml with pp = Some pp}),
"<command> Pipe sources through preprocessor <command>"
);
( "-w",
ocaml_warnings_spec ~error:false,
Printf.sprintf
"<list> Enable or disable warnings according to <list>:\n\
\ +<spec> enable warnings in <spec>\n\
\ -<spec> disable warnings in <spec>\n\
\ @<spec> enable warnings in <spec> and treat them as errors\n\
\ <spec> can be:\n\
\ <num> a single warning number\n\
\ <num1>..<num2> a range of consecutive warning numbers\n\
\ <letter> a predefined set\n\
\ default setting is %S"
Warnings.defaults_w
);
( "-warn-error",
ocaml_warnings_spec ~error:true,
Printf.sprintf
"<list> Enable or disable error status for warnings according\n\
\ to <list>. See option -w for the syntax of <list>.\n\
\ Default setting is %S"
Warnings.defaults_warn_error
);
]
* { 1 Main configuration }
let initial = {
ocaml = {
include_dirs = [];
no_std_include = false;
unsafe = false;
classic = false;
principal = false;
real_paths = true;
threads = `None;
recursive_types = false;
strict_sequence = false;
applicative_functors = true;
unsafe_string = not Config.safe_string;
nopervasives = false;
strict_formats = false;
open_modules = [];
ppx = [];
pp = None;
warnings = Warnings.backup ();
};
merlin = {
build_path = [];
source_path = [];
cmi_path = [];
cmt_path = [];
extensions = [];
suffixes = [(".ml", ".mli"); (".re", ".rei")];
stdlib = None;
reader = [];
protocol = `Json;
log_file = None;
log_sections = [];
config_path = None;
exclude_query_dir = false;
flags_to_apply = [];
flags_applied = [];
failures = [];
extension_to_reader = [(".re","reason");(".rei","reason")];
};
query = {
filename = "*buffer*";
directory = Sys.getcwd ();
verbosity = 0;
printer_width = 0;
}
}
let parse_arguments ~wd ~warning local_spec args t local =
let_ref cwd (Some wd) @@ fun () ->
Marg.parse_all ~warning arguments_table local_spec args t local
let global_flags = [
(
"-filename",
marg_path (fun path t ->
let query = t.query in
let path = Misc.canonicalize_filename path in
let filename = Filename.basename path in
let directory = Filename.dirname path in
let t = {t with query = {query with filename; directory}} in
Logger.with_log_file t.merlin.log_file
~sections:t.merlin.log_sections @@ fun () ->
get_external_config path t),
"<path> Path of the buffer; \
extension determines the kind of file (interface or implementation), \
basename is used as name of the module being definer, \
directory is used to resolve other relative paths"
);
(
"-dot-merlin",
marg_path (fun dotmerlin t -> get_external_config dotmerlin t),
"<path> Load <path> as a .merlin; if it is a directory, \
look for .merlin here or in a parent directory"
);
]
let () =
List.iter ~f:(fun name -> Hashtbl.add arguments_table name Marg.unit_ignore)
ocaml_ignored_flags;
List.iter ~f:(fun name -> Hashtbl.add arguments_table name Marg.param_ignore)
ocaml_ignored_parametrized_flags;
let lens prj upd flag : _ Marg.t = fun args a ->
let cwd' = match !cwd with
| None when a.query.directory <> "" -> Some a.query.directory
| cwd -> cwd
in
let_ref cwd cwd' @@ fun () ->
let args, b = flag args (prj a) in
args, (upd a b)
in
let add prj upd (name,flag,_doc) =
assert (not (Hashtbl.mem arguments_table name));
Hashtbl.add arguments_table name (lens prj upd flag)
in
List.iter
~f:(add (fun x -> x.ocaml) (fun x ocaml -> {x with ocaml}))
ocaml_flags;
List.iter
~f:(add (fun x -> x.merlin) (fun x merlin -> {x with merlin}))
merlin_flags;
List.iter
~f:(add (fun x -> x.query) (fun x query -> {x with query}))
query_flags;
List.iter
~f:(add (fun x -> x) (fun _ x -> x))
global_flags
let flags_for_completion () =
List.sort ~cmp:compare (
"-dot-merlin" :: "-reader" ::
List.map ~f:(fun (x,_,_) -> x) ocaml_flags
)
let document_arguments oc =
let print_doc flags =
List.iter ~f:(fun (name,_flag,doc) -> Printf.fprintf oc " %s\t%s\n" name doc)
flags
in
output_string oc "Flags affecting Merlin:\n";
print_doc merlin_flags;
print_doc query_flags;
output_string oc "Flags affecting OCaml frontend:\n";
print_doc ocaml_flags;
output_string oc "Flags accepted by ocamlc and ocamlopt but not affecting merlin will be ignored.\n"
let source_path config =
let stdlib = if config.ocaml.no_std_include then [] else [stdlib config] in
List.concat
[[config.query.directory];
stdlib;
config.merlin.source_path]
let build_path config = (
let dirs =
match config.ocaml.threads with
| `None -> config.ocaml.include_dirs
| `Threads -> "+threads" :: config.ocaml.include_dirs
| `Vmthreads -> "+vmthreads" :: config.ocaml.include_dirs
in
let dirs =
config.merlin.cmi_path @
config.merlin.build_path @
dirs
in
let stdlib = stdlib config in
let exp_dirs =
List.map ~f:(Misc.expand_directory stdlib) dirs
in
let stdlib = if config.ocaml.no_std_include then [] else [stdlib] in
let dirs = List.rev_append exp_dirs stdlib in
let result =
if config.merlin.exclude_query_dir
then dirs
else config.query.directory :: dirs
in
let result' = List.filter_dup result in
log ~title:"build_path" "%d items in path, %d after deduplication"
(List.length result) (List.length result');
result'
)
let cmt_path config = (
let dirs =
match config.ocaml.threads with
| `None -> config.ocaml.include_dirs
| `Threads -> "+threads" :: config.ocaml.include_dirs
| `Vmthreads -> "+vmthreads" :: config.ocaml.include_dirs
in
let dirs =
config.merlin.cmt_path @
config.merlin.build_path @
dirs
in
let stdlib = stdlib config in
let exp_dirs =
List.map ~f:(Misc.expand_directory stdlib) dirs
in
let stdlib = if config.ocaml.no_std_include then [] else [stdlib] in
config.query.directory :: List.rev_append exp_dirs stdlib
)
let global_modules ?(include_current=false) config = (
let modules = Misc.modules_in_path ~ext:".cmi" (build_path config) in
if include_current then modules
else match config.query.filename with
| "" -> modules
| filename -> List.remove (Misc.unitname filename) modules
)
* { 1 Accessors for other information }
let filename t = t.query.filename
let unitname t = Misc.unitname t.query.filename
|
ba4fc5da81a5bd945dbbfae55f31386b0eb1db0f9ea80e41529f0fd9caccd51b | district0x/district-registry | page.cljs | (ns district-registry.ui.home.page
(:require
[bignumber.core :as bn]
[cljs-web3.core :as web3]
[district-registry.ui.components.app-layout :refer [app-layout]]
[district-registry.ui.components.nav :as nav]
[district-registry.ui.components.stake :as stake]
[district-registry.ui.contract.district :as district]
[district.format :as format]
[district.graphql-utils :as gql-utils]
[district.ui.component.page :refer [page]]
[district.ui.graphql.subs :as gql]
[district.ui.ipfs.subs :as ipfs-subs]
[district.ui.now.subs :as now-subs]
[district.ui.router.subs :as router-subs]
[district.ui.web3-accounts.subs :as account-subs]
[re-frame.core :refer [subscribe dispatch]]
[reagent.core :as r]))
(defn build-query [active-account route-query]
[:search-districts
{:order-by (keyword "districts.order-by" (:order-by route-query))
:order-dir :desc
:statuses (case (:status route-query)
"in-registry" [:reg-entry.status/challenge-period
:reg-entry.status/commit-period
:reg-entry.status/reveal-period
:reg-entry.status/whitelisted]
"challenged" [:reg-entry.status/commit-period
:reg-entry.status/reveal-period]
"blacklisted" [:reg-entry.status/blacklisted])
:first 1000}
[:total-count
:end-cursor
:has-next-page
[:items [:reg-entry/address
:reg-entry/version
:reg-entry/status
:reg-entry/creator
:reg-entry/deposit
:reg-entry/created-on
:reg-entry/challenge-period-end
[:reg-entry/challenges
[:challenge/index
:challenge/challenger
:challenge/commit-period-end
:challenge/reveal-period-end]]
:district/meta-hash
:district/name
:district/description
:district/url
:district/github-url
:district/logo-image-hash
:district/background-image-hash
:district/dnt-staked
:district/total-supply
[:district/dnt-staked-for {:staker active-account}]
[:district/balance-of {:staker active-account}]]]]])
(defn district-image []
(let [ipfs (subscribe [::ipfs-subs/ipfs])]
(fn [image-hash]
(when image-hash
(when-let [url (:gateway @ipfs)]
[:img.district-image {:src (str (format/ensure-trailing-slash url) image-hash)}])))))
(defn district-tile [{:keys [:district/background-image-hash
:district/balance-of
:district/description
:district/dnt-staked
:district/dnt-staked-for
:district/github-url
:district/meta-hash
:district/logo-image-hash
:district/name
:district/total-supply
:district/url
:reg-entry/status
:reg-entry/address
:reg-entry/challenges
:reg-entry/deposit
:reg-entry/version]
:as district}
{:keys [:status]}]
(let [nav-to-details-props {:style {:cursor "pointer"}
:on-click #(dispatch [:district.ui.router.events/navigate
:route/detail
{:address address}])}]
[:div.grid-box
[:div.box-image nav-to-details-props
[district-image background-image-hash]]
[:div.box-text
[:div.box-logo.sized nav-to-details-props
[district-image logo-image-hash]]
[:div.inner
[:h2 nav-to-details-props (format/truncate name 64)]
[:p nav-to-details-props (format/truncate description 200)]
(when (and (= status "challenged"))
(let [{:keys [:challenge/commit-period-end :challenge/reveal-period-end] :as challenge} (last challenges)]
[:p.time-remaining [:b
(when challenge
(let [district-status (gql-utils/gql-name->kw (:reg-entry/status district))
commit-period? (= district-status :reg-entry.status/commit-period)
remaining-time @(subscribe [::now-subs/time-remaining (gql-utils/gql-date->date (if commit-period?
commit-period-end
reveal-period-end))])
has-remaining-time? (not (format/zero-time-units? remaining-time))]
(cond
(and commit-period? has-remaining-time?)
(str "Vote period ends in " (format/format-time-units remaining-time {:short? true}))
(and commit-period? (not has-remaining-time?))
"Vote period ended."
(and (not commit-period?) has-remaining-time?)
(str "Reveal period ends in " (format/format-time-units remaining-time {:short? true}))
(and (not commit-period?) (not has-remaining-time?))
"Reveal period ended."
:else "")))]]))
[:div.h-line]
[stake/stake-info address]
[stake/stake-form address {:disable-estimated-return? (= status "blacklisted")}]]
[:div.arrow-blob
(nav/a {:route [:route/detail {:address address}]}
[:span.arr.icon-arrow-right])]]]))
(defn loader []
(let [mounted? (r/atom false)]
(fn []
(when-not @mounted?
(js/setTimeout #(swap! mounted? not)))
[:div#loader-wrapper {:class (str "fade-in" (when @mounted? " visible"))}
[:div#loader
[:div.loader-graphic
;; [:img.blob.spacer {:src "/images/svg/loader-blob.svg"}]
[:div.loader-floater
[:img.bg.spacer {:src "/images/svg/loader-bg.svg"}]
[:div.turbine
[:img.base {:src "/images/svg/turbine-base.svg"}]
[:div.wheel [:img {:src "/images/svg/turbine-blade.svg"}]]
[:img.cover {:src "/images/svg/turbine-cover.svg"}]]
[:div.fan
{:data-num "1"}
[:img.base {:src "/images/svg/fan-base.svg"}]
[:div.wheel [:img {:src "/images/svg/fan-spokes.svg"}]]]
[:div.fan
{:data-num "2"}
[:img.base {:src "/images/svg/fan-base.svg"}]
[:div.wheel [:img {:src "/images/svg/fan-spokes.svg"}]]]]]]])))
(defn district-tiles [active-account route-query]
(let [q (subscribe [::gql/query
{:queries [(build-query active-account route-query)]}
{:refetch-on #{::district/approve-and-stake-for-success
::district/unstake-success}}])
result (:search-districts @q)
districts (:items result)]
(cond
(:graphql/loading? @q) [loader]
(empty? districts) [:div.no-districts
[:h2 "No districts found"]]
:else [:div.grid.spaced
(->> districts
(map (fn [{:as district
:keys [:reg-entry/address]}]
^{:key address} [district-tile district route-query]))
doall)])))
(defn- build-total-count-query [status-group]
(let [statuses (case status-group
:in-registry [:reg-entry.status/challenge-period
:reg-entry.status/commit-period
:reg-entry.status/reveal-period
:reg-entry.status/whitelisted]
:challenged [:reg-entry.status/commit-period
:reg-entry.status/reveal-period]
:blacklisted [:reg-entry.status/blacklisted])]
[:search-districts
{:order-by :districts.order-by/created-on
:order-dir :desc
:statuses statuses
:first 0}
[:total-count]]))
(defn- navigation-item [{:keys [:status :selected-status :route-query]} text]
(let [query (subscribe [::gql/query {:queries [(build-total-count-query status)]}])]
(fn []
[:li {:class (when (= selected-status (name status)) "on")}
(nav/a {:route [:route/home {} (assoc route-query :status (name status))]
:class (when-not (= status :blacklisted)
"cta-btn")}
(str text (when-let [total-count (-> @query :search-districts :total-count)]
(str " (" total-count ")"))))])))
(defmethod page :route/home []
(let [active-account (subscribe [::account-subs/active-account])
route-query (subscribe [::router-subs/active-page-query])
status (or (:status @route-query) "in-registry")
order-by (or (:order-by @route-query) "created-on")
order-by-kw (keyword "districts.order-by" order-by)
order-by-kw->str {:districts.order-by/created-on "Creation Date"
:districts.order-by/dnt-staked "DNT Staked"}
select-menu-open? (r/atom false)]
(fn []
[app-layout
[:section#intro
[:div.bg-wrap
[:div.background.sized
[:img {:src "/images/"}]]]
[:div.container
[:nav.subnav
[:ul
[navigation-item
{:status :in-registry
:selected-status status
:route-query @route-query}
"In Registry"]
[navigation-item
{:status :challenged
:selected-status status
:route-query @route-query}
"Challenged"]
[navigation-item
{:status :blacklisted
:selected-status status
:route-query @route-query}
"Blacklisted"]]]
[:p
(condp = status
"challenged" "Listed below are all the currently active challenges against districts. Users can vote in challenges with DNT. If a district wins it's challenge, it stays, but if it loses, it will be removed from the registry and placed in the blacklist, and users can no longer stake to it. To participate in the vote, click a challenged district below and scroll to the bottom of the page."
"blacklisted" "This page contains all districts removed from the registry due to a lost challenge. Any DNT still staked to these districts can be unstaked at any time using this page."
"Below is a list of all districts currently in the registry. In order to participate in governance, you will need DNT available in a connected Ethereum wallet. Simply choose the district from the list below, enter the amount you want to stake or unstake, and press the appropriate button. You can click on districts for more detail.")]]]
[:section#registry-grid
[:div.container
[:div.select-menu {:class (when @select-menu-open? "on")
:on-click #(swap! select-menu-open? not)}
[:div.select-choice.cta-btn
[:div.select-text (order-by-kw order-by-kw->str)]
[:div.arrow [:span.arr.icon-arrow-down]]]
[:div.select-drop
[:ul
(->> order-by-kw->str
keys
(remove #(= order-by-kw %))
(map (fn [k]
[:li {:key k}
(nav/a {:route [:route/home {} (assoc @route-query :order-by (name k))]}
(order-by-kw->str k))]))
doall)]]]
[district-tiles @active-account (assoc @route-query
:status status
:order-by order-by)]]]])))
| null | https://raw.githubusercontent.com/district0x/district-registry/c2dcf7978d2243a773165b18e7a76632d8ad724e/src/district_registry/ui/home/page.cljs | clojure | [:img.blob.spacer {:src "/images/svg/loader-blob.svg"}] | (ns district-registry.ui.home.page
(:require
[bignumber.core :as bn]
[cljs-web3.core :as web3]
[district-registry.ui.components.app-layout :refer [app-layout]]
[district-registry.ui.components.nav :as nav]
[district-registry.ui.components.stake :as stake]
[district-registry.ui.contract.district :as district]
[district.format :as format]
[district.graphql-utils :as gql-utils]
[district.ui.component.page :refer [page]]
[district.ui.graphql.subs :as gql]
[district.ui.ipfs.subs :as ipfs-subs]
[district.ui.now.subs :as now-subs]
[district.ui.router.subs :as router-subs]
[district.ui.web3-accounts.subs :as account-subs]
[re-frame.core :refer [subscribe dispatch]]
[reagent.core :as r]))
(defn build-query [active-account route-query]
[:search-districts
{:order-by (keyword "districts.order-by" (:order-by route-query))
:order-dir :desc
:statuses (case (:status route-query)
"in-registry" [:reg-entry.status/challenge-period
:reg-entry.status/commit-period
:reg-entry.status/reveal-period
:reg-entry.status/whitelisted]
"challenged" [:reg-entry.status/commit-period
:reg-entry.status/reveal-period]
"blacklisted" [:reg-entry.status/blacklisted])
:first 1000}
[:total-count
:end-cursor
:has-next-page
[:items [:reg-entry/address
:reg-entry/version
:reg-entry/status
:reg-entry/creator
:reg-entry/deposit
:reg-entry/created-on
:reg-entry/challenge-period-end
[:reg-entry/challenges
[:challenge/index
:challenge/challenger
:challenge/commit-period-end
:challenge/reveal-period-end]]
:district/meta-hash
:district/name
:district/description
:district/url
:district/github-url
:district/logo-image-hash
:district/background-image-hash
:district/dnt-staked
:district/total-supply
[:district/dnt-staked-for {:staker active-account}]
[:district/balance-of {:staker active-account}]]]]])
(defn district-image []
(let [ipfs (subscribe [::ipfs-subs/ipfs])]
(fn [image-hash]
(when image-hash
(when-let [url (:gateway @ipfs)]
[:img.district-image {:src (str (format/ensure-trailing-slash url) image-hash)}])))))
(defn district-tile [{:keys [:district/background-image-hash
:district/balance-of
:district/description
:district/dnt-staked
:district/dnt-staked-for
:district/github-url
:district/meta-hash
:district/logo-image-hash
:district/name
:district/total-supply
:district/url
:reg-entry/status
:reg-entry/address
:reg-entry/challenges
:reg-entry/deposit
:reg-entry/version]
:as district}
{:keys [:status]}]
(let [nav-to-details-props {:style {:cursor "pointer"}
:on-click #(dispatch [:district.ui.router.events/navigate
:route/detail
{:address address}])}]
[:div.grid-box
[:div.box-image nav-to-details-props
[district-image background-image-hash]]
[:div.box-text
[:div.box-logo.sized nav-to-details-props
[district-image logo-image-hash]]
[:div.inner
[:h2 nav-to-details-props (format/truncate name 64)]
[:p nav-to-details-props (format/truncate description 200)]
(when (and (= status "challenged"))
(let [{:keys [:challenge/commit-period-end :challenge/reveal-period-end] :as challenge} (last challenges)]
[:p.time-remaining [:b
(when challenge
(let [district-status (gql-utils/gql-name->kw (:reg-entry/status district))
commit-period? (= district-status :reg-entry.status/commit-period)
remaining-time @(subscribe [::now-subs/time-remaining (gql-utils/gql-date->date (if commit-period?
commit-period-end
reveal-period-end))])
has-remaining-time? (not (format/zero-time-units? remaining-time))]
(cond
(and commit-period? has-remaining-time?)
(str "Vote period ends in " (format/format-time-units remaining-time {:short? true}))
(and commit-period? (not has-remaining-time?))
"Vote period ended."
(and (not commit-period?) has-remaining-time?)
(str "Reveal period ends in " (format/format-time-units remaining-time {:short? true}))
(and (not commit-period?) (not has-remaining-time?))
"Reveal period ended."
:else "")))]]))
[:div.h-line]
[stake/stake-info address]
[stake/stake-form address {:disable-estimated-return? (= status "blacklisted")}]]
[:div.arrow-blob
(nav/a {:route [:route/detail {:address address}]}
[:span.arr.icon-arrow-right])]]]))
(defn loader []
(let [mounted? (r/atom false)]
(fn []
(when-not @mounted?
(js/setTimeout #(swap! mounted? not)))
[:div#loader-wrapper {:class (str "fade-in" (when @mounted? " visible"))}
[:div#loader
[:div.loader-graphic
[:div.loader-floater
[:img.bg.spacer {:src "/images/svg/loader-bg.svg"}]
[:div.turbine
[:img.base {:src "/images/svg/turbine-base.svg"}]
[:div.wheel [:img {:src "/images/svg/turbine-blade.svg"}]]
[:img.cover {:src "/images/svg/turbine-cover.svg"}]]
[:div.fan
{:data-num "1"}
[:img.base {:src "/images/svg/fan-base.svg"}]
[:div.wheel [:img {:src "/images/svg/fan-spokes.svg"}]]]
[:div.fan
{:data-num "2"}
[:img.base {:src "/images/svg/fan-base.svg"}]
[:div.wheel [:img {:src "/images/svg/fan-spokes.svg"}]]]]]]])))
(defn district-tiles [active-account route-query]
(let [q (subscribe [::gql/query
{:queries [(build-query active-account route-query)]}
{:refetch-on #{::district/approve-and-stake-for-success
::district/unstake-success}}])
result (:search-districts @q)
districts (:items result)]
(cond
(:graphql/loading? @q) [loader]
(empty? districts) [:div.no-districts
[:h2 "No districts found"]]
:else [:div.grid.spaced
(->> districts
(map (fn [{:as district
:keys [:reg-entry/address]}]
^{:key address} [district-tile district route-query]))
doall)])))
(defn- build-total-count-query [status-group]
(let [statuses (case status-group
:in-registry [:reg-entry.status/challenge-period
:reg-entry.status/commit-period
:reg-entry.status/reveal-period
:reg-entry.status/whitelisted]
:challenged [:reg-entry.status/commit-period
:reg-entry.status/reveal-period]
:blacklisted [:reg-entry.status/blacklisted])]
[:search-districts
{:order-by :districts.order-by/created-on
:order-dir :desc
:statuses statuses
:first 0}
[:total-count]]))
(defn- navigation-item [{:keys [:status :selected-status :route-query]} text]
(let [query (subscribe [::gql/query {:queries [(build-total-count-query status)]}])]
(fn []
[:li {:class (when (= selected-status (name status)) "on")}
(nav/a {:route [:route/home {} (assoc route-query :status (name status))]
:class (when-not (= status :blacklisted)
"cta-btn")}
(str text (when-let [total-count (-> @query :search-districts :total-count)]
(str " (" total-count ")"))))])))
(defmethod page :route/home []
(let [active-account (subscribe [::account-subs/active-account])
route-query (subscribe [::router-subs/active-page-query])
status (or (:status @route-query) "in-registry")
order-by (or (:order-by @route-query) "created-on")
order-by-kw (keyword "districts.order-by" order-by)
order-by-kw->str {:districts.order-by/created-on "Creation Date"
:districts.order-by/dnt-staked "DNT Staked"}
select-menu-open? (r/atom false)]
(fn []
[app-layout
[:section#intro
[:div.bg-wrap
[:div.background.sized
[:img {:src "/images/"}]]]
[:div.container
[:nav.subnav
[:ul
[navigation-item
{:status :in-registry
:selected-status status
:route-query @route-query}
"In Registry"]
[navigation-item
{:status :challenged
:selected-status status
:route-query @route-query}
"Challenged"]
[navigation-item
{:status :blacklisted
:selected-status status
:route-query @route-query}
"Blacklisted"]]]
[:p
(condp = status
"challenged" "Listed below are all the currently active challenges against districts. Users can vote in challenges with DNT. If a district wins it's challenge, it stays, but if it loses, it will be removed from the registry and placed in the blacklist, and users can no longer stake to it. To participate in the vote, click a challenged district below and scroll to the bottom of the page."
"blacklisted" "This page contains all districts removed from the registry due to a lost challenge. Any DNT still staked to these districts can be unstaked at any time using this page."
"Below is a list of all districts currently in the registry. In order to participate in governance, you will need DNT available in a connected Ethereum wallet. Simply choose the district from the list below, enter the amount you want to stake or unstake, and press the appropriate button. You can click on districts for more detail.")]]]
[:section#registry-grid
[:div.container
[:div.select-menu {:class (when @select-menu-open? "on")
:on-click #(swap! select-menu-open? not)}
[:div.select-choice.cta-btn
[:div.select-text (order-by-kw order-by-kw->str)]
[:div.arrow [:span.arr.icon-arrow-down]]]
[:div.select-drop
[:ul
(->> order-by-kw->str
keys
(remove #(= order-by-kw %))
(map (fn [k]
[:li {:key k}
(nav/a {:route [:route/home {} (assoc @route-query :order-by (name k))]}
(order-by-kw->str k))]))
doall)]]]
[district-tiles @active-account (assoc @route-query
:status status
:order-by order-by)]]]])))
|
84b03472c5036cdd8c78475339c881a60f217a8435cf3369120c5082f8f65c59 | VictorCMiraldo/generics-mrsop | Metadata.hs | # LANGUAGE UndecidableInstances #
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
# LANGUAGE PolyKinds #
{-# LANGUAGE StandaloneDeriving #-}
-- |Metadata maintenance; usefull for pretty-printing values.
module Generics.MRSOP.Base.Metadata where
import Data.Proxy
import Data.SOP.Constraint
import Generics.MRSOP.Util
import Generics.MRSOP.Base.NP
import Generics.MRSOP.Base.Universe
import Generics.MRSOP.Base.Class
type ModuleName = String
type FamilyName = String
type ConstructorName = String
type FieldName = String
-- |Since we only handled fully saturated datatypes, a 'DatatypeName'
-- needs to remember what were the arguments applied to a type.
--
-- The type @[Int]@ is represented by @Name "[]" :@@: Name "Int"@
--
infixl 5 :@:
data DatatypeName
= Name String
| DatatypeName :@: DatatypeName
deriving (Eq , Show)
-- |Provides information about the declaration of a datatype.
data DatatypeInfo :: [[Atom kon]] -> * where
ADT :: ModuleName -> DatatypeName -> NP ConstructorInfo c
-> DatatypeInfo c
New :: ModuleName -> DatatypeName -> ConstructorInfo '[ c ]
-> DatatypeInfo '[ '[ c ]]
-- |Returns the name of a module
moduleName :: DatatypeInfo code -> ModuleName
moduleName (ADT m _ _) = m
moduleName (New m _ _) = m
-- |Returns the name of a datatype
datatypeName :: DatatypeInfo code -> DatatypeName
datatypeName (ADT _ d _) = d
datatypeName (New _ d _) = d
-- |Returns information about the constructor fields
constructorInfo :: DatatypeInfo code -> NP ConstructorInfo code
constructorInfo (ADT _ _ c) = c
constructorInfo (New _ _ c) = c :* Nil
|Associativity information for infix constructors .
data Associativity
= LeftAssociative
| RightAssociative
| NotAssociative
deriving (Eq , Show)
-- |Fixity information for infix constructors.
type Fixity = Int
-- |Constructor metadata.
data ConstructorInfo :: [Atom kon] -> * where
Constructor :: ConstructorName -> ConstructorInfo xs
Infix :: ConstructorName -> Associativity -> Fixity -> ConstructorInfo '[ x , y ]
Record :: ConstructorName -> NP FieldInfo xs -> ConstructorInfo xs
-- |Returns the name of a constructor
constructorName :: ConstructorInfo con -> ConstructorName
constructorName (Constructor c) = c
constructorName (Infix c _ _) = c
constructorName (Record c _) = c
|Record fields metadata
data FieldInfo :: Atom kon -> * where
FieldInfo :: { fieldName :: FieldName } -> FieldInfo k
deriving instance Show (FieldInfo atom)
deriving instance (All (Compose Show FieldInfo) code)
=> Show (ConstructorInfo code)
deriving instance (All (Compose Show ConstructorInfo) code)
=> Show (DatatypeInfo code)
|Given a ' Family ' , provides the ' DatatypeInfo ' for the type
with index in family @fam@.
class (Family ki fam codes) => HasDatatypeInfo ki fam codes
| fam -> codes ki where
datatypeInfo :: Proxy fam -> SNat ix -> DatatypeInfo (Lkup ix codes)
|Sometimes it is more convenient to use a proxy of the type
-- in the family instead of indexes.
datatypeInfoFor :: forall ki fam codes ix ty
. ( HasDatatypeInfo ki fam codes
, ix ~ Idx ty fam , Lkup ix fam ~ ty , IsNat ix)
=> Proxy fam -> Proxy ty -> DatatypeInfo (Lkup ix codes)
datatypeInfoFor pf pty = datatypeInfo pf (getSNat $ proxyIdx pf pty)
where
proxyIdx :: Proxy fam -> Proxy ty -> Proxy (Idx ty fam)
proxyIdx _ _ = Proxy
-- ** Name Lookup
-- |This is essentially a list lookup, but needs significant type
-- information to go through. Returns the name of the @c@th constructor
-- of a sum-type.
constrInfoLkup :: Constr sum c -> DatatypeInfo sum -> ConstructorInfo (Lkup c sum)
constrInfoLkup c = go c . constructorInfo
where
go :: Constr sum c -> NP ConstructorInfo sum -> ConstructorInfo (Lkup c sum)
go CZ (ci :* _) = ci
go (CS c0) (_ :* cis) = go c0 cis
-- |Returns the constructor information for a given
-- type in the family.
constrInfoFor :: (HasDatatypeInfo ki fam codes)
=> Proxy fam
-> SNat ix
-> Constr (Lkup ix codes) c
-> ConstructorInfo (Lkup c (Lkup ix codes))
constrInfoFor pfam six c = constrInfoLkup c (datatypeInfo pfam six)
| null | https://raw.githubusercontent.com/VictorCMiraldo/generics-mrsop/b66bb6c651297cdb71655663e34ab35812b38f72/src/Generics/MRSOP/Base/Metadata.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE RankNTypes #
# LANGUAGE GADTs #
# LANGUAGE DataKinds #
# LANGUAGE StandaloneDeriving #
|Metadata maintenance; usefull for pretty-printing values.
|Since we only handled fully saturated datatypes, a 'DatatypeName'
needs to remember what were the arguments applied to a type.
The type @[Int]@ is represented by @Name "[]" :@@: Name "Int"@
|Provides information about the declaration of a datatype.
|Returns the name of a module
|Returns the name of a datatype
|Returns information about the constructor fields
|Fixity information for infix constructors.
|Constructor metadata.
|Returns the name of a constructor
in the family instead of indexes.
** Name Lookup
|This is essentially a list lookup, but needs significant type
information to go through. Returns the name of the @c@th constructor
of a sum-type.
|Returns the constructor information for a given
type in the family. | # LANGUAGE UndecidableInstances #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
module Generics.MRSOP.Base.Metadata where
import Data.Proxy
import Data.SOP.Constraint
import Generics.MRSOP.Util
import Generics.MRSOP.Base.NP
import Generics.MRSOP.Base.Universe
import Generics.MRSOP.Base.Class
type ModuleName = String
type FamilyName = String
type ConstructorName = String
type FieldName = String
infixl 5 :@:
data DatatypeName
= Name String
| DatatypeName :@: DatatypeName
deriving (Eq , Show)
data DatatypeInfo :: [[Atom kon]] -> * where
ADT :: ModuleName -> DatatypeName -> NP ConstructorInfo c
-> DatatypeInfo c
New :: ModuleName -> DatatypeName -> ConstructorInfo '[ c ]
-> DatatypeInfo '[ '[ c ]]
moduleName :: DatatypeInfo code -> ModuleName
moduleName (ADT m _ _) = m
moduleName (New m _ _) = m
datatypeName :: DatatypeInfo code -> DatatypeName
datatypeName (ADT _ d _) = d
datatypeName (New _ d _) = d
constructorInfo :: DatatypeInfo code -> NP ConstructorInfo code
constructorInfo (ADT _ _ c) = c
constructorInfo (New _ _ c) = c :* Nil
|Associativity information for infix constructors .
data Associativity
= LeftAssociative
| RightAssociative
| NotAssociative
deriving (Eq , Show)
type Fixity = Int
data ConstructorInfo :: [Atom kon] -> * where
Constructor :: ConstructorName -> ConstructorInfo xs
Infix :: ConstructorName -> Associativity -> Fixity -> ConstructorInfo '[ x , y ]
Record :: ConstructorName -> NP FieldInfo xs -> ConstructorInfo xs
constructorName :: ConstructorInfo con -> ConstructorName
constructorName (Constructor c) = c
constructorName (Infix c _ _) = c
constructorName (Record c _) = c
|Record fields metadata
data FieldInfo :: Atom kon -> * where
FieldInfo :: { fieldName :: FieldName } -> FieldInfo k
deriving instance Show (FieldInfo atom)
deriving instance (All (Compose Show FieldInfo) code)
=> Show (ConstructorInfo code)
deriving instance (All (Compose Show ConstructorInfo) code)
=> Show (DatatypeInfo code)
|Given a ' Family ' , provides the ' DatatypeInfo ' for the type
with index in family @fam@.
class (Family ki fam codes) => HasDatatypeInfo ki fam codes
| fam -> codes ki where
datatypeInfo :: Proxy fam -> SNat ix -> DatatypeInfo (Lkup ix codes)
|Sometimes it is more convenient to use a proxy of the type
datatypeInfoFor :: forall ki fam codes ix ty
. ( HasDatatypeInfo ki fam codes
, ix ~ Idx ty fam , Lkup ix fam ~ ty , IsNat ix)
=> Proxy fam -> Proxy ty -> DatatypeInfo (Lkup ix codes)
datatypeInfoFor pf pty = datatypeInfo pf (getSNat $ proxyIdx pf pty)
where
proxyIdx :: Proxy fam -> Proxy ty -> Proxy (Idx ty fam)
proxyIdx _ _ = Proxy
constrInfoLkup :: Constr sum c -> DatatypeInfo sum -> ConstructorInfo (Lkup c sum)
constrInfoLkup c = go c . constructorInfo
where
go :: Constr sum c -> NP ConstructorInfo sum -> ConstructorInfo (Lkup c sum)
go CZ (ci :* _) = ci
go (CS c0) (_ :* cis) = go c0 cis
constrInfoFor :: (HasDatatypeInfo ki fam codes)
=> Proxy fam
-> SNat ix
-> Constr (Lkup ix codes) c
-> ConstructorInfo (Lkup c (Lkup ix codes))
constrInfoFor pfam six c = constrInfoLkup c (datatypeInfo pfam six)
|
7d0257168d2e5ec104866145512290ab4334dc489d148f3352c48b1e4fec07bc | snoyberg/conduit | Fusion.hs | # LANGUAGE ExistentialQuantification #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE BangPatterns #-}
# LANGUAGE DeriveFunctor #
# LANGUAGE Trustworthy #
# LANGUAGE ScopedTypeVariables #
module Data.Conduit.Internal.Fusion
( -- ** Types
Step (..)
, Stream (..)
, ConduitWithStream
, StreamConduitT
, StreamConduit
, StreamSource
, StreamProducer
, StreamSink
, StreamConsumer
-- ** Functions
, streamConduit
, streamSource
, streamSourcePure
, unstream
) where
import Data.Conduit.Internal.Conduit
import Data.Conduit.Internal.Pipe (Pipe (..))
import Data.Functor.Identity (Identity (runIdentity))
import Data.Void (Void, absurd)
import Control.Monad.Trans.Resource (runResourceT)
-- | This is the same as stream fusion\'s Step. Constructors are renamed to
-- avoid confusion with conduit names.
data Step s o r
= Emit s o
| Skip s
| Stop r
deriving Functor
data Stream m o r = forall s. Stream
(s -> m (Step s o r))
(m s)
data ConduitWithStream i o m r = ConduitWithStream
(ConduitT i o m r)
(StreamConduitT i o m r)
type StreamConduitT i o m r = Stream m i () -> Stream m o r
type StreamConduit i m o = StreamConduitT i o m ()
type StreamSource m o = StreamConduitT () o m ()
type StreamProducer m o = forall i. StreamConduitT i o m ()
type StreamSink i m r = StreamConduitT i Void m r
type StreamConsumer i m r = forall o. StreamConduitT i o m r
unstream :: ConduitWithStream i o m r -> ConduitT i o m r
unstream (ConduitWithStream c _) = c
{-# INLINE [0] unstream #-}
fuseStream :: Monad m
=> ConduitWithStream a b m ()
-> ConduitWithStream b c m r
-> ConduitWithStream a c m r
fuseStream (ConduitWithStream a x) (ConduitWithStream b y) =
ConduitWithStream (a .| b) (y . x)
# INLINE fuseStream #
{-# RULES "conduit: fuseStream (.|)" forall left right.
unstream left .| unstream right = unstream (fuseStream left right)
#-}
{-# RULES "conduit: fuseStream (fuse)" forall left right.
fuse (unstream left) (unstream right) = unstream (fuseStream left right)
#-}
{-# RULES "conduit: fuseStream (=$=)" forall left right.
unstream left =$= unstream right = unstream (fuseStream left right)
#-}
runStream :: Monad m
=> ConduitWithStream () Void m r
-> m r
runStream (ConduitWithStream _ f) =
run $ f $ Stream emptyStep (return ())
where
emptyStep _ = return $ Stop ()
run (Stream step ms0) =
ms0 >>= loop
where
loop s = do
res <- step s
case res of
Stop r -> return r
Skip s' -> loop s'
Emit _ o -> absurd o
# INLINE runStream #
# RULES " conduit : runStream " forall stream .
runConduit ( unstream stream ) = runStream stream
#
runConduit (unstream stream) = runStream stream
#-}
{-# RULES "conduit: runStream (pure)" forall stream.
runConduitPure (unstream stream) = runIdentity (runStream stream)
#-}
# RULES " conduit : runStream ( ResourceT ) " forall stream .
runConduitRes ( unstream stream ) = runResourceT ( runStream stream )
#
runConduitRes (unstream stream) = runResourceT (runStream stream)
#-}
connectStream :: Monad m
=> ConduitWithStream () i m ()
-> ConduitWithStream i Void m r
-> m r
connectStream (ConduitWithStream _ stream) (ConduitWithStream _ f) =
run $ f $ stream $ Stream emptyStep (return ())
where
emptyStep _ = return $ Stop ()
run (Stream step ms0) =
ms0 >>= loop
where
loop s = do
res <- step s
case res of
Stop r -> return r
Skip s' -> loop s'
Emit _ o -> absurd o
# INLINE connectStream #
{-# RULES "conduit: connectStream ($$)" forall left right.
unstream left $$ unstream right = connectStream left right
#-}
connectStream1 :: Monad m
=> ConduitWithStream () i m ()
-> ConduitT i Void m r
-> m r
connectStream1 (ConduitWithStream _ fstream) (ConduitT sink0) =
case fstream $ Stream (const $ return $ Stop ()) (return ()) of
Stream step ms0 ->
let loop _ (Done r) _ = return r
loop ls (PipeM mp) s = mp >>= flip (loop ls) s
loop ls (Leftover p l) s = loop (l:ls) p s
loop _ (HaveOutput _ o) _ = absurd o
loop (l:ls) (NeedInput p _) s = loop ls (p l) s
loop [] (NeedInput p c) s = do
res <- step s
case res of
Stop () -> loop [] (c ()) s
Skip s' -> loop [] (NeedInput p c) s'
Emit s' i -> loop [] (p i) s'
in ms0 >>= loop [] (sink0 Done)
# INLINE connectStream1 #
{-# RULES "conduit: connectStream1 ($$)" forall left right.
unstream left $$ right = connectStream1 left right
#-}
# RULES " conduit : connectStream1 ( runConduit/.| ) " forall left right .
( unstream left .| right ) = connectStream1 left right
#
runConduit (unstream left .| right) = connectStream1 left right
#-}
# RULES " conduit : connectStream1 ( runConduit/=$= ) " forall left right .
( unstream left = $ = right ) = connectStream1 left right
#
runConduit (unstream left =$= right) = connectStream1 left right
#-}
# RULES " conduit : connectStream1 ( runConduit / fuse ) " forall left right .
runConduit ( fuse ( unstream left ) right ) = connectStream1 left right
#
runConduit (fuse (unstream left) right) = connectStream1 left right
#-}
{-# RULES "conduit: connectStream1 (runConduitPure/.|)" forall left right.
runConduitPure (unstream left .| right) = runIdentity (connectStream1 left right)
#-}
{-# RULES "conduit: connectStream1 (runConduitPure/=$=)" forall left right.
runConduitPure (unstream left =$= right) = runIdentity (connectStream1 left right)
#-}
{-# RULES "conduit: connectStream1 (runConduitPure/fuse)" forall left right.
runConduitPure (fuse (unstream left) right) = runIdentity (connectStream1 left right)
#-}
{-# RULES "conduit: connectStream1 (runConduitRes/.|)" forall left right.
runConduitRes (unstream left .| right) = runResourceT (connectStream1 left right)
#-}
{-# RULES "conduit: connectStream1 (runConduitRes/=$=)" forall left right.
runConduitRes (unstream left =$= right) = runResourceT (connectStream1 left right)
#-}
# RULES " conduit : connectStream1 ( runConduitRes / fuse ) " forall left right .
runConduitRes ( fuse ( unstream left ) right ) = runResourceT ( connectStream1 left right )
#
runConduitRes (fuse (unstream left) right) = runResourceT (connectStream1 left right)
#-}
connectStream2 :: forall i m r. Monad m
=> ConduitT () i m ()
-> ConduitWithStream i Void m r
-> m r
connectStream2 (ConduitT src0) (ConduitWithStream _ fstream) =
run $ fstream $ Stream step' $ return (src0 Done)
where
step' :: Pipe () () i () m () -> m (Step (Pipe () () i () m ()) i ())
step' (Done ()) = return $ Stop ()
step' (HaveOutput pipe o) = return $ Emit pipe o
step' (NeedInput _ c) = return $ Skip $ c ()
step' (PipeM mp) = Skip <$> mp
step' (Leftover p ()) = return $ Skip p
{-# INLINE step' #-}
run (Stream step ms0) =
ms0 >>= loop
where
loop s = do
res <- step s
case res of
Stop r -> return r
Emit _ o -> absurd o
Skip s' -> loop s'
# INLINE connectStream2 #
{-# RULES "conduit: connectStream2 ($$)" forall left right.
left $$ unstream right = connectStream2 left right
#-}
# RULES " conduit : connectStream2 ( runConduit/.| ) " forall left right .
( left .| unstream right ) = connectStream2 left right
#
runConduit (left .| unstream right) = connectStream2 left right
#-}
# RULES " conduit : connectStream2 ( runConduit / fuse ) " forall left right .
runConduit ( fuse left ( unstream right ) ) = connectStream2 left right
#
runConduit (fuse left (unstream right)) = connectStream2 left right
#-}
# RULES " conduit : connectStream2 ( runConduit/=$= ) " forall left right .
( left = $ = unstream right ) = connectStream2 left right
#
runConduit (left =$= unstream right) = connectStream2 left right
#-}
# RULES " conduit : connectStream2 ( runConduitPure/.| ) " forall left right .
runConduitPure ( left .| unstream right ) = runIdentity ( connectStream2 left right )
#
runConduitPure (left .| unstream right) = runIdentity (connectStream2 left right)
#-}
# RULES " conduit : connectStream2 ( runConduitPure / fuse ) " forall left right .
runConduitPure ( fuse left ( unstream right ) ) = runIdentity ( connectStream2 left right )
#
runConduitPure (fuse left (unstream right)) = runIdentity (connectStream2 left right)
#-}
# RULES " conduit : connectStream2 ( runConduitPure/=$= ) " forall left right .
runConduitPure ( left = $ = unstream right ) = runIdentity ( connectStream2 left right )
#
runConduitPure (left =$= unstream right) = runIdentity (connectStream2 left right)
#-}
# RULES " conduit : connectStream2 ( runConduitRes/.| ) " forall left right .
runConduitRes ( left .| unstream right ) = runResourceT ( connectStream2 left right )
#
runConduitRes (left .| unstream right) = runResourceT (connectStream2 left right)
#-}
# RULES " conduit : connectStream2 ( runConduitRes / fuse ) " forall left right .
runConduitRes ( fuse left ( unstream right ) ) = runResourceT ( connectStream2 left right )
#
runConduitRes (fuse left (unstream right)) = runResourceT (connectStream2 left right)
#-}
# RULES " conduit : connectStream2 ( runConduitRes/=$= ) " forall left right .
runConduitRes ( left = $ = unstream right ) = runResourceT ( connectStream2 left right )
#
runConduitRes (left =$= unstream right) = runResourceT (connectStream2 left right)
#-}
streamConduit :: ConduitT i o m r
-> (Stream m i () -> Stream m o r)
-> ConduitWithStream i o m r
streamConduit = ConduitWithStream
{-# INLINE CONLIKE streamConduit #-}
streamSource
:: Monad m
=> Stream m o ()
-> ConduitWithStream i o m ()
streamSource str@(Stream step ms0) =
ConduitWithStream con (const str)
where
con = ConduitT $ \rest -> PipeM $ do
s0 <- ms0
let loop s = do
res <- step s
case res of
Stop () -> return $ rest ()
Emit s' o -> return $ HaveOutput (PipeM $ loop s') o
Skip s' -> loop s'
loop s0
# INLINE streamSource #
streamSourcePure
:: Monad m
=> Stream Identity o ()
-> ConduitWithStream i o m ()
streamSourcePure (Stream step ms0) =
ConduitWithStream con (const $ Stream (return . runIdentity . step) (return s0))
where
s0 = runIdentity ms0
con = ConduitT $ \rest ->
let loop s =
case runIdentity $ step s of
Stop () -> rest ()
Emit s' o -> HaveOutput (loop s') o
Skip s' -> loop s'
in loop s0
# INLINE streamSourcePure #
| null | https://raw.githubusercontent.com/snoyberg/conduit/1771780ff4b606296924a28bf5d4433ae6a916f3/conduit/src/Data/Conduit/Internal/Fusion.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE BangPatterns #
** Types
** Functions
| This is the same as stream fusion\'s Step. Constructors are renamed to
avoid confusion with conduit names.
# INLINE [0] unstream #
# RULES "conduit: fuseStream (.|)" forall left right.
unstream left .| unstream right = unstream (fuseStream left right)
#
# RULES "conduit: fuseStream (fuse)" forall left right.
fuse (unstream left) (unstream right) = unstream (fuseStream left right)
#
# RULES "conduit: fuseStream (=$=)" forall left right.
unstream left =$= unstream right = unstream (fuseStream left right)
#
# RULES "conduit: runStream (pure)" forall stream.
runConduitPure (unstream stream) = runIdentity (runStream stream)
#
# RULES "conduit: connectStream ($$)" forall left right.
unstream left $$ unstream right = connectStream left right
#
# RULES "conduit: connectStream1 ($$)" forall left right.
unstream left $$ right = connectStream1 left right
#
# RULES "conduit: connectStream1 (runConduitPure/.|)" forall left right.
runConduitPure (unstream left .| right) = runIdentity (connectStream1 left right)
#
# RULES "conduit: connectStream1 (runConduitPure/=$=)" forall left right.
runConduitPure (unstream left =$= right) = runIdentity (connectStream1 left right)
#
# RULES "conduit: connectStream1 (runConduitPure/fuse)" forall left right.
runConduitPure (fuse (unstream left) right) = runIdentity (connectStream1 left right)
#
# RULES "conduit: connectStream1 (runConduitRes/.|)" forall left right.
runConduitRes (unstream left .| right) = runResourceT (connectStream1 left right)
#
# RULES "conduit: connectStream1 (runConduitRes/=$=)" forall left right.
runConduitRes (unstream left =$= right) = runResourceT (connectStream1 left right)
#
# INLINE step' #
# RULES "conduit: connectStream2 ($$)" forall left right.
left $$ unstream right = connectStream2 left right
#
# INLINE CONLIKE streamConduit # | # LANGUAGE ExistentialQuantification #
# LANGUAGE DeriveFunctor #
# LANGUAGE Trustworthy #
# LANGUAGE ScopedTypeVariables #
module Data.Conduit.Internal.Fusion
Step (..)
, Stream (..)
, ConduitWithStream
, StreamConduitT
, StreamConduit
, StreamSource
, StreamProducer
, StreamSink
, StreamConsumer
, streamConduit
, streamSource
, streamSourcePure
, unstream
) where
import Data.Conduit.Internal.Conduit
import Data.Conduit.Internal.Pipe (Pipe (..))
import Data.Functor.Identity (Identity (runIdentity))
import Data.Void (Void, absurd)
import Control.Monad.Trans.Resource (runResourceT)
data Step s o r
= Emit s o
| Skip s
| Stop r
deriving Functor
data Stream m o r = forall s. Stream
(s -> m (Step s o r))
(m s)
data ConduitWithStream i o m r = ConduitWithStream
(ConduitT i o m r)
(StreamConduitT i o m r)
type StreamConduitT i o m r = Stream m i () -> Stream m o r
type StreamConduit i m o = StreamConduitT i o m ()
type StreamSource m o = StreamConduitT () o m ()
type StreamProducer m o = forall i. StreamConduitT i o m ()
type StreamSink i m r = StreamConduitT i Void m r
type StreamConsumer i m r = forall o. StreamConduitT i o m r
unstream :: ConduitWithStream i o m r -> ConduitT i o m r
unstream (ConduitWithStream c _) = c
fuseStream :: Monad m
=> ConduitWithStream a b m ()
-> ConduitWithStream b c m r
-> ConduitWithStream a c m r
fuseStream (ConduitWithStream a x) (ConduitWithStream b y) =
ConduitWithStream (a .| b) (y . x)
# INLINE fuseStream #
runStream :: Monad m
=> ConduitWithStream () Void m r
-> m r
runStream (ConduitWithStream _ f) =
run $ f $ Stream emptyStep (return ())
where
emptyStep _ = return $ Stop ()
run (Stream step ms0) =
ms0 >>= loop
where
loop s = do
res <- step s
case res of
Stop r -> return r
Skip s' -> loop s'
Emit _ o -> absurd o
# INLINE runStream #
# RULES " conduit : runStream " forall stream .
runConduit ( unstream stream ) = runStream stream
#
runConduit (unstream stream) = runStream stream
#-}
# RULES " conduit : runStream ( ResourceT ) " forall stream .
runConduitRes ( unstream stream ) = runResourceT ( runStream stream )
#
runConduitRes (unstream stream) = runResourceT (runStream stream)
#-}
connectStream :: Monad m
=> ConduitWithStream () i m ()
-> ConduitWithStream i Void m r
-> m r
connectStream (ConduitWithStream _ stream) (ConduitWithStream _ f) =
run $ f $ stream $ Stream emptyStep (return ())
where
emptyStep _ = return $ Stop ()
run (Stream step ms0) =
ms0 >>= loop
where
loop s = do
res <- step s
case res of
Stop r -> return r
Skip s' -> loop s'
Emit _ o -> absurd o
# INLINE connectStream #
connectStream1 :: Monad m
=> ConduitWithStream () i m ()
-> ConduitT i Void m r
-> m r
connectStream1 (ConduitWithStream _ fstream) (ConduitT sink0) =
case fstream $ Stream (const $ return $ Stop ()) (return ()) of
Stream step ms0 ->
let loop _ (Done r) _ = return r
loop ls (PipeM mp) s = mp >>= flip (loop ls) s
loop ls (Leftover p l) s = loop (l:ls) p s
loop _ (HaveOutput _ o) _ = absurd o
loop (l:ls) (NeedInput p _) s = loop ls (p l) s
loop [] (NeedInput p c) s = do
res <- step s
case res of
Stop () -> loop [] (c ()) s
Skip s' -> loop [] (NeedInput p c) s'
Emit s' i -> loop [] (p i) s'
in ms0 >>= loop [] (sink0 Done)
# INLINE connectStream1 #
# RULES " conduit : connectStream1 ( runConduit/.| ) " forall left right .
( unstream left .| right ) = connectStream1 left right
#
runConduit (unstream left .| right) = connectStream1 left right
#-}
# RULES " conduit : connectStream1 ( runConduit/=$= ) " forall left right .
( unstream left = $ = right ) = connectStream1 left right
#
runConduit (unstream left =$= right) = connectStream1 left right
#-}
# RULES " conduit : connectStream1 ( runConduit / fuse ) " forall left right .
runConduit ( fuse ( unstream left ) right ) = connectStream1 left right
#
runConduit (fuse (unstream left) right) = connectStream1 left right
#-}
# RULES " conduit : connectStream1 ( runConduitRes / fuse ) " forall left right .
runConduitRes ( fuse ( unstream left ) right ) = runResourceT ( connectStream1 left right )
#
runConduitRes (fuse (unstream left) right) = runResourceT (connectStream1 left right)
#-}
connectStream2 :: forall i m r. Monad m
=> ConduitT () i m ()
-> ConduitWithStream i Void m r
-> m r
connectStream2 (ConduitT src0) (ConduitWithStream _ fstream) =
run $ fstream $ Stream step' $ return (src0 Done)
where
step' :: Pipe () () i () m () -> m (Step (Pipe () () i () m ()) i ())
step' (Done ()) = return $ Stop ()
step' (HaveOutput pipe o) = return $ Emit pipe o
step' (NeedInput _ c) = return $ Skip $ c ()
step' (PipeM mp) = Skip <$> mp
step' (Leftover p ()) = return $ Skip p
run (Stream step ms0) =
ms0 >>= loop
where
loop s = do
res <- step s
case res of
Stop r -> return r
Emit _ o -> absurd o
Skip s' -> loop s'
# INLINE connectStream2 #
# RULES " conduit : connectStream2 ( runConduit/.| ) " forall left right .
( left .| unstream right ) = connectStream2 left right
#
runConduit (left .| unstream right) = connectStream2 left right
#-}
# RULES " conduit : connectStream2 ( runConduit / fuse ) " forall left right .
runConduit ( fuse left ( unstream right ) ) = connectStream2 left right
#
runConduit (fuse left (unstream right)) = connectStream2 left right
#-}
# RULES " conduit : connectStream2 ( runConduit/=$= ) " forall left right .
( left = $ = unstream right ) = connectStream2 left right
#
runConduit (left =$= unstream right) = connectStream2 left right
#-}
# RULES " conduit : connectStream2 ( runConduitPure/.| ) " forall left right .
runConduitPure ( left .| unstream right ) = runIdentity ( connectStream2 left right )
#
runConduitPure (left .| unstream right) = runIdentity (connectStream2 left right)
#-}
# RULES " conduit : connectStream2 ( runConduitPure / fuse ) " forall left right .
runConduitPure ( fuse left ( unstream right ) ) = runIdentity ( connectStream2 left right )
#
runConduitPure (fuse left (unstream right)) = runIdentity (connectStream2 left right)
#-}
# RULES " conduit : connectStream2 ( runConduitPure/=$= ) " forall left right .
runConduitPure ( left = $ = unstream right ) = runIdentity ( connectStream2 left right )
#
runConduitPure (left =$= unstream right) = runIdentity (connectStream2 left right)
#-}
# RULES " conduit : connectStream2 ( runConduitRes/.| ) " forall left right .
runConduitRes ( left .| unstream right ) = runResourceT ( connectStream2 left right )
#
runConduitRes (left .| unstream right) = runResourceT (connectStream2 left right)
#-}
# RULES " conduit : connectStream2 ( runConduitRes / fuse ) " forall left right .
runConduitRes ( fuse left ( unstream right ) ) = runResourceT ( connectStream2 left right )
#
runConduitRes (fuse left (unstream right)) = runResourceT (connectStream2 left right)
#-}
# RULES " conduit : connectStream2 ( runConduitRes/=$= ) " forall left right .
runConduitRes ( left = $ = unstream right ) = runResourceT ( connectStream2 left right )
#
runConduitRes (left =$= unstream right) = runResourceT (connectStream2 left right)
#-}
streamConduit :: ConduitT i o m r
-> (Stream m i () -> Stream m o r)
-> ConduitWithStream i o m r
streamConduit = ConduitWithStream
streamSource
:: Monad m
=> Stream m o ()
-> ConduitWithStream i o m ()
streamSource str@(Stream step ms0) =
ConduitWithStream con (const str)
where
con = ConduitT $ \rest -> PipeM $ do
s0 <- ms0
let loop s = do
res <- step s
case res of
Stop () -> return $ rest ()
Emit s' o -> return $ HaveOutput (PipeM $ loop s') o
Skip s' -> loop s'
loop s0
# INLINE streamSource #
streamSourcePure
:: Monad m
=> Stream Identity o ()
-> ConduitWithStream i o m ()
streamSourcePure (Stream step ms0) =
ConduitWithStream con (const $ Stream (return . runIdentity . step) (return s0))
where
s0 = runIdentity ms0
con = ConduitT $ \rest ->
let loop s =
case runIdentity $ step s of
Stop () -> rest ()
Emit s' o -> HaveOutput (loop s') o
Skip s' -> loop s'
in loop s0
# INLINE streamSourcePure #
|
16bbefff330d7b5e6bc09ce4c76a7a40a2160857c679f32801eb57a954fa423f | herd/herdtools7 | myLib.mli | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2013 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
(** Open my files *)
module type Config = sig
val includes : string list
val env : string option
val libdir : string
val debug : bool
end
val pp_debug : string -> unit
module Make :
functor (C:Config) ->
sig
val find : string -> string
end
| null | https://raw.githubusercontent.com/herd/herdtools7/b86aec8db64f8812e19468893deb1cdf5bbcfb83/lib/myLib.mli | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
**************************************************************************
* Open my files | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2013 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
module type Config = sig
val includes : string list
val env : string option
val libdir : string
val debug : bool
end
val pp_debug : string -> unit
module Make :
functor (C:Config) ->
sig
val find : string -> string
end
|
e6ed5a347185a60a9793c42dd80655d40ea13a73610bc98fde258a30a73e0ea1 | cse-bristol/110-thermos-ui | tile.cljs | This file is part of THERMOS , copyright © Centre for Sustainable Energy , 2017 - 2021
Licensed under the Reciprocal Public License v1.5 . See LICENSE for licensing details .
(ns thermos-frontend.tile
(:require [reagent.core :as reagent]
[leaflet :as leaflet]
[thermos-frontend.operations :as operations]
[thermos-frontend.editor-state :as state]
[thermos-specs.document :as document]
[thermos-specs.path :as path]
[thermos-specs.candidate :as candidate]
[thermos-specs.solution :as solution]
[thermos-specs.view :as view]
[thermos-frontend.spatial :as spatial]
[thermos-frontend.theme :as theme]
[goog.object :as o]))
(declare render-candidate render-candidate-shadow render-geometry render-linestring)
(defn projection
"Create a projection function"
[tile layer]
(let [coords (.-coords tile)
size (.getTileSize layer)
zoom (.-z coords)
map-control (o/get layer "_map")]
(fn [x y]
(let [pt (.project map-control
(js/L.latLng x y)
zoom)
pt (.unscaleBy pt size)
pt (.subtract pt coords)
pt (.scaleBy pt size)]
pt))))
(defn fix-size [tile layer]
(let [size (.getTileSize layer)
width (.-x size)
height (.-y size)]
(.setAttribute tile "width" width)
(.setAttribute tile "height" height)))
;; most of the work is in here - how to paint an individual tile onto the map
;; if there is a solution we probably want to show the solution cleanly
(def ^:dynamic *point-radius*
"The screen-units radius for a Point geometry." 8.0)
(defn render-tile [has-solution? contents tile layer map-view min-max-diameter]
"Draw a tile.
`document` should be a document layer (not an atom containing a document layer),
`tile` a canvas element,
`layer` an instance of our layer component's layer class,
`map-view` is either ::view/constraints or ::view/solution,
`min-diameter` and max are the min and max, used for a linear scaling"
(let [coords (.-coords tile)
size (.getTileSize layer)
ctx (.getContext tile "2d")
width (.-x size)
height (.-y size)
zoom (.-z coords)
project (projection tile layer)
geometry-key ::spatial/jsts-geometry]
(fix-size tile layer)
(.clearRect ctx 0 0 width height)
;; Render order: non-selected buildings, selected building shadows, selected buildings,
;; non-selected paths, selected path shadows, selected paths
(let [{buildings :building paths :path} (group-by ::candidate/type contents)
{selected-buildings true non-selected-buildings false}
(group-by
(fn [x] (boolean (or (::candidate/selected x) (:in-selected-group x))))
buildings)
paths
(cond
(> zoom 14) paths
has-solution?
(filter candidate/in-solution? paths)
:else [])
use-diameters
(and (> zoom 14)
min-max-diameter
(not= (first min-max-diameter) (second min-max-diameter)))
paths
(if use-diameters
(let [[min-diameter max-diameter] min-max-diameter
dia-range (- max-diameter min-diameter)
mm-ratio (/ max-diameter min-diameter)
mm-over-1 (- mm-ratio 1)
;; clamp mm-over-1 so that we get a range that looks nice
mm-over-1 (cond
(< mm-over-1 2.5) 2.5
(> mm-over-1 4.5) 4.5
:else mm-over-1)
]
(for [path paths]
(if-let [diameter (::solution/diameter-mm path)]
(assoc path ::dia-scale
(let [ratio (/ (- diameter min-diameter) dia-range)]
(+ 1 (* mm-over-1 (Math/sqrt ratio)))))
path)))
paths)
{selected-paths true non-selected-paths false}
(group-by (comp boolean ::candidate/selected) paths)
ordinary-line-width
(cond
(> zoom 16) 1.5
:else 1)
shadow-width
(cond
(> zoom 16) 3
:else 2)
shadow-line-width
(+ ordinary-line-width shadow-width)
]
(binding [*point-radius*
(if (<= zoom 15) 3
(- zoom 10))]
;; Non-selected buildings
(doseq [candidate non-selected-buildings]
(render-candidate ordinary-line-width has-solution? candidate ctx project map-view))
;; Selected building shadows
(doseq [candidate selected-buildings]
(render-candidate-shadow shadow-line-width has-solution? candidate ctx project map-view))
;; Selected buildings
(doseq [candidate selected-buildings]
(render-candidate ordinary-line-width has-solution? candidate ctx project map-view))
;; Non-selected paths
(doseq [path non-selected-paths]
(render-candidate
(* (::dia-scale path 1) ordinary-line-width)
has-solution? path ctx project map-view))
;; Selected path shadows
(doseq [path selected-paths]
(render-candidate-shadow
(+ shadow-width (* (::dia-scale path 1) ordinary-line-width))
has-solution? path ctx project map-view))
;; Selected paths
(doseq [path selected-paths]
(render-candidate
(::dia-scale path ordinary-line-width)
has-solution? path ctx project map-view)))
)
))
(defn render-candidate
"Draw a shape for the candidate on a map.
`candidate` is a candidate map,
`ctx` is a Canvas graphics context (2D),
`project` is a function to project from real space into the canvas pixel space,
`map-view` is either ::view/constraints or ::view/solution,
`line-width` is an optionally specified line width for when you want to represent the pipe diameter."
[line-width solution candidate ctx project map-view]
(let [filtered (:filtered candidate)
in-selected-group (:in-selected-group candidate)]
(set! (.. ctx -lineCap) "round")
(case map-view
;; Colour by constraints
::view/constraints
(let [selected (::candidate/selected candidate)
inclusion (::candidate/inclusion candidate)
is-supply (candidate/has-supply? candidate)
included (candidate/is-included? candidate)
forbidden (not included)]
;; Line width
(set! (.. ctx -lineWidth) line-width)
;; Line colour
(set! (.. ctx -strokeStyle)
(cond
(= inclusion :required) theme/red
(= inclusion :optional) theme/blue
:else theme/white))
;; Fill
(set! (.. ctx -fillStyle)
(cond
is-supply
theme/supply-orange
selected
theme/dark-grey
in-selected-group
theme/white
:else
theme/light-grey
)
))
;; Colour by results of the optimisation
::view/solution
(let [selected (::candidate/selected candidate)
inclusion (::candidate/inclusion candidate)
in-solution (candidate/in-solution? candidate)
unreachable (candidate/unreachable? candidate)
alternative (candidate/got-alternative? candidate)
connected (candidate/is-connected? candidate)
supply-in-solution (candidate/supply-in-solution? candidate)]
;; Line width
(set! (.. ctx -lineWidth) line-width)
;; Line colour
(set! (.. ctx -strokeStyle)
(cond
(= unreachable :peripheral)
theme/peripheral-yellow
unreachable
theme/magenta
(and solution (not connected) (not alternative) (= inclusion :optional))
theme/beige
alternative
theme/green
in-solution
theme/in-solution-orange
:else
theme/white))
;; Fill
(set! (.. ctx -fillStyle)
(cond
supply-in-solution
theme/supply-orange
selected
theme/dark-grey
in-selected-group
theme/white
:else
theme/light-grey
))))
(set! (.. ctx -globalAlpha)
(if filtered 0.25 1)))
(render-geometry (::spatial/jsts-geometry candidate) ctx project
true false false))
(defn render-candidate-shadow
"Draw some kind of ephemeral outline for selected candidate.
Arguments are the same as render-candidate."
[line-width solution candidate ctx project map-view]
(set! (.. ctx -lineCap) "round")
(set! (.. ctx -lineJoin) "round")
(case map-view
;; Colour by constraints
::view/constraints
(let [in-selected-group (:in-selected-group candidate)
selected (::candidate/selected candidate)
inclusion (::candidate/inclusion candidate)
is-supply (candidate/has-supply? candidate)
included (candidate/is-included? candidate)
forbidden (not included)]
;; Line width
(set! (.. ctx -lineWidth) line-width)
;; Line colour
(set! (.. ctx -strokeStyle)
(cond
in-selected-group "#000000"
(= inclusion :required) theme/red-light
(= inclusion :optional) theme/blue-light
:else theme/white)))
;; Colour by results of the optimisation
::view/solution
(let [in-selected-group (:in-selected-group candidate)
selected (::candidate/selected candidate)
inclusion (::candidate/inclusion candidate)
in-solution (candidate/in-solution? candidate)
unreachable (candidate/unreachable? candidate)
alternative (candidate/got-alternative? candidate)
connected (candidate/is-connected? candidate)
supply-in-solution (candidate/supply-in-solution? candidate)]
;; Line width
(set! (.. ctx -lineWidth) line-width)
;; Line colour
(set! (.. ctx -strokeStyle)
(cond
(= unreachable :peripheral)
theme/peripheral-yellow-light
unreachable
theme/magenta-light
(and solution (not connected) (not alternative) (= inclusion :optional))
theme/beige-light
alternative
theme/green-light
in-solution
theme/in-solution-orange-light
in-selected-group "#000000"
:else
theme/white))))
(set! (.. ctx -globalAlpha) 1)
(render-geometry (::spatial/jsts-geometry candidate) ctx project
true false true))
(defn render-geometry
[geom ctx project fill? close? shadow?]
(case (.getGeometryType geom)
"Polygon"
(do (.beginPath ctx)
(render-linestring (.getExteriorRing geom) ctx project true)
;; draw the inner rings
(dotimes [n (.getNumInteriorRing geom)]
(render-linestring (.getInteriorRingN geom n) ctx project true))
;; draw the outline
(when fill? (.fill ctx))
(if shadow?
(.stroke ctx)
(do
(.save ctx)
(.clip ctx)
(set! (.. ctx -lineWidth)
(* 2 (.. ctx -lineWidth)))
(.stroke ctx)
(.restore ctx))))
"Point"
(do (.beginPath ctx)
(let [pt (project (.getY geom) (.getX geom))]
(.arc ctx
(.-x pt) (.-y pt)
*point-radius* 0 (* 2 Math/PI)))
(when fill? (.fill ctx))
(.stroke ctx))
"LineString"
(do (.beginPath ctx)
(render-linestring geom ctx project false)
(.stroke ctx))
("MultiLinestring" "MultiPolygon" "MultiPoint")
(dotimes [n (.getNumGeometries geom)]
(render-geometry (.getGeometryN geom n)
ctx project fill? close?))))
(defn render-linestring [line-string ctx project close?]
(-> line-string
(.getCoordinates)
(.forEach
(fn [coord ix]
(let [pt;; [x y]
(project (.-y coord) (.-x coord))]
(if (= 0 ix)
(.moveTo ctx (.-x pt) (.-y pt))
(.lineTo ctx (.-x pt) (.-y pt)))))))
(when close? (.closePath ctx)))
(defn render-coordinate-seq [point-seq ctx project]
(when (> (count point-seq) 1)
(let [[coord & t] point-seq]
(let [pt;; [x y]
(project (.-y coord) (.-x coord))]
(.moveTo ctx (.-x pt) (.-y pt)))
(doseq [coord t]
(let [pt;; [x y]
(project (.-y coord) (.-x coord))]
(.lineTo ctx (.-x pt) (.-y pt)))))))
| null | https://raw.githubusercontent.com/cse-bristol/110-thermos-ui/e13b96329f3c95e5a10bae431e8ae9bccdb475f4/src/thermos_frontend/tile.cljs | clojure | most of the work is in here - how to paint an individual tile onto the map
if there is a solution we probably want to show the solution cleanly
Render order: non-selected buildings, selected building shadows, selected buildings,
non-selected paths, selected path shadows, selected paths
clamp mm-over-1 so that we get a range that looks nice
Non-selected buildings
Selected building shadows
Selected buildings
Non-selected paths
Selected path shadows
Selected paths
Colour by constraints
Line width
Line colour
Fill
Colour by results of the optimisation
Line width
Line colour
Fill
Colour by constraints
Line width
Line colour
Colour by results of the optimisation
Line width
Line colour
draw the inner rings
draw the outline
[x y]
[x y]
[x y] | This file is part of THERMOS , copyright © Centre for Sustainable Energy , 2017 - 2021
Licensed under the Reciprocal Public License v1.5 . See LICENSE for licensing details .
(ns thermos-frontend.tile
(:require [reagent.core :as reagent]
[leaflet :as leaflet]
[thermos-frontend.operations :as operations]
[thermos-frontend.editor-state :as state]
[thermos-specs.document :as document]
[thermos-specs.path :as path]
[thermos-specs.candidate :as candidate]
[thermos-specs.solution :as solution]
[thermos-specs.view :as view]
[thermos-frontend.spatial :as spatial]
[thermos-frontend.theme :as theme]
[goog.object :as o]))
(declare render-candidate render-candidate-shadow render-geometry render-linestring)
(defn projection
"Create a projection function"
[tile layer]
(let [coords (.-coords tile)
size (.getTileSize layer)
zoom (.-z coords)
map-control (o/get layer "_map")]
(fn [x y]
(let [pt (.project map-control
(js/L.latLng x y)
zoom)
pt (.unscaleBy pt size)
pt (.subtract pt coords)
pt (.scaleBy pt size)]
pt))))
(defn fix-size [tile layer]
(let [size (.getTileSize layer)
width (.-x size)
height (.-y size)]
(.setAttribute tile "width" width)
(.setAttribute tile "height" height)))
(def ^:dynamic *point-radius*
"The screen-units radius for a Point geometry." 8.0)
(defn render-tile [has-solution? contents tile layer map-view min-max-diameter]
"Draw a tile.
`document` should be a document layer (not an atom containing a document layer),
`tile` a canvas element,
`layer` an instance of our layer component's layer class,
`map-view` is either ::view/constraints or ::view/solution,
`min-diameter` and max are the min and max, used for a linear scaling"
(let [coords (.-coords tile)
size (.getTileSize layer)
ctx (.getContext tile "2d")
width (.-x size)
height (.-y size)
zoom (.-z coords)
project (projection tile layer)
geometry-key ::spatial/jsts-geometry]
(fix-size tile layer)
(.clearRect ctx 0 0 width height)
(let [{buildings :building paths :path} (group-by ::candidate/type contents)
{selected-buildings true non-selected-buildings false}
(group-by
(fn [x] (boolean (or (::candidate/selected x) (:in-selected-group x))))
buildings)
paths
(cond
(> zoom 14) paths
has-solution?
(filter candidate/in-solution? paths)
:else [])
use-diameters
(and (> zoom 14)
min-max-diameter
(not= (first min-max-diameter) (second min-max-diameter)))
paths
(if use-diameters
(let [[min-diameter max-diameter] min-max-diameter
dia-range (- max-diameter min-diameter)
mm-ratio (/ max-diameter min-diameter)
mm-over-1 (- mm-ratio 1)
mm-over-1 (cond
(< mm-over-1 2.5) 2.5
(> mm-over-1 4.5) 4.5
:else mm-over-1)
]
(for [path paths]
(if-let [diameter (::solution/diameter-mm path)]
(assoc path ::dia-scale
(let [ratio (/ (- diameter min-diameter) dia-range)]
(+ 1 (* mm-over-1 (Math/sqrt ratio)))))
path)))
paths)
{selected-paths true non-selected-paths false}
(group-by (comp boolean ::candidate/selected) paths)
ordinary-line-width
(cond
(> zoom 16) 1.5
:else 1)
shadow-width
(cond
(> zoom 16) 3
:else 2)
shadow-line-width
(+ ordinary-line-width shadow-width)
]
(binding [*point-radius*
(if (<= zoom 15) 3
(- zoom 10))]
(doseq [candidate non-selected-buildings]
(render-candidate ordinary-line-width has-solution? candidate ctx project map-view))
(doseq [candidate selected-buildings]
(render-candidate-shadow shadow-line-width has-solution? candidate ctx project map-view))
(doseq [candidate selected-buildings]
(render-candidate ordinary-line-width has-solution? candidate ctx project map-view))
(doseq [path non-selected-paths]
(render-candidate
(* (::dia-scale path 1) ordinary-line-width)
has-solution? path ctx project map-view))
(doseq [path selected-paths]
(render-candidate-shadow
(+ shadow-width (* (::dia-scale path 1) ordinary-line-width))
has-solution? path ctx project map-view))
(doseq [path selected-paths]
(render-candidate
(::dia-scale path ordinary-line-width)
has-solution? path ctx project map-view)))
)
))
(defn render-candidate
"Draw a shape for the candidate on a map.
`candidate` is a candidate map,
`ctx` is a Canvas graphics context (2D),
`project` is a function to project from real space into the canvas pixel space,
`map-view` is either ::view/constraints or ::view/solution,
`line-width` is an optionally specified line width for when you want to represent the pipe diameter."
[line-width solution candidate ctx project map-view]
(let [filtered (:filtered candidate)
in-selected-group (:in-selected-group candidate)]
(set! (.. ctx -lineCap) "round")
(case map-view
::view/constraints
(let [selected (::candidate/selected candidate)
inclusion (::candidate/inclusion candidate)
is-supply (candidate/has-supply? candidate)
included (candidate/is-included? candidate)
forbidden (not included)]
(set! (.. ctx -lineWidth) line-width)
(set! (.. ctx -strokeStyle)
(cond
(= inclusion :required) theme/red
(= inclusion :optional) theme/blue
:else theme/white))
(set! (.. ctx -fillStyle)
(cond
is-supply
theme/supply-orange
selected
theme/dark-grey
in-selected-group
theme/white
:else
theme/light-grey
)
))
::view/solution
(let [selected (::candidate/selected candidate)
inclusion (::candidate/inclusion candidate)
in-solution (candidate/in-solution? candidate)
unreachable (candidate/unreachable? candidate)
alternative (candidate/got-alternative? candidate)
connected (candidate/is-connected? candidate)
supply-in-solution (candidate/supply-in-solution? candidate)]
(set! (.. ctx -lineWidth) line-width)
(set! (.. ctx -strokeStyle)
(cond
(= unreachable :peripheral)
theme/peripheral-yellow
unreachable
theme/magenta
(and solution (not connected) (not alternative) (= inclusion :optional))
theme/beige
alternative
theme/green
in-solution
theme/in-solution-orange
:else
theme/white))
(set! (.. ctx -fillStyle)
(cond
supply-in-solution
theme/supply-orange
selected
theme/dark-grey
in-selected-group
theme/white
:else
theme/light-grey
))))
(set! (.. ctx -globalAlpha)
(if filtered 0.25 1)))
(render-geometry (::spatial/jsts-geometry candidate) ctx project
true false false))
(defn render-candidate-shadow
"Draw some kind of ephemeral outline for selected candidate.
Arguments are the same as render-candidate."
[line-width solution candidate ctx project map-view]
(set! (.. ctx -lineCap) "round")
(set! (.. ctx -lineJoin) "round")
(case map-view
::view/constraints
(let [in-selected-group (:in-selected-group candidate)
selected (::candidate/selected candidate)
inclusion (::candidate/inclusion candidate)
is-supply (candidate/has-supply? candidate)
included (candidate/is-included? candidate)
forbidden (not included)]
(set! (.. ctx -lineWidth) line-width)
(set! (.. ctx -strokeStyle)
(cond
in-selected-group "#000000"
(= inclusion :required) theme/red-light
(= inclusion :optional) theme/blue-light
:else theme/white)))
::view/solution
(let [in-selected-group (:in-selected-group candidate)
selected (::candidate/selected candidate)
inclusion (::candidate/inclusion candidate)
in-solution (candidate/in-solution? candidate)
unreachable (candidate/unreachable? candidate)
alternative (candidate/got-alternative? candidate)
connected (candidate/is-connected? candidate)
supply-in-solution (candidate/supply-in-solution? candidate)]
(set! (.. ctx -lineWidth) line-width)
(set! (.. ctx -strokeStyle)
(cond
(= unreachable :peripheral)
theme/peripheral-yellow-light
unreachable
theme/magenta-light
(and solution (not connected) (not alternative) (= inclusion :optional))
theme/beige-light
alternative
theme/green-light
in-solution
theme/in-solution-orange-light
in-selected-group "#000000"
:else
theme/white))))
(set! (.. ctx -globalAlpha) 1)
(render-geometry (::spatial/jsts-geometry candidate) ctx project
true false true))
(defn render-geometry
[geom ctx project fill? close? shadow?]
(case (.getGeometryType geom)
"Polygon"
(do (.beginPath ctx)
(render-linestring (.getExteriorRing geom) ctx project true)
(dotimes [n (.getNumInteriorRing geom)]
(render-linestring (.getInteriorRingN geom n) ctx project true))
(when fill? (.fill ctx))
(if shadow?
(.stroke ctx)
(do
(.save ctx)
(.clip ctx)
(set! (.. ctx -lineWidth)
(* 2 (.. ctx -lineWidth)))
(.stroke ctx)
(.restore ctx))))
"Point"
(do (.beginPath ctx)
(let [pt (project (.getY geom) (.getX geom))]
(.arc ctx
(.-x pt) (.-y pt)
*point-radius* 0 (* 2 Math/PI)))
(when fill? (.fill ctx))
(.stroke ctx))
"LineString"
(do (.beginPath ctx)
(render-linestring geom ctx project false)
(.stroke ctx))
("MultiLinestring" "MultiPolygon" "MultiPoint")
(dotimes [n (.getNumGeometries geom)]
(render-geometry (.getGeometryN geom n)
ctx project fill? close?))))
(defn render-linestring [line-string ctx project close?]
(-> line-string
(.getCoordinates)
(.forEach
(fn [coord ix]
(project (.-y coord) (.-x coord))]
(if (= 0 ix)
(.moveTo ctx (.-x pt) (.-y pt))
(.lineTo ctx (.-x pt) (.-y pt)))))))
(when close? (.closePath ctx)))
(defn render-coordinate-seq [point-seq ctx project]
(when (> (count point-seq) 1)
(let [[coord & t] point-seq]
(project (.-y coord) (.-x coord))]
(.moveTo ctx (.-x pt) (.-y pt)))
(doseq [coord t]
(project (.-y coord) (.-x coord))]
(.lineTo ctx (.-x pt) (.-y pt)))))))
|
425831073be132e4c90e1594a68e0b145ea43e7b31001bd13c40643cec04be90 | jgm/gitit | Github.hs | # LANGUAGE CPP , OverloadedStrings , ScopedTypeVariables #
module Network.Gitit.Authentication.Github ( loginGithubUser
, getGithubUser
, GithubCallbackPars
, GithubLoginError
, ghUserMessage
, ghDetails) where
import Network.Gitit.Types
import Network.Gitit.Server
import Network.Gitit.State
import Network.Gitit.Util
import Network.Gitit.Framework
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BSL
import qualified URI.ByteString as URI
import Network.HTTP.Conduit
import Network.OAuth.OAuth2
import Control.Monad (liftM, mplus, mzero)
import Data.Maybe
import Data.Aeson
import Data.Text (Text, pack, unpack)
import Data.Text.Encoding (encodeUtf8)
import Control.Applicative
import Control.Monad.Trans (liftIO)
import Data.UUID (toString)
import Data.UUID.V4 (nextRandom)
import qualified Control.Exception as E
import Control.Monad.Except
import Prelude
loginGithubUser :: OAuth2 -> Params -> Handler
loginGithubUser githubKey params = do
state <- liftIO $ fmap toString nextRandom
base' <- getWikiBase
let destination = pDestination params `orIfNull` (base' ++ "/")
key <- newSession $ sessionDataGithubStateUrl state destination
cfg <- getConfig
addCookie (MaxAge $ sessionTimeout cfg) (mkSessionCookie key)
let usingOrg = isJust $ org $ githubAuth cfg
let scopes = "user:email" ++ if usingOrg then ",read:org" else ""
let url = appendQueryParams [("state", BS.pack state), ("scope", BS.pack scopes)] $ authorizationUrl githubKey
seeOther (BS.unpack (URI.serializeURIRef' url)) $ toResponse ("redirecting to github" :: String)
data GithubLoginError = GithubLoginError { ghUserMessage :: String
, ghDetails :: Maybe String
}
getGithubUser :: GithubConfig -- ^ Oauth2 configuration (client secret)
-> GithubCallbackPars -- ^ Authentication code gained after authorization
^ Github state , we expect the state we sent in
-> GititServerPart (Either GithubLoginError User) -- ^ user email and name (password 'none')
getGithubUser ghConfig githubCallbackPars githubState = liftIO $
newManager tlsManagerSettings >>= getUserInternal
where
getUserInternal mgr =
liftIO $ runExceptT $ do
let (Just state) = rState githubCallbackPars
if state == githubState
then do
let (Just code) = rCode githubCallbackPars
at <- withExceptT (oauthToGithubError "No access token found yet")
$ fetchAccessToken mgr (oAuth2 ghConfig) (ExchangeToken $ pack code)
liftIO >=> liftEither $ ifSuccess "User Authentication failed"
(userInfo mgr (accessToken at))
(\githubUser -> ifSuccess
("No email for user " ++ unpack (gLogin githubUser) ++ " returned by Github")
(mailInfo mgr (accessToken at))
(\githubUserMail -> do
let gitLogin = gLogin githubUser
user <- mkUser (unpack gitLogin)
(unpack $ email $ head (filter primary githubUserMail))
"none"
let mbOrg = org ghConfig
case mbOrg of
Nothing -> return $ Right user
Just githuborg -> ifSuccess
("Membership check failed: the user " ++ unpack gitLogin ++ " is required to be a member of the organization " ++ unpack githuborg ++ ".")
(orgInfo gitLogin githuborg mgr (accessToken at))
(\_ -> return $ Right user)))
else
throwError $
GithubLoginError ("The state sent to github is not the same as the state received: " ++ state ++ ", but expected sent state: " ++ githubState)
Nothing
ifSuccess errMsg failableAction successAction = E.catch
(do Right outcome <- failableAction
successAction outcome)
(\exception -> liftIO $ return $ Left $
GithubLoginError errMsg
(Just $ show (exception :: E.SomeException)))
oauthToGithubError errMsg e = GithubLoginError errMsg (Just $ show e)
data GithubCallbackPars = GithubCallbackPars { rCode :: Maybe String
, rState :: Maybe String }
deriving Show
instance FromData GithubCallbackPars where
fromData = do
vCode <- liftM Just (look "code") `mplus` return Nothing
vState <- liftM Just (look "state") `mplus` return Nothing
return GithubCallbackPars {rCode = vCode, rState = vState}
#if MIN_VERSION_hoauth2(1, 9, 0)
userInfo :: Manager -> AccessToken -> IO (Either BSL.ByteString GithubUser)
#else
userInfo :: Manager -> AccessToken -> IO (OAuth2Result OA.Errors GithubUser)
#endif
userInfo mgr token = runExceptT $ authGetJSON mgr token $ githubUri "/user"
#if MIN_VERSION_hoauth2(1, 9, 0)
mailInfo :: Manager -> AccessToken -> IO (Either BSL.ByteString [GithubUserMail])
#else
mailInfo :: Manager -> AccessToken -> IO (OAuth2Result OA.Errors [GithubUserMail])
#endif
mailInfo mgr token = runExceptT $ authGetJSON mgr token $ githubUri "/user/emails"
#if MIN_VERSION_hoauth2(1, 9, 0)
orgInfo :: Text -> Text -> Manager -> AccessToken -> IO (Either BSL.ByteString BSL.ByteString)
#else
orgInfo :: Text -> Text -> Manager -> AccessToken -> IO (OAuth2Result OA.Errors BSL.ByteString)
#endif
orgInfo gitLogin githubOrg mgr token = do
let url = githubUri $ "/orgs/" `BS.append` encodeUtf8 githubOrg `BS.append` "/members/" `BS.append` encodeUtf8 gitLogin
runExceptT $ authGetBS mgr token url
type UriPath = BS.ByteString
githubUri :: UriPath -> URI.URI
githubUri p = URI.URI { URI.uriScheme = URI.Scheme "https"
, URI.uriAuthority = Just $ URI.Authority Nothing (URI.Host "api.github.com") Nothing
, URI.uriPath = p
, URI.uriQuery = URI.Query []
, URI.uriFragment = Nothing }
data GithubUser = GithubUser { gLogin :: Text
} deriving (Show, Eq)
instance FromJSON GithubUser where
parseJSON (Object o) = GithubUser
<$> o .: "login"
parseJSON _ = mzero
data GithubUserMail = GithubUserMail { email :: Text
, primary :: Bool
} deriving (Show, Eq)
instance FromJSON GithubUserMail where
parseJSON (Object o) = GithubUserMail
<$> o .: "email"
<*> o .: "primary"
parseJSON _ = mzero
| null | https://raw.githubusercontent.com/jgm/gitit/fe36cd6074dfe27c7b30d65b49b593482943bc95/src/Network/Gitit/Authentication/Github.hs | haskell | ^ Oauth2 configuration (client secret)
^ Authentication code gained after authorization
^ user email and name (password 'none') | # LANGUAGE CPP , OverloadedStrings , ScopedTypeVariables #
module Network.Gitit.Authentication.Github ( loginGithubUser
, getGithubUser
, GithubCallbackPars
, GithubLoginError
, ghUserMessage
, ghDetails) where
import Network.Gitit.Types
import Network.Gitit.Server
import Network.Gitit.State
import Network.Gitit.Util
import Network.Gitit.Framework
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BSL
import qualified URI.ByteString as URI
import Network.HTTP.Conduit
import Network.OAuth.OAuth2
import Control.Monad (liftM, mplus, mzero)
import Data.Maybe
import Data.Aeson
import Data.Text (Text, pack, unpack)
import Data.Text.Encoding (encodeUtf8)
import Control.Applicative
import Control.Monad.Trans (liftIO)
import Data.UUID (toString)
import Data.UUID.V4 (nextRandom)
import qualified Control.Exception as E
import Control.Monad.Except
import Prelude
loginGithubUser :: OAuth2 -> Params -> Handler
loginGithubUser githubKey params = do
state <- liftIO $ fmap toString nextRandom
base' <- getWikiBase
let destination = pDestination params `orIfNull` (base' ++ "/")
key <- newSession $ sessionDataGithubStateUrl state destination
cfg <- getConfig
addCookie (MaxAge $ sessionTimeout cfg) (mkSessionCookie key)
let usingOrg = isJust $ org $ githubAuth cfg
let scopes = "user:email" ++ if usingOrg then ",read:org" else ""
let url = appendQueryParams [("state", BS.pack state), ("scope", BS.pack scopes)] $ authorizationUrl githubKey
seeOther (BS.unpack (URI.serializeURIRef' url)) $ toResponse ("redirecting to github" :: String)
data GithubLoginError = GithubLoginError { ghUserMessage :: String
, ghDetails :: Maybe String
}
^ Github state , we expect the state we sent in
getGithubUser ghConfig githubCallbackPars githubState = liftIO $
newManager tlsManagerSettings >>= getUserInternal
where
getUserInternal mgr =
liftIO $ runExceptT $ do
let (Just state) = rState githubCallbackPars
if state == githubState
then do
let (Just code) = rCode githubCallbackPars
at <- withExceptT (oauthToGithubError "No access token found yet")
$ fetchAccessToken mgr (oAuth2 ghConfig) (ExchangeToken $ pack code)
liftIO >=> liftEither $ ifSuccess "User Authentication failed"
(userInfo mgr (accessToken at))
(\githubUser -> ifSuccess
("No email for user " ++ unpack (gLogin githubUser) ++ " returned by Github")
(mailInfo mgr (accessToken at))
(\githubUserMail -> do
let gitLogin = gLogin githubUser
user <- mkUser (unpack gitLogin)
(unpack $ email $ head (filter primary githubUserMail))
"none"
let mbOrg = org ghConfig
case mbOrg of
Nothing -> return $ Right user
Just githuborg -> ifSuccess
("Membership check failed: the user " ++ unpack gitLogin ++ " is required to be a member of the organization " ++ unpack githuborg ++ ".")
(orgInfo gitLogin githuborg mgr (accessToken at))
(\_ -> return $ Right user)))
else
throwError $
GithubLoginError ("The state sent to github is not the same as the state received: " ++ state ++ ", but expected sent state: " ++ githubState)
Nothing
ifSuccess errMsg failableAction successAction = E.catch
(do Right outcome <- failableAction
successAction outcome)
(\exception -> liftIO $ return $ Left $
GithubLoginError errMsg
(Just $ show (exception :: E.SomeException)))
oauthToGithubError errMsg e = GithubLoginError errMsg (Just $ show e)
data GithubCallbackPars = GithubCallbackPars { rCode :: Maybe String
, rState :: Maybe String }
deriving Show
instance FromData GithubCallbackPars where
fromData = do
vCode <- liftM Just (look "code") `mplus` return Nothing
vState <- liftM Just (look "state") `mplus` return Nothing
return GithubCallbackPars {rCode = vCode, rState = vState}
#if MIN_VERSION_hoauth2(1, 9, 0)
userInfo :: Manager -> AccessToken -> IO (Either BSL.ByteString GithubUser)
#else
userInfo :: Manager -> AccessToken -> IO (OAuth2Result OA.Errors GithubUser)
#endif
userInfo mgr token = runExceptT $ authGetJSON mgr token $ githubUri "/user"
#if MIN_VERSION_hoauth2(1, 9, 0)
mailInfo :: Manager -> AccessToken -> IO (Either BSL.ByteString [GithubUserMail])
#else
mailInfo :: Manager -> AccessToken -> IO (OAuth2Result OA.Errors [GithubUserMail])
#endif
mailInfo mgr token = runExceptT $ authGetJSON mgr token $ githubUri "/user/emails"
#if MIN_VERSION_hoauth2(1, 9, 0)
orgInfo :: Text -> Text -> Manager -> AccessToken -> IO (Either BSL.ByteString BSL.ByteString)
#else
orgInfo :: Text -> Text -> Manager -> AccessToken -> IO (OAuth2Result OA.Errors BSL.ByteString)
#endif
orgInfo gitLogin githubOrg mgr token = do
let url = githubUri $ "/orgs/" `BS.append` encodeUtf8 githubOrg `BS.append` "/members/" `BS.append` encodeUtf8 gitLogin
runExceptT $ authGetBS mgr token url
type UriPath = BS.ByteString
githubUri :: UriPath -> URI.URI
githubUri p = URI.URI { URI.uriScheme = URI.Scheme "https"
, URI.uriAuthority = Just $ URI.Authority Nothing (URI.Host "api.github.com") Nothing
, URI.uriPath = p
, URI.uriQuery = URI.Query []
, URI.uriFragment = Nothing }
data GithubUser = GithubUser { gLogin :: Text
} deriving (Show, Eq)
instance FromJSON GithubUser where
parseJSON (Object o) = GithubUser
<$> o .: "login"
parseJSON _ = mzero
data GithubUserMail = GithubUserMail { email :: Text
, primary :: Bool
} deriving (Show, Eq)
instance FromJSON GithubUserMail where
parseJSON (Object o) = GithubUserMail
<$> o .: "email"
<*> o .: "primary"
parseJSON _ = mzero
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.